@ornexus/neocortex 4.65.1 → 4.66.1

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.
Files changed (150) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1206 -1193
  3. package/install.ps1 +243 -77
  4. package/install.sh +221 -102
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/platform-detector.js +1 -1
  7. package/packages/client/dist/agent/refresh-stubs.d.ts +50 -0
  8. package/packages/client/dist/agent/refresh-stubs.js +2 -2
  9. package/packages/client/dist/cli.js +5 -4
  10. package/packages/client/dist/commands/doctor.d.ts +26 -1
  11. package/packages/client/dist/commands/doctor.js +2 -2
  12. package/packages/client/dist/commands/invoke.d.ts +183 -5
  13. package/packages/client/dist/commands/invoke.js +94 -87
  14. package/packages/client/dist/commands/planning-qa.d.ts +64 -0
  15. package/packages/client/dist/commands/planning-qa.js +1 -0
  16. package/packages/client/dist/commands/refactor-control.js +3 -3
  17. package/packages/client/dist/commands/story-checkpoint.d.ts +3 -1
  18. package/packages/client/dist/commands/story-checkpoint.js +1 -1
  19. package/packages/client/dist/commands/story-worktree.d.ts +1 -1
  20. package/packages/client/dist/commands/story-worktree.js +1 -1
  21. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +64 -1
  22. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -3
  23. package/packages/client/dist/git/epic-lifecycle-evidence.d.ts +184 -0
  24. package/packages/client/dist/git/epic-lifecycle-evidence.js +6 -0
  25. package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
  26. package/packages/client/dist/git/git-lifecycle-store.js +9 -8
  27. package/packages/client/dist/git/governance-runtime-store.d.ts +172 -0
  28. package/packages/client/dist/git/governance-runtime-store.js +3 -0
  29. package/packages/client/dist/git/story-worktree-cleanup.js +1 -1
  30. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  31. package/packages/client/dist/git/story-worktree-manager.d.ts +39 -0
  32. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  33. package/packages/client/dist/git/story-write-set-extension.d.ts +62 -0
  34. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  35. package/packages/client/dist/memory/shared-project-memory-types.d.ts +39 -2
  36. package/packages/client/dist/memory/shared-project-memory-types.js +2 -2
  37. package/packages/client/dist/policy/subagent-approval-policy.js +1 -1
  38. package/packages/client/dist/private-execution/codex-executor.d.ts +21 -1
  39. package/packages/client/dist/private-execution/codex-executor.js +4 -4
  40. package/packages/client/dist/private-execution/delivery.d.ts +17 -11
  41. package/packages/client/dist/private-execution/delivery.js +8 -6
  42. package/packages/client/dist/private-execution/diagnosis-root-review.d.ts +89 -0
  43. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -2
  44. package/packages/client/dist/private-execution/frozen-handoff.js +3 -3
  45. package/packages/client/dist/private-execution/harness-adapters/antigravity.d.ts +9 -0
  46. package/packages/client/dist/private-execution/harness-adapters/antigravity.js +1 -0
  47. package/packages/client/dist/private-execution/harness-adapters/claude-code.d.ts +8 -0
  48. package/packages/client/dist/private-execution/harness-adapters/claude-code.js +1 -0
  49. package/packages/client/dist/private-execution/harness-adapters/codex.d.ts +7 -0
  50. package/packages/client/dist/private-execution/harness-adapters/codex.js +1 -0
  51. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.d.ts +8 -0
  52. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.js +1 -0
  53. package/packages/client/dist/private-execution/harness-adapters/cursor.d.ts +9 -0
  54. package/packages/client/dist/private-execution/harness-adapters/cursor.js +1 -0
  55. package/packages/client/dist/private-execution/harness-adapters/deepseek.d.ts +9 -0
  56. package/packages/client/dist/private-execution/harness-adapters/deepseek.js +1 -0
  57. package/packages/client/dist/private-execution/harness-adapters/gemini.d.ts +8 -0
  58. package/packages/client/dist/private-execution/harness-adapters/gemini.js +1 -0
  59. package/packages/client/dist/private-execution/harness-adapters/grok.d.ts +9 -0
  60. package/packages/client/dist/private-execution/harness-adapters/grok.js +1 -0
  61. package/packages/client/dist/private-execution/harness-adapters/index.d.ts +73 -0
  62. package/packages/client/dist/private-execution/harness-adapters/index.js +1 -0
  63. package/packages/client/dist/private-execution/harness-adapters/kimi.d.ts +9 -0
  64. package/packages/client/dist/private-execution/harness-adapters/kimi.js +1 -0
  65. package/packages/client/dist/private-execution/harness-adapters/openclaw.d.ts +9 -0
  66. package/packages/client/dist/private-execution/harness-adapters/openclaw.js +1 -0
  67. package/packages/client/dist/private-execution/harness-adapters/opencode.d.ts +7 -0
  68. package/packages/client/dist/private-execution/harness-adapters/opencode.js +1 -0
  69. package/packages/client/dist/private-execution/harness-ephemeral-home.d.ts +19 -0
  70. package/packages/client/dist/private-execution/harness-ephemeral-home.js +1 -0
  71. package/packages/client/dist/private-execution/harness-executor.d.ts +79 -0
  72. package/packages/client/dist/private-execution/harness-executor.js +1 -0
  73. package/packages/client/dist/private-execution/harness-process.d.ts +43 -0
  74. package/packages/client/dist/private-execution/harness-process.js +1 -0
  75. package/packages/client/dist/private-execution/isolated-admission.js +12 -12
  76. package/packages/client/dist/private-execution/isolated-workspace.d.ts +16 -1
  77. package/packages/client/dist/private-execution/isolated-workspace.js +1 -1
  78. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +75 -1
  79. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -5
  80. package/packages/client/dist/private-execution/planning-generation-checkpoint.d.ts +9 -1
  81. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +4 -4
  82. package/packages/client/dist/private-execution/planning-research-checkpoint.d.ts +9 -1
  83. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -4
  84. package/packages/client/dist/private-execution/root-memory-request.d.ts +4 -1
  85. package/packages/client/dist/private-execution/root-memory-request.js +1 -1
  86. package/packages/client/dist/runner/epic-background-dispatcher.d.ts +3 -1
  87. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -1
  88. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -1
  89. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -22
  90. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +6 -10
  91. package/packages/client/dist/runner/headless/managed-profile.d.ts +20 -0
  92. package/packages/client/dist/runner/headless/managed-profile.js +1 -1
  93. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -2
  94. package/packages/client/dist/runner/headless/run-yoloop.d.ts +40 -0
  95. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  96. package/packages/client/dist/runner/headless/types.d.ts +20 -0
  97. package/packages/client/dist/runner/headless/types.js +2 -2
  98. package/packages/client/dist/state/project-state-snapshot.d.ts +10 -0
  99. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  100. package/packages/client/dist/state/structural-dag-projection.d.ts +26 -0
  101. package/packages/client/dist/state/structural-dag-projection.js +1 -1
  102. package/packages/client/dist/yoloop/target-normalization.js +1 -1
  103. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +67 -0
  104. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  105. package/packages/shared/dist/compatibility/index.js +96 -0
  106. package/packages/shared/dist/planning/diagnosis-state.js +105 -1
  107. package/packages/shared/dist/project-memory-targets.js +36 -5
  108. package/targets-stubs/antigravity/README.md +1 -1
  109. package/targets-stubs/antigravity/gemini.md +1 -1
  110. package/targets-stubs/antigravity/install-antigravity.sh +1 -1
  111. package/targets-stubs/antigravity/mcp-config.json +0 -3
  112. package/targets-stubs/antigravity/neocortex.md +25 -13
  113. package/targets-stubs/antigravity/skill/SKILL.md +4 -4
  114. package/targets-stubs/claude-code/.mcp.json +0 -4
  115. package/targets-stubs/claude-code/neocortex-root.agent.yaml +2 -4
  116. package/targets-stubs/claude-code/neocortex-root.md +33 -43
  117. package/targets-stubs/claude-code/neocortex-sentinel.md +261 -0
  118. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -3
  119. package/targets-stubs/claude-code/neocortex.md +61 -84
  120. package/targets-stubs/codex/AGENTS.md +19 -18
  121. package/targets-stubs/codex/README.md +1 -1
  122. package/targets-stubs/codex/config-mcp.toml +0 -3
  123. package/targets-stubs/codex/neocortex-sentinel.toml +87 -0
  124. package/targets-stubs/codex/neocortex.toml +23 -44
  125. package/targets-stubs/cursor/README.md +1 -1
  126. package/targets-stubs/cursor/agent.md +26 -15
  127. package/targets-stubs/cursor/mcp.json +0 -3
  128. package/targets-stubs/deepseek-harness/SKILL.md +11 -8
  129. package/targets-stubs/gemini-cli/README.md +1 -1
  130. package/targets-stubs/gemini-cli/agent.md +25 -12
  131. package/targets-stubs/gemini-cli/agents/neocortex-sentinel.md +75 -0
  132. package/targets-stubs/gemini-cli/agents/neocortex.md +280 -49
  133. package/targets-stubs/gemini-cli/settings-mcp.json +0 -3
  134. package/targets-stubs/grok/SKILL.md +13 -1
  135. package/targets-stubs/grok/agents/neocortex-sentinel.md +64 -0
  136. package/targets-stubs/grok/config-mcp.toml +0 -3
  137. package/targets-stubs/grok/install-grok.sh +51 -1
  138. package/targets-stubs/kimi/mcp.json +0 -6
  139. package/targets-stubs/kimi/neocortex.md +21 -8
  140. package/targets-stubs/lib/managed-config-merge.js +301 -6
  141. package/targets-stubs/lib/managed-profile.sh +12 -1
  142. package/targets-stubs/lib/mcp-merge.js +122 -8
  143. package/targets-stubs/openclaw/SKILL.md +33 -4
  144. package/targets-stubs/opencode/neocortex-root.md +41 -41
  145. package/targets-stubs/opencode/neocortex-sentinel.md +115 -0
  146. package/targets-stubs/opencode/neocortex.md +292 -67
  147. package/targets-stubs/opencode/opencode-mcp.json +0 -7
  148. package/targets-stubs/vscode/README.md +1 -1
  149. package/targets-stubs/vscode/mcp.json +0 -4
  150. package/targets-stubs/vscode/neocortex.agent.md +29 -18
