@memnexus-ai/mx-agent-cli 0.1.294 → 0.1.295-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/__tests__/agents-md-canonicalization.test.js +31 -1
- package/dist/__tests__/agents-md-canonicalization.test.js.map +1 -1
- package/dist/__tests__/behavioral-extraction.test.js +50 -0
- package/dist/__tests__/behavioral-extraction.test.js.map +1 -1
- package/dist/__tests__/bootstrap-behavioral-contract.test.js +6 -3
- package/dist/__tests__/bootstrap-behavioral-contract.test.js.map +1 -1
- package/dist/__tests__/bundle-config.test.js +28 -2
- package/dist/__tests__/bundle-config.test.js.map +1 -1
- package/dist/__tests__/catalog-interaction.test.d.ts +25 -0
- package/dist/__tests__/catalog-interaction.test.d.ts.map +1 -0
- package/dist/__tests__/catalog-interaction.test.js +269 -0
- package/dist/__tests__/catalog-interaction.test.js.map +1 -0
- package/dist/__tests__/catalog-named-memories.test.d.ts +2 -0
- package/dist/__tests__/catalog-named-memories.test.d.ts.map +1 -0
- package/dist/__tests__/catalog-named-memories.test.js +204 -0
- package/dist/__tests__/catalog-named-memories.test.js.map +1 -0
- package/dist/__tests__/catalog-origin-main.test.d.ts +15 -0
- package/dist/__tests__/catalog-origin-main.test.d.ts.map +1 -0
- package/dist/__tests__/catalog-origin-main.test.js +296 -0
- package/dist/__tests__/catalog-origin-main.test.js.map +1 -0
- package/dist/__tests__/catalog.test.d.ts +2 -0
- package/dist/__tests__/catalog.test.d.ts.map +1 -0
- package/dist/__tests__/catalog.test.js +131 -0
- package/dist/__tests__/catalog.test.js.map +1 -0
- package/dist/__tests__/cli-build-integration.test.d.ts +2 -0
- package/dist/__tests__/cli-build-integration.test.d.ts.map +1 -0
- package/dist/__tests__/cli-build-integration.test.js +64 -0
- package/dist/__tests__/cli-build-integration.test.js.map +1 -0
- package/dist/__tests__/cli-build.test.d.ts +2 -0
- package/dist/__tests__/cli-build.test.d.ts.map +1 -0
- package/dist/__tests__/cli-build.test.js +640 -0
- package/dist/__tests__/cli-build.test.js.map +1 -0
- package/dist/__tests__/codex-deploy-config.test.js +60 -0
- package/dist/__tests__/codex-deploy-config.test.js.map +1 -1
- package/dist/__tests__/completion-rows-discriminate.test.d.ts +20 -0
- package/dist/__tests__/completion-rows-discriminate.test.d.ts.map +1 -0
- package/dist/__tests__/completion-rows-discriminate.test.js +481 -0
- package/dist/__tests__/completion-rows-discriminate.test.js.map +1 -0
- package/dist/__tests__/config-fidelity-archived-symlinks.test.d.ts +2 -0
- package/dist/__tests__/config-fidelity-archived-symlinks.test.d.ts.map +1 -0
- package/dist/__tests__/config-fidelity-archived-symlinks.test.js +127 -0
- package/dist/__tests__/config-fidelity-archived-symlinks.test.js.map +1 -0
- package/dist/__tests__/config-fidelity-display.test.d.ts +2 -0
- package/dist/__tests__/config-fidelity-display.test.d.ts.map +1 -0
- package/dist/__tests__/config-fidelity-display.test.js +77 -0
- package/dist/__tests__/config-fidelity-display.test.js.map +1 -0
- package/dist/__tests__/config-fidelity.test.js +166 -33
- package/dist/__tests__/config-fidelity.test.js.map +1 -1
- package/dist/__tests__/config-generation-gate.test.js +78 -0
- package/dist/__tests__/config-generation-gate.test.js.map +1 -1
- package/dist/__tests__/config-sync.test.js +89 -1
- package/dist/__tests__/config-sync.test.js.map +1 -1
- package/dist/__tests__/coordination-401-production-wiring.test.js +12 -7
- package/dist/__tests__/coordination-401-production-wiring.test.js.map +1 -1
- package/dist/__tests__/coordination-401-recovery.test.js +39 -32
- package/dist/__tests__/coordination-401-recovery.test.js.map +1 -1
- package/dist/__tests__/coordination-brief-pin.test.js +21 -8
- package/dist/__tests__/coordination-brief-pin.test.js.map +1 -1
- package/dist/__tests__/coordination-client.test.js +227 -3
- package/dist/__tests__/coordination-client.test.js.map +1 -1
- package/dist/__tests__/coordination-credential-endpoint.test.d.ts +24 -0
- package/dist/__tests__/coordination-credential-endpoint.test.d.ts.map +1 -0
- package/dist/__tests__/coordination-credential-endpoint.test.js +1230 -0
- package/dist/__tests__/coordination-credential-endpoint.test.js.map +1 -0
- package/dist/__tests__/coordination-memory.test.js +20 -4
- package/dist/__tests__/coordination-memory.test.js.map +1 -1
- package/dist/__tests__/coordination-provision.test.js +22 -14
- package/dist/__tests__/coordination-provision.test.js.map +1 -1
- package/dist/__tests__/coordination-status-registration.test.d.ts +16 -0
- package/dist/__tests__/coordination-status-registration.test.d.ts.map +1 -0
- package/dist/__tests__/coordination-status-registration.test.js +480 -0
- package/dist/__tests__/coordination-status-registration.test.js.map +1 -0
- package/dist/__tests__/coordination-token-multitenant.test.js +11 -11
- package/dist/__tests__/coordination-token-multitenant.test.js.map +1 -1
- package/dist/__tests__/coordination-token.test.js +35 -28
- package/dist/__tests__/coordination-token.test.js.map +1 -1
- package/dist/__tests__/creation-pr-class-check.test.d.ts +17 -0
- package/dist/__tests__/creation-pr-class-check.test.d.ts.map +1 -0
- package/dist/__tests__/creation-pr-class-check.test.js +346 -0
- package/dist/__tests__/creation-pr-class-check.test.js.map +1 -0
- package/dist/__tests__/decision-check.test.d.ts +2 -0
- package/dist/__tests__/decision-check.test.d.ts.map +1 -0
- package/dist/__tests__/decision-check.test.js +105 -0
- package/dist/__tests__/decision-check.test.js.map +1 -0
- package/dist/__tests__/digest-team-omission.test.d.ts +15 -0
- package/dist/__tests__/digest-team-omission.test.d.ts.map +1 -0
- package/dist/__tests__/digest-team-omission.test.js +247 -0
- package/dist/__tests__/digest-team-omission.test.js.map +1 -0
- package/dist/__tests__/doctor-worktree-path.test.d.ts +17 -0
- package/dist/__tests__/doctor-worktree-path.test.d.ts.map +1 -0
- package/dist/__tests__/doctor-worktree-path.test.js +158 -0
- package/dist/__tests__/doctor-worktree-path.test.js.map +1 -0
- package/dist/__tests__/fleet-data.test.js +40 -7
- package/dist/__tests__/fleet-data.test.js.map +1 -1
- package/dist/__tests__/fleet-tmux.test.js +2 -2
- package/dist/__tests__/fleet-tmux.test.js.map +1 -1
- package/dist/__tests__/generate-claude.test.js +137 -3
- package/dist/__tests__/generate-claude.test.js.map +1 -1
- package/dist/__tests__/git-env.test.d.ts +14 -0
- package/dist/__tests__/git-env.test.d.ts.map +1 -0
- package/dist/__tests__/git-env.test.js +131 -0
- package/dist/__tests__/git-env.test.js.map +1 -0
- package/dist/__tests__/git-identity-isolation.test.d.ts +33 -0
- package/dist/__tests__/git-identity-isolation.test.d.ts.map +1 -0
- package/dist/__tests__/git-identity-isolation.test.js +626 -0
- package/dist/__tests__/git-identity-isolation.test.js.map +1 -0
- package/dist/__tests__/harness-extract.test.d.ts +19 -0
- package/dist/__tests__/harness-extract.test.d.ts.map +1 -0
- package/dist/__tests__/harness-extract.test.js +566 -0
- package/dist/__tests__/harness-extract.test.js.map +1 -0
- package/dist/__tests__/harness-wiring.test.d.ts +16 -0
- package/dist/__tests__/harness-wiring.test.d.ts.map +1 -0
- package/dist/__tests__/harness-wiring.test.js +469 -0
- package/dist/__tests__/harness-wiring.test.js.map +1 -0
- package/dist/__tests__/hook-heal.test.js +17 -0
- package/dist/__tests__/hook-heal.test.js.map +1 -1
- package/dist/__tests__/init-coordination-url.test.d.ts +11 -0
- package/dist/__tests__/init-coordination-url.test.d.ts.map +1 -0
- package/dist/__tests__/init-coordination-url.test.js +114 -0
- package/dist/__tests__/init-coordination-url.test.js.map +1 -0
- package/dist/__tests__/memory-autocreate.test.js +574 -8
- package/dist/__tests__/memory-autocreate.test.js.map +1 -1
- package/dist/__tests__/memory-log-result.test.d.ts +13 -0
- package/dist/__tests__/memory-log-result.test.d.ts.map +1 -0
- package/dist/__tests__/memory-log-result.test.js +113 -0
- package/dist/__tests__/memory-log-result.test.js.map +1 -0
- package/dist/__tests__/memory-named-exists.test.d.ts +16 -0
- package/dist/__tests__/memory-named-exists.test.d.ts.map +1 -0
- package/dist/__tests__/memory-named-exists.test.js +288 -0
- package/dist/__tests__/memory-named-exists.test.js.map +1 -0
- package/dist/__tests__/mx-agent-cli-pin-validation.test.js +23 -47
- package/dist/__tests__/mx-agent-cli-pin-validation.test.js.map +1 -1
- package/dist/__tests__/mx-agent-cli-version-pin.test.js +34 -88
- package/dist/__tests__/mx-agent-cli-version-pin.test.js.map +1 -1
- package/dist/__tests__/new-project-first-team.test.d.ts +15 -0
- package/dist/__tests__/new-project-first-team.test.d.ts.map +1 -0
- package/dist/__tests__/new-project-first-team.test.js +263 -0
- package/dist/__tests__/new-project-first-team.test.js.map +1 -0
- package/dist/__tests__/otel-env.test.d.ts +2 -0
- package/dist/__tests__/otel-env.test.d.ts.map +1 -0
- package/dist/__tests__/otel-env.test.js +127 -0
- package/dist/__tests__/otel-env.test.js.map +1 -0
- package/dist/__tests__/project-config.test.js +283 -1
- package/dist/__tests__/project-config.test.js.map +1 -1
- package/dist/__tests__/provision-behavioral-contract.test.js +96 -4
- package/dist/__tests__/provision-behavioral-contract.test.js.map +1 -1
- package/dist/__tests__/provision-catalog-precondition.test.d.ts +26 -0
- package/dist/__tests__/provision-catalog-precondition.test.d.ts.map +1 -0
- package/dist/__tests__/provision-catalog-precondition.test.js +620 -0
- package/dist/__tests__/provision-catalog-precondition.test.js.map +1 -0
- package/dist/__tests__/provision-completion-rows.test.d.ts +17 -0
- package/dist/__tests__/provision-completion-rows.test.d.ts.map +1 -0
- package/dist/__tests__/provision-completion-rows.test.js +3095 -0
- package/dist/__tests__/provision-completion-rows.test.js.map +1 -0
- package/dist/__tests__/provision-identity-gate.test.d.ts +20 -0
- package/dist/__tests__/provision-identity-gate.test.d.ts.map +1 -0
- package/dist/__tests__/provision-identity-gate.test.js +600 -0
- package/dist/__tests__/provision-identity-gate.test.js.map +1 -0
- package/dist/__tests__/provision-resume.test.d.ts +26 -0
- package/dist/__tests__/provision-resume.test.d.ts.map +1 -0
- package/dist/__tests__/provision-resume.test.js +1164 -0
- package/dist/__tests__/provision-resume.test.js.map +1 -0
- package/dist/__tests__/provision-roleguide-anchors.test.d.ts +27 -0
- package/dist/__tests__/provision-roleguide-anchors.test.d.ts.map +1 -0
- package/dist/__tests__/provision-roleguide-anchors.test.js +747 -0
- package/dist/__tests__/provision-roleguide-anchors.test.js.map +1 -0
- package/dist/__tests__/provision-skeleton-fill.test.d.ts +16 -0
- package/dist/__tests__/provision-skeleton-fill.test.d.ts.map +1 -0
- package/dist/__tests__/provision-skeleton-fill.test.js +488 -0
- package/dist/__tests__/provision-skeleton-fill.test.js.map +1 -0
- package/dist/__tests__/provision-teambuilder-flow.test.js +93 -7
- package/dist/__tests__/provision-teambuilder-flow.test.js.map +1 -1
- package/dist/__tests__/repo-guard-wiring.test.d.ts +21 -0
- package/dist/__tests__/repo-guard-wiring.test.d.ts.map +1 -0
- package/dist/__tests__/repo-guard-wiring.test.js +638 -0
- package/dist/__tests__/repo-guard-wiring.test.js.map +1 -0
- package/dist/__tests__/report-format.test.d.ts +2 -0
- package/dist/__tests__/report-format.test.d.ts.map +1 -0
- package/dist/__tests__/report-format.test.js +219 -0
- package/dist/__tests__/report-format.test.js.map +1 -0
- package/dist/__tests__/runtime-codex-gateway-pilot.test.d.ts +2 -0
- package/dist/__tests__/runtime-codex-gateway-pilot.test.d.ts.map +1 -0
- package/dist/__tests__/runtime-codex-gateway-pilot.test.js +309 -0
- package/dist/__tests__/runtime-codex-gateway-pilot.test.js.map +1 -0
- package/dist/__tests__/runtime-codex-gateway-provider.test.d.ts +2 -0
- package/dist/__tests__/runtime-codex-gateway-provider.test.d.ts.map +1 -0
- package/dist/__tests__/runtime-codex-gateway-provider.test.js +163 -0
- package/dist/__tests__/runtime-codex-gateway-provider.test.js.map +1 -0
- package/dist/__tests__/runtime-identity.test.d.ts +2 -0
- package/dist/__tests__/runtime-identity.test.d.ts.map +1 -0
- package/dist/__tests__/runtime-identity.test.js +117 -0
- package/dist/__tests__/runtime-identity.test.js.map +1 -0
- package/dist/__tests__/session-pause-provisioning.test.js +6 -1
- package/dist/__tests__/session-pause-provisioning.test.js.map +1 -1
- package/dist/__tests__/session-record-disclosure.test.d.ts +24 -0
- package/dist/__tests__/session-record-disclosure.test.d.ts.map +1 -0
- package/dist/__tests__/session-record-disclosure.test.js +494 -0
- package/dist/__tests__/session-record-disclosure.test.js.map +1 -0
- package/dist/__tests__/session.test.js +35 -0
- package/dist/__tests__/session.test.js.map +1 -1
- package/dist/__tests__/slug-validation.test.js +27 -21
- package/dist/__tests__/slug-validation.test.js.map +1 -1
- package/dist/__tests__/standards-injection.test.d.ts +2 -0
- package/dist/__tests__/standards-injection.test.d.ts.map +1 -0
- package/dist/__tests__/standards-injection.test.js +179 -0
- package/dist/__tests__/standards-injection.test.js.map +1 -0
- package/dist/__tests__/start-interactive-role.test.d.ts +22 -0
- package/dist/__tests__/start-interactive-role.test.d.ts.map +1 -0
- package/dist/__tests__/start-interactive-role.test.js +204 -0
- package/dist/__tests__/start-interactive-role.test.js.map +1 -0
- package/dist/__tests__/start-team-identity.test.d.ts +25 -0
- package/dist/__tests__/start-team-identity.test.d.ts.map +1 -0
- package/dist/__tests__/start-team-identity.test.js +307 -0
- package/dist/__tests__/start-team-identity.test.js.map +1 -0
- package/dist/__tests__/team-memory-commands.test.js +142 -19
- package/dist/__tests__/team-memory-commands.test.js.map +1 -1
- package/dist/__tests__/template-sync.test.d.ts +19 -0
- package/dist/__tests__/template-sync.test.d.ts.map +1 -0
- package/dist/__tests__/template-sync.test.js +270 -0
- package/dist/__tests__/template-sync.test.js.map +1 -0
- package/dist/__tests__/test-project.test.d.ts +18 -0
- package/dist/__tests__/test-project.test.d.ts.map +1 -0
- package/dist/__tests__/test-project.test.js +465 -0
- package/dist/__tests__/test-project.test.js.map +1 -0
- package/dist/__tests__/usage-per-call-grouping.test.d.ts +25 -0
- package/dist/__tests__/usage-per-call-grouping.test.d.ts.map +1 -0
- package/dist/__tests__/usage-per-call-grouping.test.js +952 -0
- package/dist/__tests__/usage-per-call-grouping.test.js.map +1 -0
- package/dist/__tests__/verify-hooks-check-all.test.d.ts +32 -0
- package/dist/__tests__/verify-hooks-check-all.test.d.ts.map +1 -0
- package/dist/__tests__/verify-hooks-check-all.test.js +553 -0
- package/dist/__tests__/verify-hooks-check-all.test.js.map +1 -0
- package/dist/__tests__/worktree-sync-fixture.test.d.ts +17 -0
- package/dist/__tests__/worktree-sync-fixture.test.d.ts.map +1 -0
- package/dist/__tests__/worktree-sync-fixture.test.js +519 -0
- package/dist/__tests__/worktree-sync-fixture.test.js.map +1 -0
- package/dist/__tests__/worktree-sync-hardening.test.d.ts +13 -0
- package/dist/__tests__/worktree-sync-hardening.test.d.ts.map +1 -0
- package/dist/__tests__/worktree-sync-hardening.test.js +919 -0
- package/dist/__tests__/worktree-sync-hardening.test.js.map +1 -0
- package/dist/__tests__/worktree-sync-shell-free.test.d.ts +25 -0
- package/dist/__tests__/worktree-sync-shell-free.test.d.ts.map +1 -0
- package/dist/__tests__/worktree-sync-shell-free.test.js +185 -0
- package/dist/__tests__/worktree-sync-shell-free.test.js.map +1 -0
- package/dist/__tests__/worktree.test.js +75 -1
- package/dist/__tests__/worktree.test.js.map +1 -1
- package/dist/agent-config/.mx-config-generation.json +2 -2
- package/dist/agent-config/AGENTS.md.template +2 -2
- package/dist/agent-config/agents/bar-raiser.md +34 -1
- package/dist/agent-config/agents/red-team.md +34 -1
- package/dist/agent-config/agents/security-reviewer.md +22 -1
- package/dist/agent-config/claude-md/CLAUDE.core.md +6 -1
- package/dist/agent-config/claude-md/CLAUDE.overlay.memnexus.md +1 -3
- package/dist/agent-config/coordination-rosters.generated.json +10 -0
- package/dist/agent-config/hooks/HOOK-TIMEOUTS.md +27 -1
- package/dist/agent-config/hooks/OR-TRUE-AUDIT.md +8 -8
- package/dist/agent-config/hooks/auto-capture-precompact.sh +180 -83
- package/dist/agent-config/hooks/auto-capture-session-end.sh +216 -87
- package/dist/agent-config/hooks/auto-checkpoint.sh +75 -5
- package/dist/agent-config/hooks/coordination-brief.sh +290 -245
- package/dist/agent-config/hooks/deploy-verification-reminder.sh +359 -22
- package/dist/agent-config/hooks/git-mutation-guard.sh +85 -13
- package/dist/agent-config/hooks/observability-sync.sh +46 -9
- package/dist/agent-config/hooks/session-idle-gate.sh +177 -12
- package/dist/agent-config/hooks/subagent-write-guard.sh +670 -0
- package/dist/agent-config/hooks/worktree-guard.sh +36 -7
- package/dist/agent-config/settings.json +15 -2
- package/dist/agent-config/shared/creation-pr-review-checklist.md +317 -0
- package/dist/commands/bootstrap.d.ts.map +1 -1
- package/dist/commands/bootstrap.js +22 -10
- package/dist/commands/bootstrap.js.map +1 -1
- package/dist/commands/config-sync.d.ts +37 -0
- package/dist/commands/config-sync.d.ts.map +1 -1
- package/dist/commands/config-sync.js +36 -18
- package/dist/commands/config-sync.js.map +1 -1
- package/dist/commands/config.d.ts.map +1 -1
- package/dist/commands/config.js +28 -1
- package/dist/commands/config.js.map +1 -1
- package/dist/commands/coordination.d.ts +150 -8
- package/dist/commands/coordination.d.ts.map +1 -1
- package/dist/commands/coordination.js +519 -25
- package/dist/commands/coordination.js.map +1 -1
- package/dist/commands/create.d.ts +913 -1
- package/dist/commands/create.d.ts.map +1 -1
- package/dist/commands/create.js +4879 -345
- package/dist/commands/create.js.map +1 -1
- package/dist/commands/dashboard.d.ts.map +1 -1
- package/dist/commands/dashboard.js +10 -2
- package/dist/commands/dashboard.js.map +1 -1
- package/dist/commands/decision.d.ts +20 -0
- package/dist/commands/decision.d.ts.map +1 -0
- package/dist/commands/decision.js +54 -0
- package/dist/commands/decision.js.map +1 -0
- package/dist/commands/digest.d.ts.map +1 -1
- package/dist/commands/digest.js +91 -7
- package/dist/commands/digest.js.map +1 -1
- package/dist/commands/fleet-tmux.js +1 -1
- package/dist/commands/fleet-tmux.js.map +1 -1
- package/dist/commands/init.d.ts +8 -0
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +26 -1
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/list.d.ts +32 -1
- package/dist/commands/list.d.ts.map +1 -1
- package/dist/commands/list.js +98 -5
- package/dist/commands/list.js.map +1 -1
- package/dist/commands/monitor.d.ts.map +1 -1
- package/dist/commands/monitor.js +8 -2
- package/dist/commands/monitor.js.map +1 -1
- package/dist/commands/new.d.ts +2 -0
- package/dist/commands/new.d.ts.map +1 -1
- package/dist/commands/new.js +114 -21
- package/dist/commands/new.js.map +1 -1
- package/dist/commands/report.d.ts +33 -0
- package/dist/commands/report.d.ts.map +1 -0
- package/dist/commands/report.js +73 -0
- package/dist/commands/report.js.map +1 -0
- package/dist/commands/session.js +1 -1
- package/dist/commands/session.js.map +1 -1
- package/dist/commands/start.d.ts +42 -0
- package/dist/commands/start.d.ts.map +1 -1
- package/dist/commands/start.js +177 -8
- package/dist/commands/start.js.map +1 -1
- package/dist/commands/sync.d.ts +57 -0
- package/dist/commands/sync.d.ts.map +1 -1
- package/dist/commands/sync.js +117 -3
- package/dist/commands/sync.js.map +1 -1
- package/dist/commands/update.d.ts +13 -1
- package/dist/commands/update.d.ts.map +1 -1
- package/dist/commands/update.js +50 -1
- package/dist/commands/update.js.map +1 -1
- package/dist/commands/usage.d.ts +64 -0
- package/dist/commands/usage.d.ts.map +1 -1
- package/dist/commands/usage.js +96 -3
- package/dist/commands/usage.js.map +1 -1
- package/dist/commands/verify-hooks.d.ts +37 -1
- package/dist/commands/verify-hooks.d.ts.map +1 -1
- package/dist/commands/verify-hooks.js +114 -2
- package/dist/commands/verify-hooks.js.map +1 -1
- package/dist/commands/window.d.ts +10 -0
- package/dist/commands/window.d.ts.map +1 -0
- package/dist/commands/window.js +265 -0
- package/dist/commands/window.js.map +1 -0
- package/dist/commands/worktree-sync.d.ts +54 -0
- package/dist/commands/worktree-sync.d.ts.map +1 -0
- package/dist/commands/worktree-sync.js +135 -0
- package/dist/commands/worktree-sync.js.map +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +189 -14
- package/dist/index.js.map +1 -1
- package/dist/lib/agent-session.d.ts +12 -0
- package/dist/lib/agent-session.d.ts.map +1 -1
- package/dist/lib/agent-session.js +189 -42
- package/dist/lib/agent-session.js.map +1 -1
- package/dist/lib/catalog.d.ts +321 -2
- package/dist/lib/catalog.d.ts.map +1 -1
- package/dist/lib/catalog.js +490 -11
- package/dist/lib/catalog.js.map +1 -1
- package/dist/lib/claude.d.ts +65 -23
- package/dist/lib/claude.d.ts.map +1 -1
- package/dist/lib/claude.js +335 -19
- package/dist/lib/claude.js.map +1 -1
- package/dist/lib/cli-build.d.ts +172 -0
- package/dist/lib/cli-build.d.ts.map +1 -0
- package/dist/lib/cli-build.js +654 -0
- package/dist/lib/cli-build.js.map +1 -0
- package/dist/lib/code-context-file.d.ts +109 -0
- package/dist/lib/code-context-file.d.ts.map +1 -0
- package/dist/lib/code-context-file.js +219 -0
- package/dist/lib/code-context-file.js.map +1 -0
- package/dist/lib/code-context-file.test.d.ts +19 -0
- package/dist/lib/code-context-file.test.d.ts.map +1 -0
- package/dist/lib/code-context-file.test.js +202 -0
- package/dist/lib/code-context-file.test.js.map +1 -0
- package/dist/lib/config-fidelity.d.ts +40 -20
- package/dist/lib/config-fidelity.d.ts.map +1 -1
- package/dist/lib/config-fidelity.js +144 -56
- package/dist/lib/config-fidelity.js.map +1 -1
- package/dist/lib/coordination-client.d.ts +73 -0
- package/dist/lib/coordination-client.d.ts.map +1 -1
- package/dist/lib/coordination-client.js +180 -8
- package/dist/lib/coordination-client.js.map +1 -1
- package/dist/lib/coordination-token.d.ts +304 -6
- package/dist/lib/coordination-token.d.ts.map +1 -1
- package/dist/lib/coordination-token.js +851 -52
- package/dist/lib/coordination-token.js.map +1 -1
- package/dist/lib/decision-check.d.ts +48 -0
- package/dist/lib/decision-check.d.ts.map +1 -0
- package/dist/lib/decision-check.js +149 -0
- package/dist/lib/decision-check.js.map +1 -0
- package/dist/lib/fleet-data.d.ts +34 -0
- package/dist/lib/fleet-data.d.ts.map +1 -1
- package/dist/lib/fleet-data.js +37 -9
- package/dist/lib/fleet-data.js.map +1 -1
- package/dist/lib/fleet-render.js +1 -1
- package/dist/lib/fleet-render.js.map +1 -1
- package/dist/lib/git-identity.d.ts +302 -0
- package/dist/lib/git-identity.d.ts.map +1 -0
- package/dist/lib/git-identity.js +546 -0
- package/dist/lib/git-identity.js.map +1 -0
- package/dist/lib/harness/console/announce.d.ts +45 -0
- package/dist/lib/harness/console/announce.d.ts.map +1 -0
- package/dist/lib/harness/console/announce.js +48 -0
- package/dist/lib/harness/console/announce.js.map +1 -0
- package/dist/lib/harness/console/announce.test.d.ts +2 -0
- package/dist/lib/harness/console/announce.test.d.ts.map +1 -0
- package/dist/lib/harness/console/announce.test.js +104 -0
- package/dist/lib/harness/console/announce.test.js.map +1 -0
- package/dist/lib/harness/console/by-session.d.ts +50 -0
- package/dist/lib/harness/console/by-session.d.ts.map +1 -0
- package/dist/lib/harness/console/by-session.js +83 -0
- package/dist/lib/harness/console/by-session.js.map +1 -0
- package/dist/lib/harness/console/by-session.test.d.ts +2 -0
- package/dist/lib/harness/console/by-session.test.d.ts.map +1 -0
- package/dist/lib/harness/console/by-session.test.js +86 -0
- package/dist/lib/harness/console/by-session.test.js.map +1 -0
- package/dist/lib/harness/console/console.d.ts +67 -0
- package/dist/lib/harness/console/console.d.ts.map +1 -0
- package/dist/lib/harness/console/console.js +373 -0
- package/dist/lib/harness/console/console.js.map +1 -0
- package/dist/lib/harness/console/console.test.d.ts +2 -0
- package/dist/lib/harness/console/console.test.d.ts.map +1 -0
- package/dist/lib/harness/console/console.test.js +269 -0
- package/dist/lib/harness/console/console.test.js.map +1 -0
- package/dist/lib/harness/console/decision-request.d.ts +32 -0
- package/dist/lib/harness/console/decision-request.d.ts.map +1 -0
- package/dist/lib/harness/console/decision-request.js +112 -0
- package/dist/lib/harness/console/decision-request.js.map +1 -0
- package/dist/lib/harness/console/decision-request.test.d.ts +2 -0
- package/dist/lib/harness/console/decision-request.test.d.ts.map +1 -0
- package/dist/lib/harness/console/decision-request.test.js +75 -0
- package/dist/lib/harness/console/decision-request.test.js.map +1 -0
- package/dist/lib/harness/console/fixtures.d.ts +16 -0
- package/dist/lib/harness/console/fixtures.d.ts.map +1 -0
- package/dist/lib/harness/console/fixtures.js +49 -0
- package/dist/lib/harness/console/fixtures.js.map +1 -0
- package/dist/lib/harness/console/index.d.ts +15 -0
- package/dist/lib/harness/console/index.d.ts.map +1 -0
- package/dist/lib/harness/console/index.js +14 -0
- package/dist/lib/harness/console/index.js.map +1 -0
- package/dist/lib/harness/console/rank.d.ts +73 -0
- package/dist/lib/harness/console/rank.d.ts.map +1 -0
- package/dist/lib/harness/console/rank.js +113 -0
- package/dist/lib/harness/console/rank.js.map +1 -0
- package/dist/lib/harness/console/rank.test.d.ts +2 -0
- package/dist/lib/harness/console/rank.test.d.ts.map +1 -0
- package/dist/lib/harness/console/rank.test.js +124 -0
- package/dist/lib/harness/console/rank.test.js.map +1 -0
- package/dist/lib/harness/console/render.d.ts +22 -0
- package/dist/lib/harness/console/render.d.ts.map +1 -0
- package/dist/lib/harness/console/render.js +65 -0
- package/dist/lib/harness/console/render.js.map +1 -0
- package/dist/lib/harness/console/render.test.d.ts +2 -0
- package/dist/lib/harness/console/render.test.d.ts.map +1 -0
- package/dist/lib/harness/console/render.test.js +96 -0
- package/dist/lib/harness/console/render.test.js.map +1 -0
- package/dist/lib/harness/console/replay-cli.test.d.ts +2 -0
- package/dist/lib/harness/console/replay-cli.test.d.ts.map +1 -0
- package/dist/lib/harness/console/replay-cli.test.js +96 -0
- package/dist/lib/harness/console/replay-cli.test.js.map +1 -0
- package/dist/lib/harness/console/replay.d.ts +36 -0
- package/dist/lib/harness/console/replay.d.ts.map +1 -0
- package/dist/lib/harness/console/replay.js +59 -0
- package/dist/lib/harness/console/replay.js.map +1 -0
- package/dist/lib/harness/console/replay.test.d.ts +2 -0
- package/dist/lib/harness/console/replay.test.d.ts.map +1 -0
- package/dist/lib/harness/console/replay.test.js +81 -0
- package/dist/lib/harness/console/replay.test.js.map +1 -0
- package/dist/lib/harness/console/turn-reader.d.ts +50 -0
- package/dist/lib/harness/console/turn-reader.d.ts.map +1 -0
- package/dist/lib/harness/console/turn-reader.js +184 -0
- package/dist/lib/harness/console/turn-reader.js.map +1 -0
- package/dist/lib/harness/console/turn-reader.test.d.ts +2 -0
- package/dist/lib/harness/console/turn-reader.test.d.ts.map +1 -0
- package/dist/lib/harness/console/turn-reader.test.js +108 -0
- package/dist/lib/harness/console/turn-reader.test.js.map +1 -0
- package/dist/lib/harness/console/types.d.ts +109 -0
- package/dist/lib/harness/console/types.d.ts.map +1 -0
- package/dist/lib/harness/console/types.js +2 -0
- package/dist/lib/harness/console/types.js.map +1 -0
- package/dist/lib/harness/contract.d.ts +229 -0
- package/dist/lib/harness/contract.d.ts.map +1 -0
- package/dist/lib/harness/contract.js +22 -0
- package/dist/lib/harness/contract.js.map +1 -0
- package/dist/lib/harness/credential.d.ts +23 -0
- package/dist/lib/harness/credential.d.ts.map +1 -0
- package/dist/lib/harness/credential.js +81 -0
- package/dist/lib/harness/credential.js.map +1 -0
- package/dist/lib/harness/credential.test.d.ts +2 -0
- package/dist/lib/harness/credential.test.d.ts.map +1 -0
- package/dist/lib/harness/credential.test.js +74 -0
- package/dist/lib/harness/credential.test.js.map +1 -0
- package/dist/lib/harness/evaluate.d.ts +390 -0
- package/dist/lib/harness/evaluate.d.ts.map +1 -0
- package/dist/lib/harness/evaluate.js +988 -0
- package/dist/lib/harness/evaluate.js.map +1 -0
- package/dist/lib/harness/evaluate.test.d.ts +2 -0
- package/dist/lib/harness/evaluate.test.d.ts.map +1 -0
- package/dist/lib/harness/evaluate.test.js +621 -0
- package/dist/lib/harness/evaluate.test.js.map +1 -0
- package/dist/lib/harness/extract.d.ts +152 -0
- package/dist/lib/harness/extract.d.ts.map +1 -0
- package/dist/lib/harness/extract.js +1601 -0
- package/dist/lib/harness/extract.js.map +1 -0
- package/dist/lib/harness/gate.d.ts +48 -0
- package/dist/lib/harness/gate.d.ts.map +1 -0
- package/dist/lib/harness/gate.js +60 -0
- package/dist/lib/harness/gate.js.map +1 -0
- package/dist/lib/harness/gate.test.d.ts +2 -0
- package/dist/lib/harness/gate.test.d.ts.map +1 -0
- package/dist/lib/harness/gate.test.js +111 -0
- package/dist/lib/harness/gate.test.js.map +1 -0
- package/dist/lib/harness/self-check.d.ts +59 -0
- package/dist/lib/harness/self-check.d.ts.map +1 -0
- package/dist/lib/harness/self-check.js +56 -0
- package/dist/lib/harness/self-check.js.map +1 -0
- package/dist/lib/harness/self-check.test.d.ts +2 -0
- package/dist/lib/harness/self-check.test.d.ts.map +1 -0
- package/dist/lib/harness/self-check.test.js +43 -0
- package/dist/lib/harness/self-check.test.js.map +1 -0
- package/dist/lib/harness/transcript.d.ts +65 -0
- package/dist/lib/harness/transcript.d.ts.map +1 -0
- package/dist/lib/harness/transcript.js +144 -0
- package/dist/lib/harness/transcript.js.map +1 -0
- package/dist/lib/harness/transcript.test.d.ts +2 -0
- package/dist/lib/harness/transcript.test.d.ts.map +1 -0
- package/dist/lib/harness/transcript.test.js +118 -0
- package/dist/lib/harness/transcript.test.js.map +1 -0
- package/dist/lib/harness-wiring.d.ts +145 -0
- package/dist/lib/harness-wiring.d.ts.map +1 -0
- package/dist/lib/harness-wiring.js +280 -0
- package/dist/lib/harness-wiring.js.map +1 -0
- package/dist/lib/hook-staleness.d.ts +95 -0
- package/dist/lib/hook-staleness.d.ts.map +1 -0
- package/dist/lib/hook-staleness.js +304 -0
- package/dist/lib/hook-staleness.js.map +1 -0
- package/dist/lib/jsonl.d.ts +270 -2
- package/dist/lib/jsonl.d.ts.map +1 -1
- package/dist/lib/jsonl.js +472 -76
- package/dist/lib/jsonl.js.map +1 -1
- package/dist/lib/memory.d.ts +350 -23
- package/dist/lib/memory.d.ts.map +1 -1
- package/dist/lib/memory.js +751 -38
- package/dist/lib/memory.js.map +1 -1
- package/dist/lib/otel-env.d.ts +90 -0
- package/dist/lib/otel-env.d.ts.map +1 -0
- package/dist/lib/otel-env.js +98 -0
- package/dist/lib/otel-env.js.map +1 -0
- package/dist/lib/project-config.d.ts +167 -0
- package/dist/lib/project-config.d.ts.map +1 -1
- package/dist/lib/project-config.js +321 -5
- package/dist/lib/project-config.js.map +1 -1
- package/dist/lib/projects-registry.d.ts +82 -0
- package/dist/lib/projects-registry.d.ts.map +1 -0
- package/dist/lib/projects-registry.js +145 -0
- package/dist/lib/projects-registry.js.map +1 -0
- package/dist/lib/projects-registry.test.d.ts +2 -0
- package/dist/lib/projects-registry.test.d.ts.map +1 -0
- package/dist/lib/projects-registry.test.js +176 -0
- package/dist/lib/projects-registry.test.js.map +1 -0
- package/dist/lib/repo-guard-scope.d.ts +126 -0
- package/dist/lib/repo-guard-scope.d.ts.map +1 -0
- package/dist/lib/repo-guard-scope.js +249 -0
- package/dist/lib/repo-guard-scope.js.map +1 -0
- package/dist/lib/report-format.d.ts +132 -0
- package/dist/lib/report-format.d.ts.map +1 -0
- package/dist/lib/report-format.js +317 -0
- package/dist/lib/report-format.js.map +1 -0
- package/dist/lib/roster.d.ts +87 -0
- package/dist/lib/roster.d.ts.map +1 -0
- package/dist/lib/roster.js +332 -0
- package/dist/lib/roster.js.map +1 -0
- package/dist/lib/roster.test.d.ts +15 -0
- package/dist/lib/roster.test.d.ts.map +1 -0
- package/dist/lib/roster.test.js +299 -0
- package/dist/lib/roster.test.js.map +1 -0
- package/dist/lib/runtime/codex-adapter.d.ts.map +1 -1
- package/dist/lib/runtime/codex-adapter.js +5 -0
- package/dist/lib/runtime/codex-adapter.js.map +1 -1
- package/dist/lib/runtime/codex-config.d.ts +129 -0
- package/dist/lib/runtime/codex-config.d.ts.map +1 -1
- package/dist/lib/runtime/codex-config.js +225 -0
- package/dist/lib/runtime/codex-config.js.map +1 -1
- package/dist/lib/runtime/identity.d.ts +72 -0
- package/dist/lib/runtime/identity.d.ts.map +1 -0
- package/dist/lib/runtime/identity.js +128 -0
- package/dist/lib/runtime/identity.js.map +1 -0
- package/dist/lib/standards.d.ts +99 -0
- package/dist/lib/standards.d.ts.map +1 -0
- package/dist/lib/standards.js +201 -0
- package/dist/lib/standards.js.map +1 -0
- package/dist/lib/team-identity.d.ts +134 -0
- package/dist/lib/team-identity.d.ts.map +1 -0
- package/dist/lib/team-identity.js +193 -0
- package/dist/lib/team-identity.js.map +1 -0
- package/dist/lib/templates.d.ts +29 -2
- package/dist/lib/templates.d.ts.map +1 -1
- package/dist/lib/templates.js +1042 -82
- package/dist/lib/templates.js.map +1 -1
- package/dist/lib/terminal-ui.d.ts.map +1 -1
- package/dist/lib/terminal-ui.js +12 -1
- package/dist/lib/terminal-ui.js.map +1 -1
- package/dist/lib/test-project.d.ts +95 -0
- package/dist/lib/test-project.d.ts.map +1 -0
- package/dist/lib/test-project.js +103 -0
- package/dist/lib/test-project.js.map +1 -0
- package/dist/lib/vault.d.ts +60 -0
- package/dist/lib/vault.d.ts.map +1 -0
- package/dist/lib/vault.js +102 -0
- package/dist/lib/vault.js.map +1 -0
- package/dist/lib/vault.test.d.ts +17 -0
- package/dist/lib/vault.test.d.ts.map +1 -0
- package/dist/lib/vault.test.js +169 -0
- package/dist/lib/vault.test.js.map +1 -0
- package/dist/lib/window-view.d.ts +63 -0
- package/dist/lib/window-view.d.ts.map +1 -0
- package/dist/lib/window-view.js +217 -0
- package/dist/lib/window-view.js.map +1 -0
- package/dist/lib/window-view.test.d.ts +2 -0
- package/dist/lib/window-view.test.d.ts.map +1 -0
- package/dist/lib/window-view.test.js +168 -0
- package/dist/lib/window-view.test.js.map +1 -0
- package/dist/lib/worktree-sync.d.ts +439 -0
- package/dist/lib/worktree-sync.d.ts.map +1 -0
- package/dist/lib/worktree-sync.js +1167 -0
- package/dist/lib/worktree-sync.js.map +1 -0
- package/dist/lib/worktree.d.ts +58 -1
- package/dist/lib/worktree.d.ts.map +1 -1
- package/dist/lib/worktree.js +91 -4
- package/dist/lib/worktree.js.map +1 -1
- package/dist/standards/decision-request.md +98 -0
- package/dist/standards/fail-loud-standard.md +495 -0
- package/dist/standards/po-communication-standard.md +126 -0
- package/dist/standards/report-format.md +128 -0
- package/dist/standards/writing-standard.md +382 -0
- package/package.json +3 -2
- package/scripts/generate-claude.mjs +119 -46
|
@@ -0,0 +1,1167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* worktree-sync.ts — in-process worktree synchronisation with namespaced
|
|
3
|
+
* checkpoint refs (#172, revision 4; closes the post-squash-merge deadlock #156).
|
|
4
|
+
*
|
|
5
|
+
* ── WHAT THIS REPLACES ────────────────────────────────────────────────────
|
|
6
|
+
* The `mx-post-merge-sync` skill runs `git stash push` then `git reset --hard`
|
|
7
|
+
* from Bash. `refs/stash` is ONE repository-global stack shared by every linked
|
|
8
|
+
* worktree, so a positional pop can restore another team's entry. This module
|
|
9
|
+
* writes one ref per worktree per checkpoint instead: no stack, and nothing
|
|
10
|
+
* another worktree can pop.
|
|
11
|
+
*
|
|
12
|
+
* ── WHAT THE LEADER-LOCK CHECK DOES AND DOES NOT DO ───────────────────────
|
|
13
|
+
* `leader-lock.ts:12-14` states that sub-agent teammates are spawned via the
|
|
14
|
+
* Task tool INSIDE a leader session and never touch the leader lock. So the
|
|
15
|
+
* lock cannot observe teammates, and this module never claims it does. Step 0
|
|
16
|
+
* establishes only that a live leader session exists in this worktree. It does
|
|
17
|
+
* NOT establish that the caller is that leader rather than one of its
|
|
18
|
+
* teammates, because a teammate runs with the same worktree cwd and the same
|
|
19
|
+
* lock file present, and no signal available here separates the two.
|
|
20
|
+
*
|
|
21
|
+
* ── WHAT HAPPENS WHEN THE PROCESS DIES MID-SYNC ───────────────────────────
|
|
22
|
+
* An `in-progress` audit record is written before the destructive step and a
|
|
23
|
+
* terminal record after it, correlated by `runId`. An `in-progress` record with
|
|
24
|
+
* no matching terminal record is a run that died during the destructive step.
|
|
25
|
+
* That record is the ONLY protection, and it is deliberate: this module
|
|
26
|
+
* registers no signal handler. See the comment above the record for the
|
|
27
|
+
* measurement. A killed sync leaves the sync lock file behind; the next run
|
|
28
|
+
* reclaims it after finding the recorded pid gone.
|
|
29
|
+
*
|
|
30
|
+
* ── RESIDUAL RISK, STATED RATHER THAN MITIGATED ───────────────────────────
|
|
31
|
+
* A teammate writing files during the reset or the rebase can still lose work.
|
|
32
|
+
* The quiescence sample (steps 4 and 6) brackets the checkpoint, not the
|
|
33
|
+
* destructive step, and its mtime comparison is bounded by filesystem
|
|
34
|
+
* resolution. The step-0a assertion is self-reported by the party that wants
|
|
35
|
+
* the sync to proceed: it is a weaker, self-administered substitute for asking
|
|
36
|
+
* the coordinator, not that step. It is recorded so a lost-work investigation
|
|
37
|
+
* names a party. It supplies no independent verification.
|
|
38
|
+
*
|
|
39
|
+
* ── SHELL-FREE INVARIANT (success criterion 6) ────────────────────────────
|
|
40
|
+
* Every git and gh invocation ORIGINATING HERE goes through {@link runGit} /
|
|
41
|
+
* {@link runGh}, which call `execFileSync` with an argv array. No shell string,
|
|
42
|
+
* no `shell: true`, anywhere in this file. Two reused helpers from
|
|
43
|
+
* `lib/worktree.ts` (`getCurrentBranch`, `fetchOrigin`) do use `execSync` with
|
|
44
|
+
* a shell, and that is the documented residual: both take only `cwd` and both
|
|
45
|
+
* run hardcoded literals, so there is no interpolation surface. NOTHING
|
|
46
|
+
* interpolated may be routed through them.
|
|
47
|
+
*/
|
|
48
|
+
import { execFileSync } from 'node:child_process';
|
|
49
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
50
|
+
import { closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync, writeSync, } from 'node:fs';
|
|
51
|
+
import { homedir, tmpdir } from 'node:os';
|
|
52
|
+
import { basename, join } from 'node:path';
|
|
53
|
+
import { checkLiveness, readLock, sanitizeField, HEARTBEAT_FRESH_SECONDS } from './leader-lock.js';
|
|
54
|
+
import { fetchOrigin as defaultFetchOrigin, getCurrentBranch as defaultGetCurrentBranch, hasOriginRemote as defaultHasOriginRemote, refExists as defaultRefExists, } from './worktree.js';
|
|
55
|
+
// ── constants fixed by the plan ───────────────────────────────────────────
|
|
56
|
+
/** Namespace for checkpoint refs. Not under `refs/heads` or `refs/tags`, so no
|
|
57
|
+
* branch listing, no push by default, and no interaction with `refs/stash`. */
|
|
58
|
+
export const CHECKPOINT_NAMESPACE = 'refs/mx/checkpoint';
|
|
59
|
+
/** Retention, per the plan's Retention section. Named refs are GC roots, so an
|
|
60
|
+
* unbounded namespace pins every checkpointed tree forever. */
|
|
61
|
+
export const MAX_CHECKPOINTS_PER_WORKTREE = 20;
|
|
62
|
+
export const CHECKPOINT_RETENTION_DAYS = 14;
|
|
63
|
+
/** Audit log path component. One line per run, every path including refusals. */
|
|
64
|
+
export const AUDIT_LOG_FILENAME = 'worktree-sync.jsonl';
|
|
65
|
+
/**
|
|
66
|
+
* The eleven fields the plan's Audit section names, plus `runId`, in written
|
|
67
|
+
* order.
|
|
68
|
+
*
|
|
69
|
+
* `runId` is the twelfth and it is required by the crash-durability fix (red
|
|
70
|
+
* team Finding 1). A run that reaches step 7 writes TWO records, one
|
|
71
|
+
* `in-progress` before the destructive step and one terminal record after, and
|
|
72
|
+
* with several worktrees appending to one file there is otherwise no way to say
|
|
73
|
+
* which terminal record closes which start. An `in-progress` record with no
|
|
74
|
+
* matching terminal record IS the signal that a run was killed mid-step-7.
|
|
75
|
+
*
|
|
76
|
+
* This changes criterion 9's literal wording, which says exactly one line per
|
|
77
|
+
* run. The criterion's intent, that no run goes unrecorded, is strengthened
|
|
78
|
+
* rather than weakened: the invariant now enforced is exactly one TERMINAL
|
|
79
|
+
* record per run.
|
|
80
|
+
*/
|
|
81
|
+
export const AUDIT_FIELDS = [
|
|
82
|
+
'runId',
|
|
83
|
+
'timestamp',
|
|
84
|
+
'worktree',
|
|
85
|
+
'caller',
|
|
86
|
+
'quiescenceAsserted',
|
|
87
|
+
'baseRef',
|
|
88
|
+
'headBefore',
|
|
89
|
+
'headAfter',
|
|
90
|
+
'checkpointRef',
|
|
91
|
+
'syncBranch',
|
|
92
|
+
'refsPruned',
|
|
93
|
+
'outcome',
|
|
94
|
+
];
|
|
95
|
+
function toText(v) {
|
|
96
|
+
if (typeof v === 'string')
|
|
97
|
+
return v;
|
|
98
|
+
if (v && typeof v.toString === 'function')
|
|
99
|
+
return v.toString('utf-8');
|
|
100
|
+
return '';
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Default runner: `execFileSync` with an argv array. Never a shell string,
|
|
104
|
+
* never `shell: true`. A non-zero exit is returned as a status rather than
|
|
105
|
+
* thrown, so every caller decides for itself whether the failure is fatal.
|
|
106
|
+
*/
|
|
107
|
+
export const defaultExecFile = (file, args, options = {}) => {
|
|
108
|
+
try {
|
|
109
|
+
const stdout = execFileSync(file, [...args], {
|
|
110
|
+
cwd: options.cwd,
|
|
111
|
+
env: options.env,
|
|
112
|
+
timeout: options.timeoutMs,
|
|
113
|
+
encoding: 'utf-8',
|
|
114
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
115
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
116
|
+
});
|
|
117
|
+
return { status: 0, stdout: toText(stdout), stderr: '' };
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
const e = err;
|
|
121
|
+
return {
|
|
122
|
+
status: typeof e.status === 'number' ? e.status : 1,
|
|
123
|
+
stdout: toText(e.stdout),
|
|
124
|
+
stderr: toText(e.stderr) || String(e.message ?? ''),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
function dep(v, fallback) {
|
|
129
|
+
return v === undefined ? fallback : v;
|
|
130
|
+
}
|
|
131
|
+
// ── argv-only process helpers ─────────────────────────────────────────────
|
|
132
|
+
export function runGit(cwd, args, deps = {}, env) {
|
|
133
|
+
return dep(deps.exec, defaultExecFile)('git', args, { cwd, env, timeoutMs: 600_000 });
|
|
134
|
+
}
|
|
135
|
+
export function runGh(cwd, args, deps = {}) {
|
|
136
|
+
return dep(deps.exec, defaultExecFile)('gh', args, { cwd, timeoutMs: 60_000 });
|
|
137
|
+
}
|
|
138
|
+
// ── checkpoint ref naming ─────────────────────────────────────────────────
|
|
139
|
+
/**
|
|
140
|
+
* `refs/mx/checkpoint/<worktree>/<epoch-ms>-<rand6>`.
|
|
141
|
+
*
|
|
142
|
+
* Epoch MILLISECONDS plus six random hex characters. Seconds alone collide on a
|
|
143
|
+
* same-second retry; an ISO timestamp contains colons and `check-ref-format`
|
|
144
|
+
* rejects it. Both verified in this repository on 2026-08-25 and reproduced by
|
|
145
|
+
* two reviewers.
|
|
146
|
+
*/
|
|
147
|
+
export function buildCheckpointRef(worktreeName, epochMs, rand6) {
|
|
148
|
+
return `${CHECKPOINT_NAMESPACE}/${worktreeName}/${epochMs}-${rand6}`;
|
|
149
|
+
}
|
|
150
|
+
/** The `for-each-ref` pattern covering one worktree's checkpoints. */
|
|
151
|
+
export function checkpointRefPattern(worktreeName) {
|
|
152
|
+
return `${CHECKPOINT_NAMESPACE}/${worktreeName}/`;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Ask git whether a ref name is well-formed. The command REFUSES rather than
|
|
156
|
+
* constructing an invalid ref: a worktree name containing a space produces
|
|
157
|
+
* `refs/mx/checkpoint/bad name/...`, which `git check-ref-format` rejects
|
|
158
|
+
* (exit 1, verified). Validating the WHOLE ref rather than the name segment
|
|
159
|
+
* catches every other rejected character in one call.
|
|
160
|
+
*/
|
|
161
|
+
export function isValidRefName(ref, cwd, deps = {}) {
|
|
162
|
+
return runGit(cwd, ['check-ref-format', ref], deps).status === 0;
|
|
163
|
+
}
|
|
164
|
+
function defaultRand6() {
|
|
165
|
+
return randomBytes(3).toString('hex');
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* A digest of everything a concurrent writer could change cheaply: HEAD, the
|
|
169
|
+
* full porcelain status including untracked files, and per-path size and mtime.
|
|
170
|
+
*
|
|
171
|
+
* Size is in the digest because an APPEND to an already-modified tracked file
|
|
172
|
+
* leaves the porcelain line identical (` M path`) and can leave mtime unchanged
|
|
173
|
+
* within one filesystem tick. Size changes on every append, so the common
|
|
174
|
+
* background-writer shape is caught even at one-second mtime resolution. A
|
|
175
|
+
* same-length overwrite inside one tick is not caught, and that is the bound.
|
|
176
|
+
*/
|
|
177
|
+
export function sampleWorkingTree(cwd, deps = {}) {
|
|
178
|
+
const head = readHead(cwd, deps);
|
|
179
|
+
const statusResult = runGit(cwd, ['status', '--porcelain=v1', '-z', '--untracked-files=all'], deps);
|
|
180
|
+
const status = statusResult.stdout;
|
|
181
|
+
const paths = new Set();
|
|
182
|
+
for (const entry of status.split('\0')) {
|
|
183
|
+
if (!entry)
|
|
184
|
+
continue;
|
|
185
|
+
// Porcelain v1 -z entries are `XY <path>`; a rename emits the source path
|
|
186
|
+
// as its own entry with no XY prefix. Both shapes are stat'd; a path that
|
|
187
|
+
// does not resolve records as `missing`, which is itself a change signal.
|
|
188
|
+
paths.add(entry.length > 3 ? entry.slice(3) : entry);
|
|
189
|
+
}
|
|
190
|
+
const parts = [`head=${head ?? 'none'}`, `status=${status}`];
|
|
191
|
+
for (const p of [...paths].sort()) {
|
|
192
|
+
try {
|
|
193
|
+
const st = statSync(join(cwd, p));
|
|
194
|
+
parts.push(`${p}:${st.size}:${st.mtimeMs}`);
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
parts.push(`${p}:missing`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return {
|
|
201
|
+
head,
|
|
202
|
+
digest: createHash('sha256').update(parts.join('\n')).digest('hex'),
|
|
203
|
+
status,
|
|
204
|
+
readable: statusResult.status === 0,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
export function isDirty(sample) {
|
|
208
|
+
return sample.status.split('\0').some((e) => e.length > 0);
|
|
209
|
+
}
|
|
210
|
+
function readHead(cwd, deps = {}) {
|
|
211
|
+
const r = runGit(cwd, ['rev-parse', '--verify', '--quiet', '--end-of-options', 'HEAD'], deps);
|
|
212
|
+
const sha = r.stdout.trim();
|
|
213
|
+
return r.status === 0 && sha ? sha : null;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Commit the working tree and index to a namespaced ref without touching HEAD,
|
|
217
|
+
* the real index, or the working tree.
|
|
218
|
+
*
|
|
219
|
+
* A temporary `GIT_INDEX_FILE` holds the staging: `read-tree HEAD` seeds it with
|
|
220
|
+
* the committed state, `add -A --` layers the working tree over it (tracked
|
|
221
|
+
* modifications, deletions, and untracked non-ignored files), `write-tree`
|
|
222
|
+
* turns that into a tree object and `commit-tree` into a commit parented on
|
|
223
|
+
* HEAD. Only then does `update-ref` publish the name. The developer's own
|
|
224
|
+
* index is never opened.
|
|
225
|
+
*
|
|
226
|
+
* THREE commits are written, and each one is measured rather than assumed.
|
|
227
|
+
*
|
|
228
|
+
* 1. `indexCommit`, the real index as it stands BEFORE anything else runs.
|
|
229
|
+
* This is security review Must Fix 2. `read-tree HEAD` followed by
|
|
230
|
+
* `add -A` overwrites the index entry for every path with the working-tree
|
|
231
|
+
* version, so for a path in `MM` state (staged, then edited again) the
|
|
232
|
+
* staged blob is captured nowhere and `reset --hard HEAD` at step 7 leaves
|
|
233
|
+
* it dangling. `git stash push` keeps both, at `stash@{0}` and
|
|
234
|
+
* `stash@{0}^2`. This mirrors that shape exactly: the checkpoint commit's
|
|
235
|
+
* second parent IS the index commit, so `<ref>^2:<path>` yields the staged
|
|
236
|
+
* bytes and `<ref>:<path>` the working-tree bytes. Verified on git 2.49.0.
|
|
237
|
+
* 2. The full working tree, tracked plus untracked non-ignored. This is what
|
|
238
|
+
* the published ref points at, and it is what RECOVERY reads.
|
|
239
|
+
* 3. `restoreCommit`, tracked modifications only. `git cherry-pick -n` of the
|
|
240
|
+
* FULL commit fails with exit 128, "The following untracked working tree
|
|
241
|
+
* files would be overwritten by merge", because the untracked files are
|
|
242
|
+
* additions in that commit and already exist on disk. The tracked-only
|
|
243
|
+
* commit built with `add -u` cherry-picks cleanly and leaves untracked files
|
|
244
|
+
* alone, which is `git stash apply` semantics. So RESTORE reads this one.
|
|
245
|
+
*/
|
|
246
|
+
export function createCheckpoint(cwd, worktreeName, deps = {}) {
|
|
247
|
+
const nowMs = dep(deps.now, Date.now)();
|
|
248
|
+
const ref = buildCheckpointRef(worktreeName, nowMs, dep(deps.rand6, defaultRand6)());
|
|
249
|
+
if (!isValidRefName(ref, cwd, deps)) {
|
|
250
|
+
return {
|
|
251
|
+
ok: false,
|
|
252
|
+
ref: null,
|
|
253
|
+
commit: null,
|
|
254
|
+
restoreCommit: null,
|
|
255
|
+
restoreError: null,
|
|
256
|
+
indexCommit: null,
|
|
257
|
+
error: `git check-ref-format rejects "${ref}"`,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
const head = readHead(cwd, deps);
|
|
261
|
+
const suffix = defaultRand6();
|
|
262
|
+
const tmpIndex = join(tmpdir(), `mx-checkpoint-index-${nowMs}-${suffix}`);
|
|
263
|
+
const tmpIndexTracked = join(tmpdir(), `mx-checkpoint-index-u-${nowMs}-${suffix}`);
|
|
264
|
+
const env = { ...process.env, GIT_INDEX_FILE: tmpIndex };
|
|
265
|
+
const envTracked = { ...process.env, GIT_INDEX_FILE: tmpIndexTracked };
|
|
266
|
+
const fail = (error) => ({
|
|
267
|
+
ok: false,
|
|
268
|
+
ref: null,
|
|
269
|
+
commit: null,
|
|
270
|
+
restoreCommit: null,
|
|
271
|
+
restoreError: null,
|
|
272
|
+
indexCommit: null,
|
|
273
|
+
error,
|
|
274
|
+
});
|
|
275
|
+
const message = `mx-agent worktree sync checkpoint\n\nworktree: ${worktreeName}\nref: ${ref}\n`;
|
|
276
|
+
/** Stage the working tree into a throwaway index and write the tree object. */
|
|
277
|
+
const stageTree = (addArgs, stageEnv, extraAdd = null) => {
|
|
278
|
+
if (head) {
|
|
279
|
+
const rt = runGit(cwd, ['read-tree', head], deps, stageEnv);
|
|
280
|
+
if (rt.status !== 0)
|
|
281
|
+
return { error: `read-tree: ${rt.stderr.trim()}` };
|
|
282
|
+
}
|
|
283
|
+
const add = runGit(cwd, addArgs, deps, stageEnv);
|
|
284
|
+
if (add.status !== 0)
|
|
285
|
+
return { error: `add: ${add.stderr.trim()}` };
|
|
286
|
+
if (extraAdd) {
|
|
287
|
+
const extra = runGit(cwd, extraAdd, deps, stageEnv);
|
|
288
|
+
if (extra.status !== 0)
|
|
289
|
+
return { error: `add (staged-new paths): ${extra.stderr.trim()}` };
|
|
290
|
+
}
|
|
291
|
+
const wt = runGit(cwd, ['write-tree'], deps, stageEnv);
|
|
292
|
+
const tree = wt.stdout.trim();
|
|
293
|
+
if (wt.status !== 0 || !tree)
|
|
294
|
+
return { error: `write-tree: ${wt.stderr.trim()}` };
|
|
295
|
+
return { tree };
|
|
296
|
+
};
|
|
297
|
+
// Status is READ, not just stdout. A failure here returns '', and '' compares
|
|
298
|
+
// unequal to every real tree, so both `indexTree !== headTree` and
|
|
299
|
+
// `tracked.tree !== headTree` below would answer "changed" for a tree that
|
|
300
|
+
// did not change. Same defect class as the `stagedNew` call: an unread status
|
|
301
|
+
// turning a failure into a plausible-looking answer.
|
|
302
|
+
let headTree = '';
|
|
303
|
+
if (head) {
|
|
304
|
+
const ht = runGit(cwd, ['rev-parse', `${head}^{tree}`], deps);
|
|
305
|
+
headTree = ht.stdout.trim();
|
|
306
|
+
if (ht.status !== 0 || !headTree) {
|
|
307
|
+
return fail(`rev-parse ${head}^{tree}: ${ht.stderr.trim() || 'no output'}`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
try {
|
|
311
|
+
// 1. The REAL index, captured before anything touches it. `git write-tree`
|
|
312
|
+
// reads the caller's index and writes tree objects; it does not change
|
|
313
|
+
// what is staged. It fails on unmerged entries, which is a tree we
|
|
314
|
+
// refuse to checkpoint rather than half-capture.
|
|
315
|
+
let indexCommit = null;
|
|
316
|
+
if (head) {
|
|
317
|
+
const iw = runGit(cwd, ['write-tree'], deps);
|
|
318
|
+
const indexTree = iw.stdout.trim();
|
|
319
|
+
if (iw.status !== 0 || !indexTree) {
|
|
320
|
+
return fail(`write-tree on the real index: ${iw.stderr.trim() || 'unmerged entries present'}`);
|
|
321
|
+
}
|
|
322
|
+
if (indexTree !== headTree) {
|
|
323
|
+
const ic = runGit(cwd, ['commit-tree', indexTree, '-p', head, '-m', `${message}\ncapture: index state\n`], deps);
|
|
324
|
+
if (ic.status !== 0 || !ic.stdout.trim())
|
|
325
|
+
return fail(`commit-tree (index): ${ic.stderr.trim()}`);
|
|
326
|
+
indexCommit = ic.stdout.trim();
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
// 2. The full tree: tracked modifications, deletions, and untracked
|
|
330
|
+
// non-ignored files. This is what the published ref points at.
|
|
331
|
+
const full = stageTree(['add', '-A', '--'], env);
|
|
332
|
+
if (!full.tree)
|
|
333
|
+
return fail(full.error ?? 'write-tree produced nothing');
|
|
334
|
+
// Parents mirror `git stash`: [HEAD, indexCommit]. `<ref>^2` is the index.
|
|
335
|
+
const parents = [];
|
|
336
|
+
if (head)
|
|
337
|
+
parents.push('-p', head);
|
|
338
|
+
if (indexCommit)
|
|
339
|
+
parents.push('-p', indexCommit);
|
|
340
|
+
const ct = runGit(cwd, ['commit-tree', full.tree, ...parents, '-m', message], deps, env);
|
|
341
|
+
const commit = ct.stdout.trim();
|
|
342
|
+
if (ct.status !== 0 || !commit)
|
|
343
|
+
return fail(`commit-tree: ${ct.stderr.trim()}`);
|
|
344
|
+
const ur = runGit(cwd, ['update-ref', ref, commit], deps);
|
|
345
|
+
if (ur.status !== 0)
|
|
346
|
+
return fail(`update-ref: ${ur.stderr.trim()}`);
|
|
347
|
+
// 3. The restore tree. A failure here is NOT fatal: the published ref
|
|
348
|
+
// already holds everything, so the run degrades to
|
|
349
|
+
// checkpoint-without-restore rather than losing the checkpoint.
|
|
350
|
+
//
|
|
351
|
+
// `add -u` alone is NOT enough, and getting this wrong lost data.
|
|
352
|
+
// `add -u` "does not add new files" by its own documentation, so a file
|
|
353
|
+
// that was `git add`-ed but never committed is absent from this tree.
|
|
354
|
+
// Step 7's `reset --hard` then deletes it from disk, because a path in
|
|
355
|
+
// the index but not in the target commit is removed. The restore's
|
|
356
|
+
// index-only half re-staged it, producing `AD`: staged as added, gone
|
|
357
|
+
// from disk, and the command reported success. Reproduced at the
|
|
358
|
+
// plumbing level, deterministic, no race needed.
|
|
359
|
+
//
|
|
360
|
+
// Staged-new paths are therefore added explicitly. They are safe to
|
|
361
|
+
// include here for the same reason they were lost: `reset --hard`
|
|
362
|
+
// removes them from disk, so the cherry-pick that replays this tree
|
|
363
|
+
// finds nothing in its way. Untracked-and-UNSTAGED files stay excluded,
|
|
364
|
+
// because those SURVIVE step 7 and would make the cherry-pick fail with
|
|
365
|
+
// "untracked working tree files would be overwritten by merge".
|
|
366
|
+
let restoreCommit = null;
|
|
367
|
+
let restoreError = null;
|
|
368
|
+
if (head) {
|
|
369
|
+
// `--no-renames` is load-bearing. Without it git reports `git mv` as a
|
|
370
|
+
// RENAME, status `R`, which `--diff-filter=A` does not match. The
|
|
371
|
+
// destination was then missing from the restore tree, `reset --hard`
|
|
372
|
+
// deleted it, and the index-only restore left `RD`: renamed, gone from
|
|
373
|
+
// disk, exit 0, "Restored the checkpointed working tree." Measured. With
|
|
374
|
+
// `--no-renames` git reports the pair as a delete plus an ADD, so the
|
|
375
|
+
// destination path comes back here.
|
|
376
|
+
// STATUS IS CHECKED. Reading only `.stdout` here was a complete bypass of
|
|
377
|
+
// the reporting fix below: a failure of this one call yields empty
|
|
378
|
+
// stdout, `stagedNew` computes to `[]`, and `[]` is indistinguishable
|
|
379
|
+
// from "no staged-new files exist". `stageTree` then gets no `extraAdd`,
|
|
380
|
+
// succeeds, and the run reports `restored` while a staged new file is
|
|
381
|
+
// deleted from disk. `restoreError` never fired because it guards the
|
|
382
|
+
// calls INSIDE `stageTree`, not the one that feeds it. Reproduced by
|
|
383
|
+
// failing this call alone: `AD newfile.txt`, absent from disk, exit 0.
|
|
384
|
+
const stagedNewResult = runGit(cwd, ['diff', '--cached', '--name-only', '-z', '--no-renames', '--diff-filter=A', head], deps);
|
|
385
|
+
if (stagedNewResult.status !== 0) {
|
|
386
|
+
return {
|
|
387
|
+
ok: true,
|
|
388
|
+
ref,
|
|
389
|
+
commit,
|
|
390
|
+
restoreCommit: null,
|
|
391
|
+
restoreError: `diff --cached (staged-new paths): ${stagedNewResult.stderr.trim() || 'command failed'}`,
|
|
392
|
+
indexCommit,
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
const stagedNew = stagedNewResult.stdout
|
|
396
|
+
.split('\0')
|
|
397
|
+
.filter(Boolean)
|
|
398
|
+
// A path staged and then deleted from disk cannot be re-added from the
|
|
399
|
+
// working tree. It is in `indexCommit` and in the published ref.
|
|
400
|
+
.filter((rel) => existsSync(join(cwd, rel)));
|
|
401
|
+
// `-f` because the temp index is seeded from HEAD, where a force-added
|
|
402
|
+
// ignored path (`git add -f`) is both untracked and ignored, so a plain
|
|
403
|
+
// `git add` refuses it and the whole restore tree fails to build.
|
|
404
|
+
const addArgs = stagedNew.length > 0 ? ['add', '-A', '-f', '--', ...stagedNew] : null;
|
|
405
|
+
const tracked = stageTree(['add', '-u', '--'], envTracked, addArgs);
|
|
406
|
+
if (tracked.error) {
|
|
407
|
+
// Recorded, never swallowed. A null `restoreCommit` alone cannot carry
|
|
408
|
+
// this: null is also the legitimate "nothing tracked changed" case, and
|
|
409
|
+
// conflating the two is what let a failed restore report success.
|
|
410
|
+
restoreError = tracked.error;
|
|
411
|
+
}
|
|
412
|
+
else if (tracked.tree && tracked.tree !== headTree) {
|
|
413
|
+
const rc = runGit(cwd, ['commit-tree', tracked.tree, '-p', head, '-m', `${message}\nrestore-source: tracked files only\n`], deps, envTracked);
|
|
414
|
+
if (rc.status === 0 && rc.stdout.trim())
|
|
415
|
+
restoreCommit = rc.stdout.trim();
|
|
416
|
+
else
|
|
417
|
+
restoreError = `commit-tree (restore): ${rc.stderr.trim()}`;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return { ok: true, ref, commit, restoreCommit, restoreError, indexCommit };
|
|
421
|
+
}
|
|
422
|
+
finally {
|
|
423
|
+
for (const p of [tmpIndex, tmpIndexTracked]) {
|
|
424
|
+
try {
|
|
425
|
+
rmSync(p, { force: true });
|
|
426
|
+
}
|
|
427
|
+
catch {
|
|
428
|
+
/* the temp index is in tmpdir; a leftover is harmless */
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Replay the checkpointed tracked modifications onto the post-sync HEAD.
|
|
435
|
+
*
|
|
436
|
+
* This is the second half of `git stash` semantics. The plan says the
|
|
437
|
+
* checkpoint replaces every use of `git stash` in a sync path, and
|
|
438
|
+
* `mx-post-merge-sync/SKILL.md:59-74` applies its stash back by SHA after the
|
|
439
|
+
* reset. Saving without applying loses the working state of any teammate who
|
|
440
|
+
* did not read the invoking session's console, and no cross-session channel
|
|
441
|
+
* relays that message.
|
|
442
|
+
*
|
|
443
|
+
* `cherry-pick -n` gives a real three-way merge against the new HEAD, so a
|
|
444
|
+
* change that main also made does not silently clobber main's version.
|
|
445
|
+
*
|
|
446
|
+
* ON CONFLICT the working tree is returned to the committed state rather than
|
|
447
|
+
* left with conflict markers. `git cherry-pick --abort` does not work here:
|
|
448
|
+
* under `-n` git writes no CHERRY_PICK_HEAD, and abort exits 128 with "no
|
|
449
|
+
* cherry-pick or revert in progress", leaving the `UU` entries in place
|
|
450
|
+
* (probe, git 2.49.0). `reset --hard HEAD` is the cleanup that works, and it is
|
|
451
|
+
* safe precisely because the published checkpoint ref still holds everything.
|
|
452
|
+
*/
|
|
453
|
+
export function restoreCheckpoint(cwd, restoreCommit, deps = {}, indexCommit = null, headBefore = null) {
|
|
454
|
+
if (!restoreCommit && !indexCommit)
|
|
455
|
+
return { outcome: 'nothing-to-restore' };
|
|
456
|
+
// A null `restoreCommit` here is the LEGITIMATE case only: the tracked
|
|
457
|
+
// working tree matched HEAD, so there is nothing to replay and only the index
|
|
458
|
+
// needs putting back (stage a change, then revert the file on disk). The
|
|
459
|
+
// failure case never reaches this function, because the caller refuses at
|
|
460
|
+
// step 5 on `restoreError`. Skipping the cherry-pick therefore means "there
|
|
461
|
+
// was nothing to pick", not "the pick was skipped because it could not be
|
|
462
|
+
// built", and those two must never share a code path again.
|
|
463
|
+
const pick = restoreCommit
|
|
464
|
+
? runGit(cwd, ['cherry-pick', '-n', '--allow-empty', restoreCommit], deps)
|
|
465
|
+
: { status: 0, stdout: '', stderr: '', skipped: true };
|
|
466
|
+
if (pick.status === 0) {
|
|
467
|
+
// Second half of `git stash apply --index`: the cherry-pick left the index
|
|
468
|
+
// holding the WORKING-TREE bytes for every path it touched, which is wrong
|
|
469
|
+
// for any path that was staged at one version and then edited to another.
|
|
470
|
+
// `git restore --staged` rewrites index entries only, never the working
|
|
471
|
+
// tree, so the `MM` distinction survives the sync (verified, git 2.49.0).
|
|
472
|
+
if (indexCommit && headBefore) {
|
|
473
|
+
// `-z` and split on NUL. Without it, `--name-only` runs through
|
|
474
|
+
// `core.quotePath`, which defaults to true: a path with a non-ASCII byte,
|
|
475
|
+
// a space or a newline comes back C-quoted (`"caf\303\251.txt"`), and
|
|
476
|
+
// feeding that literal back as a pathspec fails. Measured: `restore
|
|
477
|
+
// --staged` exits 1 on a non-ASCII filename and the staged half of the
|
|
478
|
+
// restore is silently skipped while the working tree half succeeded.
|
|
479
|
+
// STATUS IS CHECKED, same defect class as the `stagedNew` call. An
|
|
480
|
+
// unread failure yields `[]`, which reads as "no staged paths to put
|
|
481
|
+
// back", so the index restore is skipped and the run still reports
|
|
482
|
+
// `restored` with the staged/working split silently lost.
|
|
483
|
+
const changedResult = runGit(cwd, ['diff', '--name-only', '-z', headBefore, indexCommit], deps);
|
|
484
|
+
if (changedResult.status !== 0) {
|
|
485
|
+
return {
|
|
486
|
+
outcome: 'error',
|
|
487
|
+
detail: `could not list staged paths to restore: ${changedResult.stderr.trim() || 'command failed'}`,
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
const changed = changedResult.stdout.split('\0').filter(Boolean);
|
|
491
|
+
if (changed.length > 0) {
|
|
492
|
+
const rs = runGit(cwd, ['restore', `--source=${indexCommit}`, '--staged', '--', ...changed], deps);
|
|
493
|
+
if (rs.status !== 0) {
|
|
494
|
+
return { outcome: 'error', detail: `index restore failed: ${rs.stderr.trim()}` };
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
return { outcome: 'restored' };
|
|
499
|
+
}
|
|
500
|
+
const detail = (pick.stderr || pick.stdout).trim().split('\n').slice(0, 3).join(' / ');
|
|
501
|
+
// Status is read here too. It only decides the LABEL (`conflict` versus
|
|
502
|
+
// `error`), and both exit non-zero and print the checkpoint ref, so a failure
|
|
503
|
+
// cannot lose data. It can still mislabel, which sends an operator looking
|
|
504
|
+
// for conflict markers that never existed. Unknown is reported as `error`
|
|
505
|
+
// rather than guessed, and the detail says the probe itself failed.
|
|
506
|
+
const conflictProbe = runGit(cwd, ['diff', '--name-only', '--diff-filter=U'], deps);
|
|
507
|
+
const conflicted = conflictProbe.status === 0 && conflictProbe.stdout.trim().length > 0;
|
|
508
|
+
const probeFailed = conflictProbe.status !== 0;
|
|
509
|
+
// Clear any half-applied state. `--quit` is intentionally unchecked: it is a
|
|
510
|
+
// no-op that exits non-zero when there is no sequencer state, which is the
|
|
511
|
+
// common case under `-n`, so its status carries no information. It is the
|
|
512
|
+
// only deliberately unchecked call in this function.
|
|
513
|
+
runGit(cwd, ['cherry-pick', '--quit'], deps);
|
|
514
|
+
const clean = runGit(cwd, ['reset', '--hard', 'HEAD'], deps);
|
|
515
|
+
if (clean.status !== 0) {
|
|
516
|
+
return { outcome: 'error', detail: `${detail} (and the cleanup reset failed: ${clean.stderr.trim()})` };
|
|
517
|
+
}
|
|
518
|
+
if (probeFailed) {
|
|
519
|
+
return { outcome: 'error', detail: `${detail} (the conflict probe itself failed, so this may or may not be a merge conflict)` };
|
|
520
|
+
}
|
|
521
|
+
return { outcome: conflicted ? 'conflict' : 'error', detail };
|
|
522
|
+
}
|
|
523
|
+
export function listCheckpoints(cwd, worktreeName, deps = {}) {
|
|
524
|
+
const r = runGit(cwd, ['for-each-ref', '--format=%(refname) %(committerdate:unix)', checkpointRefPattern(worktreeName)], deps);
|
|
525
|
+
if (r.status !== 0)
|
|
526
|
+
return [];
|
|
527
|
+
const out = [];
|
|
528
|
+
for (const line of r.stdout.split('\n')) {
|
|
529
|
+
const trimmed = line.trim();
|
|
530
|
+
if (!trimmed)
|
|
531
|
+
continue;
|
|
532
|
+
const sep = trimmed.lastIndexOf(' ');
|
|
533
|
+
if (sep === -1)
|
|
534
|
+
continue;
|
|
535
|
+
const ref = trimmed.slice(0, sep);
|
|
536
|
+
const committedAt = Number(trimmed.slice(sep + 1));
|
|
537
|
+
if (!ref || !Number.isFinite(committedAt))
|
|
538
|
+
continue;
|
|
539
|
+
out.push({ ref, committedAt });
|
|
540
|
+
}
|
|
541
|
+
// Newest first — the keep-window is taken from the front.
|
|
542
|
+
out.sort((a, b) => b.committedAt - a.committedAt);
|
|
543
|
+
return out;
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Delete checkpoint refs past retention. Two independent rules, both applied:
|
|
547
|
+
* anything older than `olderThanDays`, and anything beyond the newest
|
|
548
|
+
* `maxKeep`. Returns the refs actually deleted.
|
|
549
|
+
*/
|
|
550
|
+
export function pruneCheckpoints(options) {
|
|
551
|
+
const { cwd, worktreeName } = options;
|
|
552
|
+
const deps = options.deps ?? {};
|
|
553
|
+
const olderThanDays = options.olderThanDays ?? CHECKPOINT_RETENTION_DAYS;
|
|
554
|
+
const maxKeep = options.maxKeep === undefined ? MAX_CHECKPOINTS_PER_WORKTREE : options.maxKeep;
|
|
555
|
+
const nowSec = Math.floor(dep(deps.now, Date.now)() / 1000);
|
|
556
|
+
const cutoff = nowSec - olderThanDays * 86_400;
|
|
557
|
+
const refs = listCheckpoints(cwd, worktreeName, deps);
|
|
558
|
+
const doomed = new Set();
|
|
559
|
+
for (const r of refs) {
|
|
560
|
+
if (r.committedAt < cutoff)
|
|
561
|
+
doomed.add(r.ref);
|
|
562
|
+
}
|
|
563
|
+
if (maxKeep !== null && refs.length > maxKeep) {
|
|
564
|
+
for (const r of refs.slice(maxKeep))
|
|
565
|
+
doomed.add(r.ref);
|
|
566
|
+
}
|
|
567
|
+
const deleted = [];
|
|
568
|
+
for (const ref of doomed) {
|
|
569
|
+
if (runGit(cwd, ['update-ref', '-d', ref], deps).status === 0)
|
|
570
|
+
deleted.push(ref);
|
|
571
|
+
}
|
|
572
|
+
return deleted.sort();
|
|
573
|
+
}
|
|
574
|
+
/** Parse `--older-than 14d`. Accepts a bare integer as days. Returns null on
|
|
575
|
+
* anything else rather than guessing a unit. */
|
|
576
|
+
export function parseOlderThan(value) {
|
|
577
|
+
const m = /^(\d+)\s*(d|days?)?$/i.exec(value.trim());
|
|
578
|
+
if (!m)
|
|
579
|
+
return null;
|
|
580
|
+
const n = Number(m[1]);
|
|
581
|
+
return Number.isFinite(n) ? n : null;
|
|
582
|
+
}
|
|
583
|
+
// ── sync-exclusive lock (step 1) ──────────────────────────────────────────
|
|
584
|
+
/**
|
|
585
|
+
* The sync-exclusive lock prevents two syncs racing. It is unrelated to the
|
|
586
|
+
* teammate-concurrency hazard and is not counted as a mitigation for it.
|
|
587
|
+
*
|
|
588
|
+
* It lives under `~/.mx-agent/locks/`, NOT in the worktree: a lock file at the
|
|
589
|
+
* worktree root is not covered by this repository's `.gitignore` (which names
|
|
590
|
+
* `.mx-leader.lock` and root-anchored `/.mx-*.json`), so it could ride into a
|
|
591
|
+
* commit on `git add -A`, and the checkpoint's own `add -A` would capture it.
|
|
592
|
+
*/
|
|
593
|
+
export function syncLockPath(worktreeName, deps = {}) {
|
|
594
|
+
const safe = worktreeName.replace(/[^a-zA-Z0-9_.-]/g, '_');
|
|
595
|
+
return join(dep(deps.homeDir, homedir)(), '.mx-agent', 'locks', `worktree-sync-${safe}.lock`);
|
|
596
|
+
}
|
|
597
|
+
export function acquireSyncLock(worktreeName, deps = {}) {
|
|
598
|
+
const p = syncLockPath(worktreeName, deps);
|
|
599
|
+
mkdirSync(join(p, '..'), { recursive: true });
|
|
600
|
+
const payload = JSON.stringify({ pid: process.pid, startedAt: new Date(dep(deps.now, Date.now)()).toISOString() });
|
|
601
|
+
const attempt = () => {
|
|
602
|
+
try {
|
|
603
|
+
writeFileSync(p, payload + '\n', { encoding: 'utf-8', flag: 'wx' });
|
|
604
|
+
return true;
|
|
605
|
+
}
|
|
606
|
+
catch {
|
|
607
|
+
return false;
|
|
608
|
+
}
|
|
609
|
+
};
|
|
610
|
+
if (attempt())
|
|
611
|
+
return { ok: true, path: p };
|
|
612
|
+
// Present already. A lock whose PID is gone is stale — a sync that crashed
|
|
613
|
+
// mid-run must not wedge the command permanently.
|
|
614
|
+
let heldBy = null;
|
|
615
|
+
try {
|
|
616
|
+
const parsed = JSON.parse(readFileSync(p, 'utf-8'));
|
|
617
|
+
heldBy = typeof parsed.pid === 'number' ? parsed.pid : null;
|
|
618
|
+
}
|
|
619
|
+
catch {
|
|
620
|
+
heldBy = null;
|
|
621
|
+
}
|
|
622
|
+
const holderAlive = heldBy !== null && existsSync(`/proc/${heldBy}`);
|
|
623
|
+
if (holderAlive)
|
|
624
|
+
return { ok: false, heldBy, path: p };
|
|
625
|
+
try {
|
|
626
|
+
rmSync(p, { force: true });
|
|
627
|
+
}
|
|
628
|
+
catch {
|
|
629
|
+
return { ok: false, heldBy, path: p };
|
|
630
|
+
}
|
|
631
|
+
return attempt() ? { ok: true, path: p } : { ok: false, heldBy, path: p };
|
|
632
|
+
}
|
|
633
|
+
export function releaseSyncLock(worktreeName, deps = {}) {
|
|
634
|
+
try {
|
|
635
|
+
rmSync(syncLockPath(worktreeName, deps), { force: true });
|
|
636
|
+
}
|
|
637
|
+
catch {
|
|
638
|
+
/* best effort */
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
// ── audit (step 9) ────────────────────────────────────────────────────────
|
|
642
|
+
export function auditLogPath(deps = {}) {
|
|
643
|
+
return join(dep(deps.homeDir, homedir)(), '.mx-agent', 'logs', AUDIT_LOG_FILENAME);
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Append exactly one JSON line. Returns false when the append failed, and the
|
|
647
|
+
* caller says so out loud: a sanctioned destructive git operation that leaves
|
|
648
|
+
* no record is the thing `git-mutation-guard.sh` was hardened against, so a
|
|
649
|
+
* silent logging failure is not an acceptable outcome here.
|
|
650
|
+
*
|
|
651
|
+
* WRITE-TARGET HARDENING (security review, Must Fix 1). The naive
|
|
652
|
+
* `mkdirSync` + `appendFileSync` form has three measured defects, all three
|
|
653
|
+
* already reproduced against `git-mutation-guard.sh` and recorded in its header
|
|
654
|
+
* at `:244-259`:
|
|
655
|
+
*
|
|
656
|
+
* 1. A SYMLINK at the leaf is followed, so the record is appended to a file
|
|
657
|
+
* outside the log directory, and the call returns success. The "this run
|
|
658
|
+
* is unrecorded" warning therefore never prints, which is worse than a
|
|
659
|
+
* failed write: the command asserts a record exists when it does not.
|
|
660
|
+
* 2. A FIFO at the leaf blocks `open()` forever with no reader. That hang
|
|
661
|
+
* happens inside the terminal write, which runs AFTER the destructive step,
|
|
662
|
+
* so the process stops with the reset already done and the `finally` never
|
|
663
|
+
* releases the sync lock. Every later sync in that worktree then refuses.
|
|
664
|
+
* 3. A symlinked log DIRECTORY survives a leaf-only check, because both
|
|
665
|
+
* `mkdirSync` and the append follow directory symlinks.
|
|
666
|
+
*
|
|
667
|
+
* Any process running as the agent user can plant these, and a teammate in this
|
|
668
|
+
* worktree is exactly such a process. The guard's header says bash cannot
|
|
669
|
+
* express the flags that close 1 and 2. Node can, so this does:
|
|
670
|
+
* `O_NOFOLLOW` refuses a symlinked leaf, `O_NONBLOCK` refuses to block on a
|
|
671
|
+
* FIFO, and both are decided by the kernel inside the one `open()` call rather
|
|
672
|
+
* than by a check-then-use. `lstat` on the directory closes 3, and `fstat` on
|
|
673
|
+
* the returned descriptor confirms what was actually opened.
|
|
674
|
+
*/
|
|
675
|
+
export function appendAuditLine(record, deps = {}) {
|
|
676
|
+
const ordered = {};
|
|
677
|
+
for (const field of AUDIT_FIELDS)
|
|
678
|
+
ordered[field] = record[field];
|
|
679
|
+
const p = auditLogPath(deps);
|
|
680
|
+
const dir = join(p, '..');
|
|
681
|
+
let fd;
|
|
682
|
+
try {
|
|
683
|
+
mkdirSync(dir, { recursive: true });
|
|
684
|
+
// `mkdirSync` succeeds on a symlink-to-directory and the append would
|
|
685
|
+
// follow it, so the leaf test alone leaves the redirect intact one level up.
|
|
686
|
+
// `lstat` does not follow, which is the point.
|
|
687
|
+
if (!lstatSync(dir).isDirectory())
|
|
688
|
+
return false;
|
|
689
|
+
fd = openSync(p, fsConstants.O_WRONLY | fsConstants.O_APPEND | fsConstants.O_CREAT | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK, 0o600);
|
|
690
|
+
// Confirm what the kernel actually opened, not what the path looked like.
|
|
691
|
+
if (!fstatSync(fd).isFile())
|
|
692
|
+
return false;
|
|
693
|
+
writeSync(fd, JSON.stringify(ordered) + '\n');
|
|
694
|
+
return true;
|
|
695
|
+
}
|
|
696
|
+
catch {
|
|
697
|
+
return false;
|
|
698
|
+
}
|
|
699
|
+
finally {
|
|
700
|
+
if (fd !== undefined) {
|
|
701
|
+
try {
|
|
702
|
+
closeSync(fd);
|
|
703
|
+
}
|
|
704
|
+
catch {
|
|
705
|
+
/* nothing useful to do with a close failure here */
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Step 0. Refuse unless a live leader session exists in this worktree.
|
|
712
|
+
*
|
|
713
|
+
* Read the module header before extending this: the lock cannot see teammates,
|
|
714
|
+
* and it does not prove the caller IS the leader. It proves a leader session
|
|
715
|
+
* exists here. A stale or absent lock refuses; an indeterminate probe with a
|
|
716
|
+
* fresh heartbeat passes, because `/proc` being unreadable must not brick a
|
|
717
|
+
* legitimate sync (the fail-open contract in leader-lock.ts).
|
|
718
|
+
*/
|
|
719
|
+
export function checkLeaderGate(worktreePath, deps = {}) {
|
|
720
|
+
const { present, lock, parseError } = readLock(worktreePath);
|
|
721
|
+
if (!present)
|
|
722
|
+
return { held: false, reason: 'no leader lock in this worktree' };
|
|
723
|
+
// `parseError` is derived from an attacker-influenceable file and is printed
|
|
724
|
+
// to a terminal, so it goes through the same sanitizer the lock evidence uses
|
|
725
|
+
// (leader-lock.ts:307). A crafted lock could otherwise embed OSC/CSI escape
|
|
726
|
+
// sequences in the refusal message.
|
|
727
|
+
if (!lock) {
|
|
728
|
+
return { held: false, reason: `leader lock is malformed (${sanitizeField(parseError ?? 'unparseable')})` };
|
|
729
|
+
}
|
|
730
|
+
const liveness = checkLiveness(lock, worktreePath);
|
|
731
|
+
if (liveness.state === 'live')
|
|
732
|
+
return { held: true };
|
|
733
|
+
if (liveness.state === 'indeterminate' &&
|
|
734
|
+
liveness.lockAgeSeconds !== null &&
|
|
735
|
+
liveness.lockAgeSeconds <= HEARTBEAT_FRESH_SECONDS) {
|
|
736
|
+
return { held: true };
|
|
737
|
+
}
|
|
738
|
+
return {
|
|
739
|
+
held: false,
|
|
740
|
+
reason: liveness.state === 'stale'
|
|
741
|
+
? 'leader lock is stale (no live session)'
|
|
742
|
+
: 'leader liveness is indeterminate and the lock heartbeat is not fresh',
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
// ── step 7 helper: the squash point ───────────────────────────────────────
|
|
746
|
+
/**
|
|
747
|
+
* The last commit of this branch's merged pull request, read from
|
|
748
|
+
* `gh pr view --json commits` rather than guessed. Returns null when there is
|
|
749
|
+
* no merged PR for the branch, when gh is missing or unauthenticated, or when
|
|
750
|
+
* the payload does not parse: every one of those routes to the plain rebase
|
|
751
|
+
* arm, which is correct-but-slower rather than wrong.
|
|
752
|
+
*/
|
|
753
|
+
/** A full 40-character hex object name and nothing else. Anything that fails
|
|
754
|
+
* this never reaches a git command line. */
|
|
755
|
+
export const OID_RE = /^[0-9a-f]{40}$/;
|
|
756
|
+
export function findSquashPoint(cwd, branch, deps = {}) {
|
|
757
|
+
// `--limit 1` orders by CREATION, not merge time. Branch names are reused
|
|
758
|
+
// across this repository: `worktree/bootstrap-20260821` has 31 merged pull
|
|
759
|
+
// requests as measured on 2026-08-25. The newest-created is not necessarily
|
|
760
|
+
// the newest-merged, so the whole set is fetched and sorted by `mergedAt`
|
|
761
|
+
// (red team Finding 3).
|
|
762
|
+
const list = runGh(cwd, ['pr', 'list', '--head', branch, '--state', 'merged', '--limit', '100', '--json', 'number,mergedAt'], deps);
|
|
763
|
+
if (list.status !== 0)
|
|
764
|
+
return null;
|
|
765
|
+
let number = null;
|
|
766
|
+
try {
|
|
767
|
+
const parsed = JSON.parse(list.stdout || '[]');
|
|
768
|
+
if (!Array.isArray(parsed))
|
|
769
|
+
return null;
|
|
770
|
+
const usable = parsed
|
|
771
|
+
.filter((p) => typeof p.number === 'number' && typeof p.mergedAt === 'string' && p.mergedAt.length > 0)
|
|
772
|
+
.sort((a, b) => (a.mergedAt < b.mergedAt ? 1 : a.mergedAt > b.mergedAt ? -1 : 0));
|
|
773
|
+
number = usable[0]?.number ?? null;
|
|
774
|
+
}
|
|
775
|
+
catch {
|
|
776
|
+
return null;
|
|
777
|
+
}
|
|
778
|
+
if (number === null)
|
|
779
|
+
return null;
|
|
780
|
+
const view = runGh(cwd, ['pr', 'view', String(number), '--json', 'commits'], deps);
|
|
781
|
+
if (view.status !== 0)
|
|
782
|
+
return null;
|
|
783
|
+
try {
|
|
784
|
+
const parsed = JSON.parse(view.stdout || '{}');
|
|
785
|
+
const commits = parsed.commits ?? [];
|
|
786
|
+
const last = commits[commits.length - 1];
|
|
787
|
+
const oid = typeof last?.oid === 'string' ? last.oid : '';
|
|
788
|
+
// The oid comes from the GitHub API response, which is outside this
|
|
789
|
+
// program's trust boundary and reaches a git command line. Validate the
|
|
790
|
+
// shape before it goes anywhere near `rebase --onto`.
|
|
791
|
+
return OID_RE.test(oid) ? { oid, prNumber: number } : null;
|
|
792
|
+
}
|
|
793
|
+
catch {
|
|
794
|
+
return null;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
* True when some multi-step git operation is half-finished in this worktree.
|
|
799
|
+
*
|
|
800
|
+
* `MERGE_HEAD` and `CHERRY_PICK_HEAD` matter as much as the rebase states: step
|
|
801
|
+
* 7 runs `reset --hard HEAD`, which clears an in-progress merge and discards
|
|
802
|
+
* whatever conflict resolution the operator had done so far, with no warning
|
|
803
|
+
* and nothing to recover from because that work was never committed anywhere.
|
|
804
|
+
* `REVERT_HEAD` is included for the same reason.
|
|
805
|
+
*/
|
|
806
|
+
export function pendingGitOperation(cwd, deps = {}) {
|
|
807
|
+
for (const name of ['rebase-merge', 'rebase-apply', 'MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD']) {
|
|
808
|
+
const r = runGit(cwd, ['rev-parse', '--git-path', name], deps);
|
|
809
|
+
if (r.status !== 0)
|
|
810
|
+
continue;
|
|
811
|
+
const rel = r.stdout.trim();
|
|
812
|
+
if (!rel)
|
|
813
|
+
continue;
|
|
814
|
+
if (existsSync(join(cwd, rel)) || existsSync(rel))
|
|
815
|
+
return name;
|
|
816
|
+
}
|
|
817
|
+
return null;
|
|
818
|
+
}
|
|
819
|
+
/** True when a rebase specifically is in progress. Step 8 uses this to decide
|
|
820
|
+
* whether a failed rebase left state worth aborting. Uses `--git-path` so it
|
|
821
|
+
* is correct in a LINKED worktree, where the state lives under
|
|
822
|
+
* `.git/worktrees/<name>/` and not `.git/`. */
|
|
823
|
+
export function rebaseInProgress(cwd, deps = {}) {
|
|
824
|
+
for (const name of ['rebase-merge', 'rebase-apply']) {
|
|
825
|
+
const r = runGit(cwd, ['rev-parse', '--git-path', name], deps);
|
|
826
|
+
if (r.status !== 0)
|
|
827
|
+
continue;
|
|
828
|
+
const rel = r.stdout.trim();
|
|
829
|
+
if (!rel)
|
|
830
|
+
continue;
|
|
831
|
+
if (existsSync(join(cwd, rel)) || existsSync(rel))
|
|
832
|
+
return true;
|
|
833
|
+
}
|
|
834
|
+
return false;
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* The nine-step algorithm from #172, in the plan's order.
|
|
838
|
+
*
|
|
839
|
+
* The checkpoint is step 5: after the quiescence sample at step 4 and before
|
|
840
|
+
* the destructive step at step 7, with a re-sample at step 6 that aborts on
|
|
841
|
+
* change. That ordering puts the checkpoint as late as the design allows, to
|
|
842
|
+
* shrink the window rather than pretend it is closed. Do not reorder it.
|
|
843
|
+
*/
|
|
844
|
+
export function runWorktreeSyncCore(options) {
|
|
845
|
+
const deps = options.deps ?? {};
|
|
846
|
+
const cwd = options.worktreePath;
|
|
847
|
+
const worktreeName = options.worktreeName ?? basename(cwd);
|
|
848
|
+
const lines = [];
|
|
849
|
+
const emit = (l) => {
|
|
850
|
+
lines.push(l);
|
|
851
|
+
deps.emit?.(l);
|
|
852
|
+
};
|
|
853
|
+
const audit = {
|
|
854
|
+
runId: `${dep(deps.now, Date.now)()}-${dep(deps.rand6, defaultRand6)()}`,
|
|
855
|
+
timestamp: new Date(dep(deps.now, Date.now)()).toISOString(),
|
|
856
|
+
worktree: worktreeName,
|
|
857
|
+
caller: options.caller,
|
|
858
|
+
quiescenceAsserted: options.assertNoTeammatesActive === true,
|
|
859
|
+
baseRef: null,
|
|
860
|
+
headBefore: null,
|
|
861
|
+
headAfter: null,
|
|
862
|
+
checkpointRef: null,
|
|
863
|
+
syncBranch: null,
|
|
864
|
+
refsPruned: [],
|
|
865
|
+
outcome: 'error',
|
|
866
|
+
};
|
|
867
|
+
/** Guards against a terminal record being written twice when a signal
|
|
868
|
+
* handler fires around a normal return. */
|
|
869
|
+
let terminalWritten = false;
|
|
870
|
+
const writeTerminal = (outcome) => {
|
|
871
|
+
if (terminalWritten)
|
|
872
|
+
return true;
|
|
873
|
+
terminalWritten = true;
|
|
874
|
+
audit.outcome = outcome;
|
|
875
|
+
return appendAuditLine(audit, deps);
|
|
876
|
+
};
|
|
877
|
+
const finish = (outcome, exitCode) => {
|
|
878
|
+
const auditWritten = writeTerminal(outcome);
|
|
879
|
+
if (!auditWritten) {
|
|
880
|
+
emit(`WARNING: could not append the audit line to ${auditLogPath(deps)}. This run is unrecorded.`);
|
|
881
|
+
}
|
|
882
|
+
return { exitCode, audit, checkpointRef: audit.checkpointRef, lines, auditWritten };
|
|
883
|
+
};
|
|
884
|
+
// HEAD is read before every gate so even a refusal records where the
|
|
885
|
+
// worktree stood. A refused sync is exactly what someone will later look for.
|
|
886
|
+
audit.headBefore = readHead(cwd, deps);
|
|
887
|
+
audit.headAfter = audit.headBefore;
|
|
888
|
+
// ── step 0 ──────────────────────────────────────────────────────────────
|
|
889
|
+
const gate = deps.leaderGate ? deps.leaderGate(cwd) : checkLeaderGate(cwd, deps);
|
|
890
|
+
if (!gate.held) {
|
|
891
|
+
emit(`Refusing to sync: ${gate.reason}.`);
|
|
892
|
+
emit('This command runs from a leader session in this worktree. Start one, or run it there.');
|
|
893
|
+
return finish('refused-no-leader-lock', 1);
|
|
894
|
+
}
|
|
895
|
+
// A half-finished git operation is not this command's to touch. Two ways it
|
|
896
|
+
// would be destroyed otherwise: step 8's `rebase --abort` would abort SOMEONE
|
|
897
|
+
// ELSE's rebase, and step 7's `reset --hard HEAD` would clear an in-progress
|
|
898
|
+
// merge or cherry-pick along with its conflict resolution.
|
|
899
|
+
const pending = pendingGitOperation(cwd, deps);
|
|
900
|
+
if (pending) {
|
|
901
|
+
emit(`Refusing to sync: ${pending} is present, so a git operation is already half-finished here.`);
|
|
902
|
+
emit('Finish or abort it yourself. This command will not clear state it did not create.');
|
|
903
|
+
return finish('refused-rebase-in-progress', 1);
|
|
904
|
+
}
|
|
905
|
+
// ── step 0a ─────────────────────────────────────────────────────────────
|
|
906
|
+
if (!audit.quiescenceAsserted) {
|
|
907
|
+
emit('Refusing to sync: the caller has not asserted that no teammate is active in this worktree.');
|
|
908
|
+
emit('Re-run with --assert-no-teammates-active once you have confirmed it.');
|
|
909
|
+
emit('That assertion is self-reported. It is recorded in the audit line and verifies nothing on its own.');
|
|
910
|
+
return finish('refused-no-quiescence-assertion', 1);
|
|
911
|
+
}
|
|
912
|
+
// ── step 1 ──────────────────────────────────────────────────────────────
|
|
913
|
+
const lock = acquireSyncLock(worktreeName, deps);
|
|
914
|
+
if (!lock.ok) {
|
|
915
|
+
emit(`Refusing to sync: another sync holds ${lock.path}${lock.heldBy ? ` (pid ${lock.heldBy})` : ''}.`);
|
|
916
|
+
return finish('refused-sync-lock-held', 1);
|
|
917
|
+
}
|
|
918
|
+
try {
|
|
919
|
+
const hasOrigin = dep(deps.hasOriginRemote, defaultHasOriginRemote);
|
|
920
|
+
if (!hasOrigin(cwd)) {
|
|
921
|
+
emit('Refusing to sync: this repository has no `origin` remote.');
|
|
922
|
+
return finish('refused-no-origin-remote', 1);
|
|
923
|
+
}
|
|
924
|
+
const branch = dep(deps.getCurrentBranch, defaultGetCurrentBranch)(cwd);
|
|
925
|
+
if (!branch) {
|
|
926
|
+
emit('Refusing to sync: HEAD is detached, so there is no branch to rebase.');
|
|
927
|
+
return finish('refused-detached-head', 1);
|
|
928
|
+
}
|
|
929
|
+
const baseRef = `origin/${options.baseBranch}`;
|
|
930
|
+
audit.baseRef = baseRef;
|
|
931
|
+
// ── step 2 ────────────────────────────────────────────────────────────
|
|
932
|
+
// Reused unchanged from lib/worktree.ts. It takes `cwd` alone and runs a
|
|
933
|
+
// hardcoded literal; nothing interpolated is routed through it.
|
|
934
|
+
if (!dep(deps.fetchOrigin, defaultFetchOrigin)(cwd)) {
|
|
935
|
+
emit('Refusing to sync: `git fetch origin` failed, so origin state is unknown.');
|
|
936
|
+
return finish('refused-fetch-failed', 1);
|
|
937
|
+
}
|
|
938
|
+
if (!dep(deps.refExists, defaultRefExists)(baseRef, cwd)) {
|
|
939
|
+
emit(`Refusing to sync: ${baseRef} does not resolve after a successful fetch.`);
|
|
940
|
+
return finish('refused-base-ref-missing', 1);
|
|
941
|
+
}
|
|
942
|
+
// ── step 3 ────────────────────────────────────────────────────────────
|
|
943
|
+
// One slot is RESERVED for the checkpoint this run may write at step 5.
|
|
944
|
+
// The plan prunes at step 3 only and caps the namespace at 20; pruning TO
|
|
945
|
+
// 20 here and then writing one leaves 21, which fails the cap the plan
|
|
946
|
+
// states. Reserving the slot keeps "at most 20 refs per worktree" true
|
|
947
|
+
// after every run, at the cost of one slot on a clean sync.
|
|
948
|
+
audit.refsPruned = pruneCheckpoints({
|
|
949
|
+
cwd,
|
|
950
|
+
worktreeName,
|
|
951
|
+
maxKeep: MAX_CHECKPOINTS_PER_WORKTREE - 1,
|
|
952
|
+
deps,
|
|
953
|
+
});
|
|
954
|
+
if (audit.refsPruned.length > 0) {
|
|
955
|
+
emit(`Pruned ${audit.refsPruned.length} checkpoint ref(s) past retention.`);
|
|
956
|
+
}
|
|
957
|
+
// ── step 4 ────────────────────────────────────────────────────────────
|
|
958
|
+
const before = sampleWorkingTree(cwd, deps);
|
|
959
|
+
if (!before.readable) {
|
|
960
|
+
emit('Refusing to sync: `git status` failed, so the working tree state is unknown.');
|
|
961
|
+
emit('An unreadable status is not an empty one. Nothing was mutated.');
|
|
962
|
+
return finish('refused-status-unreadable', 1);
|
|
963
|
+
}
|
|
964
|
+
// ── step 5 ────────────────────────────────────────────────────────────
|
|
965
|
+
let restoreCommit = null;
|
|
966
|
+
let indexCommit = null;
|
|
967
|
+
if (isDirty(before)) {
|
|
968
|
+
const cp = createCheckpoint(cwd, worktreeName, deps);
|
|
969
|
+
if (!cp.ok || !cp.ref) {
|
|
970
|
+
emit(`Refusing to sync: the checkpoint could not be created (${cp.error ?? 'unknown error'}).`);
|
|
971
|
+
emit('Nothing was mutated. A sync that cannot save the working tree does not proceed to reset it.');
|
|
972
|
+
return finish(cp.error?.includes('check-ref-format') ? 'refused-invalid-checkpoint-ref' : 'error', 1);
|
|
973
|
+
}
|
|
974
|
+
audit.checkpointRef = cp.ref;
|
|
975
|
+
restoreCommit = cp.restoreCommit;
|
|
976
|
+
indexCommit = cp.indexCommit;
|
|
977
|
+
emit(`Checkpoint: ${cp.ref}`);
|
|
978
|
+
emit(` working tree: git show ${cp.ref}:<path>`);
|
|
979
|
+
if (cp.indexCommit) {
|
|
980
|
+
emit(` staged bytes: git show ${cp.ref}^2:<path> (the index, kept separately as git stash does)`);
|
|
981
|
+
}
|
|
982
|
+
emit(` recover all: git checkout ${cp.ref} -- <path>`);
|
|
983
|
+
// If the restore tree could not be built, the restore CANNOT happen. Say
|
|
984
|
+
// so now and mutate nothing, rather than resetting the working tree and
|
|
985
|
+
// discovering it afterwards. The operator ends up exactly where they
|
|
986
|
+
// started, plus a checkpoint ref holding everything.
|
|
987
|
+
//
|
|
988
|
+
// A run that reported success here while silently reverting a tracked
|
|
989
|
+
// edit and deleting a staged file is the reason this branch exists.
|
|
990
|
+
if (cp.restoreError && options.restore !== false) {
|
|
991
|
+
emit(`Refusing to sync: the checkpoint was written, but the restore could not be prepared.`);
|
|
992
|
+
emit(` reason: ${cp.restoreError}`);
|
|
993
|
+
emit(` Nothing was mutated. Your working tree is untouched.`);
|
|
994
|
+
emit(` Everything is also saved at ${cp.ref}:`);
|
|
995
|
+
emit(` git checkout ${cp.ref} -- <path>`);
|
|
996
|
+
emit(' Re-run with --no-restore to sync anyway and recover from the ref by hand.');
|
|
997
|
+
return finish('restore-failed', 1);
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
// ── step 6 ────────────────────────────────────────────────────────────
|
|
1001
|
+
const after = sampleWorkingTree(cwd, deps);
|
|
1002
|
+
if (!after.readable) {
|
|
1003
|
+
emit('Refusing to sync: `git status` failed on the re-sample. Nothing was mutated.');
|
|
1004
|
+
return finish('refused-status-unreadable', 1);
|
|
1005
|
+
}
|
|
1006
|
+
if (after.digest !== before.digest) {
|
|
1007
|
+
emit('Refusing to sync: the working tree changed while the checkpoint was being written.');
|
|
1008
|
+
emit('Nothing was mutated. Something is writing here — find it, then re-run.');
|
|
1009
|
+
if (audit.checkpointRef)
|
|
1010
|
+
emit(`The checkpoint written before the change is ${audit.checkpointRef}.`);
|
|
1011
|
+
return finish('refused-not-quiescent', 1);
|
|
1012
|
+
}
|
|
1013
|
+
// ── step 7 ────────────────────────────────────────────────────────────
|
|
1014
|
+
// DEVIATION FROM THE PLAN'S LITERAL NINE STEPS, flagged rather than silent.
|
|
1015
|
+
// The plan says the checkpoint replaces `git stash push` in every sync
|
|
1016
|
+
// path. `stash push` does two things: it SAVES the tracked working tree and
|
|
1017
|
+
// it CLEANS it. Steps 5 and 8 describe only the save. Without the clean,
|
|
1018
|
+
// both rebase arms of step 7 are unreachable: git refuses to start a rebase
|
|
1019
|
+
// with unstaged changes ("cannot rebase: You have unstaged changes"), so a
|
|
1020
|
+
// dirty tree could never reach a conflict, and criteria 2 and 5 could not
|
|
1021
|
+
// pass. The clean is placed HERE, after the step-6 re-sample, not inside
|
|
1022
|
+
// step 5, so it does not falsify the quiescence comparison with its own
|
|
1023
|
+
// write. Tracked modifications are already in the checkpoint. Untracked
|
|
1024
|
+
// files are NOT touched: `reset --hard` leaves them, which is what
|
|
1025
|
+
// criterion 7 requires.
|
|
1026
|
+
// The squash point is resolved BEFORE the in-progress record is written, so
|
|
1027
|
+
// a refusal here never leaves a dangling `in-progress` line.
|
|
1028
|
+
const diff = runGit(cwd, ['diff', '--quiet', baseRef, 'HEAD'], deps);
|
|
1029
|
+
let squashPoint = null;
|
|
1030
|
+
if (diff.status !== 0) {
|
|
1031
|
+
squashPoint = findSquashPoint(cwd, branch, deps);
|
|
1032
|
+
if (squashPoint) {
|
|
1033
|
+
// The oid names a commit on a branch with many merged pull requests
|
|
1034
|
+
// sharing its name. `rebase --onto <base> <oid>` replays the range
|
|
1035
|
+
// <oid>..HEAD, so an oid that is NOT an ancestor of HEAD silently
|
|
1036
|
+
// replays a stale or foreign range. Refuse instead (red team Finding 3).
|
|
1037
|
+
const anc = runGit(cwd, ['merge-base', '--is-ancestor', squashPoint.oid, 'HEAD'], deps);
|
|
1038
|
+
if (anc.status !== 0) {
|
|
1039
|
+
emit(`Refusing to sync: the squash point from pull request #${squashPoint.prNumber} is not an ancestor of HEAD.`);
|
|
1040
|
+
emit(` oid: ${squashPoint.oid}`);
|
|
1041
|
+
emit(' `rebase --onto` would replay a range this branch does not contain. Resolve by hand.');
|
|
1042
|
+
return finish('refused-squash-point-not-ancestor', 1);
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
// ── F1: crash durability ──────────────────────────────────────────────
|
|
1047
|
+
// Everything below this line mutates the repository. Output is buffered in
|
|
1048
|
+
// memory and the terminal record is written at a return point, so a process
|
|
1049
|
+
// killed here would otherwise leave no trace at all: not in the log, not on
|
|
1050
|
+
// the console. This record is what makes a killed run findable. An
|
|
1051
|
+
// `in-progress` record with no matching `runId` in a terminal record IS the
|
|
1052
|
+
// signal that a sync died during the destructive step.
|
|
1053
|
+
//
|
|
1054
|
+
// THIS RECORD IS THE WHOLE PROTECTION. There is deliberately no signal
|
|
1055
|
+
// handler here, and adding one would make things worse rather than better.
|
|
1056
|
+
// The destructive sequence below is entirely synchronous `execFileSync`,
|
|
1057
|
+
// and Node dispatches signal handlers on the event loop, which cannot turn
|
|
1058
|
+
// during synchronous code. Registering a SIGTERM or SIGINT listener also
|
|
1059
|
+
// REPLACES Node's default termination, so the only observable effect is
|
|
1060
|
+
// that the signal is discarded: an operator pressing Ctrl-C mid-reset gets
|
|
1061
|
+
// silence, and the sync runs to completion anyway. Measured three ways on
|
|
1062
|
+
// Node v22.16.0: no listener plus a synchronous block exits 143 on SIGTERM;
|
|
1063
|
+
// a listener plus a synchronous block runs to completion with the handler
|
|
1064
|
+
// never executing; a listener plus a turning event loop runs the handler.
|
|
1065
|
+
// The first behaviour is the one worth keeping, so nothing is registered.
|
|
1066
|
+
if (!appendAuditLine({ ...audit, outcome: 'in-progress' }, deps)) {
|
|
1067
|
+
emit(`Refusing to sync: could not write the in-progress audit record to ${auditLogPath(deps)}.`);
|
|
1068
|
+
emit('A destructive step that cannot be recorded does not run. Nothing was mutated.');
|
|
1069
|
+
return finish('error', 1);
|
|
1070
|
+
}
|
|
1071
|
+
{
|
|
1072
|
+
if (audit.checkpointRef) {
|
|
1073
|
+
const clean = runGit(cwd, ['reset', '--hard', 'HEAD'], deps);
|
|
1074
|
+
if (clean.status !== 0) {
|
|
1075
|
+
emit(`Could not return the working tree to its committed state: ${clean.stderr.trim()}`);
|
|
1076
|
+
emit(`Nothing further was mutated. The checkpoint is ${audit.checkpointRef}.`);
|
|
1077
|
+
return finish('error', 1);
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
if (diff.status === 0) {
|
|
1081
|
+
audit.syncBranch = 'reset';
|
|
1082
|
+
const reset = runGit(cwd, ['reset', '--hard', baseRef], deps);
|
|
1083
|
+
if (reset.status !== 0) {
|
|
1084
|
+
emit(`reset --hard ${baseRef} failed: ${reset.stderr.trim()}`);
|
|
1085
|
+
return finish('error', 1);
|
|
1086
|
+
}
|
|
1087
|
+
emit(`Reset to ${baseRef}: the trees were identical, so no tracked file content was discarded.`);
|
|
1088
|
+
emit('Commit messages, authorship, signatures and notes on the pre-reset HEAD are gone; the reflog is the only fallback and it expires.');
|
|
1089
|
+
}
|
|
1090
|
+
else {
|
|
1091
|
+
// `--end-of-options` so an oid can never be read as an option. It is
|
|
1092
|
+
// already constrained to 40 hex characters by OID_RE; this is the
|
|
1093
|
+
// second of the two independent checks.
|
|
1094
|
+
const rebaseArgs = squashPoint
|
|
1095
|
+
? ['rebase', '--onto', baseRef, '--end-of-options', squashPoint.oid]
|
|
1096
|
+
: ['rebase', baseRef];
|
|
1097
|
+
audit.syncBranch = squashPoint ? 'rebase-onto' : 'rebase';
|
|
1098
|
+
if (squashPoint) {
|
|
1099
|
+
emit(`Pull request #${squashPoint.prNumber} was squash-merged. Replaying commits after ${squashPoint.oid} onto ${baseRef}.`);
|
|
1100
|
+
}
|
|
1101
|
+
else {
|
|
1102
|
+
emit(`Rebasing onto ${baseRef}.`);
|
|
1103
|
+
}
|
|
1104
|
+
const rebase = runGit(cwd, rebaseArgs, deps);
|
|
1105
|
+
if (rebase.status !== 0) {
|
|
1106
|
+
// ── step 8 ──────────────────────────────────────────────────────
|
|
1107
|
+
// A real merge conflict leaves rebase state behind. A refused start
|
|
1108
|
+
// or an I/O failure does not. Telling them apart stops an operator
|
|
1109
|
+
// being sent to look for conflict markers that never existed.
|
|
1110
|
+
const wasConflict = rebaseInProgress(cwd, deps);
|
|
1111
|
+
emit(`Rebase failed: ${(rebase.stderr || rebase.stdout).trim()}`);
|
|
1112
|
+
if (wasConflict) {
|
|
1113
|
+
const abort = runGit(cwd, ['rebase', '--abort'], deps);
|
|
1114
|
+
if (abort.status !== 0 && rebaseInProgress(cwd, deps)) {
|
|
1115
|
+
runGit(cwd, ['rebase', '--quit'], deps);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
if (rebaseInProgress(cwd, deps)) {
|
|
1119
|
+
emit('A rebase is STILL in progress after the abort. Resolve it by hand before re-running.');
|
|
1120
|
+
}
|
|
1121
|
+
else if (wasConflict) {
|
|
1122
|
+
emit('Aborted to a clean state. No manual `git rebase --abort` is needed.');
|
|
1123
|
+
}
|
|
1124
|
+
else {
|
|
1125
|
+
emit('The rebase never started, so there was nothing to abort. This is not a merge conflict.');
|
|
1126
|
+
}
|
|
1127
|
+
if (audit.checkpointRef)
|
|
1128
|
+
emit(`Checkpoint: ${audit.checkpointRef}`);
|
|
1129
|
+
audit.headAfter = readHead(cwd, deps);
|
|
1130
|
+
return finish(wasConflict ? 'conflict' : 'rebase-failed', 1);
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
audit.headAfter = readHead(cwd, deps);
|
|
1134
|
+
// ── F2: restore ───────────────────────────────────────────────────────
|
|
1135
|
+
// Saving without applying loses the working state of any teammate who did
|
|
1136
|
+
// not read this session's console, and no cross-session channel relays it.
|
|
1137
|
+
if (audit.checkpointRef && options.restore !== false) {
|
|
1138
|
+
const restored = restoreCheckpoint(cwd, restoreCommit, deps, indexCommit, audit.headBefore);
|
|
1139
|
+
if (restored.outcome === 'restored') {
|
|
1140
|
+
emit('Restored the checkpointed working tree on top of the synced HEAD.');
|
|
1141
|
+
if (indexCommit)
|
|
1142
|
+
emit('Staged content was restored to the index separately, as `git stash apply --index` does.');
|
|
1143
|
+
}
|
|
1144
|
+
else if (restored.outcome === 'conflict' || restored.outcome === 'error') {
|
|
1145
|
+
emit(`The checkpoint could not be reapplied: ${restored.detail ?? 'unknown reason'}`);
|
|
1146
|
+
emit('The working tree was returned to the committed state rather than left half-merged.');
|
|
1147
|
+
emit(`Nothing is lost. Recover from ${audit.checkpointRef}:`);
|
|
1148
|
+
emit(` git checkout ${audit.checkpointRef} -- <path>`);
|
|
1149
|
+
emit(`HEAD is now ${audit.headAfter ?? 'unknown'}.`);
|
|
1150
|
+
// A conflict is a specific, expected outcome. Anything else is not,
|
|
1151
|
+
// and the two are told apart so the log does not send someone looking
|
|
1152
|
+
// for a merge conflict that never happened.
|
|
1153
|
+
return finish(restored.outcome === 'conflict' ? 'restore-conflict' : 'restore-failed', 1);
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
else if (audit.checkpointRef) {
|
|
1157
|
+
emit(`--no-restore: the working tree is left at the committed state. Recover from ${audit.checkpointRef}.`);
|
|
1158
|
+
}
|
|
1159
|
+
emit(`HEAD is now ${audit.headAfter ?? 'unknown'}.`);
|
|
1160
|
+
return finish('ok', 0);
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
finally {
|
|
1164
|
+
releaseSyncLock(worktreeName, deps);
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
//# sourceMappingURL=worktree-sync.js.map
|