Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix(release): track proof helpers and restore monitoring ownership

rcourtman5dbfcfc77d05
diff --git a/.gitignore b/.gitignore
index 6f01727904..51aed70d82 100644
--- a/.gitignore
+++ b/.gitignore
@@ -252,10 +252,6 @@ scripts/release_control/*
!scripts/release_control/subsystem_contracts_test.py
!scripts/release_control/subsystem_lookup.py
!scripts/release_control/subsystem_lookup_test.py
-!scripts/release_control/internal/
-scripts/release_control/internal/*
-!scripts/release_control/internal/record_rc_to_ga_rehearsal.py
-!scripts/release_control/internal/record_rc_to_ga_rehearsal_test.py
!scripts/release_control/work_claim.py
!scripts/release_control/work_claim_test.py
.agent/
diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.go
index cd4ce05149..f55c129568 100644
--- a/internal/monitoring/monitor_agents.go
+++ b/internal/monitoring/monitor_agents.go
@@ -267,6 +267,28 @@ func (m *Monitor) AllowHostAgentReenroll(hostID string) error {
return nil
}
+func (m *Monitor) lookupRemovedHostAgent(identifier, hostname string) (time.Time, bool) {
+ identifier = strings.TrimSpace(identifier)
+
+ m.mu.RLock()
+ removedAt, wasRemoved := m.removedHostAgents[identifier]
+ m.mu.RUnlock()
+ if wasRemoved {
+ return removedAt, true
+ }
+
+ for _, entry := range m.state.GetRemovedHostAgents() {
+ if strings.TrimSpace(entry.ID) == identifier {
+ return entry.RemovedAt, true
+ }
+ if strings.TrimSpace(entry.Hostname) == hostname {
+ return entry.RemovedAt, true
+ }
+ }
+
+ return time.Time{}, false
+}
+
// LinkHostAgent manually links a host agent to a specific PVE node.
// This is used when auto-linking can't disambiguate (e.g., multiple nodes with hostname "pve").
// After linking, the host agent's temperature/sensor data will appear on the correct node.
@@ -1388,28 +1410,6 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
baseIdentifier = fmt.Sprintf("agent-%s", hex.EncodeToString(sum[:6]))
}
- m.mu.RLock()
- removedAt, wasRemoved := m.removedHostAgents[baseIdentifier]
- m.mu.RUnlock()
- if !wasRemoved {
- for _, entry := range m.state.GetRemovedHostAgents() {
- if strings.TrimSpace(entry.Hostname) != hostname {
- continue
- }
- removedAt = entry.RemovedAt
- wasRemoved = true
- baseIdentifier = strings.TrimSpace(entry.ID)
- break
- }
- }
- if wasRemoved {
- log.Info().
- Str("hostID", baseIdentifier).
- Time("removedAt", removedAt).
- Msg("Rejecting report from deliberately removed host agent")
- return models.Host{}, fmt.Errorf("host agent %q had monitoring stopped at %v and cannot report again. Use Allow reconnect in Settings -> Infrastructure before reconnecting this host", baseIdentifier, removedAt.Format(time.RFC3339))
- }
-
readState := m.snapshotBackedUnifiedReadState()
var existingHosts []*unifiedresources.HostView
if readState != nil {
@@ -1476,6 +1476,15 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
}
}
+ removedAt, wasRemoved := m.lookupRemovedHostAgent(identifier, hostname)
+ if wasRemoved {
+ log.Info().
+ Str("hostID", identifier).
+ Time("removedAt", removedAt).
+ Msg("Rejecting report from deliberately removed host agent")
+ return models.Host{}, fmt.Errorf("host agent %q had monitoring stopped at %v and cannot report again. Use Allow reconnect in Settings -> Infrastructure before reconnecting this host", identifier, removedAt.Format(time.RFC3339))
+ }
+
var previous *unifiedresources.HostView
var hasPrevious bool
for _, candidate := range existingHosts {
diff --git a/internal/monitoring/monitor_extra_coverage_test.go b/internal/monitoring/monitor_extra_coverage_test.go
index 1299e6bad1..5d8423db9a 100644
--- a/internal/monitoring/monitor_extra_coverage_test.go
+++ b/internal/monitoring/monitor_extra_coverage_test.go
@@ -842,8 +842,8 @@ func (m *mockResourceStoreExtra) UnifiedResourceFreshness() time.Time {
func TestMonitor_ResourcesForBroadcast_Extra(t *testing.T) {
m := &Monitor{}
- if m.getResourcesForBroadcast() != nil {
- t.Error("Expected nil when store is nil")
+ if res := m.getResourcesForBroadcast(); res == nil || len(res) != 0 {
+ t.Fatalf("expected empty resources when store is nil, got %#v", res)
}
now := time.Now().UTC()
diff --git a/internal/monitoring/monitor_full_coverage_test.go b/internal/monitoring/monitor_full_coverage_test.go
index 6f7e0a49e2..2632e39b76 100644
--- a/internal/monitoring/monitor_full_coverage_test.go
+++ b/internal/monitoring/monitor_full_coverage_test.go
@@ -439,8 +439,8 @@ func TestMonitor_ResourceUpdate(t *testing.T) {
// getResourcesForBroadcast
res := m.getResourcesForBroadcast()
- if res != nil {
- t.Error("Expected nil resources from mock")
+ if res == nil || len(res) != 0 {
+ t.Fatalf("expected empty resources from mock, got %#v", res)
}
}
diff --git a/scripts/release_control/internal/commercial_cancellation_reactivation_proof.py b/scripts/release_control/internal/commercial_cancellation_reactivation_proof.py
new file mode 100644
index 0000000000..75db0ec30c
--- /dev/null
+++ b/scripts/release_control/internal/commercial_cancellation_reactivation_proof.py
@@ -0,0 +1,211 @@
+#!/usr/bin/env python3
+"""Run the automated proof floor for the commercial cancellation/reactivation gate."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import subprocess
+from dataclasses import asdict, dataclass
+from pathlib import Path
+
+
+@dataclass
+class CommandSpec:
+ name: str
+ cwd: str
+ command: list[str]
+
+
+@dataclass
+class CommandResult:
+ name: str
+ cwd: str
+ command: list[str]
+ ok: bool
+ exit_code: int
+ detail: str
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Run the automated proof bundle for the commercial cancellation/"
+ "reactivation release gate."
+ )
+ )
+ parser.add_argument(
+ "--pulse-dir",
+ default=str(default_pulse_dir()),
+ help="Path to the pulse repo root",
+ )
+ parser.add_argument(
+ "--pulse-pro-license-server-dir",
+ default=str(default_pulse_pro_license_server_dir()),
+ help="Path to the pulse-pro/license-server directory",
+ )
+ parser.add_argument(
+ "--frontend-dir",
+ help="Optional override for the pulse frontend-modern directory",
+ )
+ parser.add_argument(
+ "--json",
+ action="store_true",
+ help="Emit JSON instead of human-readable output",
+ )
+ parser.add_argument(
+ "--report-out",
+ help="Optional path to write a markdown report",
+ )
+ parser.add_argument(
+ "--report-title",
+ default="Commercial Cancellation/Reactivation Automated Proof",
+ help="Markdown title used when writing --report-out",
+ )
+ return parser.parse_args(argv)
+
+
+def default_pulse_dir() -> Path:
+ return Path(__file__).resolve().parents[2]
+
+
+def default_pulse_pro_license_server_dir() -> Path:
+ return default_pulse_dir().parent / "pulse-pro" / "license-server"
+
+
+def frontend_dir_from_args(args: argparse.Namespace) -> Path:
+ if args.frontend_dir:
+ return Path(args.frontend_dir).resolve()
+ return Path(args.pulse_dir).resolve() / "frontend-modern"
+
+
+def build_command_specs(args: argparse.Namespace) -> list[CommandSpec]:
+ pulse_dir = Path(args.pulse_dir).resolve()
+ pulse_pro_license_server_dir = Path(args.pulse_pro_license_server_dir).resolve()
+ frontend_dir = frontend_dir_from_args(args)
+ return [
+ CommandSpec(
+ name="pulse-api-cancellation-boundary",
+ cwd=str(pulse_dir),
+ command=[
+ "go",
+ "test",
+ "./internal/api",
+ "-run",
+ "TestStripeWebhook_SubscriptionDeleted_RevokesCapabilities",
+ "-count=1",
+ ],
+ ),
+ CommandSpec(
+ name="pulse-v5-recurring-upgrade-migration",
+ cwd=str(pulse_dir),
+ command=[
+ "go",
+ "test",
+ "./tests/migration",
+ "-run",
+ "TestV5FullUpgradeScenario/PersistedV5RecurringLicenseAutoExchanges",
+ "-count=1",
+ ],
+ ),
+ CommandSpec(
+ name="frontend-grandfathered-license-presentation",
+ cwd=str(frontend_dir),
+ command=[
+ "npm",
+ "test",
+ "--",
+ "src/utils/__tests__/licensePresentation.test.ts",
+ "src/components/Settings/__tests__/ProLicensePanel.test.tsx",
+ ],
+ ),
+ CommandSpec(
+ name="pulse-pro-public-checkout-reentry-guard",
+ cwd=str(pulse_pro_license_server_dir),
+ command=[
+ "go",
+ "test",
+ ".",
+ "-run",
+ "TestHandleCheckoutSessionCreate(_RejectsGrandfatheredPlanKey)?$",
+ "-count=1",
+ ],
+ ),
+ ]
+
+
+def summarize_output(stdout: str, stderr: str) -> str:
+ text = "\n".join(part.strip() for part in (stdout, stderr) if part.strip()).strip()
+ if not text:
+ return "pass"
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
+ summary = lines[-1]
+ if len(summary) > 240:
+ return summary[:237] + "..."
+ return summary
+
+
+def run_command(spec: CommandSpec) -> CommandResult:
+ proc = subprocess.run(
+ spec.command,
+ cwd=spec.cwd,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ return CommandResult(
+ name=spec.name,
+ cwd=spec.cwd,
+ command=spec.command,
+ ok=proc.returncode == 0,
+ exit_code=proc.returncode,
+ detail=summarize_output(proc.stdout, proc.stderr),
+ )
+
+
+def run_proof(args: argparse.Namespace) -> list[CommandResult]:
+ return [run_command(spec) for spec in build_command_specs(args)]
+
+
+def render_markdown_report(title: str, results: list[CommandResult]) -> str:
+ lines = [f"# {title}", "", "## Results", ""]
+ for result in results:
+ status = "PASS" if result.ok else "FAIL"
+ lines.append(f"- `{status}` `{result.name}`")
+ lines.append(f" - cwd: `{result.cwd}`")
+ lines.append(f" - command: `{' '.join(result.command)}`")
+ lines.append(f" - detail: {result.detail}")
+ lines.extend(
+ [
+ "",
+ "## Manual Follow-up",
+ "",
+ "- If all commands passed, continue with the manual scenarios in",
+ " `docs/release-control/v6/COMMERCIAL_CANCELLATION_REACTIVATION_E2E_TEST_PLAN.md`.",
+ "- Save the executed manual record from",
+ " `docs/release-control/v6/COMMERCIAL_CANCELLATION_REACTIVATION_RECORD_TEMPLATE.md`.",
+ ]
+ )
+ return "\n".join(lines) + "\n"
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(argv)
+ results = run_proof(args)
+ if args.report_out:
+ report_path = Path(args.report_out)
+ report_path.write_text(
+ render_markdown_report(args.report_title, results),
+ encoding="utf-8",
+ )
+ if args.json:
+ print(json.dumps([asdict(result) for result in results], indent=2))
+ else:
+ for result in results:
+ status = "PASS" if result.ok else "FAIL"
+ print(f"{status} {result.name}: {result.detail}")
+ return 0 if all(result.ok for result in results) else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release_control/internal/commercial_cancellation_reactivation_proof_test.py b/scripts/release_control/internal/commercial_cancellation_reactivation_proof_test.py
new file mode 100644
index 0000000000..0328efea83
--- /dev/null
+++ b/scripts/release_control/internal/commercial_cancellation_reactivation_proof_test.py
@@ -0,0 +1,127 @@
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import tempfile
+import unittest
+from pathlib import Path
+
+import commercial_cancellation_reactivation_proof as proof
+
+
+def run_main(argv: list[str]) -> tuple[int, str]:
+ buffer = io.StringIO()
+ with contextlib.redirect_stdout(buffer):
+ exit_code = proof.main(argv)
+ return exit_code, buffer.getvalue()
+
+
+class CommercialCancellationReactivationProofTest(unittest.TestCase):
+ def test_build_command_specs_uses_expected_directories(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ pulse_dir = Path(tmp) / "pulse"
+ pulse_dir.mkdir()
+ frontend_dir = pulse_dir / "frontend-modern"
+ frontend_dir.mkdir()
+ pulse_pro_dir = Path(tmp) / "pulse-pro" / "license-server"
+ pulse_pro_dir.mkdir(parents=True)
+ args = proof.parse_args(
+ [
+ "--pulse-dir",
+ str(pulse_dir),
+ "--pulse-pro-license-server-dir",
+ str(pulse_pro_dir),
+ ]
+ )
+ specs = proof.build_command_specs(args)
+ self.assertEqual(len(specs), 4)
+ self.assertEqual(specs[0].cwd, str(pulse_dir.resolve()))
+ self.assertEqual(specs[2].cwd, str(frontend_dir.resolve()))
+ self.assertEqual(specs[3].cwd, str(pulse_pro_dir.resolve()))
+
+ def test_run_command_success(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ result = proof.run_command(
+ proof.CommandSpec(
+ name="ok",
+ cwd=tmp,
+ command=["python3", "-c", "print('all good')"],
+ )
+ )
+ self.assertTrue(result.ok)
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(result.detail, "all good")
+
+ def test_run_command_failure_uses_stderr_summary(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ result = proof.run_command(
+ proof.CommandSpec(
+ name="fail",
+ cwd=tmp,
+ command=["python3", "-c", "import sys; sys.stderr.write('boom\\n'); sys.exit(2)"],
+ )
+ )
+ self.assertFalse(result.ok)
+ self.assertEqual(result.exit_code, 2)
+ self.assertEqual(result.detail, "boom")
+
+ def test_render_markdown_report(self) -> None:
+ report = proof.render_markdown_report(
+ "Commercial Cancellation/Reactivation Automated Proof",
+ [
+ proof.CommandResult(
+ name="pass-spec",
+ cwd="/tmp/pulse",
+ command=["go", "test", "./..."],
+ ok=True,
+ exit_code=0,
+ detail="ok",
+ ),
+ proof.CommandResult(
+ name="fail-spec",
+ cwd="/tmp/pulse-pro/license-server",
+ command=["go", "test", "."],
+ ok=False,
+ exit_code=1,
+ detail="FAIL",
+ ),
+ ],
+ )
+ self.assertIn("# Commercial Cancellation/Reactivation Automated Proof", report)
+ self.assertIn("`PASS` `pass-spec`", report)
+ self.assertIn("`FAIL` `fail-spec`", report)
+ self.assertIn("## Manual Follow-up", report)
+
+ def test_main_json_and_report(self) -> None:
+ original_run_proof = proof.run_proof
+ try:
+ proof.run_proof = lambda _args: [ # type: ignore[assignment]
+ proof.CommandResult(
+ name="fake",
+ cwd="/tmp",
+ command=["echo", "fake"],
+ ok=True,
+ exit_code=0,
+ detail="pass",
+ )
+ ]
+ with tempfile.TemporaryDirectory() as tmp:
+ report_path = Path(tmp) / "report.md"
+ exit_code, output = run_main(
+ [
+ "--report-out",
+ str(report_path),
+ "--json",
+ ]
+ )
+ self.assertEqual(exit_code, 0)
+ payload = json.loads(output)
+ self.assertEqual(payload[0]["name"], "fake")
+ self.assertIn("Manual Follow-up", report_path.read_text(encoding="utf-8"))
+ finally:
+ proof.run_proof = original_run_proof # type: ignore[assignment]
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release_control/internal/commercial_cancellation_reactivation_rehearsal.py b/scripts/release_control/internal/commercial_cancellation_reactivation_rehearsal.py
new file mode 100644
index 0000000000..e6983558b7
--- /dev/null
+++ b/scripts/release_control/internal/commercial_cancellation_reactivation_rehearsal.py
@@ -0,0 +1,163 @@
+#!/usr/bin/env python3
+"""Run the live commercial cancellation/reactivation rehearsal."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import subprocess
+from dataclasses import asdict, dataclass
+from pathlib import Path
+
+
+@dataclass
+class CommandResult:
+ name: str
+ cwd: str
+ command: list[str]
+ ok: bool
+ exit_code: int
+ detail: str
+
+
+def default_pulse_dir() -> Path:
+ return Path(__file__).resolve().parents[2]
+
+
+def default_integration_dir() -> Path:
+ return default_pulse_dir() / "tests" / "integration"
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Run the commercial cancellation/reactivation rehearsal against a live "
+ "Pulse + Stripe environment and optionally write a markdown report."
+ )
+ )
+ parser.add_argument(
+ "--pulse-dir",
+ default=str(default_pulse_dir()),
+ help="Path to the pulse repo root",
+ )
+ parser.add_argument(
+ "--integration-dir",
+ default=str(default_integration_dir()),
+ help="Path to the Pulse integration test package",
+ )
+ parser.add_argument(
+ "--project",
+ default="chromium",
+ help="Playwright project to run",
+ )
+ parser.add_argument(
+ "--json",
+ action="store_true",
+ help="Emit JSON instead of human-readable output",
+ )
+ parser.add_argument(
+ "--report-out",
+ help="Optional path to write a markdown report",
+ )
+ parser.add_argument(
+ "--report-title",
+ default="Commercial Cancellation/Reactivation Rehearsal",
+ help="Markdown title used when writing --report-out",
+ )
+ return parser.parse_args(argv)
+
+
+def summarize_output(stdout: str, stderr: str) -> str:
+ text = "\n".join(part.strip() for part in (stdout, stderr) if part.strip()).strip()
+ if not text:
+ return "pass"
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
+ summary = lines[-1]
+ if len(summary) > 240:
+ return summary[:237] + "..."
+ return summary
+
+
+def run_command(name: str, cwd: Path, command: list[str]) -> CommandResult:
+ proc = subprocess.run(
+ command,
+ cwd=str(cwd),
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ return CommandResult(
+ name=name,
+ cwd=str(cwd),
+ command=command,
+ ok=proc.returncode == 0,
+ exit_code=proc.returncode,
+ detail=summarize_output(proc.stdout, proc.stderr),
+ )
+
+
+def run_rehearsal(args: argparse.Namespace) -> list[CommandResult]:
+ pulse_dir = Path(args.pulse_dir).resolve()
+ integration_dir = Path(args.integration_dir).resolve()
+ return [
+ run_command(
+ "commercial-cancellation-automated-proof-floor",
+ pulse_dir,
+ ["python3", "scripts/release_control/commercial_cancellation_reactivation_proof.py", "--json"],
+ ),
+ run_command(
+ "commercial-cancellation-playwright-live-journey",
+ integration_dir,
+ [
+ "npm",
+ "test",
+ "--",
+ "tests/14-commercial-cancellation-reactivation.spec.ts",
+ f"--project={args.project}",
+ ],
+ ),
+ ]
+
+
+def render_markdown_report(title: str, results: list[CommandResult]) -> str:
+ lines = [f"# {title}", "", "## Results", ""]
+ for result in results:
+ status = "PASS" if result.ok else "FAIL"
+ lines.append(f"- `{status}` `{result.name}`")
+ lines.append(f" - cwd: `{result.cwd}`")
+ lines.append(f" - command: `{' '.join(result.command)}`")
+ lines.append(f" - detail: {result.detail}")
+ lines.extend(
+ [
+ "",
+ "## Environment Requirements",
+ "",
+ "- Stripe sandbox credentials and the commercial fixture env vars documented in",
+ " `tests/integration/tests/14-commercial-cancellation-reactivation.spec.ts`.",
+ "- A live Pulse runtime whose authenticated settings surface reflects the migrated",
+ " recurring commercial state under test.",
+ "- A real public checkout origin for `pulse-pro/license-server`.",
+ ]
+ )
+ return "\n".join(lines) + "\n"
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(argv)
+ results = run_rehearsal(args)
+ if args.report_out:
+ Path(args.report_out).write_text(
+ render_markdown_report(args.report_title, results),
+ encoding="utf-8",
+ )
+ if args.json:
+ print(json.dumps([asdict(result) for result in results], indent=2))
+ else:
+ for result in results:
+ status = "PASS" if result.ok else "FAIL"
+ print(f"{status} {result.name}: {result.detail}")
+ return 0 if all(result.ok for result in results) else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release_control/internal/commercial_cancellation_reactivation_rehearsal_test.py b/scripts/release_control/internal/commercial_cancellation_reactivation_rehearsal_test.py
new file mode 100644
index 0000000000..41cc034cc6
--- /dev/null
+++ b/scripts/release_control/internal/commercial_cancellation_reactivation_rehearsal_test.py
@@ -0,0 +1,89 @@
+#!/usr/bin/env python3
+"""Tests for the live commercial cancellation/reactivation rehearsal wrapper."""
+
+from __future__ import annotations
+
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+import commercial_cancellation_reactivation_rehearsal as rehearsal
+
+
+class BuildCommandTests(unittest.TestCase):
+ def test_run_rehearsal_uses_expected_commands(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ integration = root / "tests" / "integration"
+ integration.mkdir(parents=True)
+ args = rehearsal.parse_args(
+ [
+ "--pulse-dir",
+ str(root),
+ "--integration-dir",
+ str(integration),
+ "--project",
+ "chromium",
+ ]
+ )
+ recorded: list[tuple[str, Path, list[str]]] = []
+
+ def fake_run(name: str, cwd: Path, command: list[str]) -> rehearsal.CommandResult:
+ recorded.append((name, cwd, command))
+ return rehearsal.CommandResult(
+ name=name,
+ cwd=str(cwd),
+ command=command,
+ ok=True,
+ exit_code=0,
+ detail="pass",
+ )
+
+ with mock.patch.object(rehearsal, "run_command", side_effect=fake_run):
+ results = rehearsal.run_rehearsal(args)
+
+ self.assertEqual(len(results), 2)
+ self.assertEqual(recorded[0][0], "commercial-cancellation-automated-proof-floor")
+ self.assertEqual(
+ recorded[0][2],
+ [
+ "python3",
+ "scripts/release_control/commercial_cancellation_reactivation_proof.py",
+ "--json",
+ ],
+ )
+ self.assertEqual(recorded[1][0], "commercial-cancellation-playwright-live-journey")
+ self.assertEqual(
+ recorded[1][2],
+ [
+ "npm",
+ "test",
+ "--",
+ "tests/14-commercial-cancellation-reactivation.spec.ts",
+ "--project=chromium",
+ ],
+ )
+
+
+class ReportTests(unittest.TestCase):
+ def test_render_markdown_report_mentions_live_journey(self) -> None:
+ report = rehearsal.render_markdown_report(
+ "Commercial Cancellation/Reactivation Rehearsal",
+ [
+ rehearsal.CommandResult(
+ name="commercial-cancellation-playwright-live-journey",
+ cwd="/tmp/integration",
+ command=["npm", "test"],
+ ok=True,
+ exit_code=0,
+ detail="pass",
+ )
+ ],
+ )
+ self.assertIn("commercial-cancellation-playwright-live-journey", report)
+ self.assertIn("14-commercial-cancellation-reactivation.spec.ts", report)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release_control/internal/hosted_signup_billing_replay_rehearsal.py b/scripts/release_control/internal/hosted_signup_billing_replay_rehearsal.py
new file mode 100644
index 0000000000..d2ff30d481
--- /dev/null
+++ b/scripts/release_control/internal/hosted_signup_billing_replay_rehearsal.py
@@ -0,0 +1,611 @@
+#!/usr/bin/env python3
+"""Exercise the hosted signup and billing replay gate on a live Pulse runtime."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import hmac
+import json
+import time
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any
+from urllib import error, request
+
+
+@dataclass
+class CheckResult:
+ name: str
+ ok: bool
+ detail: str
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Run a live hosted-signup and billing-replay rehearsal against a hosted "
+ "Pulse instance and optionally write a markdown report."
+ )
+ )
+ parser.add_argument("--base-url", required=True, help="Hosted Pulse base URL")
+ parser.add_argument(
+ "--fail-closed-base-url",
+ help="Optional second Pulse base URL expected to fail hosted signup when public URL is missing",
+ )
+ parser.add_argument("--signup-email", required=True, help="Email to use for public signup")
+ parser.add_argument("--org-name", required=True, help="Organization name to use for public signup")
+ parser.add_argument(
+ "--timeout",
+ type=float,
+ default=30.0,
+ help="HTTP timeout in seconds",
+ )
+ parser.add_argument("--api-token", help="Optional X-API-Token for authenticated admin checks")
+ parser.add_argument("--bearer-token", help="Optional Authorization bearer token for admin checks")
+ parser.add_argument("--cookie", help="Optional Cookie header for admin checks")
+ parser.add_argument(
+ "--expected-checkout-base",
+ help="Optional prefix expected for trial-start redirect action_url",
+ )
+ parser.add_argument(
+ "--billing-org-id",
+ help="Optional org ID to use for billing-state checks instead of the signup org_id",
+ )
+ parser.add_argument(
+ "--expected-trial-subscription-state",
+ default="trial",
+ help="Expected subscription_state immediately after hosted signup",
+ )
+ parser.add_argument(
+ "--expected-trial-plan-version",
+ default="cloud_trial",
+ help="Expected plan_version immediately after hosted signup",
+ )
+ parser.add_argument(
+ "--prelink-webhook-payload-file",
+ help="Optional JSON file containing a Stripe event payload expected to fail closed before linkage",
+ )
+ parser.add_argument(
+ "--prelink-webhook-secret",
+ help="Optional Stripe webhook secret for the pre-link payload",
+ )
+ parser.add_argument(
+ "--prelink-webhook-expected-status",
+ type=int,
+ default=500,
+ help="Expected HTTP status for the pre-link webhook delivery",
+ )
+ parser.add_argument(
+ "--postlink-webhook-payload-file",
+ help="Optional JSON file containing a Stripe event payload expected to succeed after linkage",
+ )
+ parser.add_argument(
+ "--postlink-webhook-secret",
+ help="Optional Stripe webhook secret for the post-link payload",
+ )
+ parser.add_argument(
+ "--postlink-webhook-expected-status",
+ type=int,
+ default=200,
+ help="Expected HTTP status for the post-link webhook delivery",
+ )
+ parser.add_argument(
+ "--expected-postlink-subscription-state",
+ help="Optional expected subscription_state after the post-link webhook succeeds",
+ )
+ parser.add_argument(
+ "--expected-postlink-plan-version",
+ help="Optional expected plan_version after the post-link webhook succeeds",
+ )
+ parser.add_argument(
+ "--report-out",
+ help="Optional markdown report destination",
+ )
+ parser.add_argument(
+ "--report-title",
+ default="Hosted Signup Billing Replay Rehearsal",
+ help="Markdown title used when writing --report-out",
+ )
+ parser.add_argument(
+ "--json",
+ action="store_true",
+ help="Emit JSON instead of human-readable output",
+ )
+ return parser.parse_args(argv)
+
+
+def normalize_base_url(raw: str) -> str:
+ return raw.rstrip("/")
+
+
+def build_auth_headers(args: argparse.Namespace) -> dict[str, str]:
+ headers: dict[str, str] = {}
+ if args.api_token:
+ headers["X-API-Token"] = args.api_token
+ if args.bearer_token:
+ headers["Authorization"] = f"Bearer {args.bearer_token}"
+ if args.cookie:
+ headers["Cookie"] = args.cookie
+ return headers
+
+
+def summarize_body(body: bytes) -> str:
+ text = body.decode("utf-8", errors="replace").strip()
+ if not text:
+ return "<empty response>"
+ first_line = text.splitlines()[0].strip()
+ if len(first_line) > 240:
+ return first_line[:237] + "..."
+ return first_line
+
+
+def fetch(
+ method: str,
+ url: str,
+ *,
+ timeout: float,
+ json_body: dict[str, Any] | None = None,
+ body: bytes | None = None,
+ headers: dict[str, str] | None = None,
+) -> tuple[int, bytes, dict[str, str]]:
+ req_headers = dict(headers or {})
+ request_body = body
+ if json_body is not None:
+ request_body = json.dumps(json_body).encode("utf-8")
+ req_headers.setdefault("Content-Type", "application/json")
+ req = request.Request(url, data=request_body, headers=req_headers, method=method)
+ try:
+ with request.urlopen(req, timeout=timeout) as resp:
+ payload = resp.read()
+ return resp.status, payload, {key.lower(): value for key, value in resp.headers.items()}
+ except error.HTTPError as exc:
+ payload = exc.read()
+ return exc.code, payload, {key.lower(): value for key, value in exc.headers.items()}
+ except error.URLError as exc:
+ raise RuntimeError(f"{method} {url} failed: {exc.reason}") from exc
+
+
+def fetch_json(
+ method: str,
+ url: str,
+ *,
+ timeout: float,
+ json_body: dict[str, Any] | None = None,
+ body: bytes | None = None,
+ headers: dict[str, str] | None = None,
+) -> tuple[int, dict[str, Any]]:
+ status, payload, _headers = fetch(
+ method,
+ url,
+ timeout=timeout,
+ json_body=json_body,
+ body=body,
+ headers=headers,
+ )
+ try:
+ parsed = json.loads(payload.decode("utf-8")) if payload else {}
+ except json.JSONDecodeError as exc:
+ raise RuntimeError(f"{method} {url} returned non-JSON body: {summarize_body(payload)}") from exc
+ if not isinstance(parsed, dict):
+ raise RuntimeError(f"{method} {url} did not return a JSON object")
+ return status, parsed
+
+
+def make_stripe_signature(payload: bytes, secret: str, timestamp: int | None = None) -> str:
+ ts = int(time.time() if timestamp is None else timestamp)
+ signed_payload = f"{ts}.".encode("utf-8") + payload
+ digest = hmac.new(secret.encode("utf-8"), signed_payload, hashlib.sha256).hexdigest()
+ return f"t={ts},v1={digest}"
+
+
+def safe_check(name: str, fn) -> CheckResult:
+ try:
+ return fn()
+ except Exception as exc: # pragma: no cover - exercised via callers/tests
+ return CheckResult(name=name, ok=False, detail=str(exc))
+
+
+def check_fail_closed(args: argparse.Namespace) -> CheckResult:
+ status, payload = fetch_json(
+ "POST",
+ f"{normalize_base_url(args.fail_closed_base_url)}/api/public/signup",
+ timeout=args.timeout,
+ json_body={"email": args.signup_email, "org_name": args.org_name},
+ )
+ if status != 503:
+ return CheckResult(
+ name="fail-closed-signup-without-public-url",
+ ok=False,
+ detail=f"status={status}, expected 503",
+ )
+ if str(payload.get("code", "")).strip() != "public_url_missing":
+ return CheckResult(
+ name="fail-closed-signup-without-public-url",
+ ok=False,
+ detail=f"code={payload.get('code')!r}, expected 'public_url_missing'",
+ )
+ return CheckResult(
+ name="fail-closed-signup-without-public-url",
+ ok=True,
+ detail="signup failed closed with code=public_url_missing",
+ )
+
+
+def check_trial_start_redirect(args: argparse.Namespace, auth_headers: dict[str, str]) -> CheckResult:
+ if not auth_headers:
+ return CheckResult(
+ name="self-hosted-trial-redirect-to-hosted",
+ ok=False,
+ detail="authenticated admin credentials are required for this check",
+ )
+ status, payload = fetch_json(
+ "POST",
+ f"{normalize_base_url(args.base_url)}/api/license/trial/start",
+ timeout=args.timeout,
+ headers=auth_headers,
+ json_body={},
+ )
+ if status != 409:
+ return CheckResult(
+ name="self-hosted-trial-redirect-to-hosted",
+ ok=False,
+ detail=f"status={status}, expected 409",
+ )
+ code = str(payload.get("code", "")).strip()
+ if code != "trial_signup_required":
+ return CheckResult(
+ name="self-hosted-trial-redirect-to-hosted",
+ ok=False,
+ detail=f"code={code!r}, expected 'trial_signup_required'",
+ )
+ details = payload.get("details")
+ if not isinstance(details, dict):
+ return CheckResult(
+ name="self-hosted-trial-redirect-to-hosted",
+ ok=False,
+ detail="missing details.action_url in response",
+ )
+ action_url = str(details.get("action_url", "")).strip()
+ if not action_url:
+ return CheckResult(
+ name="self-hosted-trial-redirect-to-hosted",
+ ok=False,
+ detail="details.action_url was empty",
+ )
+ if args.expected_checkout_base and not action_url.startswith(args.expected_checkout_base):
+ return CheckResult(
+ name="self-hosted-trial-redirect-to-hosted",
+ ok=False,
+ detail=f"action_url={action_url!r} did not start with {args.expected_checkout_base!r}",
+ )
+ return CheckResult(
+ name="self-hosted-trial-redirect-to-hosted",
+ ok=True,
+ detail=f"returned action_url={action_url}",
+ )
+
+
+def check_public_signup(args: argparse.Namespace) -> tuple[CheckResult, str]:
+ status, payload = fetch_json(
+ "POST",
+ f"{normalize_base_url(args.base_url)}/api/public/signup",
+ timeout=args.timeout,
+ json_body={"email": args.signup_email, "org_name": args.org_name},
+ )
+ if status != 201:
+ return (
+ CheckResult(name="public-hosted-signup", ok=False, detail=f"status={status}, payload={payload!r}"),
+ "",
+ )
+ org_id = str(payload.get("org_id", "")).strip()
+ message = str(payload.get("message", "")).strip()
+ if not org_id:
+ return (
+ CheckResult(name="public-hosted-signup", ok=False, detail="response missing org_id"),
+ "",
+ )
+ if message != "Check your email for a magic link to finish signing in.":
+ return (
+ CheckResult(
+ name="public-hosted-signup",
+ ok=False,
+ detail=f"unexpected signup message {message!r}",
+ ),
+ org_id,
+ )
+ return (
+ CheckResult(name="public-hosted-signup", ok=True, detail=f"created org_id={org_id}"),
+ org_id,
+ )
+
+
+def check_magic_link_request(args: argparse.Namespace) -> CheckResult:
+ status, payload = fetch_json(
+ "POST",
+ f"{normalize_base_url(args.base_url)}/api/public/magic-link/request",
+ timeout=args.timeout,
+ json_body={"email": args.signup_email},
+ )
+ if status != 200:
+ return CheckResult(
+ name="public-magic-link-request",
+ ok=False,
+ detail=f"status={status}, payload={payload!r}",
+ )
+ if payload.get("success") is not True:
+ return CheckResult(
+ name="public-magic-link-request",
+ ok=False,
+ detail=f"success={payload.get('success')!r}, expected true",
+ )
+ return CheckResult(
+ name="public-magic-link-request",
+ ok=True,
+ detail="magic-link request succeeded",
+ )
+
+
+def check_hosted_org_list(base_url: str, timeout: float, auth_headers: dict[str, str], expected_org_id: str) -> CheckResult:
+ if not auth_headers:
+ return CheckResult(
+ name="hosted-org-list",
+ ok=False,
+ detail="authenticated admin credentials are required for this check",
+ )
+ status, payload = fetch_json(
+ "GET",
+ f"{normalize_base_url(base_url)}/api/hosted/organizations",
+ timeout=timeout,
+ headers=auth_headers,
+ )
+ if status != 200:
+ return CheckResult(name="hosted-org-list", ok=False, detail=f"status={status}, payload={payload!r}")
+ orgs: object
+ if isinstance(payload, list):
+ orgs = payload
+ else:
+ orgs = payload.get("organizations", payload)
+ if not isinstance(orgs, list):
+ return CheckResult(name="hosted-org-list", ok=False, detail="payload did not contain an organization list")
+ for entry in orgs:
+ if isinstance(entry, dict) and str(entry.get("org_id", "")).strip() == expected_org_id:
+ return CheckResult(name="hosted-org-list", ok=True, detail=f"org_id={expected_org_id} is visible")
+ return CheckResult(name="hosted-org-list", ok=False, detail=f"org_id={expected_org_id} not found")
+
+
+def check_billing_state(
+ *,
+ base_url: str,
+ timeout: float,
+ auth_headers: dict[str, str],
+ org_id: str,
+ expected_subscription_state: str | None,
+ expected_plan_version: str | None,
+ name: str,
+) -> CheckResult:
+ if not auth_headers:
+ return CheckResult(name=name, ok=False, detail="authenticated admin credentials are required for this check")
+ status, payload = fetch_json(
+ "GET",
+ f"{normalize_base_url(base_url)}/api/admin/orgs/{org_id}/billing-state",
+ timeout=timeout,
+ headers=auth_headers,
+ )
+ if status != 200:
+ return CheckResult(name=name, ok=False, detail=f"status={status}, payload={payload!r}")
+ got_state = str(payload.get("subscription_state", "")).strip()
+ got_plan = str(payload.get("plan_version", "")).strip()
+ if expected_subscription_state and got_state != expected_subscription_state:
+ return CheckResult(
+ name=name,
+ ok=False,
+ detail=f"subscription_state={got_state!r}, expected {expected_subscription_state!r}",
+ )
+ if expected_plan_version and got_plan != expected_plan_version:
+ return CheckResult(
+ name=name,
+ ok=False,
+ detail=f"plan_version={got_plan!r}, expected {expected_plan_version!r}",
+ )
+ return CheckResult(
+ name=name,
+ ok=True,
+ detail=f"subscription_state={got_state!r} plan_version={got_plan!r}",
+ )
+
+
+def load_json_payload(path: str) -> bytes:
+ raw = Path(path).read_bytes()
+ json.loads(raw.decode("utf-8"))
+ return raw
+
+
+def check_signed_webhook_delivery(
+ *,
+ base_url: str,
+ timeout: float,
+ payload_file: str,
+ secret: str,
+ expected_status: int,
+ name: str,
+) -> CheckResult:
+ payload = load_json_payload(payload_file)
+ signature = make_stripe_signature(payload, secret)
+ status, body, _headers = fetch(
+ "POST",
+ f"{normalize_base_url(base_url)}/api/stripe/webhook",
+ timeout=timeout,
+ body=payload,
+ headers={
+ "Content-Type": "application/json",
+ "Stripe-Signature": signature,
+ },
+ )
+ if status != expected_status:
+ return CheckResult(
+ name=name,
+ ok=False,
+ detail=f"status={status}, expected {expected_status}, body={summarize_body(body)}",
+ )
+ return CheckResult(
+ name=name,
+ ok=True,
+ detail=f"status={status}, body={summarize_body(body)}",
+ )
+
+
+def run_rehearsal(args: argparse.Namespace) -> list[CheckResult]:
+ auth_headers = build_auth_headers(args)
+ results: list[CheckResult] = []
+
+ if args.fail_closed_base_url:
+ results.append(safe_check("fail-closed-signup-without-public-url", lambda: check_fail_closed(args)))
+
+ if auth_headers:
+ results.append(
+ safe_check(
+ "self-hosted-trial-redirect-to-hosted",
+ lambda: check_trial_start_redirect(args, auth_headers),
+ )
+ )
+
+ signup_result, signup_org_id = check_public_signup(args)
+ results.append(signup_result)
+ if signup_org_id:
+ results.append(safe_check("public-magic-link-request", lambda: check_magic_link_request(args)))
+
+ billing_org_id = args.billing_org_id or signup_org_id
+ if auth_headers and signup_org_id:
+ results.append(
+ safe_check(
+ "hosted-org-list",
+ lambda: check_hosted_org_list(args.base_url, args.timeout, auth_headers, signup_org_id),
+ )
+ )
+ if auth_headers and billing_org_id:
+ results.append(
+ safe_check(
+ "billing-state-after-signup",
+ lambda: check_billing_state(
+ base_url=args.base_url,
+ timeout=args.timeout,
+ auth_headers=auth_headers,
+ org_id=billing_org_id,
+ expected_subscription_state=args.expected_trial_subscription_state,
+ expected_plan_version=args.expected_trial_plan_version,
+ name="billing-state-after-signup",
+ ),
+ )
+ )
+
+ if args.prelink_webhook_payload_file and args.prelink_webhook_secret:
+ results.append(
+ safe_check(
+ "prelink-webhook-delivery",
+ lambda: check_signed_webhook_delivery(
+ base_url=args.base_url,
+ timeout=args.timeout,
+ payload_file=args.prelink_webhook_payload_file,
+ secret=args.prelink_webhook_secret,
+ expected_status=args.prelink_webhook_expected_status,
+ name="prelink-webhook-delivery",
+ ),
+ )
+ )
+ if args.postlink_webhook_payload_file and args.postlink_webhook_secret:
+ results.append(
+ safe_check(
+ "postlink-webhook-delivery",
+ lambda: check_signed_webhook_delivery(
+ base_url=args.base_url,
+ timeout=args.timeout,
+ payload_file=args.postlink_webhook_payload_file,
+ secret=args.postlink_webhook_secret,
+ expected_status=args.postlink_webhook_expected_status,
+ name="postlink-webhook-delivery",
+ ),
+ )
+ )
+ if auth_headers and billing_org_id and (
+ args.expected_postlink_subscription_state or args.expected_postlink_plan_version
+ ):
+ results.append(
+ safe_check(
+ "billing-state-after-webhook",
+ lambda: check_billing_state(
+ base_url=args.base_url,
+ timeout=args.timeout,
+ auth_headers=auth_headers,
+ org_id=billing_org_id,
+ expected_subscription_state=args.expected_postlink_subscription_state,
+ expected_plan_version=args.expected_postlink_plan_version,
+ name="billing-state-after-webhook",
+ ),
+ )
+ )
+
+ return results
+
+
+def render_markdown_report(
+ *,
+ title: str,
+ base_url: str,
+ signup_email: str,
+ org_name: str,
+ results: list[CheckResult],
+) -> str:
+ lines = [
+ f"# {title}",
+ "",
+ "## Inputs",
+ "",
+ f"- Base URL: `{base_url}`",
+ f"- Signup email: `{signup_email}`",
+ f"- Org name: `{org_name}`",
+ "",
+ "## Results",
+ "",
+ ]
+ for result in results:
+ status = "PASS" if result.ok else "FAIL"
+ lines.append(f"- `{status}` `{result.name}`")
+ lines.append(f" - {result.detail}")
+ lines.extend(
+ [
+ "",
+ "## Manual Follow-up",
+ "",
+ "- If the webhook replay was only partially exercised, complete the missing replay/linkage path on the same hosted runtime and append the result.",
+ "- If the live runtime differs from the final hosted environment, rerun the same command against the actual external hosted surface before closing the gate.",
+ ]
+ )
+ return "\n".join(lines) + "\n"
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(argv)
+ results = run_rehearsal(args)
+ if args.report_out:
+ Path(args.report_out).write_text(
+ render_markdown_report(
+ title=args.report_title,
+ base_url=args.base_url,
+ signup_email=args.signup_email,
+ org_name=args.org_name,
+ results=results,
+ ),
+ encoding="utf-8",
+ )
+ if args.json:
+ print(json.dumps([asdict(result) for result in results], indent=2))
+ else:
+ for result in results:
+ status = "PASS" if result.ok else "FAIL"
+ print(f"{status} {result.name}: {result.detail}")
+ return 0 if results and all(result.ok for result in results) else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release_control/internal/hosted_signup_billing_replay_rehearsal_test.py b/scripts/release_control/internal/hosted_signup_billing_replay_rehearsal_test.py
new file mode 100644
index 0000000000..d83d656a4c
--- /dev/null
+++ b/scripts/release_control/internal/hosted_signup_billing_replay_rehearsal_test.py
@@ -0,0 +1,208 @@
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+import hosted_signup_billing_replay_rehearsal as mod
+
+
+def run_main(argv: list[str]) -> int:
+ with contextlib.redirect_stdout(io.StringIO()):
+ return mod.main(argv)
+
+
+class HostedSignupBillingReplayRehearsalTest(unittest.TestCase):
+ def test_make_stripe_signature_is_stable_for_fixed_timestamp(self) -> None:
+ sig = mod.make_stripe_signature(b'{"id":"evt_1"}', "whsec_test", timestamp=123)
+ self.assertEqual(
+ sig,
+ "t=123,v1=94d2453cc7960463874f8b9ebad526244005352e0a5320ad624d93ecc2df970d",
+ )
+
+ def test_run_rehearsal_full_flow(self) -> None:
+ prelink_payload = json.dumps({"id": "evt_pre", "type": "checkout.session.completed"}).encode("utf-8")
+ with tempfile.TemporaryDirectory() as tmp:
+ prelink_path = Path(tmp) / "pre.json"
+ prelink_path.write_bytes(prelink_payload)
+
+ args = mod.parse_args(
+ [
+ "--base-url",
+ "https://pulse.example.com",
+ "--fail-closed-base-url",
+ "https://pulse-bad.example.com",
+ "--signup-email",
+ "--org-name",
+ "Pulse Labs",
+ "--api-token",
+ "token",
+ "--expected-checkout-base",
+ "https://billing.example.com/start-pro-trial",
+ "--prelink-webhook-payload-file",
+ str(prelink_path),
+ "--prelink-webhook-secret",
+ "whsec_test",
+ "--prelink-webhook-expected-status",
+ "500",
+ ]
+ )
+
+ fetch_json_calls: list[tuple[str, str, dict[str, str] | None]] = []
+ fetch_calls: list[tuple[str, str, dict[str, str] | None, bytes | None]] = []
+
+ def fake_fetch_json(method: str, url: str, **kwargs):
+ fetch_json_calls.append((method, url, kwargs.get("headers")))
+ if url == "https://pulse-bad.example.com/api/public/signup":
+ return 503, {"code": "public_url_missing"}
+ if url == "https://pulse.example.com/api/license/trial/start":
+ return 409, {
+ "code": "trial_signup_required",
+ "details": {"action_url": "https://billing.example.com/start-pro-trial?org_id=default"},
+ }
+ if url == "https://pulse.example.com/api/public/signup":
+ return 201, {
+ "org_id": "org-123",
+ "message": "Check your email for a magic link to finish signing in.",
+ }
+ if url == "https://pulse.example.com/api/public/magic-link/request":
+ return 200, {"success": True}
+ if url == "https://pulse.example.com/api/hosted/organizations":
+ return 200, [{"org_id": "default"}, {"org_id": "org-123"}]
+ if url == "https://pulse.example.com/api/admin/orgs/org-123/billing-state":
+ return 200, {"subscription_state": "trial", "plan_version": "cloud_trial"}
+ raise AssertionError(f"unexpected fetch_json call: {method} {url}")
+
+ def fake_fetch(method: str, url: str, **kwargs):
+ fetch_calls.append((method, url, kwargs.get("headers"), kwargs.get("body")))
+ if url == "https://pulse.example.com/api/stripe/webhook":
+ return 500, b'{"code":"stripe_processing_failed"}', {"content-type": "application/json"}
+ raise AssertionError(f"unexpected fetch call: {method} {url}")
+
+ with (
+ mock.patch.object(mod, "fetch_json", side_effect=fake_fetch_json),
+ mock.patch.object(mod, "fetch", side_effect=fake_fetch),
+ ):
+ results = mod.run_rehearsal(args)
+
+ self.assertTrue(all(result.ok for result in results), [r.detail for r in results])
+ trial_headers = next(headers for _method, url, headers in fetch_json_calls if url.endswith("/api/license/trial/start"))
+ self.assertEqual(trial_headers["X-API-Token"], "token")
+ webhook_headers = next(headers for _method, url, headers, _body in fetch_calls if url.endswith("/api/stripe/webhook"))
+ self.assertIn("Stripe-Signature", webhook_headers)
+
+ def test_run_rehearsal_checks_postlink_billing_state(self) -> None:
+ post_payload = json.dumps({"id": "evt_post", "type": "checkout.session.completed"}).encode("utf-8")
+ with tempfile.TemporaryDirectory() as tmp:
+ post_path = Path(tmp) / "post.json"
+ post_path.write_bytes(post_payload)
+ billing_state_calls = 0
+
+ def fake_fetch_json(method: str, url: str, **kwargs):
+ nonlocal billing_state_calls
+ if url.endswith("/api/license/trial/start"):
+ return 409, {
+ "code": "trial_signup_required",
+ "details": {"action_url": "https://billing.example.com/start-pro-trial?org_id=default"},
+ }
+ if url.endswith("/api/public/signup"):
+ return 201, {
+ "org_id": "org-123",
+ "message": "Check your email for a magic link to finish signing in.",
+ }
+ if url.endswith("/api/public/magic-link/request"):
+ return 200, {"success": True}
+ if url.endswith("/api/hosted/organizations"):
+ return 200, [{"org_id": "org-123"}]
+ if url.endswith("/api/admin/orgs/org-123/billing-state"):
+ billing_state_calls += 1
+ if billing_state_calls == 1:
+ return 200, {"subscription_state": "trial", "plan_version": "cloud_trial"}
+ return 200, {"subscription_state": "active", "plan_version": "cloud_starter"}
+ raise AssertionError(f"unexpected fetch_json call: {method} {url}")
+
+ def fake_fetch(method: str, url: str, **kwargs):
+ if url.endswith("/api/stripe/webhook"):
+ return 200, b'{"received":true,"status":"processed"}', {}
+ raise AssertionError(f"unexpected fetch call: {method} {url}")
+
+ with (
+ mock.patch.object(mod, "fetch_json", side_effect=fake_fetch_json),
+ mock.patch.object(mod, "fetch", side_effect=fake_fetch),
+ ):
+ exit_code = run_main(
+ [
+ "--base-url",
+ "https://pulse.example.com",
+ "--signup-email",
+ "--org-name",
+ "Pulse Labs",
+ "--api-token",
+ "token",
+ "--postlink-webhook-payload-file",
+ str(post_path),
+ "--postlink-webhook-secret",
+ "whsec_test",
+ "--postlink-webhook-expected-status",
+ "200",
+ "--expected-postlink-subscription-state",
+ "active",
+ "--expected-postlink-plan-version",
+ "cloud_starter",
+ ]
+ )
+ self.assertEqual(exit_code, 0)
+
+ def test_render_markdown_report(self) -> None:
+ report = mod.render_markdown_report(
+ title="Hosted Signup Billing Replay Rehearsal",
+ base_url="https://pulse.example.com",
+ signup_email="[email protected]",
+ org_name="Pulse Labs",
+ results=[
+ mod.CheckResult(name="public-hosted-signup", ok=True, detail="created org_id=org-123"),
+ mod.CheckResult(name="postlink-webhook-delivery", ok=False, detail="status=500"),
+ ],
+ )
+ self.assertIn("# Hosted Signup Billing Replay Rehearsal", report)
+ self.assertIn("`PASS` `public-hosted-signup`", report)
+ self.assertIn("`FAIL` `postlink-webhook-delivery`", report)
+
+ def test_main_writes_report(self) -> None:
+ def fake_fetch_json(method: str, url: str, **kwargs):
+ if url.endswith("/api/public/signup"):
+ return 201, {
+ "org_id": "org-123",
+ "message": "Check your email for a magic link to finish signing in.",
+ }
+ if url.endswith("/api/public/magic-link/request"):
+ return 200, {"success": True}
+ raise AssertionError(f"unexpected fetch_json call: {method} {url}")
+
+ with tempfile.TemporaryDirectory() as tmp:
+ report_path = Path(tmp) / "report.md"
+ with mock.patch.object(mod, "fetch_json", side_effect=fake_fetch_json):
+ exit_code = mod.main(
+ [
+ "--base-url",
+ "https://pulse.example.com",
+ "--signup-email",
+ "--org-name",
+ "Pulse Labs",
+ "--report-out",
+ str(report_path),
+ ]
+ )
+ self.assertEqual(exit_code, 0)
+ self.assertIn("# Hosted Signup Billing Replay Rehearsal", report_path.read_text(encoding="utf-8"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release_control/internal/mobile_relay_auth_approvals_proof.py b/scripts/release_control/internal/mobile_relay_auth_approvals_proof.py
new file mode 100644
index 0000000000..1c7ca9d48b
--- /dev/null
+++ b/scripts/release_control/internal/mobile_relay_auth_approvals_proof.py
@@ -0,0 +1,166 @@
+#!/usr/bin/env python3
+"""Run the automated proof bundle for the mobile relay auth/approvals gate."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import subprocess
+from dataclasses import asdict, dataclass
+from pathlib import Path
+
+
+@dataclass
+class CommandSpec:
+ name: str
+ cwd: str
+ command: list[str]
+
+
+@dataclass
+class CommandResult:
+ name: str
+ cwd: str
+ command: list[str]
+ ok: bool
+ exit_code: int
+ detail: str
+
+
+def default_pulse_dir() -> Path:
+ return Path(__file__).resolve().parents[2]
+
+
+def default_pulse_mobile_dir() -> Path:
+ return default_pulse_dir().parent / "pulse-mobile"
+
+
+def default_pulse_enterprise_dir() -> Path:
+ return default_pulse_dir().parent / "pulse-enterprise"
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="Run the automated proof bundle for the mobile relay auth/approvals release gate."
+ )
+ parser.add_argument("--pulse-mobile-dir", default=str(default_pulse_mobile_dir()))
+ parser.add_argument("--pulse-enterprise-dir", default=str(default_pulse_enterprise_dir()))
+ parser.add_argument("--json", action="store_true", help="Emit JSON instead of human-readable output")
+ return parser.parse_args(argv)
+
+
+def build_command_specs(args: argparse.Namespace) -> list[CommandSpec]:
+ pulse_mobile_dir = Path(args.pulse_mobile_dir).resolve()
+ pulse_enterprise_dir = Path(args.pulse_enterprise_dir).resolve()
+ return [
+ CommandSpec(
+ name="enterprise-approval-handlers",
+ cwd=str(pulse_enterprise_dir),
+ command=[
+ "go",
+ "test",
+ "./internal/aiautofix",
+ "-run",
+ "TestHandleListApprovals|TestHandleApproveAndExecuteInvestigationFix|TestHandleApprove",
+ "-count=1",
+ ],
+ ),
+ CommandSpec(
+ name="mobile-api-client",
+ cwd=str(pulse_mobile_dir),
+ command=[
+ "npm",
+ "test",
+ "--",
+ "--runTestsByPath",
+ "src/api/__tests__/client.test.ts",
+ ],
+ ),
+ CommandSpec(
+ name="mobile-relay-runtime",
+ cwd=str(pulse_mobile_dir),
+ command=[
+ "npm",
+ "test",
+ "--",
+ "--runTestsByPath",
+ "src/hooks/__tests__/useRelay.test.ts",
+ "src/hooks/__tests__/relayPushRefresh.test.ts",
+ "src/notifications/__tests__/notificationRouting.test.ts",
+ "src/stores/__tests__/mobileAccessState.test.ts",
+ ],
+ ),
+ CommandSpec(
+ name="mobile-secure-persistence-and-approvals",
+ cwd=str(pulse_mobile_dir),
+ command=[
+ "npm",
+ "test",
+ "--",
+ "--runTestsByPath",
+ "src/__tests__/mobileRelayAuthApprovals.rehearsal.test.ts",
+ "src/utils/__tests__/secureStorage.test.ts",
+ "src/hooks/__tests__/useRelayLifecycle.test.ts",
+ "src/hooks/__tests__/approvalActionPolicy.test.ts",
+ "src/stores/__tests__/instanceStore.test.ts",
+ "src/stores/__tests__/authStore.test.ts",
+ "src/stores/__tests__/approvalStore.test.ts",
+ ],
+ ),
+ CommandSpec(
+ name="mobile-wire-protocol",
+ cwd=str(pulse_mobile_dir),
+ command=[
+ "npm",
+ "test",
+ "--",
+ "--runTestsByPath",
+ "src/relay/__tests__/client.test.ts",
+ "src/relay/__tests__/client-hardening.test.ts",
+ "src/relay/__tests__/protocol-contract.test.ts",
+ ],
+ ),
+ ]
+
+
+def summarize_output(stdout: str, stderr: str) -> str:
+ text = "\n".join(part.strip() for part in (stdout, stderr) if part.strip()).strip()
+ if not text:
+ return "pass"
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
+ summary = lines[-1]
+ if len(summary) > 240:
+ return summary[:237] + "..."
+ return summary
+
+
+def run_command(spec: CommandSpec) -> CommandResult:
+ proc = subprocess.run(spec.command, cwd=spec.cwd, capture_output=True, text=True, check=False)
+ return CommandResult(
+ name=spec.name,
+ cwd=spec.cwd,
+ command=spec.command,
+ ok=proc.returncode == 0,
+ exit_code=proc.returncode,
+ detail=summarize_output(proc.stdout, proc.stderr),
+ )
+
+
+def run_proof(args: argparse.Namespace) -> list[CommandResult]:
+ return [run_command(spec) for spec in build_command_specs(args)]
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(argv)
+ results = run_proof(args)
+ if args.json:
+ print(json.dumps([asdict(result) for result in results], indent=2))
+ else:
+ for result in results:
+ status = "PASS" if result.ok else "FAIL"
+ print(f"{status} {result.name}: {result.detail}")
+ return 0 if all(result.ok for result in results) else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release_control/internal/mobile_relay_auth_approvals_proof_test.py b/scripts/release_control/internal/mobile_relay_auth_approvals_proof_test.py
new file mode 100644
index 0000000000..011cc039af
--- /dev/null
+++ b/scripts/release_control/internal/mobile_relay_auth_approvals_proof_test.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python3
+"""Tests for the mobile relay auth/approvals proof wrapper."""
+
+from __future__ import annotations
+
+import unittest
+
+import mobile_relay_auth_approvals_proof as proof
+
+
+class MobileRelayAuthApprovalsProofTest(unittest.TestCase):
+ def test_build_command_specs_are_sorted_and_cross_repo(self) -> None:
+ args = proof.parse_args([])
+ specs = proof.build_command_specs(args)
+ self.assertEqual([spec.name for spec in specs], sorted(spec.name for spec in specs))
+ self.assertTrue(all(spec.cwd.endswith(("pulse-mobile", "pulse-enterprise")) for spec in specs))
+ self.assertTrue(any(spec.cwd.endswith("pulse-enterprise") for spec in specs))
+ self.assertTrue(any(spec.cwd.endswith("pulse-mobile") for spec in specs))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release_control/internal/msp_provider_tenant_management_rehearsal.py b/scripts/release_control/internal/msp_provider_tenant_management_rehearsal.py
new file mode 100644
index 0000000000..8bac4a4a7c
--- /dev/null
+++ b/scripts/release_control/internal/msp_provider_tenant_management_rehearsal.py
@@ -0,0 +1,498 @@
+#!/usr/bin/env python3
+"""Exercise the MSP provider tenant management gate on a live Pulse runtime."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import socket
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any
+from urllib import error, request
+
+
+@dataclass
+class CheckResult:
+ name: str
+ ok: bool
+ detail: str
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Run a live MSP provider-tenant rehearsal against a Pulse control-plane "
+ "runtime and optionally write a markdown report."
+ )
+ )
+ parser.add_argument("--base-url", required=True, help="Pulse control-plane base URL")
+ parser.add_argument("--account-id", required=True, help="MSP account ID to exercise")
+ parser.add_argument("--timeout", type=float, default=30.0, help="HTTP timeout in seconds")
+ parser.add_argument("--api-token", help="Optional X-API-Token for authenticated checks")
+ parser.add_argument("--bearer-token", help="Optional bearer token for authenticated checks")
+ parser.add_argument("--cookie", help="Optional raw Cookie header for authenticated checks")
+ parser.add_argument(
+ "--workspace-name",
+ action="append",
+ default=[],
+ help="Workspace name to create under the MSP account; may be passed multiple times",
+ )
+ parser.add_argument(
+ "--expected-plan-version",
+ default="msp_starter",
+ help="Expected canonical MSP plan version on created or returned workspaces",
+ )
+ parser.add_argument(
+ "--member-email",
+ action="append",
+ default=[],
+ help="Member email to invite under the MSP account; may be passed multiple times",
+ )
+ parser.add_argument(
+ "--member-role",
+ action="append",
+ default=[],
+ help="Role for the matching --member-email entry; defaults to tech when omitted",
+ )
+ parser.add_argument(
+ "--expected-account-kind",
+ default="msp",
+ help="Expected account.kind value on portal responses",
+ )
+ parser.add_argument(
+ "--public-signup-email",
+ help="Optional email to use for the public-cloud boundary signup check",
+ )
+ parser.add_argument(
+ "--public-signup-org-name",
+ help="Optional org_name to use for the public-cloud boundary signup check",
+ )
+ parser.add_argument(
+ "--public-signup-tier",
+ default="power",
+ help="Tier value to submit to public signup for the MSP/public boundary check",
+ )
+ parser.add_argument(
+ "--public-signup-expected-status",
+ type=int,
+ default=400,
+ help="Expected HTTP status for the MSP/public signup boundary check",
+ )
+ parser.add_argument(
+ "--public-signup-expected-code",
+ default="tier_unavailable",
+ help="Expected error code for the MSP/public signup boundary check",
+ )
+ parser.add_argument("--report-out", help="Optional markdown report destination")
+ parser.add_argument(
+ "--report-title",
+ default="MSP Provider Tenant Management Rehearsal",
+ help="Markdown title used when writing --report-out",
+ )
+ parser.add_argument("--json", action="store_true", help="Emit JSON instead of human-readable output")
+ return parser.parse_args(argv)
+
+
+def normalize_base_url(raw: str) -> str:
+ return raw.rstrip("/")
+
+
+def build_auth_headers(args: argparse.Namespace) -> dict[str, str]:
+ headers: dict[str, str] = {}
+ if args.api_token:
+ headers["X-API-Token"] = args.api_token
+ if args.bearer_token:
+ headers["Authorization"] = f"Bearer {args.bearer_token}"
+ if args.cookie:
+ headers["Cookie"] = args.cookie
+ return headers
+
+
+def summarize_body(body: bytes) -> str:
+ text = body.decode("utf-8", errors="replace").strip()
+ if not text:
+ return "<empty response>"
+ first_line = text.splitlines()[0].strip()
+ if len(first_line) > 240:
+ return first_line[:237] + "..."
+ return first_line
+
+
+def fetch(
+ method: str,
+ url: str,
+ *,
+ timeout: float,
+ json_body: dict[str, Any] | None = None,
+ headers: dict[str, str] | None = None,
+) -> tuple[int, bytes, dict[str, str]]:
+ req_headers = dict(headers or {})
+ body = None
+ if json_body is not None:
+ body = json.dumps(json_body).encode("utf-8")
+ req_headers.setdefault("Content-Type", "application/json")
+ req = request.Request(url, data=body, headers=req_headers, method=method)
+ try:
+ with request.urlopen(req, timeout=timeout) as resp:
+ payload = resp.read()
+ return resp.status, payload, {key.lower(): value for key, value in resp.headers.items()}
+ except error.HTTPError as exc:
+ payload = exc.read()
+ return exc.code, payload, {key.lower(): value for key, value in exc.headers.items()}
+ except socket.timeout as exc:
+ raise RuntimeError(f"{method} {url} timed out after {timeout:.1f}s") from exc
+ except error.URLError as exc:
+ raise RuntimeError(f"{method} {url} failed: {exc.reason}") from exc
+
+
+def fetch_json(
+ method: str,
+ url: str,
+ *,
+ timeout: float,
+ json_body: dict[str, Any] | None = None,
+ headers: dict[str, str] | None = None,
+) -> tuple[int, Any]:
+ status, payload, _headers = fetch(method, url, timeout=timeout, json_body=json_body, headers=headers)
+ try:
+ return status, json.loads(payload.decode("utf-8")) if payload else {}
+ except json.JSONDecodeError as exc:
+ raise RuntimeError(f"{method} {url} returned non-JSON body: {summarize_body(payload)}") from exc
+
+
+def safe_check(name: str, fn) -> CheckResult:
+ try:
+ return fn()
+ except Exception as exc: # pragma: no cover
+ return CheckResult(name=name, ok=False, detail=str(exc))
+
+
+def check_account_tenants(base_url: str, timeout: float, headers: dict[str, str], account_id: str) -> tuple[int, list[dict[str, Any]]]:
+ status, payload = fetch_json(
+ "GET",
+ f"{normalize_base_url(base_url)}/api/accounts/{account_id}/tenants",
+ timeout=timeout,
+ headers=headers,
+ )
+ if not isinstance(payload, list):
+ raise RuntimeError("tenant list payload was not a JSON array")
+ return status, payload
+
+
+def check_member_list(base_url: str, timeout: float, headers: dict[str, str], account_id: str) -> tuple[int, list[dict[str, Any]]]:
+ status, payload = fetch_json(
+ "GET",
+ f"{normalize_base_url(base_url)}/api/accounts/{account_id}/members",
+ timeout=timeout,
+ headers=headers,
+ )
+ if not isinstance(payload, list):
+ raise RuntimeError("member list payload was not a JSON array")
+ return status, payload
+
+
+def list_tenants_check(args: argparse.Namespace, headers: dict[str, str]) -> CheckResult:
+ if not headers:
+ return CheckResult(name="msp-tenant-list", ok=False, detail="authenticated credentials are required")
+ status, tenants = check_account_tenants(args.base_url, args.timeout, headers, args.account_id)
+ if status != 200:
+ return CheckResult(name="msp-tenant-list", ok=False, detail=f"status={status}")
+ return CheckResult(name="msp-tenant-list", ok=True, detail=f"tenant_count={len(tenants)}")
+
+
+def create_workspace_check(args: argparse.Namespace, headers: dict[str, str], display_name: str) -> CheckResult:
+ status, payload = fetch_json(
+ "POST",
+ f"{normalize_base_url(args.base_url)}/api/accounts/{args.account_id}/tenants",
+ timeout=args.timeout,
+ headers=headers,
+ json_body={"display_name": display_name},
+ )
+ if status != 201:
+ return CheckResult(
+ name=f"msp-create-workspace:{display_name}",
+ ok=False,
+ detail=f"status={status}, payload={payload!r}",
+ )
+ if not isinstance(payload, dict):
+ return CheckResult(name=f"msp-create-workspace:{display_name}", ok=False, detail="payload was not a JSON object")
+ plan_version = str(payload.get("plan_version", "")).strip()
+ tenant_id = str(payload.get("id", "")).strip()
+ account_id = str(payload.get("account_id", "")).strip()
+ if not tenant_id:
+ return CheckResult(name=f"msp-create-workspace:{display_name}", ok=False, detail="response missing tenant id")
+ if account_id != args.account_id:
+ return CheckResult(
+ name=f"msp-create-workspace:{display_name}",
+ ok=False,
+ detail=f"account_id={account_id!r}, expected {args.account_id!r}",
+ )
+ if args.expected_plan_version and plan_version != args.expected_plan_version:
+ return CheckResult(
+ name=f"msp-create-workspace:{display_name}",
+ ok=False,
+ detail=f"plan_version={plan_version!r}, expected {args.expected_plan_version!r}",
+ )
+ return CheckResult(
+ name=f"msp-create-workspace:{display_name}",
+ ok=True,
+ detail=f"tenant_id={tenant_id} plan_version={plan_version!r}",
+ )
+
+
+def invite_member_check(args: argparse.Namespace, headers: dict[str, str], email: str, role: str) -> CheckResult:
+ status, payload = fetch_json(
+ "POST",
+ f"{normalize_base_url(args.base_url)}/api/accounts/{args.account_id}/members",
+ timeout=args.timeout,
+ headers=headers,
+ json_body={"email": email, "role": role},
+ )
+ if status != 201:
+ return CheckResult(
+ name=f"msp-invite-member:{email}",
+ ok=False,
+ detail=f"status={status}, payload={payload!r}",
+ )
+ return CheckResult(name=f"msp-invite-member:{email}", ok=True, detail=f"role={role}")
+
+
+def portal_dashboard_check(args: argparse.Namespace, headers: dict[str, str], expected_min_total: int) -> CheckResult:
+ status, payload = fetch_json(
+ "GET",
+ f"{normalize_base_url(args.base_url)}/api/portal/dashboard?account_id={args.account_id}",
+ timeout=args.timeout,
+ headers=headers,
+ )
+ if status != 200:
+ return CheckResult(name="msp-portal-dashboard", ok=False, detail=f"status={status}, payload={payload!r}")
+ if not isinstance(payload, dict):
+ return CheckResult(name="msp-portal-dashboard", ok=False, detail="payload was not a JSON object")
+ account = payload.get("account")
+ summary = payload.get("summary")
+ if not isinstance(account, dict) or not isinstance(summary, dict):
+ return CheckResult(name="msp-portal-dashboard", ok=False, detail="missing account or summary object")
+ kind = str(account.get("kind", "")).strip()
+ total = int(summary.get("total", 0))
+ if args.expected_account_kind and kind != args.expected_account_kind:
+ return CheckResult(
+ name="msp-portal-dashboard",
+ ok=False,
+ detail=f"account.kind={kind!r}, expected {args.expected_account_kind!r}",
+ )
+ if total < expected_min_total:
+ return CheckResult(
+ name="msp-portal-dashboard",
+ ok=False,
+ detail=f"summary.total={total}, expected at least {expected_min_total}",
+ )
+ return CheckResult(name="msp-portal-dashboard", ok=True, detail=f"account.kind={kind!r} summary.total={total}")
+
+
+def workspace_detail_check(args: argparse.Namespace, headers: dict[str, str], tenant_id: str, expected_name: str) -> CheckResult:
+ status, payload = fetch_json(
+ "GET",
+ f"{normalize_base_url(args.base_url)}/api/portal/workspaces/{tenant_id}?account_id={args.account_id}",
+ timeout=args.timeout,
+ headers=headers,
+ )
+ if status != 200:
+ return CheckResult(name=f"msp-workspace-detail:{tenant_id}", ok=False, detail=f"status={status}, payload={payload!r}")
+ if not isinstance(payload, dict):
+ return CheckResult(name=f"msp-workspace-detail:{tenant_id}", ok=False, detail="payload was not a JSON object")
+ account = payload.get("account")
+ workspace = payload.get("workspace")
+ if not isinstance(account, dict) or not isinstance(workspace, dict):
+ return CheckResult(name=f"msp-workspace-detail:{tenant_id}", ok=False, detail="missing account or workspace object")
+ kind = str(account.get("kind", "")).strip()
+ display_name = str(workspace.get("display_name", "")).strip()
+ plan_version = str(workspace.get("plan_version", "")).strip()
+ if args.expected_account_kind and kind != args.expected_account_kind:
+ return CheckResult(
+ name=f"msp-workspace-detail:{tenant_id}",
+ ok=False,
+ detail=f"account.kind={kind!r}, expected {args.expected_account_kind!r}",
+ )
+ if expected_name and display_name != expected_name:
+ return CheckResult(
+ name=f"msp-workspace-detail:{tenant_id}",
+ ok=False,
+ detail=f"display_name={display_name!r}, expected {expected_name!r}",
+ )
+ if args.expected_plan_version and plan_version != args.expected_plan_version:
+ return CheckResult(
+ name=f"msp-workspace-detail:{tenant_id}",
+ ok=False,
+ detail=f"plan_version={plan_version!r}, expected {args.expected_plan_version!r}",
+ )
+ return CheckResult(
+ name=f"msp-workspace-detail:{tenant_id}",
+ ok=True,
+ detail=f"display_name={display_name!r} plan_version={plan_version!r}",
+ )
+
+
+def public_signup_boundary_check(args: argparse.Namespace) -> CheckResult:
+ if not args.public_signup_email or not args.public_signup_org_name:
+ return CheckResult(name="public-cloud-boundary", ok=True, detail="skipped (no public signup inputs provided)")
+ status, payload = fetch_json(
+ "POST",
+ f"{normalize_base_url(args.base_url)}/api/public/signup",
+ timeout=args.timeout,
+ json_body={
+ "email": args.public_signup_email,
+ "org_name": args.public_signup_org_name,
+ "tier": args.public_signup_tier,
+ },
+ )
+ if status != args.public_signup_expected_status:
+ return CheckResult(
+ name="public-cloud-boundary",
+ ok=False,
+ detail=f"status={status}, expected {args.public_signup_expected_status}, payload={payload!r}",
+ )
+ if not isinstance(payload, dict):
+ return CheckResult(name="public-cloud-boundary", ok=False, detail="payload was not a JSON object")
+ code = str(payload.get("code", "")).strip()
+ if args.public_signup_expected_code and code != args.public_signup_expected_code:
+ return CheckResult(
+ name="public-cloud-boundary",
+ ok=False,
+ detail=f"code={code!r}, expected {args.public_signup_expected_code!r}",
+ )
+ return CheckResult(name="public-cloud-boundary", ok=True, detail=f"status={status} code={code!r}")
+
+
+def member_pairs(args: argparse.Namespace) -> list[tuple[str, str]]:
+ roles = list(args.member_role)
+ while len(roles) < len(args.member_email):
+ roles.append("tech")
+ return list(zip(args.member_email, roles))
+
+
+def run_rehearsal(args: argparse.Namespace) -> list[CheckResult]:
+ headers = build_auth_headers(args)
+ results: list[CheckResult] = []
+ created_workspace_ids: list[tuple[str, str]] = []
+
+ results.append(safe_check("msp-tenant-list", lambda: list_tenants_check(args, headers)))
+
+ for workspace_name in args.workspace_name:
+ result = safe_check(
+ f"msp-create-workspace:{workspace_name}",
+ lambda workspace_name=workspace_name: create_workspace_check(args, headers, workspace_name),
+ )
+ results.append(result)
+ if result.ok:
+ detail_parts = result.detail.split()
+ tenant_id = detail_parts[0].split("=", 1)[1]
+ created_workspace_ids.append((tenant_id, workspace_name))
+
+ if headers:
+ try:
+ status, tenants = check_account_tenants(args.base_url, args.timeout, headers, args.account_id)
+ except Exception:
+ expected_total = max(1, len(created_workspace_ids))
+ else:
+ if status == 200:
+ expected_total = len(tenants)
+ else:
+ expected_total = max(1, len(created_workspace_ids))
+ else:
+ expected_total = max(1, len(created_workspace_ids))
+
+ for email, role in member_pairs(args):
+ results.append(safe_check(f"msp-invite-member:{email}", lambda email=email, role=role: invite_member_check(args, headers, email, role)))
+
+ results.append(safe_check("msp-member-list", lambda: _member_list_expectations(args, headers)))
+ results.append(safe_check("msp-portal-dashboard", lambda: portal_dashboard_check(args, headers, expected_total)))
+
+ for tenant_id, workspace_name in created_workspace_ids:
+ results.append(
+ safe_check(
+ f"msp-workspace-detail:{tenant_id}",
+ lambda tenant_id=tenant_id, workspace_name=workspace_name: workspace_detail_check(
+ args,
+ headers,
+ tenant_id,
+ workspace_name,
+ ),
+ )
+ )
+
+ results.append(safe_check("public-cloud-boundary", lambda: public_signup_boundary_check(args)))
+ return results
+
+
+def _member_list_expectations(args: argparse.Namespace, headers: dict[str, str]) -> CheckResult:
+ if not headers:
+ return CheckResult(name="msp-member-list", ok=False, detail="authenticated credentials are required")
+ status, members = check_member_list(args.base_url, args.timeout, headers, args.account_id)
+ if status != 200:
+ return CheckResult(name="msp-member-list", ok=False, detail=f"status={status}")
+ emails = {str(item.get('email', '')).strip() for item in members if isinstance(item, dict)}
+ missing = [email for email, _role in member_pairs(args) if email not in emails]
+ if missing:
+ return CheckResult(name="msp-member-list", ok=False, detail=f"missing members: {', '.join(missing)}")
+ return CheckResult(name="msp-member-list", ok=True, detail=f"member_count={len(members)}")
+
+
+def render_markdown_report(
+ *,
+ title: str,
+ base_url: str,
+ account_id: str,
+ results: list[CheckResult],
+) -> str:
+ lines = [
+ f"# {title}",
+ "",
+ "## Inputs",
+ "",
+ f"- Base URL: `{base_url}`",
+ f"- Account ID: `{account_id}`",
+ "",
+ "## Results",
+ "",
+ ]
+ for result in results:
+ status = "PASS" if result.ok else "FAIL"
+ lines.append(f"- `{status}` `{result.name}`")
+ lines.append(f" - {result.detail}")
+ lines.extend(
+ [
+ "",
+ "## Manual Follow-up",
+ "",
+ "- If this was run against a local or staging-only control plane, rerun it against the real external MSP environment before closing the gate.",
+ "- If account creation or billing bootstrap still required pre-seeding, record exactly which parts remained Stripe- or operations-driven outside the rehearsal surface.",
+ ]
+ )
+ return "\n".join(lines) + "\n"
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(argv)
+ results = run_rehearsal(args)
+ if args.report_out:
+ Path(args.report_out).write_text(
+ render_markdown_report(
+ title=args.report_title,
+ base_url=args.base_url,
+ account_id=args.account_id,
+ results=results,
+ ),
+ encoding="utf-8",
+ )
+ if args.json:
+ print(json.dumps([asdict(result) for result in results], indent=2))
+ else:
+ for result in results:
+ status = "PASS" if result.ok else "FAIL"
+ print(f"{status} {result.name}: {result.detail}")
+ return 0 if results and all(result.ok for result in results) else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release_control/internal/msp_provider_tenant_management_rehearsal_test.py b/scripts/release_control/internal/msp_provider_tenant_management_rehearsal_test.py
new file mode 100644
index 0000000000..23da6dc045
--- /dev/null
+++ b/scripts/release_control/internal/msp_provider_tenant_management_rehearsal_test.py
@@ -0,0 +1,211 @@
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import socket
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+import msp_provider_tenant_management_rehearsal as mod
+
+
+def run_main(argv: list[str]) -> int:
+ with contextlib.redirect_stdout(io.StringIO()):
+ return mod.main(argv)
+
+
+class MSPProviderTenantManagementRehearsalTest(unittest.TestCase):
+ def test_run_rehearsal_full_flow(self) -> None:
+ calls: list[tuple[str, str, dict | None]] = []
+ tenants_state = [
+ {"id": "t-1", "display_name": "Client One", "account_id": "acct_1", "plan_version": "msp_starter"},
+ {"id": "t-2", "display_name": "Client Two", "account_id": "acct_1", "plan_version": "msp_starter"},
+ ]
+ members_state = [
+ {"email": "[email protected]", "role": "owner"},
+ ]
+
+ def fake_fetch_json(method: str, url: str, **kwargs):
+ calls.append((method, url, kwargs.get("headers")))
+ if url.endswith("/api/accounts/acct_1/tenants") and method == "GET":
+ return 200, tenants_state
+ if url.endswith("/api/accounts/acct_1/tenants") and method == "POST":
+ payload = kwargs["json_body"]
+ tenant = {
+ "id": "t-3",
+ "display_name": payload["display_name"],
+ "account_id": "acct_1",
+ "plan_version": "msp_starter",
+ }
+ tenants_state.append(tenant)
+ return 201, tenant
+ if url.endswith("/api/accounts/acct_1/members") and method == "POST":
+ payload = kwargs["json_body"]
+ members_state.append({"email": payload["email"], "role": payload["role"]})
+ return 201, {"ok": True}
+ if url.endswith("/api/accounts/acct_1/members") and method == "GET":
+ return 200, members_state
+ if url.endswith("/api/portal/dashboard?account_id=acct_1"):
+ return 200, {
+ "account": {"kind": "msp"},
+ "summary": {"total": 3},
+ }
+ if url.endswith("/api/portal/workspaces/t-3?account_id=acct_1"):
+ return 200, {
+ "account": {"kind": "msp"},
+ "workspace": {"display_name": "Client Three", "plan_version": "msp_starter"},
+ }
+ if url.endswith("/api/public/signup"):
+ return 400, {"code": "tier_unavailable"}
+ raise AssertionError(f"unexpected call: {method} {url}")
+
+ with mock.patch.object(mod, "fetch_json", side_effect=fake_fetch_json):
+ args = mod.parse_args(
+ [
+ "--base-url",
+ "https://pulse.example.com",
+ "--account-id",
+ "acct_1",
+ "--bearer-token",
+ "token",
+ "--workspace-name",
+ "Client Three",
+ "--member-email",
+ "--member-role",
+ "tech",
+ "--public-signup-email",
+ "--public-signup-org-name",
+ "Public Boundary",
+ ]
+ )
+ results = mod.run_rehearsal(args)
+
+ self.assertTrue(all(result.ok for result in results), [result.detail for result in results])
+ headers = next(headers for method, url, headers in calls if method == "POST" and url.endswith("/api/accounts/acct_1/tenants"))
+ self.assertEqual(headers["Authorization"], "Bearer token")
+
+ def test_run_rehearsal_fails_when_created_workspace_drifts_plan(self) -> None:
+ def fake_fetch_json(method: str, url: str, **kwargs):
+ if url.endswith("/api/accounts/acct_1/tenants") and method == "GET":
+ return 200, []
+ if url.endswith("/api/accounts/acct_1/tenants") and method == "POST":
+ return 201, {
+ "id": "t-3",
+ "display_name": "Client Three",
+ "account_id": "acct_1",
+ "plan_version": "cloud_starter",
+ }
+ if url.endswith("/api/accounts/acct_1/members"):
+ return 200, []
+ if url.endswith("/api/portal/dashboard?account_id=acct_1"):
+ return 200, {"account": {"kind": "msp"}, "summary": {"total": 1}}
+ if url.endswith("/api/public/signup"):
+ return 400, {"code": "tier_unavailable"}
+ raise AssertionError(f"unexpected call: {method} {url}")
+
+ with mock.patch.object(mod, "fetch_json", side_effect=fake_fetch_json):
+ exit_code = run_main(
+ [
+ "--base-url",
+ "https://pulse.example.com",
+ "--account-id",
+ "acct_1",
+ "--api-token",
+ "token",
+ "--workspace-name",
+ "Client Three",
+ ]
+ )
+ self.assertEqual(exit_code, 1)
+
+ def test_main_returns_failure_when_workspace_create_raises_runtime_error(self) -> None:
+ def fake_fetch_json(method: str, url: str, **kwargs):
+ if url.endswith("/api/accounts/acct_1/tenants") and method == "GET":
+ return 200, []
+ if url.endswith("/api/accounts/acct_1/tenants") and method == "POST":
+ raise RuntimeError("POST https://pulse.example.com/api/accounts/acct_1/tenants returned non-JSON body: internal error")
+ if url.endswith("/api/accounts/acct_1/members") and method == "GET":
+ return 200, []
+ if url.endswith("/api/portal/dashboard?account_id=acct_1"):
+ return 200, {"account": {"kind": "msp"}, "summary": {"total": 1}}
+ raise AssertionError(f"unexpected call: {method} {url}")
+
+ with mock.patch.object(mod, "fetch_json", side_effect=fake_fetch_json):
+ exit_code = run_main(
+ [
+ "--base-url",
+ "https://pulse.example.com",
+ "--account-id",
+ "acct_1",
+ "--api-token",
+ "token",
+ "--workspace-name",
+ "Client Three",
+ ]
+ )
+ self.assertEqual(exit_code, 1)
+
+ def test_render_markdown_report(self) -> None:
+ report = mod.render_markdown_report(
+ title="MSP Provider Tenant Management Rehearsal",
+ base_url="https://pulse.example.com",
+ account_id="acct_1",
+ results=[
+ mod.CheckResult(name="msp-tenant-list", ok=True, detail="tenant_count=2"),
+ mod.CheckResult(name="public-cloud-boundary", ok=False, detail="status=500"),
+ ],
+ )
+ self.assertIn("# MSP Provider Tenant Management Rehearsal", report)
+ self.assertIn("`PASS` `msp-tenant-list`", report)
+ self.assertIn("`FAIL` `public-cloud-boundary`", report)
+
+ def test_main_writes_report(self) -> None:
+ def fake_fetch_json(method: str, url: str, **kwargs):
+ if url.endswith("/api/accounts/acct_1/tenants") and method == "GET":
+ return 200, []
+ if url.endswith("/api/accounts/acct_1/members") and method == "GET":
+ return 200, []
+ if url.endswith("/api/portal/dashboard?account_id=acct_1"):
+ return 200, {"account": {"kind": "msp"}, "summary": {"total": 1}}
+ raise AssertionError(f"unexpected call: {method} {url}")
+
+ with tempfile.TemporaryDirectory() as tmp:
+ report_path = Path(tmp) / "report.md"
+ with mock.patch.object(mod, "fetch_json", side_effect=fake_fetch_json):
+ exit_code = mod.main(
+ [
+ "--base-url",
+ "https://pulse.example.com",
+ "--account-id",
+ "acct_1",
+ "--api-token",
+ "token",
+ "--report-out",
+ str(report_path),
+ ]
+ )
+ self.assertEqual(exit_code, 0)
+ self.assertIn("# MSP Provider Tenant Management Rehearsal", report_path.read_text(encoding="utf-8"))
+
+ def test_main_returns_failure_on_timeout_without_traceback(self) -> None:
+ with mock.patch.object(mod.request, "urlopen", side_effect=socket.timeout("timed out")):
+ exit_code = run_main(
+ [
+ "--base-url",
+ "https://pulse.example.com",
+ "--account-id",
+ "acct_1",
+ "--api-token",
+ "token",
+ ]
+ )
+ self.assertEqual(exit_code, 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release_control/internal/relay_registration_reconnect_drain_proof.py b/scripts/release_control/internal/relay_registration_reconnect_drain_proof.py
new file mode 100644
index 0000000000..fdcb338f8c
--- /dev/null
+++ b/scripts/release_control/internal/relay_registration_reconnect_drain_proof.py
@@ -0,0 +1,164 @@
+#!/usr/bin/env python3
+"""Run the automated proof bundle for the relay registration/reconnect gate."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import subprocess
+from dataclasses import asdict, dataclass
+from pathlib import Path
+
+
+@dataclass
+class CommandSpec:
+ name: str
+ cwd: str
+ command: list[str]
+
+
+@dataclass
+class CommandResult:
+ name: str
+ cwd: str
+ command: list[str]
+ ok: bool
+ exit_code: int
+ detail: str
+
+
+def default_pulse_dir() -> Path:
+ return Path(__file__).resolve().parents[2]
+
+
+def default_pulse_mobile_dir() -> Path:
+ return default_pulse_dir().parent / "pulse-mobile"
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="Run the automated proof bundle for the relay registration/reconnect/drain release gate."
+ )
+ parser.add_argument("--pulse-dir", default=str(default_pulse_dir()))
+ parser.add_argument("--pulse-mobile-dir", default=str(default_pulse_mobile_dir()))
+ parser.add_argument("--frontend-dir", help="Optional override for the pulse frontend-modern directory")
+ parser.add_argument("--json", action="store_true", help="Emit JSON instead of human-readable output")
+ return parser.parse_args(argv)
+
+
+def frontend_dir_from_args(args: argparse.Namespace) -> Path:
+ if args.frontend_dir:
+ return Path(args.frontend_dir).resolve()
+ return Path(args.pulse_dir).resolve() / "frontend-modern"
+
+
+def build_command_specs(args: argparse.Namespace) -> list[CommandSpec]:
+ pulse_dir = Path(args.pulse_dir).resolve()
+ pulse_mobile_dir = Path(args.pulse_mobile_dir).resolve()
+ frontend_dir = frontend_dir_from_args(args)
+ return [
+ CommandSpec(
+ name="relay-backend-api-guards",
+ cwd=str(pulse_dir),
+ command=[
+ "go",
+ "test",
+ "./internal/api",
+ "-run",
+ "TestRelayEndpointsRequireLicenseFeature|TestRelayOnboardingEndpointsRequireLicenseFeature|TestRelayLicenseGatingResponseFormat|TestOnboardingQRPayloadStructure|TestOnboardingValidateSuccessAndFailure|TestOnboardingDeepLinkFormat",
+ "-count=1",
+ ],
+ ),
+ CommandSpec(
+ name="relay-backend-runtime",
+ cwd=str(pulse_dir),
+ command=[
+ "go",
+ "test",
+ "./internal/relay",
+ "-run",
+ "TestClient_E2E_MultiMobileClientRelay|TestClient_AbruptDisconnectCancelsInFlightHandlers|TestClient_AbruptDisconnectMultipleChannelCleanup|TestClient_DrainDuringInFlightData|TestClient_DrainWithMultipleInFlightChannels|TestClientRegister_SessionResumeRejectionClearsCachedSession|TestRunLoop_SessionResumeRejectionFallsBackToFreshRegister",
+ "-count=1",
+ ],
+ ),
+ CommandSpec(
+ name="relay-frontend-runtime",
+ cwd=str(frontend_dir),
+ command=[
+ "npx",
+ "vitest",
+ "run",
+ "src/components/Dashboard/__tests__/RelayOnboardingCard.test.tsx",
+ "src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx",
+ "src/components/Settings/__tests__/settingsReadOnlyPanels.test.tsx",
+ ],
+ ),
+ CommandSpec(
+ name="relay-managed-runtime",
+ cwd=str(pulse_dir),
+ command=[
+ "go",
+ "test",
+ "./internal/relay",
+ "-run",
+ "TestManagedRuntimeRelayRegistrationReconnectDrain",
+ "-count=1",
+ ],
+ ),
+ CommandSpec(
+ name="relay-mobile-client",
+ cwd=str(pulse_mobile_dir),
+ command=[
+ "npm",
+ "test",
+ "--",
+ "--runTestsByPath",
+ "src/relay/__tests__/client.test.ts",
+ "src/relay/__tests__/client-hardening.test.ts",
+ "src/relay/__tests__/protocol-contract.test.ts",
+ ],
+ ),
+ ]
+
+
+def summarize_output(stdout: str, stderr: str) -> str:
+ text = "\n".join(part.strip() for part in (stdout, stderr) if part.strip()).strip()
+ if not text:
+ return "pass"
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
+ summary = lines[-1]
+ if len(summary) > 240:
+ return summary[:237] + "..."
+ return summary
+
+
+def run_command(spec: CommandSpec) -> CommandResult:
+ proc = subprocess.run(spec.command, cwd=spec.cwd, capture_output=True, text=True, check=False)
+ return CommandResult(
+ name=spec.name,
+ cwd=spec.cwd,
+ command=spec.command,
+ ok=proc.returncode == 0,
+ exit_code=proc.returncode,
+ detail=summarize_output(proc.stdout, proc.stderr),
+ )
+
+
+def run_proof(args: argparse.Namespace) -> list[CommandResult]:
+ return [run_command(spec) for spec in build_command_specs(args)]
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(argv)
+ results = run_proof(args)
+ if args.json:
+ print(json.dumps([asdict(result) for result in results], indent=2))
+ else:
+ for result in results:
+ status = "PASS" if result.ok else "FAIL"
+ print(f"{status} {result.name}: {result.detail}")
+ return 0 if all(result.ok for result in results) else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release_control/internal/relay_registration_reconnect_drain_proof_test.py b/scripts/release_control/internal/relay_registration_reconnect_drain_proof_test.py
new file mode 100644
index 0000000000..41e9aeaccb
--- /dev/null
+++ b/scripts/release_control/internal/relay_registration_reconnect_drain_proof_test.py
@@ -0,0 +1,23 @@
+#!/usr/bin/env python3
+"""Tests for the relay registration/reconnect proof wrapper."""
+
+from __future__ import annotations
+
+import unittest
+
+import relay_registration_reconnect_drain_proof as proof
+
+
+class RelayRegistrationReconnectDrainProofTest(unittest.TestCase):
+ def test_build_command_specs_are_sorted_and_cover_expected_workspaces(self) -> None:
+ args = proof.parse_args([])
+ specs = proof.build_command_specs(args)
+ self.assertEqual([spec.name for spec in specs], sorted(spec.name for spec in specs))
+ self.assertIn("relay-managed-runtime", [spec.name for spec in specs])
+ self.assertTrue(any(spec.cwd.endswith("frontend-modern") for spec in specs))
+ self.assertTrue(any(spec.cwd.endswith("pulse-mobile") for spec in specs))
+ self.assertTrue(any(spec.cwd.endswith("pulse") for spec in specs))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release_control/internal/resolve_release_promotion.py b/scripts/release_control/internal/resolve_release_promotion.py
new file mode 100644
index 0000000000..a902ea0c7a
--- /dev/null
+++ b/scripts/release_control/internal/resolve_release_promotion.py
@@ -0,0 +1,228 @@
+#!/usr/bin/env python3
+"""Resolve and validate shared release-promotion metadata for governed workflows."""
+
+from __future__ import annotations
+
+import argparse
+import re
+import subprocess
+import time
+from pathlib import Path
+from typing import Callable
+
+from repo_file_io import REPO_ROOT, git_env
+
+
+SEMVER_PRERELEASE_RE = re.compile(r"-(?:rc|alpha|beta)\.\d+$")
+
+
+def normalize_tag(value: str) -> str:
+ value = (value or "").strip()
+ if not value:
+ return ""
+ if value.startswith("v"):
+ return value
+ return f"v{value}"
+
+
+def is_prerelease_version(version: str) -> bool:
+ return bool(SEMVER_PRERELEASE_RE.search(version))
+
+
+def tag_exists(tag: str) -> bool:
+ result = subprocess.run(
+ ["git", "rev-parse", "-q", "--verify", f"refs/tags/{tag}"],
+ cwd=REPO_ROOT,
+ env=git_env(),
+ capture_output=True,
+ text=True,
+ )
+ return result.returncode == 0
+
+
+def tag_commit(tag: str) -> str:
+ result = subprocess.run(
+ ["git", "rev-list", "-n1", f"refs/tags/{tag}"],
+ cwd=REPO_ROOT,
+ env=git_env(),
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ return result.stdout.strip()
+
+
+def head_descends_from(commit: str) -> bool:
+ result = subprocess.run(
+ ["git", "merge-base", "--is-ancestor", commit, "HEAD"],
+ cwd=REPO_ROOT,
+ env=git_env(),
+ )
+ return result.returncode == 0
+
+
+def tag_created_unix(tag: str) -> int:
+ result = subprocess.run(
+ ["git", "for-each-ref", "--format=%(creatordate:unix)", f"refs/tags/{tag}"],
+ cwd=REPO_ROOT,
+ env=git_env(),
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ value = result.stdout.strip().splitlines()
+ if not value or not value[0].strip():
+ raise ValueError(f"Could not determine creation time for promoted prerelease tag {tag}.")
+ return int(value[0].strip())
+
+
+def normalize_whitespace(value: str) -> str:
+ return " ".join((value or "").split())
+
+
+def resolve_metadata(
+ *,
+ version: str,
+ promoted_from_tag_input: str,
+ rollback_version_input: str,
+ ga_date_input: str,
+ v5_eos_date_input: str,
+ hotfix_exception: bool,
+ hotfix_reason_input: str,
+ release_notes_input: str,
+ tag_exists_fn: Callable[[str], bool] = tag_exists,
+ tag_commit_fn: Callable[[str], str] = tag_commit,
+ head_descends_from_fn: Callable[[str], bool] = head_descends_from,
+ tag_created_unix_fn: Callable[[str], int] = tag_created_unix,
+ now_unix_fn: Callable[[], int] = lambda: int(time.time()),
+) -> dict[str, str]:
+ tag = normalize_tag(version)
+ rollback_tag = normalize_tag(rollback_version_input)
+ ga_date = (ga_date_input or "").strip()
+ v5_eos_date = (v5_eos_date_input or "").strip()
+ hotfix_reason = normalize_whitespace(hotfix_reason_input)
+ release_notes = release_notes_input or ""
+ is_prerelease = is_prerelease_version(version)
+
+ if not rollback_tag:
+ raise ValueError(
+ "rollback_version is required for every release rehearsal and promotion so rollback can be executed explicitly."
+ )
+ if SEMVER_PRERELEASE_RE.search(rollback_tag):
+ raise ValueError(
+ f"rollback_version must point to a stable release tag, not a prerelease ({rollback_tag})."
+ )
+ if not tag_exists_fn(rollback_tag):
+ raise ValueError(f"rollback_version {rollback_tag} does not exist as a repository tag.")
+ rollback_command = f"./scripts/install.sh --version {rollback_tag}"
+
+ promoted_from_tag = ""
+ soak_hours = ""
+ if is_prerelease:
+ if hotfix_exception:
+ raise ValueError("hotfix_exception applies only to stable promotions.")
+ else:
+ promoted_from_tag = normalize_tag(promoted_from_tag_input)
+ if not promoted_from_tag:
+ raise ValueError(
+ "Stable promotion requires promoted_from_tag naming the RC being promoted."
+ )
+ if not re.match(rf"^v{re.escape(version)}-rc\.\d+$", promoted_from_tag):
+ raise ValueError(
+ f"promoted_from_tag must reference an RC tag for the same stable version ({version}), got {promoted_from_tag}."
+ )
+ if not tag_exists_fn(promoted_from_tag):
+ raise ValueError(
+ f"promoted_from_tag {promoted_from_tag} does not exist as a repository tag."
+ )
+
+ promoted_commit = tag_commit_fn(promoted_from_tag)
+ if not head_descends_from_fn(promoted_commit):
+ raise ValueError(
+ f"Stable promotion {tag} must descend from promoted prerelease tag {promoted_from_tag}."
+ )
+
+ promoted_tag_ts = tag_created_unix_fn(promoted_from_tag)
+ soak_hours_value = int((now_unix_fn() - promoted_tag_ts) / 3600)
+ soak_hours = str(soak_hours_value)
+
+ if hotfix_exception:
+ if not hotfix_reason:
+ raise ValueError("hotfix_reason is required when hotfix_exception is true.")
+ elif soak_hours_value < 72:
+ raise ValueError(
+ f"Stable promotion {tag} has only {soak_hours_value} hours of prerelease soak since {promoted_from_tag}; minimum is 72 hours unless hotfix_exception is true."
+ )
+
+ if version == "6.0.0":
+ if not re.match(r"^\d{4}-\d{2}-\d{2}$", ga_date):
+ raise ValueError(
+ "Stable v6.0.0 requires ga_date in YYYY-MM-DD form so the GA publish notice is explicit."
+ )
+ if not re.match(r"^\d{4}-\d{2}-\d{2}$", v5_eos_date):
+ raise ValueError(
+ "Stable v6.0.0 requires v5_eos_date in YYYY-MM-DD form so the support window is published explicitly."
+ )
+ if release_notes:
+ if "maintenance-only support" not in release_notes.lower():
+ raise ValueError(
+ "Stable v6.0.0 release_notes must include the Pulse v5 maintenance-only support notice."
+ )
+ if ga_date not in release_notes:
+ raise ValueError(
+ f"Stable v6.0.0 release_notes must include the exact ga_date ({ga_date})."
+ )
+ if v5_eos_date not in release_notes:
+ raise ValueError(
+ f"Stable v6.0.0 release_notes must include the exact v5_eos_date ({v5_eos_date})."
+ )
+
+ return {
+ "promoted_from_tag": promoted_from_tag,
+ "rollback_tag": rollback_tag,
+ "rollback_command": rollback_command,
+ "ga_date": ga_date,
+ "v5_eos_date": v5_eos_date,
+ "hotfix_exception": "true" if hotfix_exception else "false",
+ "hotfix_reason": hotfix_reason,
+ "soak_hours": soak_hours,
+ }
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--version", required=True)
+ parser.add_argument("--promoted-from-tag", default="")
+ parser.add_argument("--rollback-version", default="")
+ parser.add_argument("--ga-date", default="")
+ parser.add_argument("--v5-eos-date", default="")
+ parser.add_argument("--hotfix-exception", action="store_true")
+ parser.add_argument("--hotfix-reason", default="")
+ parser.add_argument("--release-notes-file", default="")
+ return parser.parse_args()
+
+
+def main() -> int:
+ args = parse_args()
+ release_notes = ""
+ if args.release_notes_file:
+ release_notes = Path(args.release_notes_file).read_text(encoding="utf-8")
+
+ metadata = resolve_metadata(
+ version=args.version,
+ promoted_from_tag_input=args.promoted_from_tag,
+ rollback_version_input=args.rollback_version,
+ ga_date_input=args.ga_date,
+ v5_eos_date_input=args.v5_eos_date,
+ hotfix_exception=args.hotfix_exception,
+ hotfix_reason_input=args.hotfix_reason,
+ release_notes_input=release_notes,
+ )
+
+ for key, value in metadata.items():
+ print(f"{key}={value}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release_control/internal/resolve_release_promotion_test.py b/scripts/release_control/internal/resolve_release_promotion_test.py
new file mode 100644
index 0000000000..e3ed24b324
--- /dev/null
+++ b/scripts/release_control/internal/resolve_release_promotion_test.py
@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+"""Unit tests for shared release-promotion metadata resolution."""
+
+from __future__ import annotations
+
+import unittest
+
+import resolve_release_promotion as resolver
+
+
+class ResolveReleasePromotionTest(unittest.TestCase):
+ def test_prerelease_requires_explicit_stable_rollback(self) -> None:
+ metadata = resolver.resolve_metadata(
+ version="6.0.0-rc.2",
+ promoted_from_tag_input="",
+ rollback_version_input="5.1.14",
+ ga_date_input="",
+ v5_eos_date_input="",
+ hotfix_exception=False,
+ hotfix_reason_input="",
+ release_notes_input="",
+ tag_exists_fn=lambda tag: tag == "v5.1.14",
+ )
+ self.assertEqual(metadata["rollback_tag"], "v5.1.14")
+ self.assertEqual(metadata["rollback_command"], "./scripts/install.sh --version v5.1.14")
+ self.assertEqual(metadata["promoted_from_tag"], "")
+ self.assertEqual(metadata["soak_hours"], "")
+
+ def test_stable_requires_matching_promoted_rc_and_soak(self) -> None:
+ metadata = resolver.resolve_metadata(
+ version="6.0.0",
+ promoted_from_tag_input="6.0.0-rc.2",
+ rollback_version_input="5.1.14",
+ ga_date_input="2026-03-20",
+ v5_eos_date_input="2026-06-18",
+ hotfix_exception=False,
+ hotfix_reason_input="",
+ release_notes_input="maintenance-only support 2026-03-20 2026-06-18",
+ tag_exists_fn=lambda tag: tag in {"v6.0.0-rc.2", "v5.1.14"},
+ tag_commit_fn=lambda tag: "abc123",
+ head_descends_from_fn=lambda commit: commit == "abc123",
+ tag_created_unix_fn=lambda tag: 100,
+ now_unix_fn=lambda: 100 + (73 * 3600),
+ )
+ self.assertEqual(metadata["promoted_from_tag"], "v6.0.0-rc.2")
+ self.assertEqual(metadata["soak_hours"], "73")
+
+ def test_stable_requires_release_notes_notice_when_supplied(self) -> None:
+ with self.assertRaisesRegex(
+ ValueError,
+ "release_notes must include the Pulse v5 maintenance-only support notice",
+ ):
+ resolver.resolve_metadata(
+ version="6.0.0",
+ promoted_from_tag_input="6.0.0-rc.2",
+ rollback_version_input="5.1.14",
+ ga_date_input="2026-03-20",
+ v5_eos_date_input="2026-06-18",
+ hotfix_exception=False,
+ hotfix_reason_input="",
+ release_notes_input="missing notice 2026-03-20 2026-06-18",
+ tag_exists_fn=lambda tag: True,
+ tag_commit_fn=lambda tag: "abc123",
+ head_descends_from_fn=lambda commit: True,
+ tag_created_unix_fn=lambda tag: 100,
+ now_unix_fn=lambda: 100 + (73 * 3600),
+ )
+
+ def test_stable_hotfix_requires_reason(self) -> None:
+ with self.assertRaisesRegex(ValueError, "hotfix_reason is required"):
+ resolver.resolve_metadata(
+ version="6.0.1",
+ promoted_from_tag_input="6.0.1-rc.1",
+ rollback_version_input="6.0.0",
+ ga_date_input="",
+ v5_eos_date_input="",
+ hotfix_exception=True,
+ hotfix_reason_input="",
+ release_notes_input="",
+ tag_exists_fn=lambda tag: True,
+ tag_commit_fn=lambda tag: "abc123",
+ head_descends_from_fn=lambda commit: True,
+ tag_created_unix_fn=lambda tag: 100,
+ now_unix_fn=lambda: 100 + (2 * 3600),
+ )
+
+ def test_stable_rejects_short_soak_without_hotfix(self) -> None:
+ with self.assertRaisesRegex(ValueError, "minimum is 72 hours unless hotfix_exception is true"):
+ resolver.resolve_metadata(
+ version="6.0.1",
+ promoted_from_tag_input="6.0.1-rc.1",
+ rollback_version_input="6.0.0",
+ ga_date_input="",
+ v5_eos_date_input="",
+ hotfix_exception=False,
+ hotfix_reason_input="",
+ release_notes_input="",
+ tag_exists_fn=lambda tag: True,
+ tag_commit_fn=lambda tag: "abc123",
+ head_descends_from_fn=lambda commit: True,
+ tag_created_unix_fn=lambda tag: 100,
+ now_unix_fn=lambda: 100 + (2 * 3600),
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release_control/internal/unified_agent_rc_rehearsal.py b/scripts/release_control/internal/unified_agent_rc_rehearsal.py
new file mode 100644
index 0000000000..5f7a564f9a
--- /dev/null
+++ b/scripts/release_control/internal/unified_agent_rc_rehearsal.py
@@ -0,0 +1,604 @@
+#!/usr/bin/env python3
+"""Validate the live unified-agent RC crossover against expected release assets."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Iterable
+from urllib import error, parse, request
+
+
+DEFAULT_RELEASE_BASE_URL = "https://github.com/rcourtman/Pulse/releases/download"
+
+
+@dataclass
+class CheckResult:
+ name: str
+ ok: bool
+ detail: str
+
+
+def safe_check(name: str, fn) -> CheckResult:
+ try:
+ return fn()
+ except Exception as exc: # pragma: no cover - exercised via caller tests
+ return CheckResult(name=name, ok=False, detail=str(exc))
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Verify that a live Pulse RC instance serves the expected unified-agent "
+ "version and release assets for the v5-to-v6 crossover rehearsal."
+ )
+ )
+ parser.add_argument("--base-url", required=True, help="Pulse server base URL")
+ parser.add_argument(
+ "--expected-version",
+ required=True,
+ help="Expected Pulse version from /api/agent/version, e.g. 6.0.0-rc.1",
+ )
+ parser.add_argument(
+ "--release-base-url",
+ default=DEFAULT_RELEASE_BASE_URL,
+ help="Release asset base URL to compare against",
+ )
+ parser.add_argument(
+ "--arch",
+ action="append",
+ default=[],
+ help="Optional unified-agent architecture to verify via /download/pulse-agent?arch=...",
+ )
+ parser.add_argument(
+ "--update-info-dir",
+ help="Optional directory containing .pulse-update-info on the upgraded machine",
+ )
+ parser.add_argument(
+ "--expected-updated-from",
+ help="Optional expected previous agent version inside .pulse-update-info",
+ )
+ parser.add_argument(
+ "--timeout",
+ type=float,
+ default=30.0,
+ help="HTTP timeout in seconds",
+ )
+ parser.add_argument(
+ "--api-token",
+ help="Optional API token sent as X-API-Token for authenticated rehearsal checks",
+ )
+ parser.add_argument(
+ "--bearer-token",
+ help="Optional API token sent as Authorization: Bearer for authenticated rehearsal checks",
+ )
+ parser.add_argument(
+ "--cookie",
+ help="Optional raw Cookie header for authenticated rehearsal checks",
+ )
+ parser.add_argument(
+ "--expected-active-agents",
+ type=int,
+ help=(
+ "Optional expected active Pulse Unified Agent count after upgrade; "
+ "verifies both /api/license/entitlements and /api/license/agent-ledger"
+ ),
+ )
+ parser.add_argument(
+ "--expected-agent-name",
+ action="append",
+ default=[],
+ help=(
+ "Optional agent display name expected in /api/license/agent-ledger after "
+ "the upgrade; may be passed multiple times"
+ ),
+ )
+ parser.add_argument(
+ "--expected-online-agents",
+ type=int,
+ help=(
+ "Optional expected number of online agents in /api/license/agent-ledger "
+ "after the upgrade"
+ ),
+ )
+ parser.add_argument(
+ "--json",
+ action="store_true",
+ help="Emit JSON instead of human-readable output",
+ )
+ parser.add_argument(
+ "--report-out",
+ help="Optional path to write a markdown rehearsal report",
+ )
+ parser.add_argument(
+ "--report-title",
+ default="Unified Agent RC Rehearsal",
+ help="Markdown title used when writing --report-out",
+ )
+ return parser.parse_args(argv)
+
+
+def normalize_base_url(url: str) -> str:
+ return url.rstrip("/")
+
+
+def summarize_http_error_body(body: bytes) -> str:
+ message = body.decode("utf-8", errors="replace").strip()
+ if not message:
+ return "<empty response>"
+ first_line = message.splitlines()[0].strip()
+ if first_line.startswith("<!DOCTYPE html") or first_line.startswith("<html"):
+ return "<html error page omitted>"
+ if len(first_line) > 240:
+ return first_line[:237] + "..."
+ return first_line
+
+
+def build_auth_headers(args: argparse.Namespace) -> dict[str, str]:
+ headers: dict[str, str] = {}
+ if args.api_token:
+ headers["X-API-Token"] = args.api_token
+ if args.bearer_token:
+ headers["Authorization"] = f"Bearer {args.bearer_token}"
+ if args.cookie:
+ headers["Cookie"] = args.cookie
+ return headers
+
+
+def fetch_bytes(
+ url: str, *, timeout: float, headers: dict[str, str] | None = None
+) -> tuple[bytes, dict[str, str]]:
+ req = request.Request(url, method="GET", headers=headers or {})
+ try:
+ with request.urlopen(req, timeout=timeout) as resp:
+ body = resp.read()
+ headers = {key.lower(): value for key, value in resp.headers.items()}
+ return body, headers
+ except error.HTTPError as exc:
+ body = exc.read()
+ message = summarize_http_error_body(body)
+ raise RuntimeError(f"{url} returned HTTP {exc.code}: {message}") from exc
+ except error.URLError as exc:
+ raise RuntimeError(f"failed to fetch {url}: {exc.reason}") from exc
+
+
+def fetch_json(
+ url: str, *, timeout: float, headers: dict[str, str] | None = None
+) -> dict[str, object]:
+ body, _headers = fetch_bytes(url, timeout=timeout, headers=headers)
+ try:
+ payload = json.loads(body.decode("utf-8"))
+ except json.JSONDecodeError as exc:
+ raise RuntimeError(f"{url} did not return valid JSON") from exc
+ if not isinstance(payload, dict):
+ raise RuntimeError(f"{url} did not return a JSON object")
+ return payload
+
+
+def sha256_hex(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+def release_asset_url(release_base_url: str, version: str, asset_name: str) -> str:
+ return f"{normalize_base_url(release_base_url)}/v{version}/{asset_name}"
+
+
+def agent_binary_asset_name(arch: str) -> str:
+ asset = f"pulse-agent-{arch}"
+ if arch.startswith("windows-"):
+ asset += ".exe"
+ return asset
+
+
+def compare_asset(
+ *,
+ name: str,
+ live_url: str,
+ release_url: str,
+ timeout: float,
+ expect_checksum_header: bool = False,
+) -> CheckResult:
+ live_body, live_headers = fetch_bytes(live_url, timeout=timeout)
+ release_body, _release_headers = fetch_bytes(release_url, timeout=timeout)
+
+ live_hash = sha256_hex(live_body)
+ release_hash = sha256_hex(release_body)
+ if live_hash != release_hash:
+ return CheckResult(
+ name=name,
+ ok=False,
+ detail=(
+ f"live asset hash {live_hash} does not match release asset hash "
+ f"{release_hash} ({release_url})"
+ ),
+ )
+
+ if expect_checksum_header:
+ checksum_header = live_headers.get("x-checksum-sha256", "").strip()
+ if checksum_header != live_hash:
+ return CheckResult(
+ name=name,
+ ok=False,
+ detail=(
+ f"X-Checksum-Sha256={checksum_header or '<missing>'} does not "
+ f"match live asset hash {live_hash}"
+ ),
+ )
+
+ served_from = live_headers.get("x-served-from")
+ served_note = f"; served_from={served_from}" if served_from else ""
+ return CheckResult(
+ name=name,
+ ok=True,
+ detail=f"matched release asset hash {live_hash}{served_note}",
+ )
+
+
+def check_version(base_url: str, expected_version: str, timeout: float) -> CheckResult:
+ payload = fetch_json(f"{base_url}/api/agent/version", timeout=timeout)
+ version = str(payload.get("version", "")).strip()
+ if version != expected_version:
+ return CheckResult(
+ name="agent-version-endpoint",
+ ok=False,
+ detail=f"reported version {version!r}, expected {expected_version!r}",
+ )
+ return CheckResult(
+ name="agent-version-endpoint",
+ ok=True,
+ detail=f"reported expected version {version}",
+ )
+
+
+def check_update_info(update_info_dir: str, expected_updated_from: str) -> CheckResult:
+ info_path = Path(update_info_dir) / ".pulse-update-info"
+ if not info_path.exists():
+ return CheckResult(
+ name="local-update-info",
+ ok=False,
+ detail=f"{info_path} is missing",
+ )
+ actual = info_path.read_text(encoding="utf-8").strip()
+ if actual != expected_updated_from:
+ return CheckResult(
+ name="local-update-info",
+ ok=False,
+ detail=f"{info_path} contains {actual!r}, expected {expected_updated_from!r}",
+ )
+ return CheckResult(
+ name="local-update-info",
+ ok=True,
+ detail=f"{info_path} contains expected previous version {actual}",
+ )
+
+
+def check_active_agent_accounting(
+ *,
+ base_url: str,
+ timeout: float,
+ auth_headers: dict[str, str],
+ expected_active_agents: int,
+) -> CheckResult:
+ if not auth_headers:
+ return CheckResult(
+ name="active-agent-accounting",
+ ok=False,
+ detail=(
+ "expected active-agent verification requires --api-token, "
+ "--bearer-token, or --cookie"
+ ),
+ )
+
+ entitlements = fetch_json(
+ f"{base_url}/api/license/entitlements",
+ timeout=timeout,
+ headers=auth_headers,
+ )
+ limits = entitlements.get("limits")
+ if not isinstance(limits, list):
+ return CheckResult(
+ name="active-agent-accounting",
+ ok=False,
+ detail="/api/license/entitlements returned no limits array",
+ )
+
+ max_agents_current: int | None = None
+ for item in limits:
+ if not isinstance(item, dict):
+ continue
+ if str(item.get("key", "")).strip() != "max_agents":
+ continue
+ current = item.get("current")
+ if not isinstance(current, int):
+ return CheckResult(
+ name="active-agent-accounting",
+ ok=False,
+ detail="max_agents current usage was missing or not an integer",
+ )
+ max_agents_current = current
+ break
+
+ if max_agents_current is None:
+ return CheckResult(
+ name="active-agent-accounting",
+ ok=False,
+ detail="/api/license/entitlements did not include max_agents",
+ )
+
+ ledger = fetch_json(
+ f"{base_url}/api/license/agent-ledger",
+ timeout=timeout,
+ headers=auth_headers,
+ )
+ agents = ledger.get("agents")
+ if not isinstance(agents, list):
+ return CheckResult(
+ name="active-agent-accounting",
+ ok=False,
+ detail="/api/license/agent-ledger returned no agents array",
+ )
+ ledger_total = ledger.get("total")
+ if not isinstance(ledger_total, int):
+ ledger_total = len(agents)
+
+ ok = (
+ max_agents_current == expected_active_agents
+ and ledger_total == expected_active_agents
+ and len(agents) == expected_active_agents
+ and max_agents_current == ledger_total
+ )
+ detail = (
+ f"entitlements max_agents.current={max_agents_current}, "
+ f"agent-ledger total={ledger_total}, "
+ f"agent-ledger agents={len(agents)}, "
+ f"expected={expected_active_agents}"
+ )
+ return CheckResult(name="active-agent-accounting", ok=ok, detail=detail)
+
+
+def check_agent_ledger_identity(
+ *,
+ base_url: str,
+ timeout: float,
+ auth_headers: dict[str, str],
+ expected_agent_names: list[str],
+ expected_online_agents: int | None,
+) -> CheckResult:
+ if not auth_headers:
+ return CheckResult(
+ name="agent-ledger-identity",
+ ok=False,
+ detail=(
+ "agent ledger identity verification requires --api-token, "
+ "--bearer-token, or --cookie"
+ ),
+ )
+
+ ledger = fetch_json(
+ f"{base_url}/api/license/agent-ledger",
+ timeout=timeout,
+ headers=auth_headers,
+ )
+ agents = ledger.get("agents")
+ if not isinstance(agents, list):
+ return CheckResult(
+ name="agent-ledger-identity",
+ ok=False,
+ detail="/api/license/agent-ledger returned no agents array",
+ )
+
+ normalized_expected_names = [name.strip() for name in expected_agent_names if name.strip()]
+ names = [str(agent.get("name", "")).strip() for agent in agents if isinstance(agent, dict)]
+ online_agents = [
+ agent
+ for agent in agents
+ if isinstance(agent, dict) and str(agent.get("status", "")).strip() == "online"
+ ]
+
+ failures: list[str] = []
+ for expected_name in normalized_expected_names:
+ matches = sum(1 for name in names if name == expected_name)
+ if matches == 0:
+ failures.append(f"missing expected agent name {expected_name!r}")
+ elif matches > 1:
+ failures.append(f"agent name {expected_name!r} appeared {matches} times")
+
+ if expected_online_agents is not None and len(online_agents) != expected_online_agents:
+ failures.append(
+ f"online agent count {len(online_agents)} did not match expected {expected_online_agents}"
+ )
+
+ detail_parts = [
+ f"ledger names={names!r}",
+ f"online_agents={len(online_agents)}",
+ ]
+ if normalized_expected_names:
+ detail_parts.append(f"expected_names={normalized_expected_names!r}")
+ if expected_online_agents is not None:
+ detail_parts.append(f"expected_online_agents={expected_online_agents}")
+ if failures:
+ detail_parts.append("failures=" + "; ".join(failures))
+
+ return CheckResult(
+ name="agent-ledger-identity",
+ ok=not failures,
+ detail=", ".join(detail_parts),
+ )
+
+
+def run_rehearsal(args: argparse.Namespace) -> list[CheckResult]:
+ base_url = normalize_base_url(args.base_url)
+ release_base_url = normalize_base_url(args.release_base_url)
+ auth_headers = build_auth_headers(args)
+ results = [
+ safe_check(
+ "agent-version-endpoint",
+ lambda: check_version(base_url, args.expected_version, args.timeout),
+ ),
+ safe_check(
+ "install-sh-asset",
+ lambda: compare_asset(
+ name="install-sh-asset",
+ live_url=f"{base_url}/install.sh",
+ release_url=release_asset_url(release_base_url, args.expected_version, "install.sh"),
+ timeout=args.timeout,
+ ),
+ ),
+ safe_check(
+ "install-ps1-asset",
+ lambda: compare_asset(
+ name="install-ps1-asset",
+ live_url=f"{base_url}/install.ps1",
+ release_url=release_asset_url(release_base_url, args.expected_version, "install.ps1"),
+ timeout=args.timeout,
+ ),
+ ),
+ ]
+
+ for arch in args.arch:
+ quoted_arch = parse.quote(arch, safe="")
+ results.append(
+ safe_check(
+ f"agent-binary-{arch}",
+ lambda arch=arch, quoted_arch=quoted_arch: compare_asset(
+ name=f"agent-binary-{arch}",
+ live_url=f"{base_url}/download/pulse-agent?arch={quoted_arch}",
+ release_url=release_asset_url(
+ release_base_url, args.expected_version, agent_binary_asset_name(arch)
+ ),
+ timeout=args.timeout,
+ expect_checksum_header=True,
+ ),
+ )
+ )
+
+ if args.update_info_dir or args.expected_updated_from:
+ if not args.update_info_dir or not args.expected_updated_from:
+ results.append(
+ CheckResult(
+ name="local-update-info",
+ ok=False,
+ detail="both --update-info-dir and --expected-updated-from are required together",
+ )
+ )
+ else:
+ results.append(
+ safe_check(
+ "local-update-info",
+ lambda: check_update_info(args.update_info_dir, args.expected_updated_from),
+ )
+ )
+
+ if args.expected_active_agents is not None:
+ results.append(
+ safe_check(
+ "active-agent-accounting",
+ lambda: check_active_agent_accounting(
+ base_url=base_url,
+ timeout=args.timeout,
+ auth_headers=auth_headers,
+ expected_active_agents=args.expected_active_agents,
+ ),
+ )
+ )
+
+ if args.expected_agent_name or args.expected_online_agents is not None:
+ results.append(
+ safe_check(
+ "agent-ledger-identity",
+ lambda: check_agent_ledger_identity(
+ base_url=base_url,
+ timeout=args.timeout,
+ auth_headers=auth_headers,
+ expected_agent_names=args.expected_agent_name,
+ expected_online_agents=args.expected_online_agents,
+ ),
+ )
+ )
+
+ return results
+
+
+def render_text(results: Iterable[CheckResult]) -> str:
+ lines: list[str] = []
+ for result in results:
+ prefix = "PASS" if result.ok else "FAIL"
+ lines.append(f"[{prefix}] {result.name}: {result.detail}")
+ lines.append(
+ "Manual follow-up still required: confirm the upgraded v5-installed agent "
+ "reconnects as one canonical v6 identity, surfaces `updated_from` exactly once, "
+ "and leaves user-visible active-agent counts aligned with runtime enforcement."
+ )
+ return "\n".join(lines)
+
+
+def render_markdown_report(
+ *,
+ title: str,
+ base_url: str,
+ expected_version: str,
+ release_base_url: str,
+ results: Iterable[CheckResult],
+) -> str:
+ lines = [
+ f"# {title}",
+ "",
+ f"- Base URL: `{base_url}`",
+ f"- Expected version: `{expected_version}`",
+ f"- Release asset base: `{release_base_url}`",
+ "",
+ "## Automated Checks",
+ "",
+ ]
+ for result in results:
+ status = "PASS" if result.ok else "FAIL"
+ lines.append(f"- `{status}` `{result.name}`: {result.detail}")
+ lines.extend(
+ [
+ "",
+ "## Manual Follow-up",
+ "",
+ "- Confirm the upgraded v5-installed agent reconnects as one canonical v6 identity.",
+ "- Confirm `updated_from` appears exactly once on the first canonical v6 report and clears on the next report.",
+ "- Confirm settings/billing active-agent counts still match runtime enforcement after the upgrade.",
+ ]
+ )
+ return "\n".join(lines)
+
+
+def write_report(path: str, content: str) -> None:
+ report_path = Path(path)
+ report_path.parent.mkdir(parents=True, exist_ok=True)
+ report_path.write_text(content + "\n", encoding="utf-8")
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(argv)
+ results = run_rehearsal(args)
+ ok = all(result.ok for result in results)
+
+ if args.report_out:
+ write_report(
+ args.report_out,
+ render_markdown_report(
+ title=args.report_title,
+ base_url=normalize_base_url(args.base_url),
+ expected_version=args.expected_version,
+ release_base_url=normalize_base_url(args.release_base_url),
+ results=results,
+ ),
+ )
+
+ if args.json:
+ print(json.dumps({"ok": ok, "results": [asdict(result) for result in results]}, indent=2))
+ else:
+ print(render_text(results))
+
+ return 0 if ok else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release_control/internal/unified_agent_rc_rehearsal_test.py b/scripts/release_control/internal/unified_agent_rc_rehearsal_test.py
new file mode 100644
index 0000000000..649ea30926
--- /dev/null
+++ b/scripts/release_control/internal/unified_agent_rc_rehearsal_test.py
@@ -0,0 +1,512 @@
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import tempfile
+import threading
+import unittest
+from dataclasses import asdict
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+
+from unified_agent_rc_rehearsal import (
+ agent_binary_asset_name,
+ check_update_info,
+ main,
+ render_markdown_report,
+ release_asset_url,
+ run_rehearsal,
+ summarize_http_error_body,
+)
+
+
+def run_main(argv: list[str]) -> int:
+ with contextlib.redirect_stdout(io.StringIO()):
+ return main(argv)
+
+
+class _FixtureHandler(BaseHTTPRequestHandler):
+ routes: dict[str, tuple[int, bytes, dict[str, str]]] = {}
+ request_headers: dict[str, dict[str, str]] = {}
+
+ def do_GET(self) -> None: # noqa: N802
+ self.request_headers[self.path] = {
+ key.lower(): value for key, value in self.headers.items()
+ }
+ status, body, headers = self.routes.get(self.path, (404, b"missing", {}))
+ self.send_response(status)
+ for key, value in headers.items():
+ self.send_header(key, value)
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, format: str, *args: object) -> None: # noqa: A003
+ return
+
+
+class UnifiedAgentRCRehearsalTest(unittest.TestCase):
+ def setUp(self) -> None:
+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), _FixtureHandler)
+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
+ self.thread.start()
+ self.base_url = f"http://127.0.0.1:{self.server.server_port}"
+
+ def tearDown(self) -> None:
+ self.server.shutdown()
+ self.server.server_close()
+ self.thread.join(timeout=2)
+
+ def set_routes(self, routes: dict[str, tuple[int, bytes, dict[str, str]]]) -> None:
+ _FixtureHandler.routes = routes
+ _FixtureHandler.request_headers = {}
+
+ def test_release_asset_url(self) -> None:
+ got = release_asset_url("https://example.invalid/releases/download/", "6.0.0-rc.1", "install.sh")
+ self.assertEqual(got, "https://example.invalid/releases/download/v6.0.0-rc.1/install.sh")
+
+ def test_agent_binary_asset_name_windows(self) -> None:
+ self.assertEqual(agent_binary_asset_name("windows-amd64"), "pulse-agent-windows-amd64.exe")
+ self.assertEqual(agent_binary_asset_name("linux-amd64"), "pulse-agent-linux-amd64")
+
+ def test_run_rehearsal_passes_with_matching_assets(self) -> None:
+ install = b"#!/bin/sh\necho install\n"
+ ps1 = b"Write-Output 'install'\n"
+ binary = b"pulse-agent-binary"
+ checksum = __import__("hashlib").sha256(binary).hexdigest()
+
+ self.set_routes(
+ {
+ "/pulse/api/agent/version": (
+ 200,
+ json.dumps({"version": "6.0.0-rc.1"}).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/pulse/install.sh": (200, install, {}),
+ "/pulse/install.ps1": (200, ps1, {}),
+ "/pulse/download/pulse-agent?arch=linux-amd64": (
+ 200,
+ binary,
+ {"X-Checksum-Sha256": checksum, "X-Served-From": "github-fallback"},
+ ),
+ "/releases/v6.0.0-rc.1/install.sh": (200, install, {}),
+ "/releases/v6.0.0-rc.1/install.ps1": (200, ps1, {}),
+ "/releases/v6.0.0-rc.1/pulse-agent-linux-amd64": (200, binary, {}),
+ }
+ )
+
+ args = type(
+ "Args",
+ (),
+ {
+ "base_url": f"{self.base_url}/pulse",
+ "expected_version": "6.0.0-rc.1",
+ "release_base_url": f"{self.base_url}/releases",
+ "arch": ["linux-amd64"],
+ "update_info_dir": None,
+ "expected_updated_from": None,
+ "timeout": 5.0,
+ "api_token": None,
+ "bearer_token": None,
+ "cookie": None,
+ "expected_active_agents": None,
+ "expected_agent_name": [],
+ "expected_online_agents": None,
+ "json": False,
+ },
+ )()
+ results = run_rehearsal(args)
+ self.assertTrue(all(result.ok for result in results), [asdict(result) for result in results])
+
+ def test_run_rehearsal_fails_on_binary_checksum_header_mismatch(self) -> None:
+ install = b"#!/bin/sh\n"
+ self.set_routes(
+ {
+ "/pulse/api/agent/version": (
+ 200,
+ json.dumps({"version": "6.0.0-rc.1"}).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/pulse/install.sh": (200, install, {}),
+ "/pulse/install.ps1": (200, b"ps1", {}),
+ "/pulse/download/pulse-agent?arch=linux-amd64": (
+ 200,
+ b"binary",
+ {"X-Checksum-Sha256": "bad"},
+ ),
+ "/releases/v6.0.0-rc.1/install.sh": (200, install, {}),
+ "/releases/v6.0.0-rc.1/install.ps1": (200, b"ps1", {}),
+ "/releases/v6.0.0-rc.1/pulse-agent-linux-amd64": (200, b"binary", {}),
+ }
+ )
+
+ exit_code = run_main(
+ [
+ "--base-url",
+ f"{self.base_url}/pulse",
+ "--expected-version",
+ "6.0.0-rc.1",
+ "--release-base-url",
+ f"{self.base_url}/releases",
+ "--arch",
+ "linux-amd64",
+ "--json",
+ ]
+ )
+ self.assertEqual(exit_code, 1)
+
+ def test_run_rehearsal_reports_missing_release_asset_without_crashing(self) -> None:
+ install = b"#!/bin/sh\n"
+ self.set_routes(
+ {
+ "/pulse/api/agent/version": (
+ 200,
+ json.dumps({"version": "6.0.0-rc.1"}).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/pulse/install.sh": (200, install, {}),
+ "/pulse/install.ps1": (200, b"ps1", {}),
+ "/releases/v6.0.0-rc.1/install.ps1": (200, b"ps1", {}),
+ }
+ )
+
+ exit_code = run_main(
+ [
+ "--base-url",
+ f"{self.base_url}/pulse",
+ "--expected-version",
+ "6.0.0-rc.1",
+ "--release-base-url",
+ f"{self.base_url}/releases",
+ "--json",
+ ]
+ )
+ self.assertEqual(exit_code, 1)
+
+ def test_summarize_http_error_body_omits_html_page(self) -> None:
+ body = b"<!DOCTYPE html>\n<html><body>missing</body></html>"
+ self.assertEqual(summarize_http_error_body(body), "<html error page omitted>")
+
+ def test_check_update_info(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ info_path = Path(tmp) / ".pulse-update-info"
+ info_path.write_text("5.1.14\n", encoding="utf-8")
+ result = check_update_info(tmp, "5.1.14")
+ self.assertTrue(result.ok)
+
+ def test_check_update_info_requires_matching_content(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ info_path = Path(tmp) / ".pulse-update-info"
+ info_path.write_text("5.1.13\n", encoding="utf-8")
+ result = check_update_info(tmp, "5.1.14")
+ self.assertFalse(result.ok)
+
+ def test_render_markdown_report(self) -> None:
+ report = render_markdown_report(
+ title="Unified Agent RC Rehearsal",
+ base_url="https://pulse.example.com",
+ expected_version="6.0.0-rc.1",
+ release_base_url="https://github.com/example/releases/download",
+ results=[
+ type("R", (), {"name": "agent-version-endpoint", "ok": True, "detail": "matched"})(),
+ type("R", (), {"name": "agent-binary-linux-amd64", "ok": False, "detail": "checksum mismatch"})(),
+ ],
+ )
+ self.assertIn("# Unified Agent RC Rehearsal", report)
+ self.assertIn("`PASS` `agent-version-endpoint`", report)
+ self.assertIn("`FAIL` `agent-binary-linux-amd64`", report)
+ self.assertIn("## Manual Follow-up", report)
+
+ def test_main_writes_report(self) -> None:
+ install = b"#!/bin/sh\necho install\n"
+ ps1 = b"Write-Output 'install'\n"
+ self.set_routes(
+ {
+ "/pulse/api/agent/version": (
+ 200,
+ json.dumps({"version": "6.0.0-rc.1"}).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/pulse/install.sh": (200, install, {}),
+ "/pulse/install.ps1": (200, ps1, {}),
+ "/releases/v6.0.0-rc.1/install.sh": (200, install, {}),
+ "/releases/v6.0.0-rc.1/install.ps1": (200, ps1, {}),
+ }
+ )
+ with tempfile.TemporaryDirectory() as tmp:
+ report_path = Path(tmp) / "report.md"
+ exit_code = main(
+ [
+ "--base-url",
+ f"{self.base_url}/pulse",
+ "--expected-version",
+ "6.0.0-rc.1",
+ "--release-base-url",
+ f"{self.base_url}/releases",
+ "--report-out",
+ str(report_path),
+ ]
+ )
+ self.assertEqual(exit_code, 0)
+ content = report_path.read_text(encoding="utf-8")
+ self.assertIn("# Unified Agent RC Rehearsal", content)
+ self.assertIn("`PASS` `install-sh-asset`", content)
+
+ def test_run_rehearsal_verifies_active_agent_accounting_via_api_token(self) -> None:
+ install = b"#!/bin/sh\necho install\n"
+ ps1 = b"Write-Output 'install'\n"
+ self.set_routes(
+ {
+ "/pulse/api/agent/version": (
+ 200,
+ json.dumps({"version": "6.0.0-rc.1"}).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/pulse/install.sh": (200, install, {}),
+ "/pulse/install.ps1": (200, ps1, {}),
+ "/pulse/api/license/entitlements": (
+ 200,
+ json.dumps(
+ {
+ "limits": [
+ {"key": "max_agents", "limit": 10, "current": 3, "state": "ok"}
+ ]
+ }
+ ).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/pulse/api/license/agent-ledger": (
+ 200,
+ json.dumps(
+ {
+ "agents": [{"name": "a"}, {"name": "b"}, {"name": "c"}],
+ "total": 3,
+ "limit": 10,
+ }
+ ).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/releases/v6.0.0-rc.1/install.sh": (200, install, {}),
+ "/releases/v6.0.0-rc.1/install.ps1": (200, ps1, {}),
+ }
+ )
+
+ exit_code = run_main(
+ [
+ "--base-url",
+ f"{self.base_url}/pulse",
+ "--expected-version",
+ "6.0.0-rc.1",
+ "--release-base-url",
+ f"{self.base_url}/releases",
+ "--api-token",
+ "token-123",
+ "--expected-active-agents",
+ "3",
+ "--json",
+ ]
+ )
+ self.assertEqual(exit_code, 0)
+ self.assertEqual(
+ _FixtureHandler.request_headers["/pulse/api/license/entitlements"].get("x-api-token"),
+ "token-123",
+ )
+ self.assertEqual(
+ _FixtureHandler.request_headers["/pulse/api/license/agent-ledger"].get("x-api-token"),
+ "token-123",
+ )
+
+ def test_run_rehearsal_fails_when_active_agent_accounting_mismatches(self) -> None:
+ install = b"#!/bin/sh\necho install\n"
+ ps1 = b"Write-Output 'install'\n"
+ self.set_routes(
+ {
+ "/pulse/api/agent/version": (
+ 200,
+ json.dumps({"version": "6.0.0-rc.1"}).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/pulse/install.sh": (200, install, {}),
+ "/pulse/install.ps1": (200, ps1, {}),
+ "/pulse/api/license/entitlements": (
+ 200,
+ json.dumps(
+ {
+ "limits": [
+ {"key": "max_agents", "limit": 10, "current": 2, "state": "ok"}
+ ]
+ }
+ ).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/pulse/api/license/agent-ledger": (
+ 200,
+ json.dumps(
+ {
+ "agents": [{"name": "a"}, {"name": "b"}, {"name": "c"}],
+ "total": 3,
+ "limit": 10,
+ }
+ ).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/releases/v6.0.0-rc.1/install.sh": (200, install, {}),
+ "/releases/v6.0.0-rc.1/install.ps1": (200, ps1, {}),
+ }
+ )
+
+ exit_code = run_main(
+ [
+ "--base-url",
+ f"{self.base_url}/pulse",
+ "--expected-version",
+ "6.0.0-rc.1",
+ "--release-base-url",
+ f"{self.base_url}/releases",
+ "--api-token",
+ "token-123",
+ "--expected-active-agents",
+ "3",
+ "--json",
+ ]
+ )
+ self.assertEqual(exit_code, 1)
+
+ def test_run_rehearsal_requires_auth_for_active_agent_accounting(self) -> None:
+ install = b"#!/bin/sh\necho install\n"
+ ps1 = b"Write-Output 'install'\n"
+ self.set_routes(
+ {
+ "/pulse/api/agent/version": (
+ 200,
+ json.dumps({"version": "6.0.0-rc.1"}).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/pulse/install.sh": (200, install, {}),
+ "/pulse/install.ps1": (200, ps1, {}),
+ "/releases/v6.0.0-rc.1/install.sh": (200, install, {}),
+ "/releases/v6.0.0-rc.1/install.ps1": (200, ps1, {}),
+ }
+ )
+
+ exit_code = run_main(
+ [
+ "--base-url",
+ f"{self.base_url}/pulse",
+ "--expected-version",
+ "6.0.0-rc.1",
+ "--release-base-url",
+ f"{self.base_url}/releases",
+ "--expected-active-agents",
+ "3",
+ "--json",
+ ]
+ )
+ self.assertEqual(exit_code, 1)
+
+ def test_run_rehearsal_verifies_expected_agent_name_and_online_status(self) -> None:
+ install = b"#!/bin/sh\necho install\n"
+ ps1 = b"Write-Output 'install'\n"
+ self.set_routes(
+ {
+ "/pulse/api/agent/version": (
+ 200,
+ json.dumps({"version": "6.0.0-rc.1"}).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/pulse/install.sh": (200, install, {}),
+ "/pulse/install.ps1": (200, ps1, {}),
+ "/pulse/api/license/agent-ledger": (
+ 200,
+ json.dumps(
+ {
+ "agents": [
+ {
+ "name": "workstation-01",
+ "type": "agent",
+ "status": "online",
+ "last_seen": "2026-03-12T12:00:00Z",
+ "source": "agent",
+ }
+ ],
+ "total": 1,
+ "limit": 10,
+ }
+ ).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/releases/v6.0.0-rc.1/install.sh": (200, install, {}),
+ "/releases/v6.0.0-rc.1/install.ps1": (200, ps1, {}),
+ }
+ )
+
+ exit_code = run_main(
+ [
+ "--base-url",
+ f"{self.base_url}/pulse",
+ "--expected-version",
+ "6.0.0-rc.1",
+ "--release-base-url",
+ f"{self.base_url}/releases",
+ "--api-token",
+ "token-123",
+ "--expected-agent-name",
+ "workstation-01",
+ "--expected-online-agents",
+ "1",
+ "--json",
+ ]
+ )
+ self.assertEqual(exit_code, 0)
+
+ def test_run_rehearsal_fails_when_expected_agent_name_is_duplicated(self) -> None:
+ install = b"#!/bin/sh\necho install\n"
+ ps1 = b"Write-Output 'install'\n"
+ self.set_routes(
+ {
+ "/pulse/api/agent/version": (
+ 200,
+ json.dumps({"version": "6.0.0-rc.1"}).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/pulse/install.sh": (200, install, {}),
+ "/pulse/install.ps1": (200, ps1, {}),
+ "/pulse/api/license/agent-ledger": (
+ 200,
+ json.dumps(
+ {
+ "agents": [
+ {"name": "workstation-01", "status": "online"},
+ {"name": "workstation-01", "status": "online"},
+ ],
+ "total": 2,
+ "limit": 10,
+ }
+ ).encode("utf-8"),
+ {"Content-Type": "application/json"},
+ ),
+ "/releases/v6.0.0-rc.1/install.sh": (200, install, {}),
+ "/releases/v6.0.0-rc.1/install.ps1": (200, ps1, {}),
+ }
+ )
+
+ exit_code = run_main(
+ [
+ "--base-url",
+ f"{self.base_url}/pulse",
+ "--expected-version",
+ "6.0.0-rc.1",
+ "--release-base-url",
+ f"{self.base_url}/releases",
+ "--api-token",
+ "token-123",
+ "--expected-agent-name",
+ "workstation-01",
+ "--json",
+ ]
+ )
+ self.assertEqual(exit_code, 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release_control/internal/verify_commit_slice.py b/scripts/release_control/internal/verify_commit_slice.py
new file mode 100644
index 0000000000..67be06deac
--- /dev/null
+++ b/scripts/release_control/internal/verify_commit_slice.py
@@ -0,0 +1,96 @@
+#!/usr/bin/env python3
+"""Run pre-commit against a proposed commit slice in an isolated git index."""
+
+from __future__ import annotations
+
+import argparse
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+from typing import Iterable
+
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+HOOK_PATH = REPO_ROOT / ".husky" / "pre-commit"
+
+
+def git_env(index_path: Path) -> dict[str, str]:
+ env = os.environ.copy()
+ env["GIT_INDEX_FILE"] = str(index_path)
+ return env
+
+
+def repo_relative_path(path: str | Path) -> str:
+ candidate = Path(path)
+ if candidate.is_absolute():
+ candidate = candidate.relative_to(REPO_ROOT)
+ return candidate.as_posix()
+
+
+def git(index_path: Path, *args: str, check: bool = True) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ ["git", *args],
+ cwd=REPO_ROOT,
+ check=check,
+ capture_output=True,
+ text=True,
+ env=git_env(index_path),
+ )
+
+
+def stage_paths(index_path: Path, paths: Iterable[str]) -> None:
+ normalized = [repo_relative_path(path) for path in paths]
+ if not normalized:
+ return
+ git(index_path, "add", "-f", "--", *normalized)
+
+
+def parse_args(argv: list[str]) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="Verify a proposed commit slice by running .husky/pre-commit in a copied index."
+ )
+ parser.add_argument(
+ "--add-updated",
+ action="store_true",
+ help="Stage all tracked modifications (`git add -u`) into the copied index before explicit paths.",
+ )
+ parser.add_argument(
+ "--show-staged",
+ action="store_true",
+ help="Print the staged file list in the copied index before running the hook.",
+ )
+ parser.add_argument(
+ "paths",
+ nargs="*",
+ help="Explicit repo-relative or absolute paths to stage into the copied index.",
+ )
+ return parser.parse_args(argv)
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(list(argv or sys.argv[1:]))
+ with tempfile.NamedTemporaryFile(prefix="pulse-index.", delete=True) as tmp_index:
+ index_path = Path(tmp_index.name)
+ git(index_path, "read-tree", "HEAD")
+ if args.add_updated:
+ git(index_path, "add", "-u")
+ stage_paths(index_path, args.paths)
+
+ if args.show_staged:
+ staged = git(index_path, "diff", "--cached", "--name-only").stdout.strip()
+ if staged:
+ print(staged)
+
+ result = subprocess.run(
+ [str(HOOK_PATH)],
+ cwd=REPO_ROOT,
+ env=git_env(index_path),
+ text=True,
+ )
+ return result.returncode
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/release_control/internal/verify_commit_slice_test.py b/scripts/release_control/internal/verify_commit_slice_test.py
new file mode 100644
index 0000000000..c8ef9d2e5f
--- /dev/null
+++ b/scripts/release_control/internal/verify_commit_slice_test.py
@@ -0,0 +1,100 @@
+import os
+import subprocess
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from verify_commit_slice import main, repo_relative_path
+
+
+class VerifyCommitSliceTest(unittest.TestCase):
+ def git(self, repo_root: Path, *args: str, check: bool = True) -> subprocess.CompletedProcess:
+ env = os.environ.copy()
+ env.pop("GIT_INDEX_FILE", None)
+ return subprocess.run(
+ ["git", *args],
+ cwd=repo_root,
+ check=check,
+ capture_output=True,
+ text=True,
+ env=env,
+ )
+
+ def init_repo(self, repo_root: Path) -> None:
+ self.git(repo_root, "init")
+ self.git(repo_root, "config", "user.name", "Pulse Test")
+ self.git(repo_root, "config", "user.email", "[email protected]")
+
+ def test_repo_relative_path_normalizes_absolute_paths(self) -> None:
+ repo_root = Path("/tmp/pulse")
+ with patch("verify_commit_slice.REPO_ROOT", repo_root):
+ self.assertEqual(repo_relative_path(repo_root / "docs/file.txt"), "docs/file.txt")
+
+ def test_main_stages_requested_paths_in_isolated_index(self) -> None:
+ with tempfile.TemporaryDirectory() as tmpdir:
+ repo_root = Path(tmpdir)
+ hook = repo_root / ".husky" / "pre-commit"
+ tracked = repo_root / "tracked.txt"
+ explicit = repo_root / "explicit.txt"
+ ignored = repo_root / "ignored.txt"
+
+ hook.parent.mkdir(parents=True, exist_ok=True)
+ tracked.write_text("tracked\n", encoding="utf-8")
+ explicit.write_text("explicit\n", encoding="utf-8")
+ ignored.write_text("ignored\n", encoding="utf-8")
+ (repo_root / ".gitignore").write_text("ignored.txt\n", encoding="utf-8")
+ hook.write_text(
+ "#!/usr/bin/env bash\n"
+ "set -euo pipefail\n"
+ "git diff --cached --name-only | sort > slice.out\n",
+ encoding="utf-8",
+ )
+ hook.chmod(0o755)
+
+ self.init_repo(repo_root)
+ self.git(repo_root, "add", ".gitignore", "tracked.txt", ".husky/pre-commit")
+ self.git(repo_root, "commit", "-m", "initial")
+
+ tracked.write_text("tracked updated\n", encoding="utf-8")
+
+ with patch("verify_commit_slice.REPO_ROOT", repo_root), patch(
+ "verify_commit_slice.HOOK_PATH", hook
+ ):
+ self.assertEqual(
+ main(["--add-updated", "explicit.txt", "ignored.txt"]),
+ 0,
+ )
+
+ self.assertEqual(
+ (repo_root / "slice.out").read_text(encoding="utf-8").splitlines(),
+ ["explicit.txt", "ignored.txt", "tracked.txt"],
+ )
+ live_index = self.git(repo_root, "diff", "--cached", "--name-only").stdout.strip()
+ self.assertEqual(live_index, "")
+
+ def test_main_propagates_hook_failure(self) -> None:
+ with tempfile.TemporaryDirectory() as tmpdir:
+ repo_root = Path(tmpdir)
+ hook = repo_root / ".husky" / "pre-commit"
+ tracked = repo_root / "tracked.txt"
+
+ hook.parent.mkdir(parents=True, exist_ok=True)
+ tracked.write_text("tracked\n", encoding="utf-8")
+ hook.write_text("#!/usr/bin/env bash\nexit 7\n", encoding="utf-8")
+ hook.chmod(0o755)
+
+ self.init_repo(repo_root)
+ self.git(repo_root, "add", "tracked.txt", ".husky/pre-commit")
+ self.git(repo_root, "commit", "--no-verify", "-m", "initial")
+
+ tracked.write_text("tracked updated\n", encoding="utf-8")
+
+ with patch("verify_commit_slice.REPO_ROOT", repo_root), patch(
+ "verify_commit_slice.HOOK_PATH", hook
+ ):
+ self.assertEqual(main(["--add-updated"]), 7)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release_control/internal/work_claim.py b/scripts/release_control/internal/work_claim.py
new file mode 100644
index 0000000000..e2619804e5
--- /dev/null
+++ b/scripts/release_control/internal/work_claim.py
@@ -0,0 +1,203 @@
+#!/usr/bin/env python3
+"""Create or reserve governed work claims against the active Pulse profile."""
+
+from __future__ import annotations
+
+import argparse
+from copy import deepcopy
+from datetime import datetime, timedelta, timezone
+import json
+import re
+import sys
+from pathlib import Path
+from typing import Any
+
+from control_plane import DEFAULT_CONTROL_PLANE
+from status_audit import audit_status_payload, load_status_payload, status_schema_contract
+
+
+STATUS_PATH = Path(DEFAULT_CONTROL_PLANE["status_path"])
+
+
+def _slug(value: str) -> str:
+ compact = re.sub(r"[^a-z0-9]+", "-", value.strip().lower())
+ compact = compact.strip("-")
+ return compact or "work"
+
+
+def _claim_sort_key(claim: dict[str, Any]) -> tuple[str, str]:
+ return (str(claim["claimed_at"]), str(claim["id"]).casefold())
+
+
+def build_work_claim(
+ *,
+ work_kind: str,
+ work_id: str,
+ summary: str,
+ agent_id: str,
+ target_id: str,
+ now_utc: datetime,
+ duration_hours: int,
+ claim_id: str | None = None,
+) -> dict[str, Any]:
+ claimed_at = now_utc.replace(microsecond=0)
+ expires_at = claimed_at + timedelta(hours=duration_hours)
+ claim_id = claim_id or f"claim-{_slug(work_kind)}-{_slug(work_id)}-{claimed_at.strftime('%Y%m%d%H%M%S')}"
+ timestamp = claimed_at.isoformat().replace("+00:00", "Z")
+ return {
+ "id": claim_id,
+ "agent_id": agent_id,
+ "summary": summary,
+ "target_id": target_id,
+ "claimed_at": timestamp,
+ "heartbeat_at": timestamp,
+ "expires_at": expires_at.replace(microsecond=0).isoformat().replace("+00:00", "Z"),
+ "work_item": {
+ "kind": work_kind,
+ "id": work_id,
+ },
+ }
+
+
+def apply_claim(
+ payload: dict[str, Any],
+ claim: dict[str, Any],
+ *,
+ replace_claim_ids: list[str],
+) -> dict[str, Any]:
+ updated = deepcopy(payload)
+ raw_claims = list(updated.get("work_claims", []))
+ raw_claims = [entry for entry in raw_claims if str(entry.get("id", "")) not in set(replace_claim_ids)]
+ raw_claims.append(claim)
+ raw_claims.sort(key=_claim_sort_key)
+ updated["work_claims"] = raw_claims
+ return updated
+
+
+def reserve_claim(
+ *,
+ payload: dict[str, Any],
+ work_kind: str,
+ work_id: str,
+ summary: str,
+ agent_id: str,
+ target_id: str | None,
+ duration_hours: int,
+ claim_id: str | None,
+ replace_claim_ids: list[str],
+ now_utc: datetime | None = None,
+) -> tuple[dict[str, Any], dict[str, Any], list[str]]:
+ baseline_report = audit_status_payload(payload, schema_contract=status_schema_contract())
+ baseline_errors = set(str(error) for error in baseline_report.get("errors", []))
+ now_utc = now_utc or datetime.now(timezone.utc)
+ target_id = target_id or str(DEFAULT_CONTROL_PLANE["active_target_id"])
+ claim = build_work_claim(
+ work_kind=work_kind,
+ work_id=work_id,
+ summary=summary,
+ agent_id=agent_id,
+ target_id=target_id,
+ now_utc=now_utc,
+ duration_hours=duration_hours,
+ claim_id=claim_id,
+ )
+ updated_payload = apply_claim(payload, claim, replace_claim_ids=replace_claim_ids)
+ updated_report = audit_status_payload(updated_payload, schema_contract=status_schema_contract())
+ new_errors = [str(error) for error in updated_report.get("errors", []) if str(error) not in baseline_errors]
+ return claim, updated_payload, new_errors
+
+
+def write_status_payload(payload: dict[str, Any], *, path: Path = STATUS_PATH) -> None:
+ path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
+
+
+def parse_args(argv: list[str]) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description="Create or reserve a governed work claim.")
+ parser.add_argument("--kind", required=True, help="Work item kind, such as lane or release-gate.")
+ parser.add_argument("--id", required=True, help="Work item id, such as L14.")
+ parser.add_argument("--summary", required=True, help="Short human summary for the claim.")
+ parser.add_argument("--agent-id", required=True, help="Stable agent identifier recorded in the claim.")
+ parser.add_argument("--target-id", help="Override the target id; defaults to the active target.")
+ parser.add_argument("--claim-id", help="Override the generated claim id.")
+ parser.add_argument(
+ "--duration-hours",
+ type=int,
+ default=2,
+ help="Claim duration before expiry. Defaults to 2 hours.",
+ )
+ parser.add_argument(
+ "--replace-claim-id",
+ action="append",
+ default=[],
+ help="Existing claim id to replace in the same write.",
+ )
+ parser.add_argument(
+ "--write",
+ action="store_true",
+ help="Write the updated work_claims list back to status.json when validation passes.",
+ )
+ parser.add_argument(
+ "--pretty",
+ action="store_true",
+ help="Render a concise human summary instead of JSON.",
+ )
+ return parser.parse_args(argv)
+
+
+def render_pretty(claim: dict[str, Any], errors: list[str], *, wrote: bool) -> str:
+ lines = [
+ "work_claim:",
+ f" id={claim['id']}",
+ f" target={claim['target_id']}",
+ f" work={claim['work_item']['kind']}:{claim['work_item']['id']}",
+ f" agent={claim['agent_id']}",
+ f" expires_at={claim['expires_at']}",
+ f" wrote={'yes' if wrote else 'no'}",
+ ]
+ if errors:
+ lines.append("errors:")
+ for error in errors:
+ lines.append(f" - {error}")
+ else:
+ lines.append("status: ready")
+ return "\n".join(lines)
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(list(argv or []))
+ payload = load_status_payload()
+ claim, updated_payload, errors = reserve_claim(
+ payload=payload,
+ work_kind=args.kind,
+ work_id=args.id,
+ summary=args.summary,
+ agent_id=args.agent_id,
+ target_id=args.target_id,
+ duration_hours=args.duration_hours,
+ claim_id=args.claim_id,
+ replace_claim_ids=list(args.replace_claim_id),
+ )
+ wrote = False
+ if not errors and args.write:
+ write_status_payload(updated_payload)
+ wrote = True
+
+ if args.pretty:
+ print(render_pretty(claim, errors, wrote=wrote))
+ else:
+ print(
+ json.dumps(
+ {
+ "claim": claim,
+ "errors": errors,
+ "wrote": wrote,
+ },
+ indent=2,
+ sort_keys=True,
+ )
+ )
+ return 1 if errors else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/release_control/internal/work_claim_test.py b/scripts/release_control/internal/work_claim_test.py
new file mode 100644
index 0000000000..4a3df4401e
--- /dev/null
+++ b/scripts/release_control/internal/work_claim_test.py
@@ -0,0 +1,98 @@
+import unittest
+from datetime import datetime, timezone
+from unittest.mock import patch
+
+from work_claim import apply_claim, build_work_claim, parse_args, reserve_claim
+
+
+class WorkClaimTest(unittest.TestCase):
+ def test_parse_args_accepts_write_and_replace(self) -> None:
+ args = parse_args(
+ [
+ "--kind",
+ "lane",
+ "--id",
+ "L14",
+ "--summary",
+ "Tighten trust proof routing.",
+ "--agent-id",
+ "codex-gpt5",
+ "--replace-claim-id",
+ "claim-old",
+ "--write",
+ "--pretty",
+ ]
+ )
+ self.assertEqual(args.kind, "lane")
+ self.assertEqual(args.id, "L14")
+ self.assertEqual(args.replace_claim_id, ["claim-old"])
+ self.assertTrue(args.write)
+ self.assertTrue(args.pretty)
+
+ def test_build_work_claim_uses_active_target_shape(self) -> None:
+ claim = build_work_claim(
+ work_kind="lane",
+ work_id="L14",
+ summary="Tighten trust proof routing.",
+ agent_id="codex-gpt5",
+ target_id="v6-rc-stabilization",
+ now_utc=datetime(2026, 3, 13, 18, 0, 0, tzinfo=timezone.utc),
+ duration_hours=2,
+ )
+ self.assertEqual(claim["target_id"], "v6-rc-stabilization")
+ self.assertEqual(claim["work_item"], {"kind": "lane", "id": "L14"})
+ self.assertEqual(claim["claimed_at"], "2026-03-13T18:00:00Z")
+ self.assertEqual(claim["heartbeat_at"], "2026-03-13T18:00:00Z")
+ self.assertEqual(claim["expires_at"], "2026-03-13T20:00:00Z")
+
+ def test_apply_claim_replaces_and_sorts(self) -> None:
+ payload = {
+ "work_claims": [
+ {
+ "id": "claim-b",
+ "claimed_at": "2026-03-13T10:00:00Z",
+ },
+ {
+ "id": "claim-a",
+ "claimed_at": "2026-03-13T09:00:00Z",
+ },
+ ]
+ }
+ claim = {
+ "id": "claim-c",
+ "claimed_at": "2026-03-13T08:00:00Z",
+ }
+ updated = apply_claim(payload, claim, replace_claim_ids=["claim-b"])
+ self.assertEqual([entry["id"] for entry in updated["work_claims"]], ["claim-c", "claim-a"])
+
+ def test_reserve_claim_reports_new_audit_errors_only(self) -> None:
+ payload = {"work_claims": [{"id": "claim-existing", "claimed_at": "2026-03-13T17:00:00Z"}]}
+ baseline_report = {"errors": ["unchanged baseline error"]}
+ updated_report = {
+ "errors": [
+ "unchanged baseline error",
+ "active work claims ['claim-existing', 'claim-lane-l14-20260313180000'] overlap on lane:L14",
+ ]
+ }
+ with patch("work_claim.audit_status_payload", side_effect=[baseline_report, updated_report]):
+ claim, _updated, errors = reserve_claim(
+ payload=payload,
+ work_kind="lane",
+ work_id="L14",
+ summary="Tighten trust proof routing.",
+ agent_id="codex-gpt5",
+ target_id="v6-rc-stabilization",
+ duration_hours=2,
+ claim_id="claim-lane-l14-20260313180000",
+ replace_claim_ids=[],
+ now_utc=datetime(2026, 3, 13, 18, 0, 0, tzinfo=timezone.utc),
+ )
+ self.assertEqual(claim["id"], "claim-lane-l14-20260313180000")
+ self.assertEqual(
+ errors,
+ ["active work claims ['claim-existing', 'claim-lane-l14-20260313180000'] overlap on lane:L14"],
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release_control/internal/worktree_base.py b/scripts/release_control/internal/worktree_base.py
new file mode 100644
index 0000000000..8184880e1b
--- /dev/null
+++ b/scripts/release_control/internal/worktree_base.py
@@ -0,0 +1,141 @@
+#!/usr/bin/env python3
+"""Ensure the canonical clean landing worktree exists for a base branch."""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+import subprocess
+import sys
+
+from repo_file_io import REPO_ROOT
+from worktree_claim import WORKTREES_ROOT, list_worktrees
+
+
+def git(*args: str, cwd: Path, check: bool = True) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ ["git", *args],
+ cwd=cwd,
+ check=check,
+ capture_output=True,
+ text=True,
+ )
+
+
+def base_slug(branch_name: str) -> str:
+ return "base__" + branch_name.replace("/", "__")
+
+
+def canonical_base_worktree_path(*, repo_root: Path, branch_name: str) -> Path:
+ return WORKTREES_ROOT / repo_root.name / base_slug(branch_name)
+
+
+def find_worktree_by_path(*, repo_root: Path, path: Path) -> dict[str, str] | None:
+ target = path.resolve()
+ for entry in list_worktrees(repo_root=repo_root):
+ if Path(entry.get("worktree", "")).resolve() == target:
+ return entry
+ return None
+
+
+def is_clean_worktree(*, repo_root: Path) -> bool:
+ return not git("status", "--porcelain", cwd=repo_root).stdout.strip()
+
+
+def create_base_worktree(*, repo_root: Path, branch_name: str, path: Path) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ subprocess.run(
+ ["git", "worktree", "add", str(path), branch_name],
+ cwd=repo_root,
+ check=True,
+ )
+
+
+def parse_args(argv: list[str]) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="Ensure the canonical clean landing worktree exists for a base branch."
+ )
+ parser.add_argument(
+ "--base-branch",
+ default="pulse/v6",
+ help="Base branch that should own the canonical landing worktree. Defaults to pulse/v6.",
+ )
+ parser.add_argument(
+ "--write",
+ action="store_true",
+ help="Create the canonical landing worktree if it does not exist and validation passes.",
+ )
+ parser.add_argument(
+ "--pretty",
+ action="store_true",
+ help="Render a concise human summary instead of JSON.",
+ )
+ return parser.parse_args(argv)
+
+
+def render_pretty(*, branch_name: str, path: Path, existed: bool, clean: bool, errors: list[str], wrote: bool) -> str:
+ lines = [
+ "worktree_base:",
+ f" base_branch={branch_name}",
+ f" path={path}",
+ f" existed={'yes' if existed else 'no'}",
+ f" clean={'yes' if clean else 'no'}",
+ f" wrote={'yes' if wrote else 'no'}",
+ ]
+ if errors:
+ lines.append("errors:")
+ for error in errors:
+ lines.append(f" - {error}")
+ else:
+ lines.append("status: ready")
+ return "\n".join(lines)
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(list(argv or []))
+ path = canonical_base_worktree_path(repo_root=REPO_ROOT, branch_name=args.base_branch)
+ entry = find_worktree_by_path(repo_root=REPO_ROOT, path=path)
+ errors: list[str] = []
+ existed = entry is not None
+ clean = False
+
+ if entry is not None:
+ branch_ref = entry.get("branch", "")
+ if branch_ref != f"refs/heads/{args.base_branch}":
+ errors.append(f"canonical landing worktree is not on {args.base_branch}: {branch_ref or 'detached'}")
+ clean = is_clean_worktree(repo_root=path)
+ if not clean:
+ errors.append(f"canonical landing worktree is dirty: {path}")
+ elif path.exists():
+ errors.append(f"canonical landing path exists on disk but is not a registered worktree: {path}")
+
+ wrote = False
+ if not errors and not existed and args.write:
+ create_base_worktree(repo_root=REPO_ROOT, branch_name=args.base_branch, path=path)
+ wrote = True
+ existed = True
+ clean = is_clean_worktree(repo_root=path)
+
+ if args.pretty:
+ print(render_pretty(branch_name=args.base_branch, path=path, existed=existed, clean=clean, errors=errors, wrote=wrote))
+ else:
+ print(
+ json.dumps(
+ {
+ "base_branch": args.base_branch,
+ "path": str(path),
+ "existed": existed,
+ "clean": clean,
+ "errors": errors,
+ "wrote": wrote,
+ },
+ indent=2,
+ sort_keys=True,
+ )
+ )
+ return 1 if errors else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/release_control/internal/worktree_base_test.py b/scripts/release_control/internal/worktree_base_test.py
new file mode 100644
index 0000000000..66cbabf437
--- /dev/null
+++ b/scripts/release_control/internal/worktree_base_test.py
@@ -0,0 +1,27 @@
+import tempfile
+import unittest
+from pathlib import Path
+
+from worktree_base import base_slug, canonical_base_worktree_path, parse_args
+
+
+class WorktreeBaseTest(unittest.TestCase):
+ def test_parse_args_accepts_write(self) -> None:
+ args = parse_args(["--base-branch", "pulse/v6", "--write", "--pretty"])
+ self.assertEqual(args.base_branch, "pulse/v6")
+ self.assertTrue(args.write)
+ self.assertTrue(args.pretty)
+
+ def test_base_slug_replaces_slashes(self) -> None:
+ self.assertEqual(base_slug("pulse/v6"), "base__pulse__v6")
+
+ def test_canonical_base_worktree_path_uses_workspace_root(self) -> None:
+ path = canonical_base_worktree_path(
+ repo_root=Path("/Volumes/Development/pulse/repos/pulse"),
+ branch_name="pulse/v6",
+ )
+ self.assertEqual(path, Path("/Volumes/Development/pulse/worktrees/pulse/base__pulse__v6"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release_control/internal/worktree_claim.py b/scripts/release_control/internal/worktree_claim.py
new file mode 100644
index 0000000000..a526ecf6e4
--- /dev/null
+++ b/scripts/release_control/internal/worktree_claim.py
@@ -0,0 +1,195 @@
+#!/usr/bin/env python3
+"""Reserve a governed slice and create an isolated git worktree for it."""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+import subprocess
+import sys
+from typing import Any
+
+from repo_file_io import REPO_ROOT
+from work_claim import reserve_claim, write_status_payload, _slug
+
+
+WORKSPACE_ROOT = REPO_ROOT.parents[1]
+WORKTREES_ROOT = WORKSPACE_ROOT / "worktrees"
+DEFAULT_BASE_BRANCH = "pulse/v6"
+
+
+def build_branch_name(*, agent_id: str, work_kind: str, work_id: str) -> str:
+ return f"pulse/{_slug(agent_id)}/{_slug(work_kind)}-{_slug(work_id)}"
+
+
+def branch_path_slug(branch_name: str) -> str:
+ if branch_name.startswith("pulse/"):
+ branch_name = branch_name[len("pulse/") :]
+ return branch_name.replace("/", "__")
+
+
+def build_worktree_path(*, repo_root: Path, branch_name: str) -> Path:
+ return WORKTREES_ROOT / repo_root.name / branch_path_slug(branch_name)
+
+
+def parse_worktree_list(output: str) -> list[dict[str, str]]:
+ entries: list[dict[str, str]] = []
+ current: dict[str, str] = {}
+ for line in output.splitlines():
+ if not line.strip():
+ if current:
+ entries.append(current)
+ current = {}
+ continue
+ key, _, value = line.partition(" ")
+ current[key] = value
+ if current:
+ entries.append(current)
+ return entries
+
+
+def list_worktrees(*, repo_root: Path = REPO_ROOT) -> list[dict[str, str]]:
+ result = subprocess.run(
+ ["git", "worktree", "list", "--porcelain"],
+ cwd=repo_root,
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ return parse_worktree_list(result.stdout)
+
+
+def validate_worktree_target(*, repo_root: Path, branch_name: str, path: Path) -> list[str]:
+ errors: list[str] = []
+ path = path.resolve()
+ for entry in list_worktrees(repo_root=repo_root):
+ existing_path = Path(entry.get("worktree", "")).resolve()
+ branch_ref = entry.get("branch", "")
+ if existing_path == path:
+ errors.append(f"worktree path already exists in git worktree list: {path}")
+ if branch_ref == f"refs/heads/{branch_name}":
+ errors.append(f"branch already checked out in another worktree: {branch_name}")
+ if path.exists():
+ errors.append(f"worktree path already exists on disk: {path}")
+ return errors
+
+
+def create_worktree(*, repo_root: Path, path: Path, branch_name: str, base_branch: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ subprocess.run(
+ ["git", "worktree", "add", "-b", branch_name, str(path), base_branch],
+ cwd=repo_root,
+ check=True,
+ )
+
+
+def render_pretty(*, claim: dict[str, Any], branch_name: str, path: Path, errors: list[str], wrote: bool) -> str:
+ lines = [
+ "worktree_claim:",
+ f" claim_id={claim['id']}",
+ f" target={claim['target_id']}",
+ f" work={claim['work_item']['kind']}:{claim['work_item']['id']}",
+ f" agent={claim['agent_id']}",
+ f" branch={branch_name}",
+ f" path={path}",
+ f" wrote={'yes' if wrote else 'no'}",
+ ]
+ if errors:
+ lines.append("errors:")
+ for error in errors:
+ lines.append(f" - {error}")
+ else:
+ lines.append("status: ready")
+ return "\n".join(lines)
+
+
+def parse_args(argv: list[str]) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="Reserve a governed slice and create an isolated git worktree for it."
+ )
+ parser.add_argument("--kind", required=True, help="Work item kind, such as lane or release-gate.")
+ parser.add_argument("--id", required=True, help="Work item id, such as L15.")
+ parser.add_argument("--summary", required=True, help="Short human summary for the claim.")
+ parser.add_argument("--agent-id", required=True, help="Stable agent identifier recorded in the claim.")
+ parser.add_argument("--target-id", help="Override the target id; defaults to the active target.")
+ parser.add_argument("--claim-id", help="Override the generated claim id.")
+ parser.add_argument("--branch", help="Override the generated branch name.")
+ parser.add_argument("--path", help="Override the generated worktree path.")
+ parser.add_argument("--base-branch", default=DEFAULT_BASE_BRANCH, help="Base branch for the new worktree.")
+ parser.add_argument(
+ "--duration-hours",
+ type=int,
+ default=2,
+ help="Claim duration before expiry. Defaults to 2 hours.",
+ )
+ parser.add_argument(
+ "--replace-claim-id",
+ action="append",
+ default=[],
+ help="Existing claim id to replace in the same write.",
+ )
+ parser.add_argument(
+ "--write",
+ action="store_true",
+ help="Write the updated work_claims list and create the worktree when validation passes.",
+ )
+ parser.add_argument(
+ "--pretty",
+ action="store_true",
+ help="Render a concise human summary instead of JSON.",
+ )
+ return parser.parse_args(argv)
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(list(argv or []))
+ from status_audit import load_status_payload
+
+ payload = load_status_payload()
+ claim, updated_payload, errors = reserve_claim(
+ payload=payload,
+ work_kind=args.kind,
+ work_id=args.id,
+ summary=args.summary,
+ agent_id=args.agent_id,
+ target_id=args.target_id,
+ duration_hours=args.duration_hours,
+ claim_id=args.claim_id,
+ replace_claim_ids=list(args.replace_claim_id),
+ )
+ branch_name = args.branch or build_branch_name(
+ agent_id=args.agent_id,
+ work_kind=args.kind,
+ work_id=args.id,
+ )
+ path = Path(args.path) if args.path else build_worktree_path(repo_root=REPO_ROOT, branch_name=branch_name)
+ errors.extend(validate_worktree_target(repo_root=REPO_ROOT, branch_name=branch_name, path=path))
+
+ wrote = False
+ if not errors and args.write:
+ write_status_payload(updated_payload)
+ create_worktree(repo_root=REPO_ROOT, path=path, branch_name=branch_name, base_branch=args.base_branch)
+ wrote = True
+
+ if args.pretty:
+ print(render_pretty(claim=claim, branch_name=branch_name, path=path, errors=errors, wrote=wrote))
+ else:
+ print(
+ json.dumps(
+ {
+ "claim": claim,
+ "branch": branch_name,
+ "path": str(path),
+ "errors": errors,
+ "wrote": wrote,
+ },
+ indent=2,
+ sort_keys=True,
+ )
+ )
+ return 1 if errors else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/release_control/internal/worktree_claim_test.py b/scripts/release_control/internal/worktree_claim_test.py
new file mode 100644
index 0000000000..fe161a480b
--- /dev/null
+++ b/scripts/release_control/internal/worktree_claim_test.py
@@ -0,0 +1,100 @@
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from worktree_claim import (
+ branch_path_slug,
+ build_branch_name,
+ build_worktree_path,
+ parse_args,
+ parse_worktree_list,
+ validate_worktree_target,
+)
+
+
+class WorktreeClaimTest(unittest.TestCase):
+ def test_parse_args_accepts_write_and_overrides(self) -> None:
+ args = parse_args(
+ [
+ "--kind",
+ "lane",
+ "--id",
+ "L15",
+ "--summary",
+ "Tighten storage recovery coherence.",
+ "--agent-id",
+ "claude-code",
+ "--branch",
+ "pulse/claude-code/lane-l15",
+ "--path",
+ "/tmp/pulse-l15",
+ "--write",
+ "--pretty",
+ ]
+ )
+ self.assertEqual(args.kind, "lane")
+ self.assertEqual(args.id, "L15")
+ self.assertEqual(args.branch, "pulse/claude-code/lane-l15")
+ self.assertEqual(args.path, "/tmp/pulse-l15")
+ self.assertTrue(args.write)
+ self.assertTrue(args.pretty)
+
+ def test_build_branch_name_uses_pulse_prefix(self) -> None:
+ self.assertEqual(
+ build_branch_name(agent_id="Claude Code", work_kind="lane", work_id="L15"),
+ "pulse/claude-code/lane-l15",
+ )
+
+ def test_build_worktree_path_uses_workspace_root(self) -> None:
+ path = build_worktree_path(
+ repo_root=Path("/Volumes/Development/pulse/repos/pulse"),
+ branch_name="pulse/claude-code/lane-l15",
+ )
+ self.assertEqual(
+ path,
+ Path("/Volumes/Development/pulse/worktrees/pulse/claude-code__lane-l15"),
+ )
+
+ def test_branch_path_slug_drops_prefix_and_replaces_slashes(self) -> None:
+ self.assertEqual(branch_path_slug("pulse/codex-gpt5/lane-l16"), "codex-gpt5__lane-l16")
+
+ def test_parse_worktree_list_reads_porcelain_records(self) -> None:
+ entries = parse_worktree_list(
+ "worktree /tmp/pulse-main\nHEAD abc123\nbranch refs/heads/pulse/v6\n\n"
+ "worktree /tmp/pulse-l15\nHEAD def456\nbranch refs/heads/pulse/claude/lane-l15\n\n"
+ )
+ self.assertEqual(len(entries), 2)
+ self.assertEqual(entries[1]["worktree"], "/tmp/pulse-l15")
+ self.assertEqual(entries[1]["branch"], "refs/heads/pulse/claude/lane-l15")
+
+ def test_validate_worktree_target_rejects_existing_branch_or_path(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ existing = Path(tmp) / "existing"
+ existing.mkdir()
+ with patch(
+ "worktree_claim.list_worktrees",
+ return_value=[
+ {
+ "worktree": str(existing),
+ "branch": "refs/heads/pulse/claude-code/lane-l15",
+ }
+ ],
+ ):
+ errors = validate_worktree_target(
+ repo_root=Path("/Volumes/Development/pulse/repos/pulse"),
+ branch_name="pulse/claude-code/lane-l15",
+ path=existing,
+ )
+ self.assertEqual(
+ errors,
+ [
+ f"worktree path already exists in git worktree list: {existing.resolve()}",
+ "branch already checked out in another worktree: pulse/claude-code/lane-l15",
+ f"worktree path already exists on disk: {existing.resolve()}",
+ ],
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release_control/internal/worktree_finish.py b/scripts/release_control/internal/worktree_finish.py
new file mode 100644
index 0000000000..3d5898c331
--- /dev/null
+++ b/scripts/release_control/internal/worktree_finish.py
@@ -0,0 +1,190 @@
+#!/usr/bin/env python3
+"""Land an isolated worktree's finished slice onto the base branch worktree."""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+import subprocess
+import sys
+from typing import Any
+
+from repo_file_io import REPO_ROOT
+from worktree_base import canonical_base_worktree_path
+from worktree_claim import list_worktrees
+
+
+def git(*args: str, cwd: Path, check: bool = True) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ ["git", *args],
+ cwd=cwd,
+ check=check,
+ capture_output=True,
+ text=True,
+ )
+
+
+def current_branch(*, repo_root: Path) -> str:
+ return git("branch", "--show-current", cwd=repo_root).stdout.strip()
+
+
+def current_head(*, repo_root: Path) -> str:
+ return git("rev-parse", "HEAD", cwd=repo_root).stdout.strip()
+
+
+def is_clean_worktree(*, repo_root: Path) -> bool:
+ return not git("status", "--porcelain", cwd=repo_root).stdout.strip()
+
+
+def branch_worktree_path(*, repo_root: Path, branch_name: str, preferred_path: Path | None = None) -> Path | None:
+ preferred = preferred_path.resolve() if preferred_path is not None else None
+ fallback: Path | None = None
+ for entry in list_worktrees(repo_root=repo_root):
+ if entry.get("branch") != f"refs/heads/{branch_name}":
+ continue
+ candidate = Path(entry["worktree"]).resolve()
+ if preferred is not None and candidate == preferred:
+ return candidate
+ if fallback is None:
+ fallback = candidate
+ return fallback
+
+
+def commits_ahead_of_base(*, repo_root: Path, base_branch: str) -> list[str]:
+ output = git("rev-list", "--reverse", f"{base_branch}..HEAD", cwd=repo_root).stdout.strip()
+ return [line for line in output.splitlines() if line.strip()]
+
+
+def cherry_pick_commits(*, base_worktree: Path, commits: list[str]) -> None:
+ for commit in commits:
+ subprocess.run(["git", "cherry-pick", commit], cwd=base_worktree, check=True)
+
+
+def parse_args(argv: list[str]) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="Land an isolated worktree's finished slice onto the base branch worktree."
+ )
+ parser.add_argument(
+ "--base-branch",
+ default="pulse/v6",
+ help="Base branch that receives the finished slice. Defaults to pulse/v6.",
+ )
+ parser.add_argument(
+ "--write",
+ action="store_true",
+ help="Cherry-pick the finished commit(s) onto the base branch worktree when validation passes.",
+ )
+ parser.add_argument(
+ "--pretty",
+ action="store_true",
+ help="Render a concise human summary instead of JSON.",
+ )
+ return parser.parse_args(argv)
+
+
+def render_pretty(
+ *,
+ current_worktree: Path,
+ current_branch_name: str,
+ base_branch: str,
+ base_worktree: Path | None,
+ commits: list[str],
+ errors: list[str],
+ wrote: bool,
+) -> str:
+ lines = [
+ "worktree_finish:",
+ f" current_worktree={current_worktree}",
+ f" current_branch={current_branch_name}",
+ f" base_branch={base_branch}",
+ f" base_worktree={base_worktree if base_worktree is not None else 'missing'}",
+ f" commit_count={len(commits)}",
+ f" wrote={'yes' if wrote else 'no'}",
+ ]
+ if commits:
+ lines.append("commits:")
+ for commit in commits:
+ lines.append(f" - {commit}")
+ if errors:
+ lines.append("errors:")
+ for error in errors:
+ lines.append(f" - {error}")
+ else:
+ lines.append("status: ready")
+ return "\n".join(lines)
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = parse_args(list(argv or []))
+ errors: list[str] = []
+ current_worktree = REPO_ROOT.resolve()
+ current_branch_name = current_branch(repo_root=current_worktree)
+ preferred_base = canonical_base_worktree_path(repo_root=current_worktree, branch_name=args.base_branch)
+ base_worktree = branch_worktree_path(
+ repo_root=current_worktree, branch_name=args.base_branch, preferred_path=preferred_base
+ )
+
+ if not current_branch_name:
+ errors.append("current worktree is not on a branch")
+ if current_branch_name == args.base_branch:
+ errors.append("current worktree is already on the base branch")
+ if base_worktree is None:
+ errors.append(
+ f"no canonical landing worktree found for base branch {args.base_branch}; run worktree_base.py first"
+ )
+ elif base_worktree == current_worktree:
+ errors.append("base branch worktree resolves to the current worktree")
+ elif base_worktree != preferred_base.resolve():
+ errors.append(
+ f"base branch is checked out at {base_worktree}, not at canonical landing path {preferred_base.resolve()}"
+ )
+
+ commits: list[str] = []
+ if not errors:
+ commits = commits_ahead_of_base(repo_root=current_worktree, base_branch=args.base_branch)
+ if not commits:
+ errors.append(f"no commits ahead of {args.base_branch} to land")
+ if not is_clean_worktree(repo_root=current_worktree):
+ errors.append("current worktree has uncommitted changes")
+ if base_worktree is not None and not is_clean_worktree(repo_root=base_worktree):
+ errors.append(f"base worktree is dirty: {base_worktree}")
+
+ wrote = False
+ if not errors and args.write and base_worktree is not None:
+ cherry_pick_commits(base_worktree=base_worktree, commits=commits)
+ wrote = True
+
+ if args.pretty:
+ print(
+ render_pretty(
+ current_worktree=current_worktree,
+ current_branch_name=current_branch_name,
+ base_branch=args.base_branch,
+ base_worktree=base_worktree,
+ commits=commits,
+ errors=errors,
+ wrote=wrote,
+ )
+ )
+ else:
+ print(
+ json.dumps(
+ {
+ "current_worktree": str(current_worktree),
+ "current_branch": current_branch_name,
+ "base_branch": args.base_branch,
+ "base_worktree": str(base_worktree) if base_worktree is not None else None,
+ "commits": commits,
+ "errors": errors,
+ "wrote": wrote,
+ },
+ indent=2,
+ sort_keys=True,
+ )
+ )
+ return 1 if errors else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/release_control/internal/worktree_finish_test.py b/scripts/release_control/internal/worktree_finish_test.py
new file mode 100644
index 0000000000..202afda401
--- /dev/null
+++ b/scripts/release_control/internal/worktree_finish_test.py
@@ -0,0 +1,47 @@
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from worktree_finish import commits_ahead_of_base, parse_args, render_pretty
+
+
+class WorktreeFinishTest(unittest.TestCase):
+ def test_parse_args_accepts_write_and_base_branch(self) -> None:
+ args = parse_args(["--base-branch", "pulse/v6", "--write", "--pretty"])
+ self.assertEqual(args.base_branch, "pulse/v6")
+ self.assertTrue(args.write)
+ self.assertTrue(args.pretty)
+
+ def test_commits_ahead_of_base_splits_rev_list_output(self) -> None:
+ with patch(
+ "worktree_finish.git",
+ return_value=type("Result", (), {"stdout": "abc123\ndef456\n"})(),
+ ):
+ self.assertEqual(
+ commits_ahead_of_base(
+ repo_root=Path("/Volumes/Development/pulse/repos/pulse"),
+ base_branch="pulse/v6",
+ ),
+ ["abc123", "def456"],
+ )
+
+ def test_render_pretty_includes_commit_count_and_errors(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ worktree = Path(tmp) / "source"
+ base = Path(tmp) / "base"
+ output = render_pretty(
+ current_worktree=worktree,
+ current_branch_name="pulse/claude-code/lane-l15",
+ base_branch="pulse/v6",
+ base_worktree=base,
+ commits=["abc123"],
+ errors=["base worktree is dirty"],
+ wrote=False,
+ )
+ self.assertIn("commit_count=1", output)
+ self.assertIn("base worktree is dirty", output)
+
+
+if __name__ == "__main__":
+ unittest.main()