@@ -0,0 +1,172 @@
1
+ export declare const GOVERNANCE_RUNTIME_STORE_DIRECTORY: "neocortex-governance";
2
+ export declare const GOVERNANCE_RUNTIME_STORE_VERSION: "v1";
3
+ export declare const GOVERNANCE_RUNTIME_STORE_KIND: "story-governance-runtime-store";
4
+ export declare const GOVERNANCE_RUNTIME_PROJECT_STATE_FILE: "project-state.json";
5
+ export declare const GOVERNANCE_RUNTIME_MAX_FILE_BYTES: number;
6
+ export declare const GOVERNANCE_RUNTIME_MAX_STORY_BYTES: number;
7
+ export declare const GOVERNANCE_RUNTIME_MAX_ENTRIES = 4;
8
+ /** DEC-05: the read-only project-state mirror uses the state-merge cap. */
9
+ export declare const GOVERNANCE_RUNTIME_MAX_PROJECT_STATE_BYTES: number;
10
+ export declare const GOVERNANCE_STATE_PATH: ".neocortex/state.json";
11
+ /** DEC-02: trailer binding a code-only commit to the store digest. */
12
+ export declare const GOVERNANCE_DIGEST_TRAILER: "Neocortex-Governance-Digest";
13
+ /** Checkpoint trailer keys plus the governance trailer (single-valued, same parser). */
14
+ export declare const GOVERNANCE_CHECKPOINT_TRAILER_KEYS: readonly string[];
15
+ /** DEC-01: lifecycle checkpoint receipt-ref prefixes. */
16
+ export declare const GOVERNANCE_RECEIPT_REF_PREFIX: "governance-runtime:";
17
+ export declare const GOVERNANCE_REVISION_REF_PREFIX: "governance-runtime-revision:";
18
+ export declare const GOVERNANCE_REASON_CODES: Readonly<{
19
+ readonly AMBIGUOUS: "governance-tracking-ambiguous";
20
+ readonly UNAVAILABLE: "governance-mode-unavailable";
21
+ readonly UNSAFE: "governance-runtime-store-unsafe";
22
+ readonly CONFLICT: "governance-runtime-store-conflict";
23
+ readonly OVER_LIMIT: "governance-runtime-store-over-limit";
24
+ readonly MISMATCH: "governance-runtime-evidence-mismatch";
25
+ readonly EVIDENCE_MISSING: "governance-runtime-evidence-missing";
26
+ readonly WRITE_SET_FORBIDDEN: "direct-yolo-write-set-governance-forbidden";
27
+ }>;
28
+ export type GovernanceReasonCode = (typeof GOVERNANCE_REASON_CODES)[keyof typeof GOVERNANCE_REASON_CODES];
29
+ export type GovernanceMode = 'tracked' | 'runtime-store';
30
+ export type GovernanceModeResult = {
31
+ readonly ok: true;
32
+ readonly mode: GovernanceMode;
33
+ } | {
34
+ readonly ok: false;
35
+ readonly reasonCode: 'governance-tracking-ambiguous' | 'governance-mode-unavailable';
36
+ };
37
+ export interface GovernanceEntry {
38
+ readonly path: string;
39
+ readonly sha256: string;
40
+ readonly bytes: number;
41
+ }
42
+ export interface StoryGovernanceDocument {
43
+ readonly schemaVersion: 1;
44
+ readonly kind: typeof GOVERNANCE_RUNTIME_STORE_KIND;
45
+ readonly epicId: string;
46
+ readonly storyId: string;
47
+ readonly revision: number;
48
+ readonly entries: readonly GovernanceEntry[];
49
+ readonly governanceDigest: string;
50
+ readonly [key: string]: unknown;
51
+ }
52
+ export interface StoryGovernanceReceipt {
53
+ readonly schemaVersion: 1;
54
+ readonly mode: 'runtime-store';
55
+ readonly storyId: string;
56
+ readonly epicId: string;
57
+ readonly revision: number;
58
+ readonly governanceDigest: string;
59
+ readonly entryCount: number;
60
+ readonly commitSha?: string;
61
+ }
62
+ export type GovernanceResult<T> = {
63
+ readonly ok: true;
64
+ readonly value: T;
65
+ } | {
66
+ readonly ok: false;
67
+ readonly reasonCode: GovernanceReasonCode;
68
+ };
69
+ /** The four governance paths of one story (state entry + three evidence files). */
70
+ export declare function storyGovernancePaths(storyId: string): readonly string[];
71
+ export declare function storyReviewGovernancePath(storyId: string): string;
72
+ /** True for any path under `.neocortex/` (case-insensitive), refused in `runtime-store` commits. */
73
+ export declare function isGovernanceRepositoryPath(path: string): boolean;
74
+ /**
75
+ * Spec R1 / ADR-1. `tracked` when `.neocortex/state.json` is tracked in index
76
+ * and HEAD (index only for an unborn HEAD); `runtime-store` when it and every
77
+ * story evidence path are absent from both; anything else is ambiguous.
78
+ * Read-only: no index, ref or worktree effect.
79
+ */
80
+ export declare function detectGovernanceModeSync(input: {
81
+ readonly projectRoot: string;
82
+ readonly storyId?: string;
83
+ }): GovernanceModeResult;
84
+ export declare function detectGovernanceMode(input: {
85
+ readonly projectRoot: string;
86
+ readonly storyId?: string;
87
+ }): Promise<GovernanceModeResult>;
88
+ /** Spec R5: canonical digest of the entries sorted by path. */
89
+ export declare function computeGovernanceDigest(entries: readonly GovernanceEntry[]): string;
90
+ /**
91
+ * Spec R4. `expectedRevision` is the current document revision (0 when
92
+ * absent); a different current revision is `governance-runtime-store-conflict`.
93
+ * Identical content to the current document is a no-op returning it.
94
+ * Unknown fields of the current document are preserved.
95
+ */
96
+ export declare function writeStoryGovernance(input: {
97
+ readonly projectRoot: string;
98
+ readonly epicId: string;
99
+ readonly storyId: string;
100
+ readonly expectedRevision: number;
101
+ readonly files: Readonly<Record<string, Buffer | string>>;
102
+ }): GovernanceResult<StoryGovernanceReceipt>;
103
+ export interface VerifiedStoryGovernance {
104
+ readonly receipt: StoryGovernanceReceipt;
105
+ /** Verified bytes by governance path. Never serialized into public output. */
106
+ readonly files: ReadonlyMap<string, Buffer>;
107
+ }
108
+ /** Spec R5: read and verify the store; absent → `governance-runtime-evidence-missing`. */
109
+ export declare function readStoryGovernanceSync(input: {
110
+ readonly projectRoot: string;
111
+ readonly epicId: string;
112
+ readonly storyId: string;
113
+ }): GovernanceResult<VerifiedStoryGovernance>;
114
+ /** Current store revision (0 when absent); used as the CAS precondition of the next write. */
115
+ export declare function storyGovernanceRevisionSync(input: {
116
+ readonly projectRoot: string;
117
+ readonly epicId: string;
118
+ readonly storyId: string;
119
+ }): GovernanceResult<number>;
120
+ /**
121
+ * Spec R9 / AC3: the store must verify and its digest must equal the expected
122
+ * one. Missing, divergent or tampered → `governance-runtime-evidence-mismatch`.
123
+ */
124
+ export declare function verifyStoryGovernanceBinding(input: {
125
+ readonly projectRoot: string;
126
+ readonly epicId: string;
127
+ readonly storyId: string;
128
+ readonly expectedGovernanceDigest: string | undefined;
129
+ }): GovernanceResult<VerifiedStoryGovernance>;
130
+ /** DEC-06: canonical JSON of the story record only (never the whole project state). */
131
+ export declare function storyStateEntryBytes(storyId: string, entry: unknown): Buffer;
132
+ /**
133
+ * DEC-04/06: read the local, untracked governance of one story from a
134
+ * checkout (the source the root wrote). Returns the files keyed by governance
135
+ * path; the three evidence files are required. Read-only.
136
+ */
137
+ export declare function readLocalStoryGovernanceSync(input: {
138
+ readonly projectRoot: string;
139
+ readonly storyId: string;
140
+ }): GovernanceResult<Readonly<Record<string, Buffer>>>;
141
+ /**
142
+ * DEC-04: capture the local governance of a story into the store (CAS on the
143
+ * observed revision). Idempotent for identical content.
144
+ */
145
+ export declare function captureStoryGovernanceSync(input: {
146
+ readonly projectRoot: string;
147
+ readonly epicId: string;
148
+ readonly storyId: string;
149
+ }): GovernanceResult<StoryGovernanceReceipt>;
150
+ /**
151
+ * DEC-05: write the read-only project-state mirror (main checkout, `runtime-store`).
152
+ * The mirror is a projection, never an authority for writes.
153
+ */
154
+ export declare function writeProjectStateMirrorSync(input: {
155
+ readonly projectRoot: string;
156
+ readonly bytes: Buffer;
157
+ }): GovernanceResult<string>;
158
+ /** DEC-05: read the project-state mirror; undefined when absent. */
159
+ export declare function readProjectStateMirrorSync(projectRoot: string): GovernanceResult<Buffer | undefined>;
160
+ /**
161
+ * Spec R8 / DEC-05: the project state source of a checkout. A present local
162
+ * `.neocortex/state.json` is used as-is. Without it, a `runtime-store`
163
+ * checkout (a story worktree) reads the store mirror. Otherwise undefined.
164
+ */
165
+ export declare function readGovernanceStateSourceSync(projectRoot: string): GovernanceResult<Buffer | undefined>;
166
+ /** Store location for diagnostics in tests only; never part of public output. */
167
+ export declare function governanceStoreDirectoryForTests(projectRoot: string, epicId: string, storyId: string): string;
168
+ /** Lists nothing outside the store; used to assert no stray files in tests. */
169
+ export declare function listGovernanceStoreEntriesForTests(projectRoot: string, epicId: string, storyId: string): readonly string[];
170
+ export declare function governanceReceiptRefs(receipt: Pick<StoryGovernanceReceipt, 'governanceDigest' | 'revision'>): readonly string[];
171
+ /** DEC-01: governance digest recorded in a lifecycle checkpoint's receipt refs, if any. */
172
+ export declare function governanceDigestFromReceiptRefs(refs: unknown): string | undefined;
@@ -0,0 +1,3 @@
1
+ import{execFileSync as P}from"node:child_process";import{createHash as ce,randomBytes as J}from"node:crypto";import{closeSync as M,existsSync as l,fsyncSync as x,lstatSync as N,mkdirSync as Y,openSync as b,readFileSync as E,readdirSync as ae,realpathSync as G,renameSync as fe,unlinkSync as D,writeSync as K}from"node:fs";import{isAbsolute as U,join as u,relative as de,resolve as g}from"node:path";import{STORY_CHECKPOINT_TRAILER_KEYS as ue}from"./neocortex-trailers.js";const X="neocortex-governance",Z="v1",W="story-governance-runtime-store",F="project-state.json",R=1024*1024,ye=4*1024*1024,q=4,_=32*1024*1024,I=".neocortex/state.json",le="Neocortex-Governance-Digest",ke=Object.freeze([...ue,le]),k="governance-runtime:",Se="governance-runtime-revision:",n=Object.freeze({AMBIGUOUS:"governance-tracking-ambiguous",UNAVAILABLE:"governance-mode-unavailable",UNSAFE:"governance-runtime-store-unsafe",CONFLICT:"governance-runtime-store-conflict",OVER_LIMIT:"governance-runtime-store-over-limit",MISMATCH:"governance-runtime-evidence-mismatch",EVIDENCE_MISSING:"governance-runtime-evidence-missing",WRITE_SET_FORBIDDEN:"direct-yolo-write-set-governance-forbidden"}),w=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,L=/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/,C=/^[a-f0-9]{64}$/,Ee=".lock",Ie=6e4,Ae=40,ge=25;class O extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function i(e){throw new O(e)}function T(e){return Object.freeze([I,`.neocortex/stories/${e}/qa-gate-result.json`,`.neocortex/stories/${e}/validation-evidence.md`,`.neocortex/stories/${e}/review.md`])}function we(e){return`.neocortex/stories/${e}/review.md`}function Le(e){return/^\.neocortex(?:\/|$)/i.test(e)}function p(e,t){return String(P("git",[...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:4*1024*1024}))}function Ne(e,t){try{return P("git",[...t],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}function Q(e){try{if(e.storyId!==void 0&&!L.test(e.storyId))return{ok:!1,reasonCode:n.UNAVAILABLE};if(p(e.projectRoot,["rev-parse","--is-inside-work-tree"]).trim()!=="true")return{ok:!1,reasonCode:n.UNAVAILABLE};const t=Ne(e.projectRoot,["rev-parse","--verify","--quiet","HEAD^{commit}"]),r=e.storyId?T(e.storyId):[I],o=new Set(p(e.projectRoot,["ls-files","-z","--",...r]).split("\0").filter(Boolean)),c=t?new Set(p(e.projectRoot,["ls-tree","-r","-z","--name-only","HEAD","--",...r]).split("\0").filter(Boolean)):new Set,a=o.has(I),s=c.has(I);return a&&(s||!t)?{ok:!0,mode:"tracked"}:a!==s?{ok:!1,reasonCode:n.AMBIGUOUS}:o.size>0||c.size>0?{ok:!1,reasonCode:n.AMBIGUOUS}:{ok:!0,mode:"runtime-store"}}catch{return{ok:!1,reasonCode:n.UNAVAILABLE}}}async function Ve(e){return Q(e)}function ee(){return process.platform!=="win32"&&typeof process.getuid=="function"}function y(e,t){const r=N(e);r.isSymbolicLink()&&i(n.UNSAFE),(t==="file"?!r.isFile():!r.isDirectory())&&i(n.UNSAFE),ee()&&r.uid!==process.getuid()&&i(n.UNSAFE),ee()&&(r.mode&63)!==0&&i(n.UNSAFE)}function te(e){let t,r;try{r=G(e),t=p(r,["rev-parse","--git-common-dir"]).trim()}catch{i(n.UNAVAILABLE)}const o=U(t)?g(t):g(r,t);let c;try{c=G(o);const s=N(c);(s.isSymbolicLink()||!s.isDirectory())&&i(n.UNSAFE)}catch(s){if(s instanceof O)throw s;i(n.UNAVAILABLE)}c!==o&&i(n.UNSAFE);const a=p(r,["rev-parse","--git-common-dir"]).trim();return(U(a)?g(a):g(r,a))!==o&&i(n.UNSAFE),c}function v(e,t,r){const o=te(e);let c=o;for(const a of[X,Z,...t]){w.test(a)||i(n.UNSAFE);const s=u(c,a);if(!l(s)){let d=!1;try{d=N(s).isSymbolicLink()}catch{}if(d&&i(n.UNSAFE),!r)return;try{Y(s,{mode:448})}catch(S){S.code!=="EEXIST"&&i(n.UNSAFE)}}y(s,"directory"),G(s)!==s&&i(n.UNSAFE);const f=de(o,s);(!f||f.startsWith("..")||U(f))&&i(n.UNSAFE),c=s}return c}function pe(e){if(process.platform==="win32")return;const t=b(e,"r");try{x(t)}finally{M(t)}}function V(e,t,r){const o=u(e,t);(l(o)||h(o))&&y(o,"file");const c=u(e,`.${t}.${process.pid}.${J(6).toString("hex")}.tmp`),a=b(c,"wx",384);try{let s=0;for(;s<r.length;)s+=K(a,r,s,r.length-s);x(a)}finally{M(a)}try{fe(c,o)}catch{try{D(c)}catch{}i(n.UNSAFE)}y(o,"file"),pe(e)}function h(e){try{return N(e).isSymbolicLink()}catch{return!1}}function ve(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function he(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function re(e,t){const r=u(e,Ee),o=J(12).toString("hex");let c;for(let a=0;a<Ae&&c===void 0;a+=1)try{c=b(r,"wx",384),K(c,JSON.stringify({pid:process.pid,token:o,at:Date.now()})),x(c)}catch(s){s.code!=="EEXIST"&&i(n.UNSAFE);try{y(r,"file");const f=JSON.parse(E(r,"utf8"));if(typeof f.pid=="number"&&typeof f.at=="number"&&Date.now()-f.at>Ie&&!he(f.pid)){D(r);continue}}catch(f){if(f instanceof O)throw f}ve(ge)}c===void 0&&i(n.CONFLICT);try{return t()}finally{M(c);try{JSON.parse(E(r,"utf8")).token===o&&D(r)}catch{}}}function m(e){return ce("sha256").update(e).digest("hex")}function oe(e){const t=[...e].sort((r,o)=>r.path<o.path?-1:r.path>o.path?1:0).map(r=>({path:r.path,sha256:r.sha256,bytes:r.bytes}));return m(JSON.stringify({domain:"neocortex.p228.governance-runtime-store.v1",entries:t}))}function me(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return!1;const o=e,c=new Set(T(r));return o.schemaVersion===1&&o.kind===W&&o.epicId===t&&o.storyId===r&&Number.isSafeInteger(o.revision)&&o.revision>=1&&typeof o.governanceDigest=="string"&&C.test(o.governanceDigest)&&Array.isArray(o.entries)&&o.entries.length>=1&&o.entries.length<=q&&new Set(o.entries.map(a=>a?.path)).size===o.entries.length&&o.entries.every(a=>{const s=a;return s&&typeof s.path=="string"&&c.has(s.path)&&typeof s.sha256=="string"&&C.test(s.sha256)&&Number.isSafeInteger(s.bytes)&&s.bytes>=0&&s.bytes<=R})}function j(e,t,r){const o=u(e,"governance.json");if(!l(o)&&!h(o))return;y(o,"file");const c=E(o);c.length>R&&i(n.MISMATCH);let a;try{a=JSON.parse(c.toString("utf8"))}catch{i(n.MISMATCH)}return me(a,t,r)||i(n.MISMATCH),a}function ne(e,t){oe(t.entries)!==t.governanceDigest&&i(n.MISMATCH);const r=u(e,"blobs"),o=new Map;try{y(r,"directory")}catch{i(n.MISMATCH)}for(const c of t.entries){const a=u(r,c.sha256);try{y(a,"file")}catch{i(n.MISMATCH)}const s=E(a);(s.length!==c.bytes||m(s)!==c.sha256)&&i(n.MISMATCH),o.set(c.path,s)}return o}function B(e,t){return Object.freeze({schemaVersion:1,mode:"runtime-store",storyId:e.storyId,epicId:e.epicId,revision:e.revision,governanceDigest:e.governanceDigest,entryCount:e.entries.length,...t?{commitSha:t}:{}})}function A(e){try{return{ok:!0,value:e()}}catch(t){return t instanceof O?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:n.UNSAFE}}}function H(e,t){(!w.test(e)||!L.test(t)||!w.test(t))&&i(n.UNSAFE)}function Re(e){return A(()=>{H(e.epicId,e.storyId);const t=T(e.storyId),r=Object.keys(e.files).sort();(r.length===0||r.length>q||r.some(f=>!t.includes(f)))&&i(n.UNSAFE);const o=r.map(f=>{const d=e.files[f];return Buffer.isBuffer(d)?d:Buffer.from(d,"utf8")});(o.some(f=>f.length>R)||o.reduce((f,d)=>f+d.length,0)>ye)&&i(n.OVER_LIMIT);const c=r.map((f,d)=>Object.freeze({path:f,sha256:m(o[d]),bytes:o[d].length})),a=oe(c),s=v(e.projectRoot,[e.epicId,e.storyId],!0);return re(s,()=>{const f=j(s,e.epicId,e.storyId),d=f?.revision??0;if(d!==e.expectedRevision&&i(n.CONFLICT),f&&f.governanceDigest===a)return ne(s,f),B(f);const S=u(s,"blobs");l(S)||(h(S)&&i(n.UNSAFE),Y(S,{mode:448})),y(S,"directory"),c.forEach((se,ie)=>V(S,se.sha256,o[ie]));const $=Object.freeze({...f??{},schemaVersion:1,kind:W,epicId:e.epicId,storyId:e.storyId,revision:d+1,entries:Object.freeze(c),governanceDigest:a});return V(s,"governance.json",Buffer.from(`${JSON.stringify($,null,2)}
2
+ `,"utf8")),B($)})})}function _e(e){return A(()=>{H(e.epicId,e.storyId);const t=v(e.projectRoot,[e.epicId,e.storyId],!1);t||i(n.EVIDENCE_MISSING);const r=j(t,e.epicId,e.storyId);r||i(n.EVIDENCE_MISSING);const o=ne(t,r);return Object.freeze({receipt:B(r),files:o})})}function Ce(e){return A(()=>{H(e.epicId,e.storyId);const t=v(e.projectRoot,[e.epicId,e.storyId],!1);return t?j(t,e.epicId,e.storyId)?.revision??0:0})}function je(e){if(typeof e.expectedGovernanceDigest!="string"||!C.test(e.expectedGovernanceDigest))return{ok:!1,reasonCode:n.MISMATCH};const t=_e(e);return t.ok?t.value.receipt.governanceDigest!==e.expectedGovernanceDigest?{ok:!1,reasonCode:n.MISMATCH}:t:{ok:!1,reasonCode:t.reasonCode===n.UNSAFE?t.reasonCode:n.MISMATCH}}function Oe(e,t){return Buffer.from(`${JSON.stringify({storyId:e,entry:t},null,2)}
3
+ `,"utf8")}function z(e,t){if(!l(e)&&!h(e))return;const r=N(e);return(r.isSymbolicLink()||!r.isFile())&&i(n.UNSAFE),r.size>t&&i(n.OVER_LIMIT),E(e)}function Te(e){return A(()=>{L.test(e.storyId)||i(n.UNSAFE);const t=g(e.projectRoot),r=z(u(t,I),_);r||i(n.EVIDENCE_MISSING);let o;try{o=JSON.parse(r.toString("utf8"))}catch{i(n.MISMATCH)}const c=o?.stories,a=c&&typeof c=="object"&&!Array.isArray(c)?c[e.storyId]:void 0;(!a||typeof a!="object"||Array.isArray(a))&&i(n.EVIDENCE_MISSING);const s={[I]:Oe(e.storyId,a)};for(const f of T(e.storyId).slice(1)){const d=z(u(t,f),R);d||i(n.EVIDENCE_MISSING),s[f]=d}return Object.freeze(s)})}function Be(e){const t=Te(e);if(!t.ok)return t;const r=Ce(e);return r.ok?Re({...e,expectedRevision:r.value,files:t.value}):r}function He(e){return A(()=>{e.bytes.length>_&&i(n.OVER_LIMIT);try{JSON.parse(e.bytes.toString("utf8"))}catch{i(n.MISMATCH)}const t=v(e.projectRoot,[],!0);return re(t,()=>{const r=u(t,F);return l(r)&&(y(r,"file"),E(r).equals(e.bytes))||V(t,F,e.bytes),m(e.bytes)})})}function Me(e){return A(()=>{const t=v(e,[],!1);if(!t)return;const r=u(t,F);if(!l(r)&&!h(r))return;y(r,"file");const o=E(r);o.length>_&&i(n.OVER_LIMIT);try{JSON.parse(o.toString("utf8"))}catch{i(n.MISMATCH)}return o})}function ze(e){return A(()=>{const t=z(u(g(e),I),_);if(t)return t;const r=Q({projectRoot:e});if(!r.ok||r.mode!=="runtime-store")return;const o=Me(e);return o.ok||i(o.reasonCode),o.value})}function xe(e,t,r){return u(te(e),X,Z,t,r)}function $e(e,t,r){const o=xe(e,t,r);return l(o)?ae(o).sort():[]}function Pe(e){return Object.freeze([`${k}${e.governanceDigest}`,`${Se}${e.revision}`])}function Je(e){if(!Array.isArray(e))return;const t=e.filter(r=>typeof r=="string"&&r.startsWith(k)).map(r=>r.slice(k.length));return t.length!==1||!C.test(t[0])?t.length===0?void 0:"invalid":t[0]}export{ke as GOVERNANCE_CHECKPOINT_TRAILER_KEYS,le as GOVERNANCE_DIGEST_TRAILER,n as GOVERNANCE_REASON_CODES,k as GOVERNANCE_RECEIPT_REF_PREFIX,Se as GOVERNANCE_REVISION_REF_PREFIX,q as GOVERNANCE_RUNTIME_MAX_ENTRIES,R as GOVERNANCE_RUNTIME_MAX_FILE_BYTES,_ as GOVERNANCE_RUNTIME_MAX_PROJECT_STATE_BYTES,ye as GOVERNANCE_RUNTIME_MAX_STORY_BYTES,F as GOVERNANCE_RUNTIME_PROJECT_STATE_FILE,X as GOVERNANCE_RUNTIME_STORE_DIRECTORY,W as GOVERNANCE_RUNTIME_STORE_KIND,Z as GOVERNANCE_RUNTIME_STORE_VERSION,I as GOVERNANCE_STATE_PATH,Be as captureStoryGovernanceSync,oe as computeGovernanceDigest,Ve as detectGovernanceMode,Q as detectGovernanceModeSync,Je as governanceDigestFromReceiptRefs,Pe as governanceReceiptRefs,xe as governanceStoreDirectoryForTests,Le as isGovernanceRepositoryPath,$e as listGovernanceStoreEntriesForTests,ze as readGovernanceStateSourceSync,Te as readLocalStoryGovernanceSync,Me as readProjectStateMirrorSync,_e as readStoryGovernanceSync,T as storyGovernancePaths,Ce as storyGovernanceRevisionSync,we as storyReviewGovernancePath,Oe as storyStateEntryBytes,je as verifyStoryGovernanceBinding,He as writeProjectStateMirrorSync,Re as writeStoryGovernance};
@@ -1,4 +1,4 @@
1
- import{createHash as ke,randomBytes as Z}from"node:crypto";import{existsSync as M}from"node:fs";import{chmod as _e,open as ee,readFile as B,readdir as te,rename as Ae,rm as V,stat as $,unlink as Se}from"node:fs/promises";import{hostname as Oe}from"node:os";import{join as A}from"node:path";import{GIT_LIFECYCLE_RUNTIME_DIRECTORY as F,STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as re,assertGitLifecyclePrivateFile as se,compactStoryWorktreeJournal as be,ensureGitLifecyclePrivateChildDirectory as De,ensureStoryWorktreeJournal as oe,gitLifecycleRuntimeDirectory as ne,isStoryWorktreeCleanupReceiptRecord as ae,mutateGitLifecycleRuntime as ie,readGitLifecycleRuntime as j}from"./git-lifecycle-store.js";import{GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as de}from"./git-lifecycle-step-ids.js";import{StoryWorktreeManager as Ne,digestStoryWorktreeReceiptLocal as ce,runStoryWorktreeGit as S,storyWorktreePathAbsence as Te}from"./story-worktree-manager.js";const G="story-worktree-cleanup.json",Y="story-worktree-bundles",Ce=256,le=Object.freeze(["success","failure","abandon","orphan-recovery"]),Pe=Object.freeze(["active","integrated","failed","abandoned","bundled","remove-pending","removed"]),Le=Object.freeze({MANUAL_PRESERVED:"manual-worktree-preserved",REMOVE_PENDING:"story-worktree-remove-pending",ORPHAN_RECOVERED:"story-worktree-orphan-recovered",ORPHAN_UNPROVEN:"story-worktree-orphan-unproven",OWNER_ALIVE:"story-worktree-owner-alive",LEASE_LIVE:"story-worktree-lease-live",CLAIMED:"story-worktree-cleanup-claimed",IN_PROGRESS:"story-worktree-cleanup-in-progress",DIRTY_PRESERVED:"story-worktree-dirty-preserved",BUNDLE_QUOTA:"story-worktree-bundle-quota-exceeded",BUNDLE_FAILED:"story-worktree-bundle-failed",BUNDLE_UNVERIFIED:"story-worktree-bundle-unverified",REMOTE_DIVERGED:"story-worktree-remote-sha-diverged",REMOTE_UNVERIFIED:"story-worktree-remote-unverified",REMOTE_ABSENT:"story-worktree-remote-absent",REMOTE_UNPRESERVED:"story-worktree-remote-unpreserved",REMOTE_UNKNOWN:"story-worktree-remote-unknown",BRANCH_MOVED:"story-worktree-branch-moved",BRANCH_CHECKED_OUT:"story-worktree-branch-checked-out",ADOPTED_BRANCH:"story-worktree-adopted-branch-preserved",ENTRY_CONFLICT:"story-worktree-entry-conflict",STATE_INVALID:"story-worktree-cleanup-state-invalid",SWEEP_FAILED:"story-worktree-sweep-failed",ORPHAN_PROGRESS_RESET:"story-worktree-orphan-progress-reset",ORPHAN_PROGRESS_PRESERVED:"story-worktree-orphan-progress-preserved"}),i=Le,ue=10080*60*1e3,Me=600*1e3,Be=64,Ve=512*1024*1024,he=3,Ue=50,xe=/^swt-[a-f0-9]{24}$/,K=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,fe=/^[a-f0-9]{64}$/,We=/^[a-f0-9]{16}$/,me=/^P[1-9][0-9]*$/,He=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,pe=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ee=/^nx\/P[1-9][0-9]*\/[a-f0-9]{8}$/,$e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/,Re=/^swt-[a-f0-9]{24}-[a-f0-9]{12}\.bundle$/,z=["integrated","failed","abandoned","bundled","remove-pending"],Fe="last_step,status,steps_completed",je=new Set(["backlog","ready_to_start"]);function Ge(l){const{runtime:e,epicId:t,storyId:r}=l,s=O(e.stories[r]),n=s?Object.keys(s).filter(p=>p!=="write_set_extension").sort():[];if(n.length===0)return"none";const o=s.steps_completed;if(!(n.join(",")===Fe&&s.status==="branch-ready"&&s.last_step===de&&Array.isArray(o)&&o.length===1&&o[0]===de)||!l.loss.worktreeAbsent||!l.loss.branchGone||l.loss.bundled||Object.values(e.storyWorktrees?.entries??{}).some(p=>p.storyId===r&&p.leaseId!==l.recoveredLeaseId))return"preserved";let h;try{h=l.trackedText===void 0?void 0:O(JSON.parse(l.trackedText))}catch{return"preserved"}const a=O(h?.stories),d=O(a?.[r]),g=d?.steps_completed;if(!d||!je.has(String(d.status))||g!==void 0&&(!Array.isArray(g)||g.length>0)||d.branch_name||d.checkpoint||d.commit_sha)return"preserved";const E=O(O(e.epics[t])?.story_worktree_evidence);if(E!==void 0){const p=E.receipts,D=E.specAcceptances;if(p!==void 0&&!Array.isArray(p)||D!==void 0&&!Array.isArray(D))return"preserved";const c=R=>{const y=O(R);return!y||y.storyId===r||Array.isArray(y.storyIds)&&y.storyIds.includes(r)};if(p?.some(c)||D?.some(c))return"preserved"}return"reset"}class H extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function u(l){throw new H(l)}function x(l){return ke("sha256").update(l).digest("hex")}function q(l){return new Promise(e=>setTimeout(e,l))}function we(l){return[...new Set(l)]}function Ye(l){try{return process.kill(l,0),!0}catch(e){return e.code==="EPERM"}}function J(l,e){return`${l}-${e.slice(0,12)}.bundle`}function ge(l=Oe()){return x(`neocortex.p225.owner-host|${l}`)}function O(l){return l!==null&&typeof l=="object"&&!Array.isArray(l)?l:void 0}const ye=["schemaVersion","leaseId","epicId","storyId","state","removeAttempts","updatedAt"],Ke=new Set([...ye,"trigger","headSha","bundleDigest","bundleBytes","bundleExpiresAt","remotePush","remoteBranchRemoved","ownerPid","ownerHostDigest","claimToken","claimExpiresAt"]);function Ie(l,e){const t=O(e);if(!t||Object.keys(t).some(n=>!Ke.has(n))||ye.some(n=>t[n]===void 0))return!1;const r=t.remotePush===void 0?void 0:O(t.remotePush);if(t.remotePush!==void 0&&(!r||Object.keys(r).length!==3||typeof r.remote!="string"||!pe.test(r.remote)||typeof r.branch!="string"||!Ee.test(r.branch)||!r.branch.startsWith(`nx/${String(t.epicId)}/`)||typeof r.sha!="string"||!K.test(r.sha)))return!1;const s=n=>t[n]===void 0||typeof t[n]=="string"&&$e.test(t[n])&&Number.isFinite(Date.parse(t[n]));return t.schemaVersion===1&&t.leaseId===l&&xe.test(l)&&typeof t.epicId=="string"&&me.test(t.epicId)&&typeof t.storyId=="string"&&He.test(t.storyId)&&t.storyId.startsWith(`${t.epicId}.`)&&Pe.includes(t.state)&&Number.isSafeInteger(t.removeAttempts)&&t.removeAttempts>=0&&t.removeAttempts<=1e3&&s("updatedAt")&&s("bundleExpiresAt")&&s("claimExpiresAt")&&t.claimToken===void 0==(t.claimExpiresAt===void 0)&&(t.claimToken===void 0||typeof t.claimToken=="string"&&We.test(t.claimToken))&&(t.trigger===void 0||le.includes(t.trigger))&&(t.headSha===void 0||typeof t.headSha=="string"&&K.test(t.headSha))&&(t.bundleDigest===void 0||typeof t.bundleDigest=="string"&&fe.test(t.bundleDigest)&&t.headSha!==void 0&&t.bundleExpiresAt!==void 0)&&(t.bundleBytes===void 0||Number.isSafeInteger(t.bundleBytes)&&t.bundleBytes>0)&&(t.remoteBranchRemoved===void 0||typeof t.remoteBranchRemoved=="boolean")&&(t.ownerPid===void 0||Number.isSafeInteger(t.ownerPid)&&t.ownerPid>0)&&(t.ownerHostDigest===void 0||typeof t.ownerHostDigest=="string"&&fe.test(t.ownerHostDigest))}function Q(l){let e;try{e=JSON.parse(l)}catch{u(i.STATE_INVALID)}const t=O(e),r=O(t?.records);return(!t||Object.keys(t).length!==2||t.schemaVersion!==1||!r||Object.keys(r).length>Ce||!Object.entries(r).every(([s,n])=>Ie(s,n)))&&u(i.STATE_INVALID),{schemaVersion:1,records:r}}async function ve(l){const e=A(l,F),t=A(e,G);if(!M(t))return{schemaVersion:1,records:{}};try{await se(t,e)}catch{u(i.STATE_INVALID)}return Q(await B(t,"utf8"))}function P(l,e){return l?.claimToken!==void 0&&l.claimExpiresAt!==void 0&&Date.parse(l.claimExpiresAt)>e}async function at(l,e,t=Date.now()){try{const r=(await ve(l)).records[e];return r!==void 0&&(z.includes(r.state)||P(r,t))}catch{return!0}}class ze{options;manager;now;isProcessAlive;constructor(e){this.options=e,this.manager=e.manager??new Ne({projectRoot:e.projectRoot,...e.worktreeRoot?{worktreeRoot:e.worktreeRoot}:{},...e.now?{now:e.now}:{}}),this.now=e.now??(()=>new Date),this.isProcessAlive=e.isProcessAlive??Ye}async readState(e){return ve(e?.commonDir??(await this.facts()).commonDir)}async recordPush(e){return this.guard(async()=>{(typeof e.remote!="string"||!pe.test(e.remote))&&u("story-worktree-remote-invalid");const t=await this.probe(e.leaseId);(t.ownership!=="proven"||!t.headSha)&&u("story-worktree-ownership-unproven"),(t.entry.workspaceMechanism!=="client_managed_worktree"||!Ee.test(t.entry.temporaryBranch))&&u(i.ADOPTED_BRANCH),await this.gitOk(t.facts.mainRoot,["config","--get",`remote.${e.remote}.url`])||u(i.REMOTE_UNKNOWN);const r=await this.lsRemote(t.facts.mainRoot,e.remote,t.entry.temporaryBranch);r===null&&u(i.REMOTE_UNVERIFIED),r===void 0&&u(i.REMOTE_ABSENT),r!==t.headSha&&u(i.REMOTE_DIVERGED);const s={remote:e.remote,branch:t.entry.temporaryBranch,sha:r};return await this.update(t.entry,void 0,n=>{const o={...n,remotePush:s};return delete o.remoteBranchRemoved,o}),{ok:!0,value:{leaseId:t.entry.leaseId,...s}}})}async registerOwnerProcess(e){return this.guard(async()=>{(!Number.isSafeInteger(e.pid)||e.pid<=0)&&u("story-worktree-owner-pid-invalid");const t=await this.probe(e.leaseId);return await this.update(t.entry,void 0,r=>({...r,ownerPid:e.pid,ownerHostDigest:ge()})),{ok:!0,value:{leaseId:t.entry.leaseId}}})}async cleanup(e){return this.guard(async()=>({ok:!0,value:await this.cleanupUnguarded(e)}))}async sweep(e={}){return this.guard(async()=>{e.epicId!==void 0&&!me.test(e.epicId)&&u("story-worktree-identity-invalid");const t=e.dryRun===!0,r=await this.facts(),s=await j(this.options.projectRoot),n=Object.values(s.storyWorktrees?.entries??{}),o=n.filter(c=>e.epicId===void 0||c.epicId===e.epicId).sort((c,R)=>c.leaseId.localeCompare(R.leaseId)),f=await this.readState(r),m=this.now().getTime(),h=ge(),a=[],d=[];for(const c of o){const R=f.records[c.leaseId],y=R!==void 0&&z.includes(R.state),C=Date.parse(c.expiresAt)<=m,k=R?.ownerPid!==void 0&&R.ownerHostDigest===h&&this.isProcessAlive(R.ownerPid),L=!k&&!P(R,m)&&!y&&!C&&c.state==="active"&&await Te(c.worktreePath)==="enoent";if(!L&&(k||P(R,m)||!y&&!C)){const T=k?i.OWNER_ALIVE:P(R,m)?i.CLAIMED:i.LEASE_LIVE;a.push({leaseId:c.leaseId,action:"skipped",reasonCode:T});continue}const W=y?R?.trigger==="success"&&C?"orphan-recovery":R?.trigger??"orphan-recovery":"orphan-recovery";let v;try{v={ok:!0,value:await this.cleanupUnguarded({leaseId:c.leaseId,trigger:W,dryRun:t,...L?{requireVanished:!0}:{}})}}catch(T){v={ok:!1,reasonCode:T instanceof H?T.reasonCode:i.SWEEP_FAILED}}if(!v.ok&&L&&v.reasonCode===i.LEASE_LIVE){a.push({leaseId:c.leaseId,action:"skipped",reasonCode:i.LEASE_LIVE});continue}if(!v.ok){a.push({leaseId:c.leaseId,action:"preserved",reasonCode:v.reasonCode}),d.push(v.reasonCode);continue}const _=v.value,N=await this.reconcileOrphanProgress(c,_,r,t);_.outcome==="dry-run"?a.push({leaseId:c.leaseId,action:"planned",plannedActions:_.plannedActions??[]}):_.outcome==="remove-pending"?(a.push({leaseId:c.leaseId,action:"remove-pending",reasonCode:i.REMOVE_PENDING,..._.bundleDigest?{bundleDigest:_.bundleDigest}:{}}),d.push(i.REMOVE_PENDING)):(a.push({leaseId:c.leaseId,action:"recovered",reasonCode:i.ORPHAN_RECOVERED,..._.bundleDigest?{bundleDigest:_.bundleDigest}:{},..._.absenceProof?{absenceProof:_.absenceProof}:{}}),d.push(i.ORPHAN_RECOVERED)),N&&(a.push(N),N.reasonCode&&d.push(N.reasonCode))}const g=new Set(n.map(c=>c.leaseId));for(const c of Object.values(f.records).sort((R,y)=>R.leaseId.localeCompare(y.leaseId))){if(g.has(c.leaseId)||c.state==="removed"||P(c,m)||e.epicId!==void 0&&c.epicId!==e.epicId)continue;const R=await this.closeDetachedRecord(c,r,t);a.push({leaseId:c.leaseId,action:t?"planned":"record-closed",...R?{reasonCode:R}:{}}),R&&d.push(R)}const E=await this.expireBundles(f,r,m,t),p=await this.manager.registeredWorktrees();p.ok||u(p.reasonCode);const D=p.value.worktrees.filter(c=>!n.some(R=>this.manager.sameWorktreePath(R.worktreePath,c.path))).length;return D>0&&d.push(i.MANUAL_PRESERVED),{ok:!0,value:{dryRun:t,entriesScanned:o.length,recovered:a.filter(c=>c.action==="recovered").length,removePending:a.filter(c=>c.action==="remove-pending").length,preserved:a.filter(c=>c.action==="preserved").length,skipped:a.filter(c=>c.action==="skipped").length,manualWorktreesPreserved:D,bundlesExpired:E,items:a,reasonCodes:we(d)}}})}async cleanupUnguarded(e){le.includes(e.trigger)||u("story-worktree-trigger-invalid");const t=await this.probe(e.leaseId),{entry:r,facts:s}=t;e.requireVanished===!0&&(t.pathAbsence!=="enoent"||r.state!=="active")&&u(i.LEASE_LIVE);const o=(await this.readState(s)).records[r.leaseId];if(r.state==="creating")return e.trigger!=="orphan-recovery"&&u("story-worktree-ownership-unproven"),this.recoverCreating(t,e.dryRun===!0);const f=o!==void 0&&z.includes(o.state);let m=!1;t.pathExists||(t.pathAbsence!=="enoent"&&u(i.ORPHAN_UNPROVEN),e.trigger!=="orphan-recovery"&&!f&&u("story-worktree-ownership-unproven"),m=!0),!m&&t.ownership!=="proven"&&u("story-worktree-ownership-unproven"),!m&&t.clean!==!0&&u(e.trigger==="success"?"story-worktree-dirty":i.DIRTY_PRESERVED),t.epicHead||u("story-worktree-epic-branch-missing");const h=t.epicHead,a=m?t.branchSha:t.headSha;!m&&!a&&u("story-worktree-git-failed");const d=t.integrated===!0;e.trigger==="success"&&!d&&u("story-worktree-not-integrated");const g=r.workspaceMechanism==="client_managed_worktree",E=o?.bundleDigest!==void 0&&o.headSha!==void 0&&o.headSha===a&&await this.bundleMatches(s,r.leaseId,o.headSha,o.bundleDigest),p=!d&&a!==void 0&&(g||e.trigger==="orphan-recovery")&&!E,D=o?.remotePush!==void 0&&o.remoteBranchRemoved!==!0;if(e.dryRun===!0){const y=[...p?["bundle-unintegrated-range"]:[],m?"drop-worktree-metadata":"remove-worktree",...g&&t.branchSha?["delete-local-branch"]:[],...D?["delete-remote-branch"]:[]];return{leaseId:r.leaseId,outcome:"dry-run",trigger:e.trigger,state:o?.state??"active",plannedActions:y,preservedReasonCodes:[]}}const c=await this.claim(r);let R=!1;try{let y=E?o?.bundleDigest:void 0;if(p){const I=await this.createBundle(t,a,h);y=I.digest,await this.update(r,c,w=>({...w,state:"bundled",trigger:e.trigger,headSha:a,bundleDigest:I.digest,bundleBytes:I.bytes,bundleExpiresAt:new Date(this.now().getTime()+(this.options.bundleTtlMs??ue)).toISOString()}))}else if(!E){const I=d?"integrated":e.trigger==="failure"?"failed":"abandoned";await this.update(r,c,w=>({...w,state:w.state==="remove-pending"?"remove-pending":I,trigger:e.trigger,...a?{headSha:a}:{}}))}if(m)await S(s.mainRoot,["worktree","remove",r.worktreePath]);else{const I=this.options.removeAttempts??he;if(!await this.removeWithRetry(s.mainRoot,r.worktreePath,I))return await this.update(r,c,w=>({...w,state:"remove-pending",trigger:e.trigger,removeAttempts:Math.min(1e3,w.removeAttempts+I)})),{leaseId:r.leaseId,outcome:"remove-pending",trigger:e.trigger,state:"remove-pending",...y?{bundleDigest:y}:{},preservedReasonCodes:[i.REMOVE_PENDING]}}await S(s.mainRoot,["worktree","prune"]);const C=await this.manager.registeredWorktrees();C.ok||u(C.reasonCode),C.value.worktrees.some(I=>this.manager.sameWorktreePath(I.path,r.worktreePath))&&u(i.ORPHAN_UNPROVEN);const k=[];let L=!1;if(!g)k.push(i.ADOPTED_BRANCH);else if(t.branchSha){const I=a??t.branchSha,w=d||y!==void 0,b=C.value.worktrees.some(U=>U.branch===r.temporaryBranch);w?b?k.push(i.BRANCH_CHECKED_OUT):await this.gitOk(s.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,I])?L=!0:k.push(i.BRANCH_MOVED):k.push(i.ORPHAN_UNPROVEN)}const W=(await this.readState(s)).records[r.leaseId]??o,v=await this.deleteRemote(r,s,W,c,{epicHead:h,...a?{tip:a}:{},bundled:y!==void 0});v.reasonCode&&k.push(v.reasonCode);const _=W?.remotePush!==void 0&&!v.removed&&(v.reasonCode===i.REMOTE_UNVERIFIED||v.reasonCode===i.REMOTE_UNPRESERVED),N=this.now().toISOString(),T={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${x(`${r.leaseId}|${r.nonceDigest}|${e.trigger}|${N}`).slice(0,24)}`,epicId:r.epicId,storyId:r.storyId,leaseId:r.leaseId,trigger:e.trigger,worktreeRemoved:!0,localBranchRemoved:L,remoteBranchRemoved:v.removed,...k[0]?{preservedReasonCode:k[0]}:{},cleanedAt:N};ae(T)||u("story-worktree-receipt-invalid"),await this.mutate(I=>{const w=oe(I),b=w.entries[r.leaseId];for((!b||b.nonceDigest!==r.nonceDigest)&&u(i.ENTRY_CONFLICT),delete w.entries[r.leaseId],w.cleanupReceipts.push({...T});w.cleanupReceipts.length>re;)w.cleanupReceipts.shift()},I=>{const w=I.records[r.leaseId];if(w)if(_&&w.remotePush!==void 0){const b=w.state==="removed"||w.state==="remove-pending"||w.state==="active"?w.bundleDigest?"bundled":"integrated":w.state,U={...w,state:b,updatedAt:N,remoteBranchRemoved:!1};delete U.claimToken,delete U.claimExpiresAt,I.records[r.leaseId]=U}else if(w.bundleDigest){const b={...w,state:"removed",updatedAt:N,remoteBranchRemoved:v.removed};delete b.claimToken,delete b.claimExpiresAt,I.records[r.leaseId]=b}else delete I.records[r.leaseId]}),R=!0;const X=m?{worktree:"enoent",branch:t.branchSha?"present":await this.branchAbsence(s,r.temporaryBranch),bundled:y!==void 0}:void 0;return{leaseId:r.leaseId,outcome:"removed",trigger:e.trigger,state:"removed",receipt:T,receiptDigest:ce(T),...y?{bundleDigest:y}:{},preservedReasonCodes:we(k),...X?{absenceProof:X}:{}}}finally{R||await this.releaseClaim(r,c).catch(()=>{})}}async recoverCreating(e,t){const{entry:r,facts:s}=e,n={leaseId:r.leaseId,trigger:"orphan-recovery",preservedReasonCodes:[]};let o=!1;if(e.pathExists){const h=await S(r.worktreePath,["rev-parse","HEAD"]),a=await S(r.worktreePath,["symbolic-ref","--quiet","--short","HEAD"]),d=await S(r.worktreePath,["status","--porcelain=v1","--untracked-files=all","-z"]);e.registered&&h.ok&&h.stdout.trim()===r.baseSha&&a.ok&&a.stdout.trim()===r.temporaryBranch&&d.ok&&d.stdout.length===0||u(i.ORPHAN_UNPROVEN),o=!0}else e.pathAbsence!=="enoent"&&u(i.ORPHAN_UNPROVEN),e.branchCheckedOut&&u(i.ORPHAN_UNPROVEN);if(e.branchSha!==void 0&&e.branchSha!==r.baseSha&&u(i.ORPHAN_UNPROVEN),t)return{...n,outcome:"dry-run",state:"active",plannedActions:[...o?["remove-worktree"]:[],...e.branchSha?["delete-local-branch"]:[],"drop-reservation"]};const f=await this.claim(r);let m=!1;try{o&&!await this.removeWithRetry(s.mainRoot,r.worktreePath,this.options.removeAttempts??he)&&u(i.REMOVE_PENDING),o&&await S(s.mainRoot,["worktree","prune"]);let h=!1;e.branchSha&&(h=await this.gitOk(s.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]));const a=this.now().toISOString(),d={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${x(`${r.leaseId}|${r.nonceDigest}|creating|${a}`).slice(0,24)}`,epicId:r.epicId,storyId:r.storyId,leaseId:r.leaseId,trigger:"orphan-recovery",worktreeRemoved:o,localBranchRemoved:h,remoteBranchRemoved:!1,...e.branchSha&&!h?{preservedReasonCode:i.BRANCH_MOVED}:{},cleanedAt:a};return ae(d)||u("story-worktree-receipt-invalid"),await this.mutate(g=>{const E=oe(g),p=E.entries[r.leaseId];for((!p||p.state!=="creating"||p.nonceDigest!==r.nonceDigest)&&u(i.ENTRY_CONFLICT),delete E.entries[r.leaseId],E.cleanupReceipts.push({...d});E.cleanupReceipts.length>re;)E.cleanupReceipts.shift()},g=>{delete g.records[r.leaseId]}),m=!0,{...n,outcome:"reclaimed",state:"removed",receipt:d,receiptDigest:ce(d),preservedReasonCodes:d.preservedReasonCode?[d.preservedReasonCode]:[]}}finally{m||await this.releaseClaim(r,f).catch(()=>{})}}async closeDetachedRecord(e,t,r){let s,n=e.remoteBranchRemoved===!0;if(e.remotePush&&!n){const o=await S(t.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/epic/${e.epicId}^{commit}`]);if(!(o.ok&&await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",e.remotePush.sha,o.stdout.trim()])))s=i.REMOTE_UNPRESERVED;else if(!r){const m=await this.deleteRecordedRemote(t.mainRoot,e.remotePush);n=m.removed,s=m.reasonCode}}return r||s===i.REMOTE_UNPRESERVED||s===i.REMOTE_UNVERIFIED||await this.mutate(void 0,o=>{const f=o.records[e.leaseId];!f||f.state==="removed"||(f.bundleDigest?o.records[e.leaseId]={...f,state:"removed",remoteBranchRemoved:n,updatedAt:this.now().toISOString()}:delete o.records[e.leaseId])}),s}async deleteRemote(e,t,r,s,n){const o=r?.remotePush;if(!o)return{removed:!1};if(r?.remoteBranchRemoved===!0)return{removed:!0};if(e.workspaceMechanism!=="client_managed_worktree"||o.branch!==e.temporaryBranch)return{removed:!1,reasonCode:i.ADOPTED_BRANCH};const f=await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",o.sha,n.epicHead]),m=!f&&n.bundled&&n.tip!==void 0&&await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",o.sha,n.tip]);if(!f&&!m)return{removed:!1,reasonCode:i.REMOTE_UNPRESERVED};const h=await this.deleteRecordedRemote(t.mainRoot,o);return h.removed&&await this.update(e,s,a=>({...a,remoteBranchRemoved:!0})),h}async deleteRecordedRemote(e,t){if(!await this.gitOk(e,["config","--get",`remote.${t.remote}.url`]))return{removed:!1,reasonCode:i.REMOTE_UNKNOWN};const r=await this.lsRemote(e,t.remote,t.branch);return r===null?{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}:r===void 0?{removed:!1,reasonCode:i.REMOTE_ABSENT}:r!==t.sha?{removed:!1,reasonCode:i.REMOTE_DIVERGED}:await this.gitOk(e,["push","--porcelain",`--force-with-lease=refs/heads/${t.branch}:${t.sha}`,t.remote,"--delete",`refs/heads/${t.branch}`])?await this.lsRemote(e,t.remote,t.branch)===void 0?{removed:!0}:{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}:{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}}async lsRemote(e,t,r){const s=await S(e,["ls-remote","--heads",t,`refs/heads/${r}`]);if(!s.ok)return null;const n=s.stdout.split(`
1
+ import{createHash as ke,randomBytes as Z}from"node:crypto";import{existsSync as M}from"node:fs";import{chmod as _e,open as ee,readFile as B,readdir as te,rename as Ae,rm as V,stat as $,unlink as Se}from"node:fs/promises";import{hostname as Oe}from"node:os";import{join as A}from"node:path";import{GIT_LIFECYCLE_RUNTIME_DIRECTORY as F,STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as re,assertGitLifecyclePrivateFile as se,compactStoryWorktreeJournal as be,ensureGitLifecyclePrivateChildDirectory as De,ensureStoryWorktreeJournal as oe,gitLifecycleRuntimeDirectory as ne,isStoryWorktreeCleanupReceiptRecord as ae,mutateGitLifecycleRuntime as ie,readGitLifecycleRuntime as j}from"./git-lifecycle-store.js";import{GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as de}from"./git-lifecycle-step-ids.js";import{StoryWorktreeManager as Ne,digestStoryWorktreeReceiptLocal as ce,runStoryWorktreeGit as S,storyWorktreePathAbsence as Te}from"./story-worktree-manager.js";const G="story-worktree-cleanup.json",Y="story-worktree-bundles",Ce=256,le=Object.freeze(["success","failure","abandon","orphan-recovery"]),Pe=Object.freeze(["active","integrated","failed","abandoned","bundled","remove-pending","removed"]),Le=Object.freeze({MANUAL_PRESERVED:"manual-worktree-preserved",REMOVE_PENDING:"story-worktree-remove-pending",ORPHAN_RECOVERED:"story-worktree-orphan-recovered",ORPHAN_UNPROVEN:"story-worktree-orphan-unproven",OWNER_ALIVE:"story-worktree-owner-alive",LEASE_LIVE:"story-worktree-lease-live",CLAIMED:"story-worktree-cleanup-claimed",IN_PROGRESS:"story-worktree-cleanup-in-progress",DIRTY_PRESERVED:"story-worktree-dirty-preserved",BUNDLE_QUOTA:"story-worktree-bundle-quota-exceeded",BUNDLE_FAILED:"story-worktree-bundle-failed",BUNDLE_UNVERIFIED:"story-worktree-bundle-unverified",REMOTE_DIVERGED:"story-worktree-remote-sha-diverged",REMOTE_UNVERIFIED:"story-worktree-remote-unverified",REMOTE_ABSENT:"story-worktree-remote-absent",REMOTE_UNPRESERVED:"story-worktree-remote-unpreserved",REMOTE_UNKNOWN:"story-worktree-remote-unknown",BRANCH_MOVED:"story-worktree-branch-moved",BRANCH_CHECKED_OUT:"story-worktree-branch-checked-out",ADOPTED_BRANCH:"story-worktree-adopted-branch-preserved",ENTRY_CONFLICT:"story-worktree-entry-conflict",STATE_INVALID:"story-worktree-cleanup-state-invalid",SWEEP_FAILED:"story-worktree-sweep-failed",ORPHAN_PROGRESS_RESET:"story-worktree-orphan-progress-reset",ORPHAN_PROGRESS_PRESERVED:"story-worktree-orphan-progress-preserved"}),i=Le,ue=10080*60*1e3,Me=600*1e3,Be=64,Ve=512*1024*1024,he=3,Ue=50,xe=/^swt-[a-f0-9]{24}$/,K=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,fe=/^[a-f0-9]{64}$/,We=/^[a-f0-9]{16}$/,me=/^P[1-9][0-9]*$/,He=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,pe=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ee=/^nx\/P[1-9][0-9]*\/[a-f0-9]{8}$/,$e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/,Re=/^swt-[a-f0-9]{24}-[a-f0-9]{12}\.bundle$/,z=["integrated","failed","abandoned","bundled","remove-pending"],Fe="last_step,status,steps_completed",je=new Set(["backlog","ready_to_start"]);function Ge(l){const{runtime:e,epicId:t,storyId:r}=l,s=O(e.stories[r]),n=s?Object.keys(s).filter(p=>p!=="write_set_extension").sort():[];if(n.length===0)return"none";const o=s.steps_completed;if(!(n.join(",")===Fe&&s.status==="branch-ready"&&s.last_step===de&&Array.isArray(o)&&o.length===1&&o[0]===de)||!l.loss.worktreeAbsent||!l.loss.branchGone||l.loss.bundled||Object.values(e.storyWorktrees?.entries??{}).some(p=>p.storyId===r&&p.leaseId!==l.recoveredLeaseId))return"preserved";let h;try{h=l.trackedText===void 0?void 0:O(JSON.parse(l.trackedText))}catch{return"preserved"}const a=O(h?.stories),d=O(a?.[r]),g=d?.steps_completed;if(!d||!je.has(String(d.status))||g!==void 0&&(!Array.isArray(g)||g.length>0)||d.branch_name||d.checkpoint||d.commit_sha)return"preserved";const E=O(O(e.epics[t])?.story_worktree_evidence);if(E!==void 0){const p=E.receipts,D=E.specAcceptances;if(p!==void 0&&!Array.isArray(p)||D!==void 0&&!Array.isArray(D))return"preserved";const c=R=>{const y=O(R);return y?.kind==="story-worktree-lease"?!1:!y||y.storyId===r||Array.isArray(y.storyIds)&&y.storyIds.includes(r)};if(p?.some(c)||D?.some(c))return"preserved"}return"reset"}class H extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function u(l){throw new H(l)}function x(l){return ke("sha256").update(l).digest("hex")}function q(l){return new Promise(e=>setTimeout(e,l))}function we(l){return[...new Set(l)]}function Ye(l){try{return process.kill(l,0),!0}catch(e){return e.code==="EPERM"}}function J(l,e){return`${l}-${e.slice(0,12)}.bundle`}function ge(l=Oe()){return x(`neocortex.p225.owner-host|${l}`)}function O(l){return l!==null&&typeof l=="object"&&!Array.isArray(l)?l:void 0}const ye=["schemaVersion","leaseId","epicId","storyId","state","removeAttempts","updatedAt"],Ke=new Set([...ye,"trigger","headSha","bundleDigest","bundleBytes","bundleExpiresAt","remotePush","remoteBranchRemoved","ownerPid","ownerHostDigest","claimToken","claimExpiresAt"]);function Ie(l,e){const t=O(e);if(!t||Object.keys(t).some(n=>!Ke.has(n))||ye.some(n=>t[n]===void 0))return!1;const r=t.remotePush===void 0?void 0:O(t.remotePush);if(t.remotePush!==void 0&&(!r||Object.keys(r).length!==3||typeof r.remote!="string"||!pe.test(r.remote)||typeof r.branch!="string"||!Ee.test(r.branch)||!r.branch.startsWith(`nx/${String(t.epicId)}/`)||typeof r.sha!="string"||!K.test(r.sha)))return!1;const s=n=>t[n]===void 0||typeof t[n]=="string"&&$e.test(t[n])&&Number.isFinite(Date.parse(t[n]));return t.schemaVersion===1&&t.leaseId===l&&xe.test(l)&&typeof t.epicId=="string"&&me.test(t.epicId)&&typeof t.storyId=="string"&&He.test(t.storyId)&&t.storyId.startsWith(`${t.epicId}.`)&&Pe.includes(t.state)&&Number.isSafeInteger(t.removeAttempts)&&t.removeAttempts>=0&&t.removeAttempts<=1e3&&s("updatedAt")&&s("bundleExpiresAt")&&s("claimExpiresAt")&&t.claimToken===void 0==(t.claimExpiresAt===void 0)&&(t.claimToken===void 0||typeof t.claimToken=="string"&&We.test(t.claimToken))&&(t.trigger===void 0||le.includes(t.trigger))&&(t.headSha===void 0||typeof t.headSha=="string"&&K.test(t.headSha))&&(t.bundleDigest===void 0||typeof t.bundleDigest=="string"&&fe.test(t.bundleDigest)&&t.headSha!==void 0&&t.bundleExpiresAt!==void 0)&&(t.bundleBytes===void 0||Number.isSafeInteger(t.bundleBytes)&&t.bundleBytes>0)&&(t.remoteBranchRemoved===void 0||typeof t.remoteBranchRemoved=="boolean")&&(t.ownerPid===void 0||Number.isSafeInteger(t.ownerPid)&&t.ownerPid>0)&&(t.ownerHostDigest===void 0||typeof t.ownerHostDigest=="string"&&fe.test(t.ownerHostDigest))}function Q(l){let e;try{e=JSON.parse(l)}catch{u(i.STATE_INVALID)}const t=O(e),r=O(t?.records);return(!t||Object.keys(t).length!==2||t.schemaVersion!==1||!r||Object.keys(r).length>Ce||!Object.entries(r).every(([s,n])=>Ie(s,n)))&&u(i.STATE_INVALID),{schemaVersion:1,records:r}}async function ve(l){const e=A(l,F),t=A(e,G);if(!M(t))return{schemaVersion:1,records:{}};try{await se(t,e)}catch{u(i.STATE_INVALID)}return Q(await B(t,"utf8"))}function P(l,e){return l?.claimToken!==void 0&&l.claimExpiresAt!==void 0&&Date.parse(l.claimExpiresAt)>e}async function at(l,e,t=Date.now()){try{const r=(await ve(l)).records[e];return r!==void 0&&(z.includes(r.state)||P(r,t))}catch{return!0}}class ze{options;manager;now;isProcessAlive;constructor(e){this.options=e,this.manager=e.manager??new Ne({projectRoot:e.projectRoot,...e.worktreeRoot?{worktreeRoot:e.worktreeRoot}:{},...e.now?{now:e.now}:{}}),this.now=e.now??(()=>new Date),this.isProcessAlive=e.isProcessAlive??Ye}async readState(e){return ve(e?.commonDir??(await this.facts()).commonDir)}async recordPush(e){return this.guard(async()=>{(typeof e.remote!="string"||!pe.test(e.remote))&&u("story-worktree-remote-invalid");const t=await this.probe(e.leaseId);(t.ownership!=="proven"||!t.headSha)&&u("story-worktree-ownership-unproven"),(t.entry.workspaceMechanism!=="client_managed_worktree"||!Ee.test(t.entry.temporaryBranch))&&u(i.ADOPTED_BRANCH),await this.gitOk(t.facts.mainRoot,["config","--get",`remote.${e.remote}.url`])||u(i.REMOTE_UNKNOWN);const r=await this.lsRemote(t.facts.mainRoot,e.remote,t.entry.temporaryBranch);r===null&&u(i.REMOTE_UNVERIFIED),r===void 0&&u(i.REMOTE_ABSENT),r!==t.headSha&&u(i.REMOTE_DIVERGED);const s={remote:e.remote,branch:t.entry.temporaryBranch,sha:r};return await this.update(t.entry,void 0,n=>{const o={...n,remotePush:s};return delete o.remoteBranchRemoved,o}),{ok:!0,value:{leaseId:t.entry.leaseId,...s}}})}async registerOwnerProcess(e){return this.guard(async()=>{(!Number.isSafeInteger(e.pid)||e.pid<=0)&&u("story-worktree-owner-pid-invalid");const t=await this.probe(e.leaseId);return await this.update(t.entry,void 0,r=>({...r,ownerPid:e.pid,ownerHostDigest:ge()})),{ok:!0,value:{leaseId:t.entry.leaseId}}})}async cleanup(e){return this.guard(async()=>({ok:!0,value:await this.cleanupUnguarded(e)}))}async sweep(e={}){return this.guard(async()=>{e.epicId!==void 0&&!me.test(e.epicId)&&u("story-worktree-identity-invalid");const t=e.dryRun===!0,r=await this.facts(),s=await j(this.options.projectRoot),n=Object.values(s.storyWorktrees?.entries??{}),o=n.filter(c=>e.epicId===void 0||c.epicId===e.epicId).sort((c,R)=>c.leaseId.localeCompare(R.leaseId)),f=await this.readState(r),m=this.now().getTime(),h=ge(),a=[],d=[];for(const c of o){const R=f.records[c.leaseId],y=R!==void 0&&z.includes(R.state),C=Date.parse(c.expiresAt)<=m,k=R?.ownerPid!==void 0&&R.ownerHostDigest===h&&this.isProcessAlive(R.ownerPid),L=!k&&!P(R,m)&&!y&&!C&&c.state==="active"&&await Te(c.worktreePath)==="enoent";if(!L&&(k||P(R,m)||!y&&!C)){const T=k?i.OWNER_ALIVE:P(R,m)?i.CLAIMED:i.LEASE_LIVE;a.push({leaseId:c.leaseId,action:"skipped",reasonCode:T});continue}const W=y?R?.trigger==="success"&&C?"orphan-recovery":R?.trigger??"orphan-recovery":"orphan-recovery";let v;try{v={ok:!0,value:await this.cleanupUnguarded({leaseId:c.leaseId,trigger:W,dryRun:t,...L?{requireVanished:!0}:{}})}}catch(T){v={ok:!1,reasonCode:T instanceof H?T.reasonCode:i.SWEEP_FAILED}}if(!v.ok&&L&&v.reasonCode===i.LEASE_LIVE){a.push({leaseId:c.leaseId,action:"skipped",reasonCode:i.LEASE_LIVE});continue}if(!v.ok){a.push({leaseId:c.leaseId,action:"preserved",reasonCode:v.reasonCode}),d.push(v.reasonCode);continue}const _=v.value,N=await this.reconcileOrphanProgress(c,_,r,t);_.outcome==="dry-run"?a.push({leaseId:c.leaseId,action:"planned",plannedActions:_.plannedActions??[]}):_.outcome==="remove-pending"?(a.push({leaseId:c.leaseId,action:"remove-pending",reasonCode:i.REMOVE_PENDING,..._.bundleDigest?{bundleDigest:_.bundleDigest}:{}}),d.push(i.REMOVE_PENDING)):(a.push({leaseId:c.leaseId,action:"recovered",reasonCode:i.ORPHAN_RECOVERED,..._.bundleDigest?{bundleDigest:_.bundleDigest}:{},..._.absenceProof?{absenceProof:_.absenceProof}:{}}),d.push(i.ORPHAN_RECOVERED)),N&&(a.push(N),N.reasonCode&&d.push(N.reasonCode))}const g=new Set(n.map(c=>c.leaseId));for(const c of Object.values(f.records).sort((R,y)=>R.leaseId.localeCompare(y.leaseId))){if(g.has(c.leaseId)||c.state==="removed"||P(c,m)||e.epicId!==void 0&&c.epicId!==e.epicId)continue;const R=await this.closeDetachedRecord(c,r,t);a.push({leaseId:c.leaseId,action:t?"planned":"record-closed",...R?{reasonCode:R}:{}}),R&&d.push(R)}const E=await this.expireBundles(f,r,m,t),p=await this.manager.registeredWorktrees();p.ok||u(p.reasonCode);const D=p.value.worktrees.filter(c=>!n.some(R=>this.manager.sameWorktreePath(R.worktreePath,c.path))).length;return D>0&&d.push(i.MANUAL_PRESERVED),{ok:!0,value:{dryRun:t,entriesScanned:o.length,recovered:a.filter(c=>c.action==="recovered").length,removePending:a.filter(c=>c.action==="remove-pending").length,preserved:a.filter(c=>c.action==="preserved").length,skipped:a.filter(c=>c.action==="skipped").length,manualWorktreesPreserved:D,bundlesExpired:E,items:a,reasonCodes:we(d)}}})}async cleanupUnguarded(e){le.includes(e.trigger)||u("story-worktree-trigger-invalid");const t=await this.probe(e.leaseId),{entry:r,facts:s}=t;e.requireVanished===!0&&(t.pathAbsence!=="enoent"||r.state!=="active")&&u(i.LEASE_LIVE);const o=(await this.readState(s)).records[r.leaseId];if(r.state==="creating")return e.trigger!=="orphan-recovery"&&u("story-worktree-ownership-unproven"),this.recoverCreating(t,e.dryRun===!0);const f=o!==void 0&&z.includes(o.state);let m=!1;t.pathExists||(t.pathAbsence!=="enoent"&&u(i.ORPHAN_UNPROVEN),e.trigger!=="orphan-recovery"&&!f&&u("story-worktree-ownership-unproven"),m=!0),!m&&t.ownership!=="proven"&&u("story-worktree-ownership-unproven"),!m&&t.clean!==!0&&u(e.trigger==="success"?"story-worktree-dirty":i.DIRTY_PRESERVED),t.epicHead||u("story-worktree-epic-branch-missing");const h=t.epicHead,a=m?t.branchSha:t.headSha;!m&&!a&&u("story-worktree-git-failed");const d=t.integrated===!0;e.trigger==="success"&&!d&&u("story-worktree-not-integrated");const g=r.workspaceMechanism==="client_managed_worktree",E=o?.bundleDigest!==void 0&&o.headSha!==void 0&&o.headSha===a&&await this.bundleMatches(s,r.leaseId,o.headSha,o.bundleDigest),p=!d&&a!==void 0&&(g||e.trigger==="orphan-recovery")&&!E,D=o?.remotePush!==void 0&&o.remoteBranchRemoved!==!0;if(e.dryRun===!0){const y=[...p?["bundle-unintegrated-range"]:[],m?"drop-worktree-metadata":"remove-worktree",...g&&t.branchSha?["delete-local-branch"]:[],...D?["delete-remote-branch"]:[]];return{leaseId:r.leaseId,outcome:"dry-run",trigger:e.trigger,state:o?.state??"active",plannedActions:y,preservedReasonCodes:[]}}const c=await this.claim(r);let R=!1;try{let y=E?o?.bundleDigest:void 0;if(p){const I=await this.createBundle(t,a,h);y=I.digest,await this.update(r,c,w=>({...w,state:"bundled",trigger:e.trigger,headSha:a,bundleDigest:I.digest,bundleBytes:I.bytes,bundleExpiresAt:new Date(this.now().getTime()+(this.options.bundleTtlMs??ue)).toISOString()}))}else if(!E){const I=d?"integrated":e.trigger==="failure"?"failed":"abandoned";await this.update(r,c,w=>({...w,state:w.state==="remove-pending"?"remove-pending":I,trigger:e.trigger,...a?{headSha:a}:{}}))}if(m)await S(s.mainRoot,["worktree","remove",r.worktreePath]);else{const I=this.options.removeAttempts??he;if(!await this.removeWithRetry(s.mainRoot,r.worktreePath,I))return await this.update(r,c,w=>({...w,state:"remove-pending",trigger:e.trigger,removeAttempts:Math.min(1e3,w.removeAttempts+I)})),{leaseId:r.leaseId,outcome:"remove-pending",trigger:e.trigger,state:"remove-pending",...y?{bundleDigest:y}:{},preservedReasonCodes:[i.REMOVE_PENDING]}}await S(s.mainRoot,["worktree","prune"]);const C=await this.manager.registeredWorktrees();C.ok||u(C.reasonCode),C.value.worktrees.some(I=>this.manager.sameWorktreePath(I.path,r.worktreePath))&&u(i.ORPHAN_UNPROVEN);const k=[];let L=!1;if(!g)k.push(i.ADOPTED_BRANCH);else if(t.branchSha){const I=a??t.branchSha,w=d||y!==void 0,b=C.value.worktrees.some(U=>U.branch===r.temporaryBranch);w?b?k.push(i.BRANCH_CHECKED_OUT):await this.gitOk(s.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,I])?L=!0:k.push(i.BRANCH_MOVED):k.push(i.ORPHAN_UNPROVEN)}const W=(await this.readState(s)).records[r.leaseId]??o,v=await this.deleteRemote(r,s,W,c,{epicHead:h,...a?{tip:a}:{},bundled:y!==void 0});v.reasonCode&&k.push(v.reasonCode);const _=W?.remotePush!==void 0&&!v.removed&&(v.reasonCode===i.REMOTE_UNVERIFIED||v.reasonCode===i.REMOTE_UNPRESERVED),N=this.now().toISOString(),T={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${x(`${r.leaseId}|${r.nonceDigest}|${e.trigger}|${N}`).slice(0,24)}`,epicId:r.epicId,storyId:r.storyId,leaseId:r.leaseId,trigger:e.trigger,worktreeRemoved:!0,localBranchRemoved:L,remoteBranchRemoved:v.removed,...k[0]?{preservedReasonCode:k[0]}:{},cleanedAt:N};ae(T)||u("story-worktree-receipt-invalid"),await this.mutate(I=>{const w=oe(I),b=w.entries[r.leaseId];for((!b||b.nonceDigest!==r.nonceDigest)&&u(i.ENTRY_CONFLICT),delete w.entries[r.leaseId],w.cleanupReceipts.push({...T});w.cleanupReceipts.length>re;)w.cleanupReceipts.shift()},I=>{const w=I.records[r.leaseId];if(w)if(_&&w.remotePush!==void 0){const b=w.state==="removed"||w.state==="remove-pending"||w.state==="active"?w.bundleDigest?"bundled":"integrated":w.state,U={...w,state:b,updatedAt:N,remoteBranchRemoved:!1};delete U.claimToken,delete U.claimExpiresAt,I.records[r.leaseId]=U}else if(w.bundleDigest){const b={...w,state:"removed",updatedAt:N,remoteBranchRemoved:v.removed};delete b.claimToken,delete b.claimExpiresAt,I.records[r.leaseId]=b}else delete I.records[r.leaseId]}),R=!0;const X=m?{worktree:"enoent",branch:t.branchSha?"present":await this.branchAbsence(s,r.temporaryBranch),bundled:y!==void 0}:void 0;return{leaseId:r.leaseId,outcome:"removed",trigger:e.trigger,state:"removed",receipt:T,receiptDigest:ce(T),...y?{bundleDigest:y}:{},preservedReasonCodes:we(k),...X?{absenceProof:X}:{}}}finally{R||await this.releaseClaim(r,c).catch(()=>{})}}async recoverCreating(e,t){const{entry:r,facts:s}=e,n={leaseId:r.leaseId,trigger:"orphan-recovery",preservedReasonCodes:[]};let o=!1;if(e.pathExists){const h=await S(r.worktreePath,["rev-parse","HEAD"]),a=await S(r.worktreePath,["symbolic-ref","--quiet","--short","HEAD"]),d=await S(r.worktreePath,["status","--porcelain=v1","--untracked-files=all","-z"]);e.registered&&h.ok&&h.stdout.trim()===r.baseSha&&a.ok&&a.stdout.trim()===r.temporaryBranch&&d.ok&&d.stdout.length===0||u(i.ORPHAN_UNPROVEN),o=!0}else e.pathAbsence!=="enoent"&&u(i.ORPHAN_UNPROVEN),e.branchCheckedOut&&u(i.ORPHAN_UNPROVEN);if(e.branchSha!==void 0&&e.branchSha!==r.baseSha&&u(i.ORPHAN_UNPROVEN),t)return{...n,outcome:"dry-run",state:"active",plannedActions:[...o?["remove-worktree"]:[],...e.branchSha?["delete-local-branch"]:[],"drop-reservation"]};const f=await this.claim(r);let m=!1;try{o&&!await this.removeWithRetry(s.mainRoot,r.worktreePath,this.options.removeAttempts??he)&&u(i.REMOVE_PENDING),o&&await S(s.mainRoot,["worktree","prune"]);let h=!1;e.branchSha&&(h=await this.gitOk(s.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]));const a=this.now().toISOString(),d={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${x(`${r.leaseId}|${r.nonceDigest}|creating|${a}`).slice(0,24)}`,epicId:r.epicId,storyId:r.storyId,leaseId:r.leaseId,trigger:"orphan-recovery",worktreeRemoved:o,localBranchRemoved:h,remoteBranchRemoved:!1,...e.branchSha&&!h?{preservedReasonCode:i.BRANCH_MOVED}:{},cleanedAt:a};return ae(d)||u("story-worktree-receipt-invalid"),await this.mutate(g=>{const E=oe(g),p=E.entries[r.leaseId];for((!p||p.state!=="creating"||p.nonceDigest!==r.nonceDigest)&&u(i.ENTRY_CONFLICT),delete E.entries[r.leaseId],E.cleanupReceipts.push({...d});E.cleanupReceipts.length>re;)E.cleanupReceipts.shift()},g=>{delete g.records[r.leaseId]}),m=!0,{...n,outcome:"reclaimed",state:"removed",receipt:d,receiptDigest:ce(d),preservedReasonCodes:d.preservedReasonCode?[d.preservedReasonCode]:[]}}finally{m||await this.releaseClaim(r,f).catch(()=>{})}}async closeDetachedRecord(e,t,r){let s,n=e.remoteBranchRemoved===!0;if(e.remotePush&&!n){const o=await S(t.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/epic/${e.epicId}^{commit}`]);if(!(o.ok&&await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",e.remotePush.sha,o.stdout.trim()])))s=i.REMOTE_UNPRESERVED;else if(!r){const m=await this.deleteRecordedRemote(t.mainRoot,e.remotePush);n=m.removed,s=m.reasonCode}}return r||s===i.REMOTE_UNPRESERVED||s===i.REMOTE_UNVERIFIED||await this.mutate(void 0,o=>{const f=o.records[e.leaseId];!f||f.state==="removed"||(f.bundleDigest?o.records[e.leaseId]={...f,state:"removed",remoteBranchRemoved:n,updatedAt:this.now().toISOString()}:delete o.records[e.leaseId])}),s}async deleteRemote(e,t,r,s,n){const o=r?.remotePush;if(!o)return{removed:!1};if(r?.remoteBranchRemoved===!0)return{removed:!0};if(e.workspaceMechanism!=="client_managed_worktree"||o.branch!==e.temporaryBranch)return{removed:!1,reasonCode:i.ADOPTED_BRANCH};const f=await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",o.sha,n.epicHead]),m=!f&&n.bundled&&n.tip!==void 0&&await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",o.sha,n.tip]);if(!f&&!m)return{removed:!1,reasonCode:i.REMOTE_UNPRESERVED};const h=await this.deleteRecordedRemote(t.mainRoot,o);return h.removed&&await this.update(e,s,a=>({...a,remoteBranchRemoved:!0})),h}async deleteRecordedRemote(e,t){if(!await this.gitOk(e,["config","--get",`remote.${t.remote}.url`]))return{removed:!1,reasonCode:i.REMOTE_UNKNOWN};const r=await this.lsRemote(e,t.remote,t.branch);return r===null?{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}:r===void 0?{removed:!1,reasonCode:i.REMOTE_ABSENT}:r!==t.sha?{removed:!1,reasonCode:i.REMOTE_DIVERGED}:await this.gitOk(e,["push","--porcelain",`--force-with-lease=refs/heads/${t.branch}:${t.sha}`,t.remote,"--delete",`refs/heads/${t.branch}`])?await this.lsRemote(e,t.remote,t.branch)===void 0?{removed:!0}:{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}:{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}}async lsRemote(e,t,r){const s=await S(e,["ls-remote","--heads",t,`refs/heads/${r}`]);if(!s.ok)return null;const n=s.stdout.split(`
2
2
  `).map(f=>f.trim()).find(f=>f.endsWith(` refs/heads/${r}`));if(!n)return;const o=n.split(" ")[0]??"";return K.test(o)?o:null}async createBundle(e,t,r){const{entry:s,facts:n}=e,o=await De(await ne(this.options.projectRoot),Y),f=J(s.leaseId,t),h=(await te(o)).filter(c=>Re.test(c)).filter(c=>c!==f);h.length>=(this.options.maxBundles??Be)&&u(i.BUNDLE_QUOTA);let a=0;for(const c of h)a+=(await $(A(o,c))).size;const d=A(o,f);await V(d,{force:!0});const g=`refs/heads/${s.temporaryBranch}`;await this.gitOk(n.mainRoot,["bundle","create",d,g,`^${r}`])||(await V(d,{force:!0}),u(i.BUNDLE_FAILED)),process.platform!=="win32"&&await _e(d,384);const E=(await $(d)).size;a+E>(this.options.maxBundleBytes??Ve)&&(await V(d,{force:!0}),u(i.BUNDLE_QUOTA));const p=await S(n.mainRoot,["bundle","list-heads",d]);return(!await this.gitOk(n.mainRoot,["bundle","verify","--quiet",d])||!p.ok||!p.stdout.split(`
3
3
  `).some(c=>c.trim()===`${t} ${g}`))&&(await V(d,{force:!0}),u(i.BUNDLE_UNVERIFIED)),{digest:x(await B(d)),bytes:E}}async bundleMatches(e,t,r,s){try{const n=A(e.commonDir,F,Y,J(t,r));return x(await B(n))===s}catch{return!1}}async expireBundles(e,t,r,s){const n=A(t.commonDir,F,Y),o=Object.values(e.records).filter(a=>a.state==="removed"&&a.bundleExpiresAt!==void 0&&Date.parse(a.bundleExpiresAt)<=r),f=new Set(Object.values(e.records).filter(a=>a.bundleDigest!==void 0&&a.headSha!==void 0&&!o.some(d=>d.leaseId===a.leaseId)).map(a=>J(a.leaseId,a.headSha))),m=this.options.bundleTtlMs??ue,h=[];if(M(n))for(const a of(await te(n)).filter(d=>Re.test(d)&&!f.has(d))){const d=a.slice(0,28),g=e.records[d];(o.some(E=>E.leaseId===d)||!g&&r-(await $(A(n,a))).mtimeMs>=m)&&h.push(a)}if(s||h.length===0&&o.length===0)return h.length;await this.mutate(void 0,a=>{for(const d of o){const g=a.records[d.leaseId];g?.state==="removed"&&g.bundleExpiresAt===d.bundleExpiresAt&&delete a.records[d.leaseId]}});for(const a of h)await V(A(n,a),{force:!0});return h.length}async reconcileOrphanProgress(e,t,r,s){let n;if(t.outcome==="dry-run"){const h=t.plannedActions??[];if(!h.includes("drop-worktree-metadata"))return;const a=await this.branchAbsence(r,e.temporaryBranch);n={worktreeAbsent:!0,bundled:h.includes("bundle-unintegrated-range"),branchGone:a==="absent"||a==="present"&&h.includes("delete-local-branch")}}else{const h=t.absenceProof;if(t.outcome!=="removed"||!h)return;n={worktreeAbsent:h.worktree==="enoent",bundled:h.bundled,branchGone:h.branch==="absent"||h.branch==="present"&&t.receipt?.localBranchRemoved===!0}}const o={leaseId:e.leaseId,storyId:e.storyId},f={...o,action:"progress-preserved",reasonCode:i.ORPHAN_PROGRESS_PRESERVED},m=A(this.options.projectRoot,".neocortex","state.json");for(let h=1;h<=3;h++){let a,d;try{a=await j(this.options.projectRoot),d=M(m)?await B(m,"utf8"):void 0}catch{return f}const g=Ge({runtime:a,trackedText:d,epicId:e.epicId,storyId:e.storyId,recoveredLeaseId:e.leaseId,loss:n});if(g==="none")return;if(g==="preserved")return f;if(s)return{...o,action:"planned",reasonCode:i.ORPHAN_PROGRESS_RESET,plannedActions:["reset-story-phase-1-progress"]};try{return await ie(this.options.projectRoot,E=>{const p=E.stories[e.storyId];if(!p)throw new Error("git-lifecycle-runtime-revision-conflict");delete p.status,delete p.last_step,delete p.steps_completed,Object.keys(p).length===0&&delete E.stories[e.storyId]},{expectedRevision:a.revision,preCommit:async()=>{if((M(m)?await B(m,"utf8"):void 0)!==d)throw new Error("git-lifecycle-runtime-revision-conflict")}}),{...o,action:"progress-reset",reasonCode:i.ORPHAN_PROGRESS_RESET}}catch(E){if(!(E instanceof Error&&E.message==="git-lifecycle-runtime-revision-conflict"))return f}}return f}async branchAbsence(e,t){const r=await S(e.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${t}`]);return r.ok?"present":r.exitCode===1?"absent":"unknown"}async removeWithRetry(e,t,r){const s=this.options.removeWorktree??((o,f)=>this.gitOk(o,["worktree","remove",f])),n=this.options.removeDelayMs??Ue;for(let o=1;o<=r;o++){if(await s(e,t))return!0;o<r&&await q(n*o)}return!1}async probe(e){const t=await this.manager.probe(e);return t.ok||u(t.reasonCode),t.value}async facts(){const e=await this.manager.registeredWorktrees();return e.ok||u(e.reasonCode),e.value.facts}async gitOk(e,t){return(await S(e,t)).ok}async claim(e){const t=Z(8).toString("hex");return await this.mutate(r=>{const s=r.storyWorktrees?.entries[e.leaseId];(!s||s.nonceDigest!==e.nonceDigest)&&u(i.ENTRY_CONFLICT)},r=>{const s=this.now().getTime(),n=r.records[e.leaseId]??this.emptyRecord(e);P(n,s)&&u(i.CLAIMED),r.records[e.leaseId]={...n,claimToken:t,claimExpiresAt:new Date(s+(this.options.claimTtlMs??Me)).toISOString(),updatedAt:new Date(s).toISOString()}}),t}async releaseClaim(e,t){await this.mutate(void 0,r=>{const s=r.records[e.leaseId];if(!s||s.claimToken!==t)return;const n={...s};delete n.claimToken,delete n.claimExpiresAt,s.state!=="active"||s.remotePush!==void 0||s.ownerPid!==void 0||s.bundleDigest!==void 0||s.removeAttempts>0?r.records[e.leaseId]=n:delete r.records[e.leaseId]})}emptyRecord(e){return{schemaVersion:1,leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,state:"active",removeAttempts:0,updatedAt:this.now().toISOString()}}async update(e,t,r){await this.mutate(s=>{const n=s.storyWorktrees?.entries[e.leaseId];(!n||n.nonceDigest!==e.nonceDigest)&&u(i.ENTRY_CONFLICT)},s=>{const n=s.records[e.leaseId]??this.emptyRecord(e);P(n,this.now().getTime())&&n.claimToken!==t&&u(i.CLAIMED);const o={...r(n),updatedAt:this.now().toISOString()};Ie(e.leaseId,o)||u(i.STATE_INVALID),s.records[e.leaseId]=o})}async mutate(e,t){const r=this.options.lockRetry?.attempts??40,s=this.options.lockRetry?.delayMs??25;for(let n=1;;n++)try{await ie(this.options.projectRoot,o=>{e?.(o),be(o)},{preCommit:async()=>{const o=await ne(this.options.projectRoot),f=A(o,G);let m={schemaVersion:1,records:{}};if(M(f)&&(await se(f,o),m={schemaVersion:1,records:{...Q(await B(f,"utf8")).records}}),t(m),Object.keys(m.records).length===0){M(f)&&await Se(f);return}const h=`${JSON.stringify(m,null,2)}
4
4
  `;Q(h),await qe(o,G,h)}});return}catch(o){if(!(o instanceof Error&&(o.message==="git-lifecycle-runtime-lock-active"||o.code==="ENOENT"&&o.message.includes("runtime.lock")))||n>=r)throw o;await q(s*Math.min(n,8)+Math.floor(Math.random()*s))}}async guard(e){try{return await e()}catch(t){if(t instanceof H)return{ok:!1,reasonCode:t.reasonCode};const r=t instanceof Error?t.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(r)?{ok:!1,reasonCode:r}:{ok:!1,reasonCode:"story-worktree-internal-error"}}}}async function qe(l,e,t){const r=A(l,`.${e}.${Z(6).toString("hex")}.tmp`),s=await ee(r,"wx",384);try{await s.writeFile(t,"utf8"),await s.sync()}finally{await s.close()}try{await Ae(r,A(l,e))}catch(n){throw await V(r,{force:!0}),n}try{const n=await ee(l,"r");try{await n.sync()}finally{await n.close()}}catch(n){if(process.platform!=="win32")throw n}}const Je=new Set([i.MANUAL_PRESERVED]);async function Qe(l,e={}){let t;try{const s=await j(l);if(t=new ze({...e,projectRoot:l}),!(Object.keys(s.storyWorktrees?.entries??{}).length>0)&&Object.keys((await t.readState()).records).length===0)return{reasonCodes:[]}}catch(s){return{reasonCodes:s instanceof H?[s.reasonCode]:[]}}const r=await t.sweep({...e.epicId?{epicId:e.epicId}:{},...e.dryRun?{dryRun:!0}:{}});return r.ok?{reasonCodes:r.value.reasonCodes.filter(s=>!Je.has(s)),value:r.value}:{reasonCodes:[r.reasonCode]}}function it(l,e=r=>Qe(r),t=r=>{process.kill(process.pid,r)}){let r=!1;const s=o=>{r||(r=!0,n(),Promise.race([e(l),q(25e3)]).catch(()=>{}).finally(()=>t(o)))},n=()=>{process.removeListener("SIGINT",s),process.removeListener("SIGTERM",s)};return process.once("SIGINT",s),process.once("SIGTERM",s),n}export{Y as STORY_WORKTREE_BUNDLE_DIRECTORY,G as STORY_WORKTREE_CLEANUP_FILE,Ce as STORY_WORKTREE_CLEANUP_MAX_RECORDS,Le as STORY_WORKTREE_CLEANUP_REASON_CODES,Pe as STORY_WORKTREE_CLEANUP_STATES,le as STORY_WORKTREE_CLEANUP_TRIGGERS,ze as StoryWorktreeCleanup,Ge as classifyStoryWorktreeOrphanProgress,it as installStoryWorktreeSignalSweep,Ie as isStoryWorktreeCleanupRecord,Q as parseStoryWorktreeCleanupDocument,J as storyWorktreeBundleFileName,at as storyWorktreeCleanupInProgress,ge as storyWorktreeOwnerHostDigest,Qe as sweepStoryWorktreeOrphans};
@@ -1,3 +1,3 @@
1
- import{execFile as Xe}from"node:child_process";import{createHash as wt}from"node:crypto";import{readFile as pt,realpath as be}from"node:fs/promises";import{join as ut,resolve as Ae}from"node:path";import{yoloopDomainHash as mt}from"../../../shared/dist/yoloop/canonical.js";import{DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS as Qe,directYoloCommitIdempotencyKey as Ze,directYoloWaveQaCoverage as kt,finalizeDirectYoloStoryCheckpoint as It,persistDirectYoloWaveStoryCheckpoint as vt,pushDirectYoloWaveHead as St,resolveDirectYoloIntegrationAuthority as et,runDirectYoloWaveP205 as bt,validateDirectYoloWriteSet as At}from"./direct-yolo-checkpoint.js";import{acquireGitLifecyclePhysicalIntegrationLock as Be,appendStoryWorktreeEvidence as xt,applyGitLifecycleRuntimeOverlay as Rt,ensureRuntimeEpic as xe,isStoryWorktreeIntegrationReceiptRecord as Et,mutateGitLifecycleRuntime as we,publicStoryReviewArtifactFromGit as _t,readGitLifecycleRuntime as U,readStoryWorktreeEvidence as tt,releaseGitLifecyclePhysicalIntegrationLock as je,verifyGitLifecyclePhysicalIntegrationLock as rt}from"./git-lifecycle-store.js";import{mergeStateJsonFields as Ot,STATE_JSON_FIELD_MERGE_MAX_BYTES as Tt}from"./state-json-field-merge.js";import{StoryWorktreeManager as Re}from"./story-worktree-manager.js";import{rootMemoryEffectDigest as Ct}from"../private-execution/root-memory-git-evidence.js";const Dt="neocortex.p225.story-worktree-receipt.v1",Pt=200,pe="Neocortex-Story-Worktree-Tip",ot=3e4,ce=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,Ht=/^swt-[a-f0-9]{24}$/,Ee=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class _e extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function i(e){throw new _e(e)}const it=32*1024*1024;function P(e,t,s){return new Promise(a=>{Xe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:it,timeout:ot,env:{...process.env,...s,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(r,g)=>{const n=r?typeof r.code=="number"?r.code:128:0;a({code:n,stdout:String(g??"")})})})}function nt(e,t,s){return new Promise(a=>{const r=Xe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:it,timeout:ot,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(g,n)=>{const f=g?typeof g.code=="number"?g.code:128:0;a({code:f,stdout:String(n??"")})});r.stdin?.on("error",()=>{}),r.stdin?.end(s)})}async function p(e,t,s,a){const r=await P(e,t,a);return r.code!==0&&i(s),r.stdout.trim()}async function O(e,t){return(await P(e,t)).code===0}function de(e){return wt("sha256").update(e).digest("hex")}function at(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(e)&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function q(e,t){const s=`${t}: `,a=e.split(`
2
- `).map(r=>r.trim()).filter(r=>r.startsWith(s));return a.length===1?a[0].slice(s.length):void 0}function Ne(e){return mt(Dt,e)}function V(e,t){return(tt(e,t)?.receipts??[]).filter(Et)}function ue(e){const t=[...e].sort((s,a)=>s.integrationIndex-a.integrationIndex);t.forEach((s,a)=>{(s.integrationIndex!==a+1||a>0&&s.epicHeadBeforeSha!==t[a-1].epicHeadAfterSha)&&i("story-worktree-integration-chain-invalid")})}function fe(e,t){const s=[...e].sort((a,r)=>r.integrationIndex-a.integrationIndex)[0];s&&s.epicHeadAfterSha!==t&&i("story-worktree-integration-chain-invalid")}const Bt=new Set(["done","merged","completed","released"]);function st(e,t,s,a,r,g=new Set){(tt(e,s)?.receipts??[]).some(d=>d.kind==="phase-one-receipt"&&d.storyId===a||d.kind==="spec-barrier-receipt"&&Array.isArray(d.storyIds)&&d.storyIds.includes(a))||i("story-worktree-integration-unbound");const u=new Set(V(e,s).filter(d=>d.outcome==="integrated").map(d=>d.storyId));for(const d of r){if(!d.startsWith(`${s}.`))continue;const S=t[d],m=!!e.stories[d]?.checkpoint||typeof S?.status=="string"&&Bt.has(S.status);!u.has(d)&&!g.has(d)&&!m&&i("story-worktree-integration-dependency-waiting")}}function jt(e){const t=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",s=`int-${de(["p225-integration-receipt-v1",e.epicId,e.storyId,String(e.index),e.before,e.after,e.checkpointDigest,e.outcome].join("\0")).slice(0,32)}`;return Object.freeze({schemaVersion:1,kind:"integration-receipt",receiptId:s,epicId:e.epicId,storyId:e.storyId,integrationOwner:"root_agent",integrationIndex:e.index,epicHeadBeforeSha:e.before,epicHeadAfterSha:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,reasonCode:t,integratedAt:e.integratedAt})}function ze(e){return de(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function Oe(e){let t;return await we(e.projectRoot,s=>{const a=V(s,e.epicId);ue(a);const r=[...a].sort((n,f)=>f.integrationIndex-n.integrationIndex)[0];r&&r.epicHeadAfterSha!==e.before&&i("story-worktree-integration-chain-invalid"),[...a].filter(n=>n.storyId===e.storyId).sort((n,f)=>f.integrationIndex-n.integrationIndex)[0]?.outcome==="integrated"&&i("story-worktree-integration-already-integrated"),t=jt({epicId:e.epicId,storyId:e.storyId,index:a.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),xt(s,e.epicId,{receipts:[t]})},{preCommit:async()=>{await p(e.projectRoot,["rev-parse",`refs/heads/${e.executionBranch}`],"story-worktree-integration-epic-branch-missing")!==(e.expectedEpicHead??e.after)&&i("story-worktree-integration-epic-head-raced"),e.expectedEpicHead!==void 0&&e.expectedEpicHead!==e.after&&!await O(e.projectRoot,["merge-base","--is-ancestor",e.after,e.expectedEpicHead])&&i("story-worktree-integration-epic-head-raced")}}),t}function me(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:Ne(e.receipt)})}}async function Nt(e){let t,s,a="";const r=Ae(e.projectRoot);try{(typeof e.storyId!="string"||!Ee.test(e.storyId))&&i("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!Ht.test(e.leaseId)&&i("story-worktree-integration-lease-invalid");const g=await be(await p(r,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),n=await be(await p(r,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));g!==n&&i("story-worktree-integration-not-root");let f;try{f=await et(r,e.storyId)}catch(y){i(y instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(y.message)?y.message:"story-worktree-integration-authority-invalid")}const{epicId:l,executionBranch:u,storyId:d}=f;a=l;const S=new Date(e.nowIso??Date.now()).toISOString(),m=`refs/heads/${u}`,h=await p(r,["rev-parse",m],"story-worktree-integration-epic-branch-missing");await p(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==h&&i("story-worktree-integration-root-head-mismatch");const D=f.originBinding;(!D||!await O(r,["merge-base","--is-ancestor",D.originHeadSha,h]))&&i("story-worktree-integration-origin-binding-invalid");const b=await U(r,{required:!0}),I=V(b,l);ue(I);const H=I.filter(y=>y.storyId===d).sort((y,x)=>x.integrationIndex-y.integrationIndex),A=b.stories[d]?.checkpoint;if(H[0]?.outcome==="integrated")return me({storyId:d,epicId:l,outcome:"already-integrated",receipt:H[0],...A?.headSha?{checkpointHeadSha:A.headSha}:{}});const G=Array.isArray(f.story.depends_on)?f.story.depends_on.filter(y=>typeof y=="string"):[],R=await ft(r,b);st(b,R,l,d,G);const j=Object.values(b.storyWorktrees?.entries??{}).filter(y=>y.storyId===d&&y.epicId===l&&y.state==="active"&&(e.leaseId===void 0||y.leaseId===e.leaseId));if(A&&typeof A.headSha=="string"){const y=A.headSha,x=await p(r,["show","--no-patch","--format=%B",y],"story-worktree-integration-git-failed");(q(x,"Neocortex-Story")!==d||!q(x,pe))&&i("story-worktree-integration-checkpoint-not-worktree"),y!==h&&i("story-worktree-integration-epic-head-raced"),fe(I,A.baseSha);const ee=await lt(r,d,`recover-${y.slice(0,40)}`,()=>Oe({projectRoot:r,epicId:l,storyId:d,executionBranch:u,before:A.baseSha,after:y,checkpointDigest:ze(A),outcome:"integrated",integratedAt:S})),ne=j.length===1?await $e(r,j[0].leaseId,y):!1;return me({storyId:d,epicId:l,outcome:"integrated",receipt:ee,checkpointHeadSha:y,worktreeRealigned:ne})}const N=Object.values(b.storyWorktrees?.entries??{}).filter(y=>y.storyId===d&&y.epicId===l&&y.state==="active"&&(e.leaseId===void 0||y.leaseId===e.leaseId));N.length===0&&i("story-worktree-integration-lease-missing"),N.length>1&&i("story-worktree-integration-lease-ambiguous");const C=N[0];C.executionBranch!==u&&i("story-worktree-integration-lease-invalid");const E=await new Re({projectRoot:r}).probe(C.leaseId);(!E.ok||E.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),E.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const re=await p(r,["rev-parse",`refs/heads/${C.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");E.value.headSha!==re&&i("story-worktree-integration-worktree-dirty");const B=await p(r,["show","--no-patch","--format=%B",h],"story-worktree-integration-git-failed"),X=q(B,pe)===re&&q(B,"Neocortex-Story")===d;let _,M,k,J=!1;if(X){_=await p(r,["rev-parse",`${h}^`],"story-worktree-integration-git-failed"),M=h;const y=q(B,"Neocortex-Bundle-Digest")??"",x=q(B,"Neocortex-Claim-Revision")??"";k=Ze({storyId:d,epicId:l,executionBranch:u,baseSha:_,bundleDigest:y,graphRevision:f.graphRevision,claimRevision:x}),fe(I,_)}else{fe(I,h);const y=await dt(r,f,d,h,re);if(y.kind==="conflict")return await qe({projectRoot:r,epicId:l,storyId:d,executionBranch:u,epicHead:h,tip:re,conflictPaths:y.conflictPaths,integratedAt:S,chain:H});const x=y.changedPaths;M=y.commitSha,k=y.idempotencyKey,_=h,J=!0,(!await O(r,["diff","--cached","--quiet"])||!await O(r,["diff","--quiet","HEAD","--",...x]))&&i("story-worktree-integration-root-dirty")}const Q=await U(r,{required:!0}),$=Q.epics[l]?.branch_lease,oe=$&&$.ownerStoryId===d&&$.sessionId===k&&$.idempotencyKey===k&&Date.parse(String($.expiresAt))>Date.now()?$:void 0;$&&!oe&&Date.parse(String($.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const K=oe??{schemaVersion:1,ownerStoryId:d,sessionId:k,idempotencyKey:k,acquiredAt:S,expiresAt:new Date(Date.parse(S)+Qe).toISOString()};t=await Be(r,{kind:"direct",storyId:d,sessionId:k,idempotencyKey:k,expiresAt:String(K.expiresAt),persistent:!0,createdAt:String(K.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const Y=t;oe||(await we(r,y=>{const x=xe(y,l),ee=x.branch_lease;ee&&Date.parse(String(ee.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(x.origin_binding)!==JSON.stringify(D)&&i("story-worktree-integration-origin-binding-invalid"),x.graph_revision!==f.graphRevision&&i("story-worktree-integration-graph-revision-raced"),x.branch_lease=K},{expectedRevision:Q.revision,preCommit:async y=>{await rt(Y.path,Y.owner)||i("story-worktree-integration-lock-raced");const x=V(y,l);ue(x),fe(x,_),await p(r,["rev-parse",m],"story-worktree-integration-epic-branch-missing")!==h&&i("story-worktree-integration-epic-head-raced")}}),s=K),J&&((await p(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==h||await p(r,["rev-parse",m],"story-worktree-integration-git-failed")!==h)&&i("story-worktree-integration-epic-head-raced"),await O(r,["merge","--ff-only","--no-edit",M])||i("story-worktree-integration-ff-refused"),await p(r,["rev-parse",m],"story-worktree-integration-git-failed")!==M&&i("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let Z;const ie=await It({projectRoot:r,storyId:d,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,afterCheckpointPersist:async()=>{const y=(await U(r,{required:!0})).stories[d]?.checkpoint;(!y||y.headSha!==M||y.baseSha!==_)&&i("story-worktree-integration-checkpoint-mismatch"),Z=await Oe({projectRoot:r,epicId:l,storyId:d,executionBranch:u,before:_,after:M,checkpointDigest:ze(y),outcome:"integrated",integratedAt:S})}});if(!ie.ok)return{ok:!1,reasonCode:ie.reasonCode};const L=ie.value;(L.headSha!==M||L.baseSha!==_||!Z)&&i("story-worktree-integration-checkpoint-mismatch");const le=await $e(r,C.leaseId,M);return me({storyId:d,epicId:l,outcome:"integrated",receipt:Z,checkpointHeadSha:M,worktreeRealigned:le})}catch(g){if(g instanceof _e)return{ok:!1,reasonCode:g.reasonCode};const n=g instanceof Error?g.message:"";return/^(?:git-lifecycle|direct-yolo)-[a-z0-9-]{1,80}$/.test(n)?{ok:!1,reasonCode:n}:{ok:!1,reasonCode:"story-worktree-integration-failed"}}finally{if(t?.ok&&await je(t.path,t.owner).catch(()=>{}),s&&a){const g=s;await we(r,n=>{const f=xe(n,a),l=f.branch_lease;l&&l.sessionId===g.sessionId&&l.idempotencyKey===g.idempotencyKey&&l.acquiredAt===g.acquiredAt&&(f.branch_lease=null)}).catch(()=>{})}}}const We=".neocortex/state.json",Te=".neocortex",Ce="state.json",W="story-worktree-integration-state-merge-git-failed";function De(e){const t=[];for(const s of e.split("\0")){if(!s)continue;const a=s.indexOf(" "),[r,g,n]=s.slice(0,a).split(" ");(a<0||!r||!g||!n)&&i(W),t.push({mode:r,type:g,oid:n,name:s.slice(a+1)})}return t}function zt(e){return e.map(t=>`${t.mode} ${t.type} ${t.oid} ${t.name}\0`).join("")}async function ct(e,t,s,a){const r=await P(e,["ls-tree","-z",t]);r.code!==0&&i(W);const g=De(r.stdout).filter(l=>l.name!==s),n=await nt(e,["mktree","-z"],zt([...g,a])),f=n.stdout.trim();return(n.code!==0||!ce.test(f))&&i(W),f}async function Me(e,t){const s=await P(e,["ls-tree","-z",t,"--",We]);s.code!==0&&i(W);const a=De(s.stdout).find(r=>r.name===We);return a?((a.type!=="blob"||a.mode!=="100644"&&a.mode!=="100755")&&i("state-merge-input-invalid"),ce.test(a.oid)||i(W),a.oid):null}async function Le(e,t){t===null&&i("state-merge-input-invalid");const s=await P(e,["cat-file","-s",t]),a=Number.parseInt(s.stdout.trim(),10);(s.code!==0||!Number.isSafeInteger(a)||a<0||a>Tt)&&i(W);const r=await P(e,["cat-file","blob",t]);return r.code!==0&&i(W),r.stdout}async function Wt(e){try{const{projectRoot:t,mergeBase:s,epicHead:a,tip:r,tree:g,storyId:n,epicId:f}=e,l={ok:!0,tree:g,conflictPaths:[...e.conflictPaths],merged:!1},u=await Me(t,s),d=await Me(t,r);if(u===d)return l;const S=await Le(t,u),m=await Le(t,await Me(t,a)),h=await Le(t,d),D=await p(t,["show","--no-patch","--format=%cI",r],W),b=Ot({base:S,epic:m,story:h,storyId:n,epicId:f,aggregateTimestamp:D});if(!b.ok)return{ok:!1,reasonCode:b.reasonCode};const I=e.conflictPaths.filter(E=>E!==We),H=await P(t,["ls-tree","-z",g,"--",Te]);H.code!==0&&i(W);const A=De(H.stdout).find(E=>E.name===Te);if(!A||A.type!=="tree")return{ok:!1,reasonCode:"state-merge-input-invalid"};const G=await P(t,["ls-tree","-z",A.oid,"--",Ce]);G.code!==0&&i(W);const R=De(G.stdout).find(E=>E.name===Ce);if(R&&(R.type!=="blob"||R.mode!=="100644"&&R.mode!=="100755"))return{ok:!1,reasonCode:"state-merge-input-invalid"};const j=await nt(t,["hash-object","-w","--stdin"],b.bytes),N=j.stdout.trim();if((j.code!==0||!ce.test(N))&&i(W),R?.oid===N)return{ok:!0,tree:g,conflictPaths:I,merged:!0};const C=await ct(t,A.oid,Ce,{mode:R?.mode??"100644",type:"blob",oid:N,name:Ce});return{ok:!0,tree:await ct(t,g,Te,{mode:A.mode,type:"tree",oid:C,name:Te}),conflictPaths:I,merged:!0}}catch(t){return t instanceof _e?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:W}}}async function dt(e,t,s,a,r){const{epicId:g,executionBranch:n}=t;await O(e,["merge-base","--is-ancestor",r,a])&&i("story-worktree-integration-range-empty");const f=await p(e,["merge-base",a,r],"story-worktree-integration-unrelated-history"),l=await P(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${f}`,a,r]);l.code!==0&&l.code!==1&&i("story-worktree-integration-git-unsupported");const u=l.stdout.split("\0"),d=u[0]?.trim()??"";ce.test(d)||i("story-worktree-integration-git-unsupported");const S=l.code===1?[...new Set(u.slice(1).filter(at))].sort():[];l.code===1&&S.length===0&&i("story-worktree-integration-git-failed");const m=await Wt({projectRoot:e,mergeBase:f,epicHead:a,tip:r,tree:d,storyId:s,epicId:g,conflictPaths:S});m.ok||i(m.reasonCode);const h=m.tree;if(m.conflictPaths.length>0)return{kind:"conflict",conflictPaths:m.conflictPaths.slice(0,Pt)};const D=(await p(e,["diff","--name-only","-z",a,h],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),b=At(D,t.authorizedWriteSet,s,t.rootMemoryEffect);b.ok||i(b.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":"story-worktree-integration-write-set-invalid");const I=_t(e,s,h);I?.verdict!=="approved"&&i("story-worktree-integration-review-not-approved");const H=await P(e,["diff","--binary","--full-index",a,h]);H.code!==0&&i("story-worktree-integration-git-failed");const A=H.stdout;A||i("story-worktree-integration-range-empty");const G=de(A),R=de([...t.authorizedWriteSet].sort().join("\0")),j=Ze({storyId:s,epicId:g,executionBranch:n,baseSha:a,bundleDigest:G,graphRevision:t.graphRevision,claimRevision:R}),N=(await p(e,["show","--no-patch","--format=%s",r],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${s}): integrate story worktree`,C=[`Neocortex-Story: ${s}`,`Neocortex-Epic: ${g}`,`Neocortex-Execution-Branch: ${n}`,`Neocortex-Prepared-Base: ${a}`,`Neocortex-Bundle-Digest: ${G}`,`Neocortex-Review-Artifact-Digest: ${I.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${R}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${Ct(t.rootMemoryEffect)}`]:[],`${pe}: ${r}`],T=(await p(e,["show","--no-patch","--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI",r],"story-worktree-integration-git-failed")).split("\0");T.length!==6&&i("story-worktree-integration-git-failed");const E=await p(e,["commit-tree",h,"-p",a,"-m",N,"-m",`Story: ${s}`,"-m",C.join(`
3
- `)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:T[0],GIT_AUTHOR_EMAIL:T[1],GIT_AUTHOR_DATE:T[2],GIT_COMMITTER_NAME:T[3],GIT_COMMITTER_EMAIL:T[4],GIT_COMMITTER_DATE:T[5]});return ce.test(E)||i("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:E,changedPaths:D,idempotencyKey:j}}async function ft(e,t){const s=JSON.parse(await pt(ut(e,".neocortex","state.json"),"utf8")),r=Rt(s,t).stories;return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}async function lt(e,t,s,a){const r=await Be(e,{kind:"direct",storyId:t,sessionId:s,idempotencyKey:s,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});r.ok||i(r.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");try{return await a()}finally{await je(r.path,r.owner).catch(()=>{})}}async function $e(e,t,s){const a=await new Re({projectRoot:e}).probe(t);return!a.ok||a.value.ownership!=="proven"||a.value.clean!==!0?!1:O(a.value.entry.worktreePath,["reset","--keep",s])}async function qe(e){const t=de(["p225-integration-conflict-v1",e.storyId,e.epicHead,e.tip,...e.conflictPaths].join("\0")),s=e.chain[0];if(s?.outcome==="conflict-reopened"&&s.epicHeadAfterSha===e.epicHead&&s.checkpointDigest===t)return me({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:s,conflictPaths:Object.freeze([...e.conflictPaths])});const a=()=>Oe({projectRoot:e.projectRoot,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,before:e.epicHead,after:e.epicHead,checkpointDigest:t,outcome:"conflict-reopened",integratedAt:e.integratedAt}),r=e.lockHeld?await a():await lt(e.projectRoot,e.storyId,`conflict-${t.slice(0,48)}`,a);return me({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:r,conflictPaths:Object.freeze([...e.conflictPaths])})}const Mt=64,Lt="@ornexus/neocortex",Ge=Object.freeze(["dist","packages/shared/dist","packages/client/dist","packages/server/dist"]);for(const e of Ge)if(!at(e)||/[*?[\]!:]/.test(e))throw new Error("story-worktree-wave-build-output-path-invalid");async function $t(e){return O(e,["clean","-X","-f","-q","--",...Ge])}async function qt(e,t){const s=await P(e,["show",`${t}:package.json`]);if(s.code!==0)return[];try{return JSON.parse(s.stdout)?.name===Lt?Ge:[]}catch{return[]}}function Gt(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function tr(e){let t,s,a="",r=0,g;const n=Ae(e.projectRoot);try{const f=e.storyIds;(!Array.isArray(f)||f.length===0||f.length>Mt||new Set(f).size!==f.length||f.some(o=>typeof o!="string"||!Ee.test(o)))&&i("story-worktree-wave-stories-invalid");const l=await be(await p(n,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),u=await be(await p(n,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));l!==u&&i("story-worktree-integration-not-root");const d=new Map;for(const o of f)try{d.set(o,await et(n,o))}catch(c){i(c instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(c.message)?c.message:"story-worktree-integration-authority-invalid")}const S=d.get(f[0]),{epicId:m,executionBranch:h}=S;for(const o of d.values())(o.epicId!==m||o.executionBranch!==h||o.graphRevision!==S.graphRevision||JSON.stringify(o.originBinding)!==JSON.stringify(S.originBinding))&&i("story-worktree-wave-epic-mixed");a=m;const D=new Date(e.nowIso??Date.now()).toISOString(),b=`refs/heads/${h}`,I=await p(n,["rev-parse",b],"story-worktree-integration-epic-branch-missing");(await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==I||await p(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==h)&&i("story-worktree-integration-root-head-mismatch");const H=S.originBinding;(!H||!await O(n,["merge-base","--is-ancestor",H.originHeadSha,I]))&&i("story-worktree-integration-origin-binding-invalid");const A=o=>{const c=d.get(o).story;return Array.isArray(c.depends_on)?c.depends_on.filter(w=>typeof w=="string"):[]},G=new Map(f.map((o,c)=>[o,c]));f.forEach((o,c)=>{for(const w of A(o)){const v=G.get(w);v!==void 0&&v>=c&&i("story-worktree-wave-order-invalid")}});const R=await U(n,{required:!0}),j=V(R,m);ue(j);const N=o=>j.filter(c=>c.storyId===o).sort((c,w)=>w.integrationIndex-c.integrationIndex)[0],C=f.filter(o=>N(o)?.outcome!=="integrated"),T=new Map(f.filter(o=>!C.includes(o)).map(o=>{const c=N(o),w=R.stories[o]?.checkpoint;return[o,Object.freeze({storyId:o,outcome:"already-integrated",receiptDigest:Ne(c),...w?.headSha?{checkpointHeadSha:w.headSha}:{}})]})),E=o=>({ok:!0,value:Object.freeze({epicId:m,...o,gateRuns:r,stories:Object.freeze(f.map(c=>T.get(c)??Object.freeze({storyId:c,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(C.length===0)return E({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:I,epicHeadAfterSha:I,gateRunCap:0});const re=new Set(C),B=[];let X=I;for(let o=0;o<C.length;o++){const c=await p(n,["show","--no-patch","--format=%B",X],"story-worktree-integration-git-failed"),w=q(c,"Neocortex-Story");if(!w||!re.has(w)||!q(c,pe))break;B.unshift(X),X=await p(n,["rev-parse",`${X}^`],"story-worktree-integration-git-failed")}const _=X;fe(j,_);const M=await ft(n,R),k=[];let J,Q=_;for(const[o,c]of C.entries()){const w=d.get(c);st(R,M,m,c,A(c),new Set(C.slice(0,o)));const v=Object.values(R.storyWorktrees?.entries??{}).filter(F=>F.storyId===c&&F.epicId===m&&F.state==="active"),z=R.stories[c]?.checkpoint;if(z&&typeof z.headSha=="string"){const F=z.headSha,Ve=await p(n,["show","--no-patch","--format=%B",F],"story-worktree-integration-git-failed");(q(Ve,"Neocortex-Story")!==c||!q(Ve,pe))&&i("story-worktree-integration-checkpoint-not-worktree"),(z.baseSha!==Q||B[o]!==F)&&i("story-worktree-integration-checkpoint-mismatch");const ht=(await p(n,["diff-tree","--no-commit-id","--name-only","-r","-z",F],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);k.push({storyId:c,sha:F,changedPaths:ht,...v.length===1?{leaseId:v[0].leaseId}:{}}),Q=F;continue}v.length===0&&i("story-worktree-integration-lease-missing"),v.length>1&&i("story-worktree-integration-lease-ambiguous");const ve=v[0];ve.executionBranch!==h&&i("story-worktree-integration-lease-invalid");const Se=await new Re({projectRoot:n}).probe(ve.leaseId);(!Se.ok||Se.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),Se.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const He=await p(n,["rev-parse",`refs/heads/${ve.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Se.value.headSha!==He&&i("story-worktree-integration-worktree-dirty");const se=await dt(n,w,c,Q,He);if(se.kind==="conflict"){o<B.length&&i("story-worktree-wave-resume-mismatch"),J={storyId:c,tip:He,conflictPaths:se.conflictPaths};break}o<B.length&&B[o]!==se.commitSha&&i("story-worktree-wave-resume-mismatch"),k.push({storyId:c,sha:se.commitSha,changedPaths:se.changedPaths,leaseId:ve.leaseId}),Q=se.commitSha}if(k.length<B.length&&i("story-worktree-wave-resume-mismatch"),k.length===0){const o=J,c=await qe({projectRoot:n,epicId:m,storyId:o.storyId,executionBranch:h,epicHead:I,tip:o.tip,conflictPaths:o.conflictPaths,integratedAt:D,chain:j.filter(w=>w.storyId===o.storyId).sort((w,v)=>v.integrationIndex-w.integrationIndex)});return c.ok?(T.set(o.storyId,Object.freeze({storyId:o.storyId,outcome:"conflict-reopened",receiptDigest:c.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...o.conflictPaths])})),E({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:I,epicHeadAfterSha:I,gateRunCap:0})):{ok:!1,reasonCode:c.reasonCode,gateRuns:r}}const $=k[k.length-1].sha,oe=[...new Set(k.flatMap(o=>o.changedPaths))].sort();(!await O(n,["diff","--cached","--quiet"])||!await O(n,["diff","--quiet","HEAD","--",...oe]))&&i("story-worktree-integration-root-dirty");const K=Gt(k.length),Y=de(["p205-wave-lease-v1",m,h,_,...k.map(o=>o.sha)].join("\0")),Z=k[0].storyId,ie=await U(n,{required:!0}),L=ie.epics[m]?.branch_lease,le=L&&L.ownerStoryId===Z&&L.sessionId===Y&&L.idempotencyKey===Y&&Date.parse(String(L.expiresAt))>Date.now()?L:void 0;L&&!le&&Date.parse(String(L.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const y=le??{schemaVersion:1,ownerStoryId:Z,sessionId:Y,idempotencyKey:Y,acquiredAt:D,expiresAt:new Date(Date.parse(D)+Qe*K).toISOString()};t=await Be(n,{kind:"direct",storyId:Z,sessionId:Y,idempotencyKey:Y,expiresAt:String(y.expiresAt),persistent:!0,createdAt:String(y.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const x=t;le||await we(n,o=>{const c=xe(o,m),w=c.branch_lease;w&&Date.parse(String(w.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(c.origin_binding)!==JSON.stringify(H)&&i("story-worktree-integration-origin-binding-invalid"),c.graph_revision!==S.graphRevision&&i("story-worktree-integration-graph-revision-raced"),c.branch_lease=y},{expectedRevision:ie.revision,preCommit:async o=>{await rt(x.path,x.owner)||i("story-worktree-integration-lock-raced");const c=V(o,m);ue(c),fe(c,_),await p(n,["rev-parse",b],"story-worktree-integration-epic-branch-missing")!==I&&i("story-worktree-integration-epic-head-raced")}}),s=y;const ee=new Set(k.map(o=>o.sha));let ne=!0;if(e.push&&B.length>0){const o=(await P(n,["ls-remote","--heads",e.remote??"origin",b])).stdout.split(/\s+/)[0]??"";ce.test(o)&&await O(n,["merge-base","--is-ancestor",B[0],o])&&(ne=!1)}let ae=I;const ke=async o=>{if((await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==ae||await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==ae||await p(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==h)&&i("story-worktree-integration-epic-head-raced"),ae===o)return;const c=await O(n,["merge-base","--is-ancestor",ae,o]);!c&&(!ne||!ee.has(ae))&&i("story-worktree-wave-pushed-immovable"),(!(c?await O(n,["merge","--ff-only","--no-edit",o]):await O(n,["reset","--keep",o]))||await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==o||await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==o)&&i("story-worktree-integration-ff-refused"),ae=o};g=ne?{epicRef:b,base:_,owned:ee}:void 0,await ke($),await e.afterWaveFastForward?.();const gt=[...new Set([S.graphRevision,...k.map(o=>R.stories[o.storyId]?.checkpoint?.graphRevision).filter(o=>typeof o=="string")])],yt=await qt(n,_),Pe=async()=>{yt.length!==0&&(await(e.cleanBuildOutputs??$t)(n)||i("story-worktree-wave-clean-failed"))},Ke=async o=>{const c=k[o];await ke(c.sha),r>=K&&i("story-worktree-wave-gate-cap-exceeded"),r>0&&await Pe(),r++;const w=await bt({projectRoot:n,headSha:c.sha,storyId:c.storyId,graphRevisions:gt,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==c.sha||await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==c.sha||!await O(n,["diff","--cached","--quiet"])||!await O(n,["diff","--quiet","HEAD","--",...oe]))&&i("story-worktree-integration-epic-head-raced"),!w.ok&&w.kind==="infrastructure"&&i(w.reasonCode),w},Ie=await Ke(k.length-1);let Ye=k.length-1,Fe=Ie.ok?Ie.authorities:void 0,ge,ye;if(!Ie.ok){ne||i("story-worktree-wave-gate-failed-pushed");let o=-1,c=k.length-1;for(ye=Ie.reasonCode;c-o>1;){const v=Math.floor((o+c)/2),z=await Ke(v);z.ok?(o=v,Fe=z.authorities):(c=v,ye=z.reasonCode)}ge=c,Ye=o;const w=k[c].storyId;if(T.set(w,Object.freeze({storyId:w,outcome:"gate-failed",reasonCode:ye})),o<0)return await ke(_),await Pe(),g=void 0,E({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:w,failureReasonCode:ye,epicHeadBeforeSha:I,epicHeadAfterSha:_,gateRunCap:K});await ke(k[o].sha),await Pe()}const te=k.slice(0,Ye+1),he=te[te.length-1].sha,Je=kt({epicId:m,executionBranch:h,waveHeadSha:he,waveStoryIds:te.map(o=>o.storyId),waveCommitShas:te.map(o=>o.sha)});e.push&&(g=void 0,await St(n,e.remote??"origin",h,he)||i("story-worktree-wave-remote-head-mismatch")),g=void 0;const Ue=[];for(const[o,c]of te.entries()){const w=o===0?_:te[o-1].sha,v=await vt({projectRoot:n,storyId:c.storyId,headSha:c.sha,coverage:Je,authorities:Fe,expectedLease:y,physicalLock:x,...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});v.ok||i(v.reasonCode),(v.value.headSha!==c.sha||v.value.baseSha!==w)&&i("story-worktree-integration-checkpoint-mismatch");const z=await Oe({projectRoot:n,epicId:m,storyId:c.storyId,executionBranch:h,before:w,after:c.sha,checkpointDigest:ze(v.value),outcome:"integrated",integratedAt:D,expectedEpicHead:he});Ue.push(c.storyId),T.set(c.storyId,Object.freeze({storyId:c.storyId,outcome:"integrated",checkpointHeadSha:c.sha,receiptDigest:Ne(z)})),await e.afterWaveStoryPersist?.(c.storyId)}if(J&&ge===void 0){const o=J,c=await U(n,{required:!0}),w=await qe({projectRoot:n,epicId:m,storyId:o.storyId,executionBranch:h,epicHead:he,tip:o.tip,conflictPaths:o.conflictPaths,integratedAt:D,chain:V(c,m).filter(v=>v.storyId===o.storyId).sort((v,z)=>z.integrationIndex-v.integrationIndex),lockHeld:!0});w.ok||i(w.reasonCode),T.set(o.storyId,Object.freeze({storyId:o.storyId,outcome:"conflict-reopened",receiptDigest:w.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...o.conflictPaths])}))}for(const o of te){if(!o.leaseId)continue;const c=await $e(n,o.leaseId,o.sha);T.set(o.storyId,Object.freeze({...T.get(o.storyId),worktreeRealigned:c}))}return E({outcome:ge!==void 0?"gate-failed":J?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Ue),...ge!==void 0?{failedStoryId:k[ge].storyId,failureReasonCode:ye}:{},epicHeadBeforeSha:I,epicHeadAfterSha:he,qaCoverage:Je,gateRunCap:K})}catch(f){let l=f instanceof _e?f.reasonCode:f instanceof Error&&/^(?:git-lifecycle|direct-yolo|p205)-[a-z0-9-]{1,80}$/.test(f.message)?f.message:"story-worktree-integration-failed";if(g){const u=g,d=(await P(n,["rev-parse",u.epicRef])).stdout.trim(),S=(await P(n,["rev-parse","HEAD"])).stdout.trim();d!==u.base&&(d!==S||!u.owned.has(d)||!await O(n,["reset","--keep",u.base]))&&(l="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:l,gateRuns:r}}finally{if(t?.ok&&await je(t.path,t.owner).catch(()=>{}),s&&a){const f=s;await we(n,l=>{const u=xe(l,a),d=u.branch_lease;d&&d.sessionId===f.sessionId&&d.idempotencyKey===f.idempotencyKey&&d.acquiredAt===f.acquiredAt&&(u.branch_lease=null)}).catch(()=>{})}}}async function rr(e){const t=e.integrationOrder;if(!Array.isArray(t)||t.length===0||new Set(t).size!==t.length||t.some(l=>typeof l!="string"||!Ee.test(l)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const s=e.integrate??Nt,a=new Set(e.readyStoryIds),r=Ae(e.projectRoot);let g;try{const l=await U(r,{required:!0}),u=new Set(t.map(d=>d.split(".")[0]));g=new Set([...u].flatMap(d=>V(l,d)).filter(d=>d.outcome==="integrated").map(d=>d.storyId))}catch{return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-evidence-invalid"}}const n=[],f=[];for(const l of t){if(g.has(l))continue;if(!a.has(l))return{results:n,integratedStoryIds:f,stoppedAt:l,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:u,readyStoryIds:d,integrate:S,...m}=e,h=await s({...m,projectRoot:r,storyId:l});if(n.push({storyId:l,result:h}),!h.ok)return{results:n,integratedStoryIds:f,stoppedAt:l,reasonCode:h.reasonCode};if(h.value.outcome==="conflict-reopened")return{results:n,integratedStoryIds:f,stoppedAt:l,reasonCode:"integration-conflict-reopened"};f.push(l),g.add(l)}return{results:n,integratedStoryIds:f}}async function or(e){const t=Ae(e.projectRoot),s=e.manager??new Re({projectRoot:t});let a;try{a=await U(t,{required:!0})}catch{return e.directives.map(()=>({storyId:"",ok:!1,reasonCode:"story-worktree-sync-evidence-invalid"}))}const r=[];for(const g of e.directives){const n=g&&typeof g=="object"&&!Array.isArray(g)?g:void 0,f=typeof n?.storyId=="string"&&Ee.test(n.storyId)?n.storyId:"";if(!f){r.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const l=Object.values(a.storyWorktrees?.entries??{}).filter(d=>d.storyId===f&&d.state==="active");if(l.length!==1){r.push({storyId:f,ok:!1,reasonCode:l.length===0?"story-worktree-lease-missing":"story-worktree-lease-ambiguous"});continue}const u=await s.sync({leaseId:l[0].leaseId,directive:g});r.push(u.ok?{storyId:f,ok:!0,outcome:u.value.outcome,integratedSha:u.value.integratedSha}:{storyId:f,ok:!1,reasonCode:u.reasonCode,...u.conflictPaths?{conflictPaths:u.conflictPaths}:{}})}return r}export{Pt as STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS,Dt as STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN,We as STORY_WORKTREE_STATE_JSON_PATH,Ge as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PATHS,Lt as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PROJECT,Mt as STORY_WORKTREE_WAVE_MAX_STORIES,Ne as digestStoryWorktreeIntegrationReceipt,Nt as integrateStoryWorktree,tr as integrateStoryWorktreeWave,rr as integrateStoryWorktreesInOrder,Wt as resolveStoryWorktreeStateJsonMerge,qt as storyWorktreeWaveBuildOutputPaths,Gt as storyWorktreeWaveGateRunCap,or as syncReleasedDependents};
1
+ import{execFile as Ze}from"node:child_process";import{createHash as kt}from"node:crypto";import{readFile as It,realpath as Re}from"node:fs/promises";import{join as vt,resolve as xe}from"node:path";import{yoloopDomainHash as St}from"../../../shared/dist/yoloop/canonical.js";import{DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS as et,directYoloCommitIdempotencyKey as tt,directYoloWaveQaCoverage as bt,finalizeDirectYoloStoryCheckpoint as At,persistDirectYoloWaveStoryCheckpoint as Rt,pushDirectYoloWaveHead as xt,resolveDirectYoloIntegrationAuthority as rt,runDirectYoloWaveP205 as Et,validateDirectYoloWriteSet as _t,verifyDirectYoloIntegrationCommit as ot}from"./direct-yolo-checkpoint.js";import{acquireGitLifecyclePhysicalIntegrationLock as Me,appendStoryWorktreeEvidence as Ct,applyGitLifecycleRuntimeOverlay as Dt,ensureRuntimeEpic as Ee,isStoryWorktreeIntegrationReceiptRecord as Tt,mutateGitLifecycleRuntime as ue,publicStoryReviewArtifactFromBytes as Ot,publicStoryReviewArtifactFromGit as Pt,readGitLifecycleRuntime as V,readStoryWorktreeEvidence as it,releaseGitLifecyclePhysicalIntegrationLock as We,verifyGitLifecyclePhysicalIntegrationLock as nt}from"./git-lifecycle-store.js";import{mergeStateJsonFields as Ht,STATE_JSON_FIELD_MERGE_MAX_BYTES as Bt}from"./state-json-field-merge.js";import{GOVERNANCE_DIGEST_TRAILER as at,GOVERNANCE_REASON_CODES as de,readStoryGovernanceSync as Nt,storyReviewGovernancePath as Mt}from"./governance-runtime-store.js";import{StoryWorktreeManager as _e}from"./story-worktree-manager.js";import{rootMemoryEffectDigest as Wt}from"../private-execution/root-memory-git-evidence.js";const zt="neocortex.p225.story-worktree-receipt.v1",jt=200,me="Neocortex-Story-Worktree-Tip",st=3e4,fe=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,Lt=/^swt-[a-f0-9]{24}$/,Ce=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class De extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function i(e){throw new De(e)}const ct=32*1024*1024;function P(e,t,a){return new Promise(c=>{Ze("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:ct,timeout:st,env:{...process.env,...a,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(o,l)=>{const n=o?typeof o.code=="number"?o.code:128:0;c({code:n,stdout:String(l??"")})})})}function dt(e,t,a){return new Promise(c=>{const o=Ze("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:ct,timeout:st,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(l,n)=>{const f=l?typeof l.code=="number"?l.code:128:0;c({code:f,stdout:String(n??"")})});o.stdin?.on("error",()=>{}),o.stdin?.end(a)})}async function w(e,t,a,c){const o=await P(e,t,c);return o.code!==0&&i(a),o.stdout.trim()}async function C(e,t){return(await P(e,t)).code===0}function ge(e){return kt("sha256").update(e).digest("hex")}function ft(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(e)&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function z(e,t){const a=`${t}: `,c=e.split(`
2
+ `).map(o=>o.trim()).filter(o=>o.startsWith(a));return c.length===1?c[0].slice(a.length):void 0}function ze(e){return St(zt,e)}function X(e,t){return(it(e,t)?.receipts??[]).filter(Tt)}function ke(e){const t=[...e].sort((a,c)=>a.integrationIndex-c.integrationIndex);t.forEach((a,c)=>{(a.integrationIndex!==c+1||c>0&&a.epicHeadBeforeSha!==t[c-1].epicHeadAfterSha)&&i("story-worktree-integration-chain-invalid")})}function le(e,t){const a=[...e].sort((c,o)=>o.integrationIndex-c.integrationIndex)[0];a&&a.epicHeadAfterSha!==t&&i("story-worktree-integration-chain-invalid")}const $t=new Set(["done","merged","completed","released"]);function gt(e,t,a,c,o,l=new Set){(it(e,a)?.receipts??[]).some(d=>d.kind==="phase-one-receipt"&&d.storyId===c||d.kind==="spec-barrier-receipt"&&Array.isArray(d.storyIds)&&d.storyIds.includes(c))||i("story-worktree-integration-unbound");const u=new Set(X(e,a).filter(d=>d.outcome==="integrated").map(d=>d.storyId));for(const d of o){if(!d.startsWith(`${a}.`))continue;const b=t[d],m=!!e.stories[d]?.checkpoint||typeof b?.status=="string"&&$t.has(b.status);!u.has(d)&&!l.has(d)&&!m&&i("story-worktree-integration-dependency-waiting")}}function Gt(e){const t=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",a=`int-${ge(["p225-integration-receipt-v1",e.epicId,e.storyId,String(e.index),e.before,e.after,e.checkpointDigest,e.outcome].join("\0")).slice(0,32)}`;return Object.freeze({schemaVersion:1,kind:"integration-receipt",receiptId:a,epicId:e.epicId,storyId:e.storyId,integrationOwner:"root_agent",integrationIndex:e.index,epicHeadBeforeSha:e.before,epicHeadAfterSha:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,reasonCode:t,integratedAt:e.integratedAt})}function je(e){return ge(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function Te(e){let t;return await ue(e.projectRoot,a=>{const c=X(a,e.epicId);ke(c);const o=[...c].sort((n,f)=>f.integrationIndex-n.integrationIndex)[0];o&&o.epicHeadAfterSha!==e.before&&i("story-worktree-integration-chain-invalid"),[...c].filter(n=>n.storyId===e.storyId).sort((n,f)=>f.integrationIndex-n.integrationIndex)[0]?.outcome==="integrated"&&i("story-worktree-integration-already-integrated"),t=Gt({epicId:e.epicId,storyId:e.storyId,index:c.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),Ct(a,e.epicId,{receipts:[t]})},{preCommit:async()=>{await w(e.projectRoot,["rev-parse",`refs/heads/${e.executionBranch}`],"story-worktree-integration-epic-branch-missing")!==(e.expectedEpicHead??e.after)&&i("story-worktree-integration-epic-head-raced"),e.expectedEpicHead!==void 0&&e.expectedEpicHead!==e.after&&!await C(e.projectRoot,["merge-base","--is-ancestor",e.after,e.expectedEpicHead])&&i("story-worktree-integration-epic-head-raced")}}),t}function Ie(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:ze(e.receipt)})}}async function qt(e){let t,a,c="";const o=xe(e.projectRoot);try{(typeof e.storyId!="string"||!Ce.test(e.storyId))&&i("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!Lt.test(e.leaseId)&&i("story-worktree-integration-lease-invalid");const l=await Re(await w(o,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),n=await Re(await w(o,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));l!==n&&i("story-worktree-integration-not-root");let f;try{f=await rt(o,e.storyId)}catch(h){i(h instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(h.message)?h.message:"story-worktree-integration-authority-invalid")}const{epicId:g,executionBranch:u,storyId:d}=f;c=g;const b=new Date(e.nowIso??Date.now()).toISOString(),m=`refs/heads/${u}`,p=await w(o,["rev-parse",m],"story-worktree-integration-epic-branch-missing");await w(o,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==p&&i("story-worktree-integration-root-head-mismatch");const T=f.originBinding;(!T||!await C(o,["merge-base","--is-ancestor",T.originHeadSha,p]))&&i("story-worktree-integration-origin-binding-invalid");const A=await V(o,{required:!0}),v=X(A,g);ke(v);const H=v.filter(h=>h.storyId===d).sort((h,x)=>x.integrationIndex-h.integrationIndex),R=A.stories[d]?.checkpoint;if(H[0]?.outcome==="integrated")return Ie({storyId:d,epicId:g,outcome:"already-integrated",receipt:H[0],...R?.headSha?{checkpointHeadSha:R.headSha}:{}});const q=Array.isArray(f.story.depends_on)?f.story.depends_on.filter(h=>typeof h=="string"):[],E=await yt(o,A);gt(A,E,g,d,q);const B=Object.values(A.storyWorktrees?.entries??{}).filter(h=>h.storyId===d&&h.epicId===g&&h.state==="active"&&(e.leaseId===void 0||h.leaseId===e.leaseId));if(R&&typeof R.headSha=="string"){const h=R.headSha,x=await w(o,["show","--no-patch","--format=%B",h],"story-worktree-integration-git-failed");(z(x,"Neocortex-Story")!==d||!z(x,me))&&i("story-worktree-integration-checkpoint-not-worktree"),h!==p&&i("story-worktree-integration-epic-head-raced"),le(v,R.baseSha);const re=await wt(o,d,`recover-${h.slice(0,40)}`,()=>Te({projectRoot:o,epicId:g,storyId:d,executionBranch:u,before:R.baseSha,after:h,checkpointDigest:je(R),outcome:"integrated",integratedAt:b})),ae=B.length===1?await qe(o,B[0].leaseId,h):!1;return Ie({storyId:d,epicId:g,outcome:"integrated",receipt:re,checkpointHeadSha:h,worktreeRealigned:ae})}const M=Object.values(A.storyWorktrees?.entries??{}).filter(h=>h.storyId===d&&h.epicId===g&&h.state==="active"&&(e.leaseId===void 0||h.leaseId===e.leaseId));M.length===0&&i("story-worktree-integration-lease-missing"),M.length>1&&i("story-worktree-integration-lease-ambiguous");const D=M[0];D.executionBranch!==u&&i("story-worktree-integration-lease-invalid");const S=await new _e({projectRoot:o}).probe(D.leaseId);(!S.ok||S.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),S.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const F=await w(o,["rev-parse",`refs/heads/${D.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");S.value.headSha!==F&&i("story-worktree-integration-worktree-dirty");const N=await w(o,["show","--no-patch","--format=%B",p],"story-worktree-integration-git-failed"),Q=z(N,me)===F&&z(N,"Neocortex-Story")===d;let _,W,k,U=!1;if(Q){_=await w(o,["rev-parse",`${p}^`],"story-worktree-integration-git-failed"),W=p;const h=z(N,"Neocortex-Bundle-Digest")??"",x=z(N,"Neocortex-Claim-Revision")??"";k=tt({storyId:d,epicId:g,executionBranch:u,baseSha:_,bundleDigest:h,graphRevision:f.graphRevision,claimRevision:x}),le(v,_)}else{le(v,p);const h=await ht(o,f,d,p,F);if(h.kind==="conflict")return await Fe({projectRoot:o,epicId:g,storyId:d,executionBranch:u,epicHead:p,tip:F,conflictPaths:h.conflictPaths,integratedAt:b,chain:H});const x=h.changedPaths;W=h.commitSha,k=h.idempotencyKey,_=p,U=!0,(!await C(o,["diff","--cached","--quiet"])||!await C(o,["diff","--quiet","HEAD","--",...x]))&&i("story-worktree-integration-root-dirty")}const Z=await ot(f,d,W);Z.ok||i(Z.reasonCode);const ee=await V(o,{required:!0}),G=ee.epics[g]?.branch_lease,ie=G&&G.ownerStoryId===d&&G.sessionId===k&&G.idempotencyKey===k&&Date.parse(String(G.expiresAt))>Date.now()?G:void 0;G&&!ie&&Date.parse(String(G.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const K=ie??{schemaVersion:1,ownerStoryId:d,sessionId:k,idempotencyKey:k,acquiredAt:b,expiresAt:new Date(Date.parse(b)+et).toISOString()};t=await Me(o,{kind:"direct",storyId:d,sessionId:k,idempotencyKey:k,expiresAt:String(K.expiresAt),persistent:!0,createdAt:String(K.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const Y=t;ie||(await ue(o,h=>{const x=Ee(h,g),re=x.branch_lease;re&&Date.parse(String(re.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(x.origin_binding)!==JSON.stringify(T)&&i("story-worktree-integration-origin-binding-invalid"),x.graph_revision!==f.graphRevision&&i("story-worktree-integration-graph-revision-raced"),x.branch_lease=K},{expectedRevision:ee.revision,preCommit:async h=>{await nt(Y.path,Y.owner)||i("story-worktree-integration-lock-raced");const x=X(h,g);ke(x),le(x,_),await w(o,["rev-parse",m],"story-worktree-integration-epic-branch-missing")!==p&&i("story-worktree-integration-epic-head-raced")}}),a=K),U&&((await w(o,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==p||await w(o,["rev-parse",m],"story-worktree-integration-git-failed")!==p)&&i("story-worktree-integration-epic-head-raced"),await C(o,["merge","--ff-only","--no-edit",W])||i("story-worktree-integration-ff-refused"),await w(o,["rev-parse",m],"story-worktree-integration-git-failed")!==W&&i("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let te;const ne=await At({projectRoot:o,storyId:d,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,preFastForwardAuthorizedWriteSet:f.authorizedWriteSet,afterCheckpointPersist:async()=>{const h=(await V(o,{required:!0})).stories[d]?.checkpoint;(!h||h.headSha!==W||h.baseSha!==_)&&i("story-worktree-integration-checkpoint-mismatch"),te=await Te({projectRoot:o,epicId:g,storyId:d,executionBranch:u,before:_,after:W,checkpointDigest:je(h),outcome:"integrated",integratedAt:b})}});if(!ne.ok)return{ok:!1,reasonCode:ne.reasonCode};const $=ne.value;($.headSha!==W||$.baseSha!==_||!te)&&i("story-worktree-integration-checkpoint-mismatch");const he=await qe(o,D.leaseId,W);return Ie({storyId:d,epicId:g,outcome:"integrated",receipt:te,checkpointHeadSha:W,worktreeRealigned:he})}catch(l){if(l instanceof De)return{ok:!1,reasonCode:l.reasonCode};const n=l instanceof Error?l.message:"";return/^(?:git-lifecycle|direct-yolo)-[a-z0-9-]{1,80}$/.test(n)?{ok:!1,reasonCode:n}:{ok:!1,reasonCode:"story-worktree-integration-failed"}}finally{if(t?.ok&&await We(t.path,t.owner).catch(()=>{}),a&&c){const l=a;await ue(o,n=>{const f=Ee(n,c),g=f.branch_lease;g&&g.sessionId===l.sessionId&&g.idempotencyKey===l.idempotencyKey&&g.acquiredAt===l.acquiredAt&&(f.branch_lease=null)}).catch(()=>{})}}}const Le=".neocortex/state.json",Oe=".neocortex",Pe="state.json",j="story-worktree-integration-state-merge-git-failed";function He(e){const t=[];for(const a of e.split("\0")){if(!a)continue;const c=a.indexOf(" "),[o,l,n]=a.slice(0,c).split(" ");(c<0||!o||!l||!n)&&i(j),t.push({mode:o,type:l,oid:n,name:a.slice(c+1)})}return t}function Ft(e){return e.map(t=>`${t.mode} ${t.type} ${t.oid} ${t.name}\0`).join("")}async function lt(e,t,a,c){const o=await P(e,["ls-tree","-z",t]);o.code!==0&&i(j);const l=He(o.stdout).filter(g=>g.name!==a),n=await dt(e,["mktree","-z"],Ft([...l,c])),f=n.stdout.trim();return(n.code!==0||!fe.test(f))&&i(j),f}async function $e(e,t){const a=await P(e,["ls-tree","-z",t,"--",Le]);a.code!==0&&i(j);const c=He(a.stdout).find(o=>o.name===Le);return c?((c.type!=="blob"||c.mode!=="100644"&&c.mode!=="100755")&&i("state-merge-input-invalid"),fe.test(c.oid)||i(j),c.oid):null}async function Ge(e,t){t===null&&i("state-merge-input-invalid");const a=await P(e,["cat-file","-s",t]),c=Number.parseInt(a.stdout.trim(),10);(a.code!==0||!Number.isSafeInteger(c)||c<0||c>Bt)&&i(j);const o=await P(e,["cat-file","blob",t]);return o.code!==0&&i(j),o.stdout}async function Kt(e){try{const{projectRoot:t,mergeBase:a,epicHead:c,tip:o,tree:l,storyId:n,epicId:f}=e,g={ok:!0,tree:l,conflictPaths:[...e.conflictPaths],merged:!1},u=await $e(t,a),d=await $e(t,o);if(u===d)return g;const b=await Ge(t,u),m=await Ge(t,await $e(t,c)),p=await Ge(t,d),T=await w(t,["show","--no-patch","--format=%cI",o],j),A=Ht({base:b,epic:m,story:p,storyId:n,epicId:f,aggregateTimestamp:T});if(!A.ok)return{ok:!1,reasonCode:A.reasonCode};const v=e.conflictPaths.filter(S=>S!==Le),H=await P(t,["ls-tree","-z",l,"--",Oe]);H.code!==0&&i(j);const R=He(H.stdout).find(S=>S.name===Oe);if(!R||R.type!=="tree")return{ok:!1,reasonCode:"state-merge-input-invalid"};const q=await P(t,["ls-tree","-z",R.oid,"--",Pe]);q.code!==0&&i(j);const E=He(q.stdout).find(S=>S.name===Pe);if(E&&(E.type!=="blob"||E.mode!=="100644"&&E.mode!=="100755"))return{ok:!1,reasonCode:"state-merge-input-invalid"};const B=await dt(t,["hash-object","-w","--stdin"],A.bytes),M=B.stdout.trim();if((B.code!==0||!fe.test(M))&&i(j),E?.oid===M)return{ok:!0,tree:l,conflictPaths:v,merged:!0};const D=await lt(t,R.oid,Pe,{mode:E?.mode??"100644",type:"blob",oid:M,name:Pe});return{ok:!0,tree:await lt(t,l,Oe,{mode:R.mode,type:"tree",oid:D,name:Oe}),conflictPaths:v,merged:!0}}catch(t){return t instanceof De?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:j}}}async function ht(e,t,a,c,o){const{epicId:l,executionBranch:n}=t;await C(e,["merge-base","--is-ancestor",o,c])&&i("story-worktree-integration-range-empty");const f=await w(e,["merge-base",c,o],"story-worktree-integration-unrelated-history"),g=await P(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${f}`,c,o]);g.code!==0&&g.code!==1&&i("story-worktree-integration-git-unsupported");const u=g.stdout.split("\0"),d=u[0]?.trim()??"";fe.test(d)||i("story-worktree-integration-git-unsupported");const b=g.code===1?[...new Set(u.slice(1).filter(ft))].sort():[];g.code===1&&b.length===0&&i("story-worktree-integration-git-failed");const m=await Kt({projectRoot:e,mergeBase:f,epicHead:c,tip:o,tree:d,storyId:a,epicId:l,conflictPaths:b});m.ok||i(m.reasonCode);const p=m.tree;if(m.conflictPaths.length>0)return{kind:"conflict",conflictPaths:m.conflictPaths.slice(0,jt)};const T=(await w(e,["diff","--name-only","-z",c,p],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),A=_t(T,t.authorizedWriteSet,a,t.rootMemoryEffect,t.governanceMode);A.ok||i(A.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":A.reasonCode===de.WRITE_SET_FORBIDDEN?de.WRITE_SET_FORBIDDEN:"story-worktree-integration-write-set-invalid");const v=t.governanceMode==="runtime-store"?await Yt(e,l,a,o):void 0,H=v?v.review:Pt(e,a,p);H?.verdict!=="approved"&&i("story-worktree-integration-review-not-approved");const R=await P(e,["diff","--binary","--full-index",c,p]);R.code!==0&&i("story-worktree-integration-git-failed");const q=R.stdout;q||i("story-worktree-integration-range-empty");const E=ge(q),B=ge([...t.authorizedWriteSet].sort().join("\0")),M=tt({storyId:a,epicId:l,executionBranch:n,baseSha:c,bundleDigest:E,graphRevision:t.graphRevision,claimRevision:B}),D=(await w(e,["show","--no-patch","--format=%s",o],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${a}): integrate story worktree`,L=[`Neocortex-Story: ${a}`,`Neocortex-Epic: ${l}`,`Neocortex-Execution-Branch: ${n}`,`Neocortex-Prepared-Base: ${c}`,`Neocortex-Bundle-Digest: ${E}`,`Neocortex-Review-Artifact-Digest: ${H.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${B}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${Wt(t.rootMemoryEffect)}`]:[],...v?[`${at}: ${v.governanceDigest}`]:[],`${me}: ${o}`],S=(await w(e,["show","--no-patch","--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI",o],"story-worktree-integration-git-failed")).split("\0");S.length!==6&&i("story-worktree-integration-git-failed");const F=await w(e,["commit-tree",p,"-p",c,"-m",D,"-m",`Story: ${a}`,"-m",L.join(`
3
+ `)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:S[0],GIT_AUTHOR_EMAIL:S[1],GIT_AUTHOR_DATE:S[2],GIT_COMMITTER_NAME:S[3],GIT_COMMITTER_EMAIL:S[4],GIT_COMMITTER_DATE:S[5]});return fe.test(F)||i("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:F,changedPaths:T,idempotencyKey:M}}async function Yt(e,t,a,c){const o=await w(e,["show","--no-patch","--format=%B",c],"story-worktree-integration-git-failed"),l=z(o,at);l===void 0&&i("story-worktree-integration-governance-trailer-missing");const n=Nt({projectRoot:e,epicId:t,storyId:a});n.ok||i(n.reasonCode===de.UNSAFE?n.reasonCode:de.MISMATCH);const f=n.value.receipt.governanceDigest;l!==f&&i(de.MISMATCH);const g=n.value.files.get(Mt(a));return g||i(de.MISMATCH),{governanceDigest:f,review:Ot(a,g)}}async function yt(e,t){const a=JSON.parse(await It(vt(e,".neocortex","state.json"),"utf8")),o=Dt(a,t).stories;return o&&typeof o=="object"&&!Array.isArray(o)?o:{}}async function wt(e,t,a,c){const o=await Me(e,{kind:"direct",storyId:t,sessionId:a,idempotencyKey:a,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});o.ok||i(o.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");try{return await c()}finally{await We(o.path,o.owner).catch(()=>{})}}async function qe(e,t,a){const c=await new _e({projectRoot:e}).probe(t);return!c.ok||c.value.ownership!=="proven"||c.value.clean!==!0?!1:C(c.value.entry.worktreePath,["reset","--keep",a])}async function Fe(e){const t=ge(["p225-integration-conflict-v1",e.storyId,e.epicHead,e.tip,...e.conflictPaths].join("\0")),a=e.chain[0];if(a?.outcome==="conflict-reopened"&&a.epicHeadAfterSha===e.epicHead&&a.checkpointDigest===t)return Ie({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:a,conflictPaths:Object.freeze([...e.conflictPaths])});const c=()=>Te({projectRoot:e.projectRoot,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,before:e.epicHead,after:e.epicHead,checkpointDigest:t,outcome:"conflict-reopened",integratedAt:e.integratedAt}),o=e.lockHeld?await c():await wt(e.projectRoot,e.storyId,`conflict-${t.slice(0,48)}`,c);return Ie({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:o,conflictPaths:Object.freeze([...e.conflictPaths])})}const Jt=64,Ut="@ornexus/neocortex",Ke=Object.freeze(["dist","packages/shared/dist","packages/client/dist","packages/server/dist"]);for(const e of Ke)if(!ft(e)||/[*?[\]!:]/.test(e))throw new Error("story-worktree-wave-build-output-path-invalid");async function Vt(e){return C(e,["clean","-X","-f","-q","--",...Ke])}async function Xt(e,t){const a=await P(e,["show",`${t}:package.json`]);if(a.code!==0)return[];try{return JSON.parse(a.stdout)?.name===Ut?Ke:[]}catch{return[]}}function Qt(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function fr(e){let t,a,c="",o=0,l;const n=xe(e.projectRoot);try{const f=e.storyIds;(!Array.isArray(f)||f.length===0||f.length>Jt||new Set(f).size!==f.length||f.some(r=>typeof r!="string"||!Ce.test(r)))&&i("story-worktree-wave-stories-invalid");const g=await Re(await w(n,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),u=await Re(await w(n,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));g!==u&&i("story-worktree-integration-not-root");const d=new Map;for(const r of f)try{d.set(r,await rt(n,r))}catch(s){i(s instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(s.message)?s.message:"story-worktree-integration-authority-invalid")}const b=d.get(f[0]),{epicId:m,executionBranch:p}=b;for(const r of d.values())(r.epicId!==m||r.executionBranch!==p||r.graphRevision!==b.graphRevision||JSON.stringify(r.originBinding)!==JSON.stringify(b.originBinding))&&i("story-worktree-wave-epic-mixed");c=m;const T=new Date(e.nowIso??Date.now()).toISOString(),A=`refs/heads/${p}`,v=await w(n,["rev-parse",A],"story-worktree-integration-epic-branch-missing");(await w(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==v||await w(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==p)&&i("story-worktree-integration-root-head-mismatch");const H=b.originBinding;(!H||!await C(n,["merge-base","--is-ancestor",H.originHeadSha,v]))&&i("story-worktree-integration-origin-binding-invalid");const R=r=>{const s=d.get(r).story;return Array.isArray(s.depends_on)?s.depends_on.filter(y=>typeof y=="string"):[]},q=new Map(f.map((r,s)=>[r,s]));f.forEach((r,s)=>{for(const y of R(r)){const I=q.get(y);I!==void 0&&I>=s&&i("story-worktree-wave-order-invalid")}});const E=await V(n,{required:!0}),B=X(E,m);ke(B);const M=r=>B.filter(s=>s.storyId===r).sort((s,y)=>y.integrationIndex-s.integrationIndex)[0],D=f.filter(r=>M(r)?.outcome!=="integrated"),L=new Map(f.filter(r=>!D.includes(r)).map(r=>{const s=M(r),y=E.stories[r]?.checkpoint;return[r,Object.freeze({storyId:r,outcome:"already-integrated",receiptDigest:ze(s),...y?.headSha?{checkpointHeadSha:y.headSha}:{}})]})),S=r=>({ok:!0,value:Object.freeze({epicId:m,...r,gateRuns:o,stories:Object.freeze(f.map(s=>L.get(s)??Object.freeze({storyId:s,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(D.length===0)return S({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:v,epicHeadAfterSha:v,gateRunCap:0});const F=new Set(D),N=[];let Q=v;for(let r=0;r<D.length;r++){const s=await w(n,["show","--no-patch","--format=%B",Q],"story-worktree-integration-git-failed"),y=z(s,"Neocortex-Story");if(!y||!F.has(y)||!z(s,me))break;N.unshift(Q),Q=await w(n,["rev-parse",`${Q}^`],"story-worktree-integration-git-failed")}const _=Q;le(B,_);const W=await yt(n,E),k=[];let U,Z=_;for(const[r,s]of D.entries()){const y=d.get(s);gt(E,W,m,s,R(s),new Set(D.slice(0,r)));const I=Object.values(E.storyWorktrees?.entries??{}).filter(J=>J.storyId===s&&J.epicId===m&&J.state==="active"),O=E.stories[s]?.checkpoint;if(O&&typeof O.headSha=="string"){const J=O.headSha,Qe=await w(n,["show","--no-patch","--format=%B",J],"story-worktree-integration-git-failed");(z(Qe,"Neocortex-Story")!==s||!z(Qe,me))&&i("story-worktree-integration-checkpoint-not-worktree"),(O.baseSha!==Z||N[r]!==J)&&i("story-worktree-integration-checkpoint-mismatch");const mt=(await w(n,["diff-tree","--no-commit-id","--name-only","-r","-z",J],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);k.push({storyId:s,sha:J,changedPaths:mt,...I.length===1?{leaseId:I[0].leaseId}:{},...typeof O.graphRevision=="string"?{checkpointGraphRevision:O.graphRevision}:{}}),Z=J;continue}I.length===0&&i("story-worktree-integration-lease-missing"),I.length>1&&i("story-worktree-integration-lease-ambiguous");const be=I[0];be.executionBranch!==p&&i("story-worktree-integration-lease-invalid");const Ae=await new _e({projectRoot:n}).probe(be.leaseId);(!Ae.ok||Ae.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),Ae.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const Ne=await w(n,["rev-parse",`refs/heads/${be.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Ae.value.headSha!==Ne&&i("story-worktree-integration-worktree-dirty");const ce=await ht(n,y,s,Z,Ne);if(ce.kind==="conflict"){r<N.length&&i("story-worktree-wave-resume-mismatch"),U={storyId:s,tip:Ne,conflictPaths:ce.conflictPaths};break}r<N.length&&N[r]!==ce.commitSha&&i("story-worktree-wave-resume-mismatch"),k.push({storyId:s,sha:ce.commitSha,changedPaths:ce.changedPaths,leaseId:be.leaseId}),Z=ce.commitSha}if(k.length<N.length&&i("story-worktree-wave-resume-mismatch"),k.length===0){const r=U,s=await Fe({projectRoot:n,epicId:m,storyId:r.storyId,executionBranch:p,epicHead:v,tip:r.tip,conflictPaths:r.conflictPaths,integratedAt:T,chain:B.filter(y=>y.storyId===r.storyId).sort((y,I)=>I.integrationIndex-y.integrationIndex)});return s.ok?(L.set(r.storyId,Object.freeze({storyId:r.storyId,outcome:"conflict-reopened",receiptDigest:s.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...r.conflictPaths])})),S({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:v,epicHeadAfterSha:v,gateRunCap:0})):{ok:!1,reasonCode:s.reasonCode,gateRuns:o}}const ee=new Map;for(const r of k){if(r.checkpointGraphRevision!==void 0){const y=await w(n,["show","--no-patch","--format=%B",r.sha],"story-worktree-integration-git-failed"),I=z(y,"Neocortex-Graph-Revision");I===void 0&&i("direct-yolo-trailer-missing:neocortex-graph-revision"),I!==r.checkpointGraphRevision&&i("direct-yolo-trailer-mismatch:neocortex-graph-revision"),ee.set(r.sha,I);continue}const s=await ot(d.get(r.storyId),r.storyId,r.sha);s.ok||i(s.reasonCode),ee.set(r.sha,s.value.graphRevision)}const G=k[k.length-1].sha,ie=[...new Set(k.flatMap(r=>r.changedPaths))].sort();(!await C(n,["diff","--cached","--quiet"])||!await C(n,["diff","--quiet","HEAD","--",...ie]))&&i("story-worktree-integration-root-dirty");const K=Qt(k.length),Y=ge(["p205-wave-lease-v1",m,p,_,...k.map(r=>r.sha)].join("\0")),te=k[0].storyId,ne=await V(n,{required:!0}),$=ne.epics[m]?.branch_lease,he=$&&$.ownerStoryId===te&&$.sessionId===Y&&$.idempotencyKey===Y&&Date.parse(String($.expiresAt))>Date.now()?$:void 0;$&&!he&&Date.parse(String($.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const h=he??{schemaVersion:1,ownerStoryId:te,sessionId:Y,idempotencyKey:Y,acquiredAt:T,expiresAt:new Date(Date.parse(T)+et*K).toISOString()};t=await Me(n,{kind:"direct",storyId:te,sessionId:Y,idempotencyKey:Y,expiresAt:String(h.expiresAt),persistent:!0,createdAt:String(h.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const x=t;he||await ue(n,r=>{const s=Ee(r,m),y=s.branch_lease;y&&Date.parse(String(y.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(s.origin_binding)!==JSON.stringify(H)&&i("story-worktree-integration-origin-binding-invalid"),s.graph_revision!==b.graphRevision&&i("story-worktree-integration-graph-revision-raced"),s.branch_lease=h},{expectedRevision:ne.revision,preCommit:async r=>{await nt(x.path,x.owner)||i("story-worktree-integration-lock-raced");const s=X(r,m);ke(s),le(s,_),await w(n,["rev-parse",A],"story-worktree-integration-epic-branch-missing")!==v&&i("story-worktree-integration-epic-head-raced")}}),a=h;const re=new Set(k.map(r=>r.sha));let ae=!0;if(e.push&&N.length>0){const r=(await P(n,["ls-remote","--heads",e.remote??"origin",A])).stdout.split(/\s+/)[0]??"";fe.test(r)&&await C(n,["merge-base","--is-ancestor",N[0],r])&&(ae=!1)}let se=v;const ve=async r=>{if((await w(n,["rev-parse",A],"story-worktree-integration-git-failed")!==se||await w(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==se||await w(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==p)&&i("story-worktree-integration-epic-head-raced"),se===r)return;const s=await C(n,["merge-base","--is-ancestor",se,r]);!s&&(!ae||!re.has(se))&&i("story-worktree-wave-pushed-immovable"),(!(s?await C(n,["merge","--ff-only","--no-edit",r]):await C(n,["reset","--keep",r]))||await w(n,["rev-parse",A],"story-worktree-integration-git-failed")!==r||await w(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==r)&&i("story-worktree-integration-ff-refused"),se=r};l=ae?{epicRef:A,base:_,owned:re}:void 0,await ve(G),await e.afterWaveFastForward?.();const pt=[...new Set(k.map(r=>ee.get(r.sha)))],ut=await Xt(n,_),Be=async()=>{ut.length!==0&&(await(e.cleanBuildOutputs??Vt)(n)||i("story-worktree-wave-clean-failed"))},Ye=async r=>{const s=k[r];await ve(s.sha),o>=K&&i("story-worktree-wave-gate-cap-exceeded"),o>0&&await Be(),o++;const y=await Et({projectRoot:n,headSha:s.sha,storyId:s.storyId,graphRevisions:pt,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await w(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==s.sha||await w(n,["rev-parse",A],"story-worktree-integration-git-failed")!==s.sha||!await C(n,["diff","--cached","--quiet"])||!await C(n,["diff","--quiet","HEAD","--",...ie]))&&i("story-worktree-integration-epic-head-raced"),!y.ok&&y.kind==="infrastructure"&&i(y.reasonCode),y},Se=await Ye(k.length-1);let Je=k.length-1,Ue=Se.ok?Se.authorities:void 0,ye,we;if(!Se.ok){ae||i("story-worktree-wave-gate-failed-pushed");let r=-1,s=k.length-1;for(we=Se.reasonCode;s-r>1;){const I=Math.floor((r+s)/2),O=await Ye(I);O.ok?(r=I,Ue=O.authorities):(s=I,we=O.reasonCode)}ye=s,Je=r;const y=k[s].storyId;if(L.set(y,Object.freeze({storyId:y,outcome:"gate-failed",reasonCode:we})),r<0)return await ve(_),await Be(),l=void 0,S({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:y,failureReasonCode:we,epicHeadBeforeSha:v,epicHeadAfterSha:_,gateRunCap:K});await ve(k[r].sha),await Be()}const oe=k.slice(0,Je+1),pe=oe[oe.length-1].sha,Ve=bt({epicId:m,executionBranch:p,waveHeadSha:pe,waveStoryIds:oe.map(r=>r.storyId),waveCommitShas:oe.map(r=>r.sha)});e.push&&(l=void 0,await xt(n,e.remote??"origin",p,pe)||i("story-worktree-wave-remote-head-mismatch")),l=void 0;const Xe=[];for(const[r,s]of oe.entries()){const y=r===0?_:oe[r-1].sha,I=await Rt({projectRoot:n,storyId:s.storyId,headSha:s.sha,coverage:Ve,authorities:Ue,expectedLease:h,physicalLock:x,authorizedWriteSet:d.get(s.storyId).authorizedWriteSet,expectedGraphRevision:ee.get(s.sha),...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});I.ok||i(I.reasonCode),(I.value.headSha!==s.sha||I.value.baseSha!==y)&&i("story-worktree-integration-checkpoint-mismatch");const O=await Te({projectRoot:n,epicId:m,storyId:s.storyId,executionBranch:p,before:y,after:s.sha,checkpointDigest:je(I.value),outcome:"integrated",integratedAt:T,expectedEpicHead:pe});Xe.push(s.storyId),L.set(s.storyId,Object.freeze({storyId:s.storyId,outcome:"integrated",checkpointHeadSha:s.sha,receiptDigest:ze(O)})),await e.afterWaveStoryPersist?.(s.storyId)}if(U&&ye===void 0){const r=U,s=await V(n,{required:!0}),y=await Fe({projectRoot:n,epicId:m,storyId:r.storyId,executionBranch:p,epicHead:pe,tip:r.tip,conflictPaths:r.conflictPaths,integratedAt:T,chain:X(s,m).filter(I=>I.storyId===r.storyId).sort((I,O)=>O.integrationIndex-I.integrationIndex),lockHeld:!0});y.ok||i(y.reasonCode),L.set(r.storyId,Object.freeze({storyId:r.storyId,outcome:"conflict-reopened",receiptDigest:y.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...r.conflictPaths])}))}for(const r of oe){if(!r.leaseId)continue;const s=await qe(n,r.leaseId,r.sha);L.set(r.storyId,Object.freeze({...L.get(r.storyId),worktreeRealigned:s}))}return S({outcome:ye!==void 0?"gate-failed":U?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Xe),...ye!==void 0?{failedStoryId:k[ye].storyId,failureReasonCode:we}:{},epicHeadBeforeSha:v,epicHeadAfterSha:pe,qaCoverage:Ve,gateRunCap:K})}catch(f){let g=f instanceof De?f.reasonCode:f instanceof Error&&/^(?:git-lifecycle|direct-yolo|p205)-[a-z0-9-]{1,80}$/.test(f.message)?f.message:"story-worktree-integration-failed";if(l){const u=l,d=(await P(n,["rev-parse",u.epicRef])).stdout.trim(),b=(await P(n,["rev-parse","HEAD"])).stdout.trim();d!==u.base&&(d!==b||!u.owned.has(d)||!await C(n,["reset","--keep",u.base]))&&(g="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:g,gateRuns:o}}finally{if(t?.ok&&await We(t.path,t.owner).catch(()=>{}),a&&c){const f=a;await ue(n,g=>{const u=Ee(g,c),d=u.branch_lease;d&&d.sessionId===f.sessionId&&d.idempotencyKey===f.idempotencyKey&&d.acquiredAt===f.acquiredAt&&(u.branch_lease=null)}).catch(()=>{})}}}async function gr(e){const t=e.integrationOrder;if(!Array.isArray(t)||t.length===0||new Set(t).size!==t.length||t.some(g=>typeof g!="string"||!Ce.test(g)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const a=e.integrate??qt,c=new Set(e.readyStoryIds),o=xe(e.projectRoot);let l;try{const g=await V(o,{required:!0}),u=new Set(t.map(d=>d.split(".")[0]));l=new Set([...u].flatMap(d=>X(g,d)).filter(d=>d.outcome==="integrated").map(d=>d.storyId))}catch{return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-evidence-invalid"}}const n=[],f=[];for(const g of t){if(l.has(g))continue;if(!c.has(g))return{results:n,integratedStoryIds:f,stoppedAt:g,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:u,readyStoryIds:d,integrate:b,...m}=e,p=await a({...m,projectRoot:o,storyId:g});if(n.push({storyId:g,result:p}),!p.ok)return{results:n,integratedStoryIds:f,stoppedAt:g,reasonCode:p.reasonCode};if(p.value.outcome==="conflict-reopened")return{results:n,integratedStoryIds:f,stoppedAt:g,reasonCode:"integration-conflict-reopened"};f.push(g),l.add(g)}return{results:n,integratedStoryIds:f}}async function lr(e){const t=xe(e.projectRoot),a=e.manager??new _e({projectRoot:t});let c;try{c=await V(t,{required:!0})}catch{return e.directives.map(()=>({storyId:"",ok:!1,reasonCode:"story-worktree-sync-evidence-invalid"}))}const o=[];for(const l of e.directives){const n=l&&typeof l=="object"&&!Array.isArray(l)?l:void 0,f=typeof n?.storyId=="string"&&Ce.test(n.storyId)?n.storyId:"";if(!f){o.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const g=Object.values(c.storyWorktrees?.entries??{}).filter(d=>d.storyId===f&&d.state==="active");if(g.length!==1){o.push({storyId:f,ok:!1,reasonCode:g.length===0?"story-worktree-lease-missing":"story-worktree-lease-ambiguous"});continue}const u=await a.sync({leaseId:g[0].leaseId,directive:l});o.push(u.ok?{storyId:f,ok:!0,outcome:u.value.outcome,integratedSha:u.value.integratedSha}:{storyId:f,ok:!1,reasonCode:u.reasonCode,...u.conflictPaths?{conflictPaths:u.conflictPaths}:{}})}return o}export{jt as STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS,zt as STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN,Le as STORY_WORKTREE_STATE_JSON_PATH,Ke as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PATHS,Ut as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PROJECT,Jt as STORY_WORKTREE_WAVE_MAX_STORIES,ze as digestStoryWorktreeIntegrationReceipt,qt as integrateStoryWorktree,fr as integrateStoryWorktreeWave,gr as integrateStoryWorktreesInOrder,Kt as resolveStoryWorktreeStateJsonMerge,Xt as storyWorktreeWaveBuildOutputPaths,Qt as storyWorktreeWaveGateRunCap,lr as syncReleasedDependents};
@@ -192,9 +192,20 @@ export declare class StoryWorktreeManager {
192
192
  status(input: {
193
193
  readonly leaseId?: string;
194
194
  readonly epicId?: string;
195
+ readonly storyId?: string;
195
196
  }): Promise<StoryWorktreeResult<{
196
197
  readonly entries: readonly StoryWorktreeStatusValue[];
197
198
  }>>;
199
+ /**
200
+ * P230.03 (AC2, REQ-06): proof that a phase-2 child runs inside its own
201
+ * story worktree. The main worktree (first `worktree list` entry) refuses
202
+ * with `story-worktree-phase-two-root-checkout`; any other checkout that is
203
+ * not the active, owned worktree of the story refuses with
204
+ * `story-worktree-phase-two-lease-mismatch`. Read-only; path-free output.
205
+ */
206
+ assertPhaseTwo(input: {
207
+ readonly storyId: string;
208
+ }): Promise<StoryWorktreeResult<StoryWorktreeStatusValue>>;
198
209
  release(input: {
199
210
  readonly leaseId: string;
200
211
  }): Promise<StoryWorktreeResult<StoryWorktreeReleaseValue>>;
@@ -232,8 +243,36 @@ export declare class StoryWorktreeManager {
232
243
  private enableWindowsLongPaths;
233
244
  private ownershipProven;
234
245
  private ownedEntry;
246
+ /**
247
+ * P229.08 REQ-01 (P229-EX-05): committed bytes of the claims sidecar when the
248
+ * worktree's only difference is a reconciled sidecar, i.e. exactly one status
249
+ * entry ` M .neocortex/pending-epic-claims.json`, a regular file whose valid
250
+ * document keeps a strict subset of the committed operations with identical
251
+ * values (claim acknowledgement only removes entries). Anything else,
252
+ * including an untracked sidecar, a symlink or a merge in progress, is
253
+ * `undefined` so the caller keeps `native-worktree-dirty`. Never writes.
254
+ */
255
+ private reconciledClaimsSidecar;
256
+ /** Atomic restore of the committed sidecar bytes (temp file + rename, same directory). */
257
+ private restoreClaimsSidecar;
258
+ /**
259
+ * P229.08 REQ-05 (P229-EX-07): the epic's planning document exists in
260
+ * `probeRev` but not in the authorized base, so the epic branch was born
261
+ * before its planning commit. Only an existing base commit is probed.
262
+ */
263
+ private planningMissingFromBase;
264
+ /** Refuses `create`/`adopt` before any write when the root checkout's planning is not in the base. */
265
+ private assertPlanningInBase;
266
+ /**
267
+ * P229.08 REQ-05: a HEAD that is not an ancestor of the base and whose own
268
+ * commits (`merge-base..HEAD`) touch only this epic's planning artifacts,
269
+ * which the base lacks. Any Git failure or other path keeps the generic code.
270
+ */
271
+ private planningOnlyDrift;
235
272
  private clean;
236
273
  private project;
274
+ /** P230.09: bind the returned lease into the epic evidence; typed refusal on conflict. */
275
+ private bindLeaseEvidence;
237
276
  private leaseValue;
238
277
  /**
239
278
  * DEC-05 (P227.10 D-001): make `@neocortex/shared` resolve to the worktree's