@ornexus/neocortex 4.65.0 → 4.66.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1193 -1193
- package/install.ps1 +243 -77
- package/install.sh +221 -102
- package/package.json +2 -2
- package/packages/client/dist/adapters/platform-detector.js +1 -1
- package/packages/client/dist/agent/refresh-stubs.d.ts +50 -0
- package/packages/client/dist/agent/refresh-stubs.js +2 -2
- package/packages/client/dist/cli.js +5 -4
- package/packages/client/dist/commands/invoke.d.ts +35 -5
- package/packages/client/dist/commands/invoke.js +86 -84
- package/packages/client/dist/commands/planning-qa.d.ts +7 -0
- package/packages/client/dist/commands/planning-qa.js +1 -0
- package/packages/client/dist/commands/refactor-control.js +3 -3
- package/packages/client/dist/commands/story-checkpoint.d.ts +1 -1
- package/packages/client/dist/commands/story-checkpoint.js +1 -1
- package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +13 -1
- package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -3
- package/packages/client/dist/git/git-lifecycle-store.d.ts +14 -0
- package/packages/client/dist/git/git-lifecycle-store.js +8 -8
- package/packages/client/dist/git/governance-runtime-store.d.ts +172 -0
- package/packages/client/dist/git/governance-runtime-store.js +3 -0
- package/packages/client/dist/git/story-worktree-integration.js +3 -3
- package/packages/client/dist/memory/shared-project-memory-types.d.ts +39 -2
- package/packages/client/dist/memory/shared-project-memory-types.js +2 -2
- package/packages/client/dist/policy/subagent-approval-policy.js +1 -1
- package/packages/client/dist/private-execution/codex-executor.d.ts +8 -1
- package/packages/client/dist/private-execution/delivery.d.ts +17 -11
- package/packages/client/dist/private-execution/delivery.js +8 -6
- package/packages/client/dist/private-execution/diagnosis-root-review.d.ts +89 -0
- package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -2
- package/packages/client/dist/private-execution/frozen-handoff.js +3 -3
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +75 -1
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -5
- package/packages/client/dist/private-execution/planning-generation-checkpoint.d.ts +9 -1
- package/packages/client/dist/private-execution/planning-generation-checkpoint.js +4 -4
- package/packages/client/dist/private-execution/planning-research-checkpoint.d.ts +9 -1
- package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -4
- package/packages/client/dist/private-execution/root-memory-request.d.ts +4 -1
- package/packages/client/dist/private-execution/root-memory-request.js +1 -1
- package/packages/client/dist/runner/epic-background-dispatcher.d.ts +3 -1
- package/packages/client/dist/runner/epic-background-dispatcher.js +1 -1
- package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -1
- package/packages/client/dist/runner/headless/managed-profile.d.ts +20 -0
- package/packages/client/dist/runner/headless/managed-profile.js +1 -1
- package/packages/client/dist/runner/headless/opencode-adapter.js +2 -2
- package/packages/client/dist/runner/headless/run-yoloop.d.ts +40 -0
- package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
- package/packages/client/dist/runner/headless/types.d.ts +20 -0
- package/packages/client/dist/runner/headless/types.js +2 -2
- package/packages/client/dist/state/project-state-snapshot.js +1 -1
- package/packages/client/dist/yoloop/target-normalization.js +1 -1
- package/packages/shared/dist/compatibility/index.js +68 -0
- package/packages/shared/dist/planning/diagnosis-state.js +105 -1
- package/packages/shared/dist/project-memory-targets.js +36 -5
- package/targets-stubs/antigravity/README.md +1 -1
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/install-antigravity.sh +1 -1
- package/targets-stubs/antigravity/mcp-config.json +0 -3
- package/targets-stubs/antigravity/neocortex.md +25 -13
- package/targets-stubs/antigravity/skill/SKILL.md +4 -4
- package/targets-stubs/claude-code/.mcp.json +0 -4
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +2 -4
- package/targets-stubs/claude-code/neocortex-root.md +33 -43
- package/targets-stubs/claude-code/neocortex-sentinel.md +261 -0
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -3
- package/targets-stubs/claude-code/neocortex.md +61 -84
- package/targets-stubs/codex/AGENTS.md +19 -18
- package/targets-stubs/codex/README.md +1 -1
- package/targets-stubs/codex/config-mcp.toml +0 -3
- package/targets-stubs/codex/neocortex-sentinel.toml +87 -0
- package/targets-stubs/codex/neocortex.toml +23 -44
- package/targets-stubs/cursor/README.md +1 -1
- package/targets-stubs/cursor/agent.md +26 -15
- package/targets-stubs/cursor/mcp.json +0 -3
- package/targets-stubs/deepseek-harness/SKILL.md +11 -8
- package/targets-stubs/gemini-cli/README.md +1 -1
- package/targets-stubs/gemini-cli/agent.md +25 -12
- package/targets-stubs/gemini-cli/agents/neocortex-sentinel.md +75 -0
- package/targets-stubs/gemini-cli/agents/neocortex.md +280 -49
- package/targets-stubs/gemini-cli/settings-mcp.json +0 -3
- package/targets-stubs/grok/SKILL.md +12 -0
- package/targets-stubs/grok/agents/neocortex.md +64 -0
- package/targets-stubs/grok/config-mcp.toml +0 -3
- package/targets-stubs/grok/install-grok.sh +14 -1
- package/targets-stubs/kimi/mcp.json +0 -6
- package/targets-stubs/kimi/neocortex.md +21 -8
- package/targets-stubs/lib/managed-config-merge.js +285 -6
- package/targets-stubs/lib/managed-profile.sh +12 -1
- package/targets-stubs/lib/mcp-merge.js +110 -5
- package/targets-stubs/openclaw/SKILL.md +33 -4
- package/targets-stubs/opencode/neocortex-root.md +41 -41
- package/targets-stubs/opencode/neocortex-sentinel.md +115 -0
- package/targets-stubs/opencode/neocortex.md +292 -67
- package/targets-stubs/opencode/opencode-mcp.json +0 -7
- package/targets-stubs/vscode/README.md +1 -1
- package/targets-stubs/vscode/mcp.json +0 -4
- 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,3 +1,3 @@
|
|
|
1
|
-
import{execFile as
|
|
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 Qe}from"node:child_process";import{createHash as ut}from"node:crypto";import{readFile as mt,realpath as Ae}from"node:fs/promises";import{join as kt,resolve as Ee}from"node:path";import{yoloopDomainHash as It}from"../../../shared/dist/yoloop/canonical.js";import{DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS as Ze,directYoloCommitIdempotencyKey as et,directYoloWaveQaCoverage as vt,finalizeDirectYoloStoryCheckpoint as St,persistDirectYoloWaveStoryCheckpoint as bt,pushDirectYoloWaveHead as At,resolveDirectYoloIntegrationAuthority as tt,runDirectYoloWaveP205 as Et,validateDirectYoloWriteSet as Rt}from"./direct-yolo-checkpoint.js";import{acquireGitLifecyclePhysicalIntegrationLock as Ne,appendStoryWorktreeEvidence as xt,applyGitLifecycleRuntimeOverlay as _t,ensureRuntimeEpic as Re,isStoryWorktreeIntegrationReceiptRecord as Tt,mutateGitLifecycleRuntime as pe,publicStoryReviewArtifactFromBytes as Ct,publicStoryReviewArtifactFromGit as Dt,readGitLifecycleRuntime as V,readStoryWorktreeEvidence as rt,releaseGitLifecyclePhysicalIntegrationLock as Me,verifyGitLifecyclePhysicalIntegrationLock as ot}from"./git-lifecycle-store.js";import{mergeStateJsonFields as Ot,STATE_JSON_FIELD_MERGE_MAX_BYTES as Pt}from"./state-json-field-merge.js";import{GOVERNANCE_DIGEST_TRAILER as it,GOVERNANCE_REASON_CODES as ce,readStoryGovernanceSync as Ht,storyReviewGovernancePath as Bt}from"./governance-runtime-store.js";import{StoryWorktreeManager as xe}from"./story-worktree-manager.js";import{rootMemoryEffectDigest as Nt}from"../private-execution/root-memory-git-evidence.js";const Mt="neocortex.p225.story-worktree-receipt.v1",Wt=200,ue="Neocortex-Story-Worktree-Tip",nt=3e4,de=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,zt=/^swt-[a-f0-9]{24}$/,_e=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class Te extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function o(e){throw new Te(e)}const at=32*1024*1024;function O(e,t,a){return new Promise(s=>{Qe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:at,timeout:nt,env:{...process.env,...a,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(r,g)=>{const n=r?typeof r.code=="number"?r.code:128:0;s({code:n,stdout:String(g??"")})})})}function st(e,t,a){return new Promise(s=>{const r=Qe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:at,timeout:nt,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(g,n)=>{const f=g?typeof g.code=="number"?g.code:128:0;s({code:f,stdout:String(n??"")})});r.stdin?.on("error",()=>{}),r.stdin?.end(a)})}async function h(e,t,a,s){const r=await O(e,t,s);return r.code!==0&&o(a),r.stdout.trim()}async function T(e,t){return(await O(e,t)).code===0}function fe(e){return ut("sha256").update(e).digest("hex")}function ct(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 $(e,t){const a=`${t}: `,s=e.split(`
|
|
2
|
+
`).map(r=>r.trim()).filter(r=>r.startsWith(a));return s.length===1?s[0].slice(a.length):void 0}function We(e){return It(Mt,e)}function X(e,t){return(rt(e,t)?.receipts??[]).filter(Tt)}function me(e){const t=[...e].sort((a,s)=>a.integrationIndex-s.integrationIndex);t.forEach((a,s)=>{(a.integrationIndex!==s+1||s>0&&a.epicHeadBeforeSha!==t[s-1].epicHeadAfterSha)&&o("story-worktree-integration-chain-invalid")})}function le(e,t){const a=[...e].sort((s,r)=>r.integrationIndex-s.integrationIndex)[0];a&&a.epicHeadAfterSha!==t&&o("story-worktree-integration-chain-invalid")}const jt=new Set(["done","merged","completed","released"]);function dt(e,t,a,s,r,g=new Set){(rt(e,a)?.receipts??[]).some(d=>d.kind==="phase-one-receipt"&&d.storyId===s||d.kind==="spec-barrier-receipt"&&Array.isArray(d.storyIds)&&d.storyIds.includes(s))||o("story-worktree-integration-unbound");const u=new Set(X(e,a).filter(d=>d.outcome==="integrated").map(d=>d.storyId));for(const d of r){if(!d.startsWith(`${a}.`))continue;const S=t[d],m=!!e.stories[d]?.checkpoint||typeof S?.status=="string"&&jt.has(S.status);!u.has(d)&&!g.has(d)&&!m&&o("story-worktree-integration-dependency-waiting")}}function Lt(e){const t=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",a=`int-${fe(["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 ze(e){return fe(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function Ce(e){let t;return await pe(e.projectRoot,a=>{const s=X(a,e.epicId);me(s);const r=[...s].sort((n,f)=>f.integrationIndex-n.integrationIndex)[0];r&&r.epicHeadAfterSha!==e.before&&o("story-worktree-integration-chain-invalid"),[...s].filter(n=>n.storyId===e.storyId).sort((n,f)=>f.integrationIndex-n.integrationIndex)[0]?.outcome==="integrated"&&o("story-worktree-integration-already-integrated"),t=Lt({epicId:e.epicId,storyId:e.storyId,index:s.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),xt(a,e.epicId,{receipts:[t]})},{preCommit:async()=>{await h(e.projectRoot,["rev-parse",`refs/heads/${e.executionBranch}`],"story-worktree-integration-epic-branch-missing")!==(e.expectedEpicHead??e.after)&&o("story-worktree-integration-epic-head-raced"),e.expectedEpicHead!==void 0&&e.expectedEpicHead!==e.after&&!await T(e.projectRoot,["merge-base","--is-ancestor",e.after,e.expectedEpicHead])&&o("story-worktree-integration-epic-head-raced")}}),t}function ke(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:We(e.receipt)})}}async function $t(e){let t,a,s="";const r=Ee(e.projectRoot);try{(typeof e.storyId!="string"||!_e.test(e.storyId))&&o("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!zt.test(e.leaseId)&&o("story-worktree-integration-lease-invalid");const g=await Ae(await h(r,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),n=await Ae(await h(r,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));g!==n&&o("story-worktree-integration-not-root");let f;try{f=await tt(r,e.storyId)}catch(y){o(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;s=l;const S=new Date(e.nowIso??Date.now()).toISOString(),m=`refs/heads/${u}`,w=await h(r,["rev-parse",m],"story-worktree-integration-epic-branch-missing");await h(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==w&&o("story-worktree-integration-root-head-mismatch");const D=f.originBinding;(!D||!await T(r,["merge-base","--is-ancestor",D.originHeadSha,w]))&&o("story-worktree-integration-origin-binding-invalid");const A=await V(r,{required:!0}),I=X(A,l);me(I);const P=I.filter(y=>y.storyId===d).sort((y,R)=>R.integrationIndex-y.integrationIndex),E=A.stories[d]?.checkpoint;if(P[0]?.outcome==="integrated")return ke({storyId:d,epicId:l,outcome:"already-integrated",receipt:P[0],...E?.headSha?{checkpointHeadSha:E.headSha}:{}});const G=Array.isArray(f.story.depends_on)?f.story.depends_on.filter(y=>typeof y=="string"):[],x=await gt(r,A);dt(A,x,l,d,G);const H=Object.values(A.storyWorktrees?.entries??{}).filter(y=>y.storyId===d&&y.epicId===l&&y.state==="active"&&(e.leaseId===void 0||y.leaseId===e.leaseId));if(E&&typeof E.headSha=="string"){const y=E.headSha,R=await h(r,["show","--no-patch","--format=%B",y],"story-worktree-integration-git-failed");($(R,"Neocortex-Story")!==d||!$(R,ue))&&o("story-worktree-integration-checkpoint-not-worktree"),y!==w&&o("story-worktree-integration-epic-head-raced"),le(I,E.baseSha);const te=await yt(r,d,`recover-${y.slice(0,40)}`,()=>Ce({projectRoot:r,epicId:l,storyId:d,executionBranch:u,before:E.baseSha,after:y,checkpointDigest:ze(E),outcome:"integrated",integratedAt:S})),ne=H.length===1?await qe(r,H[0].leaseId,y):!1;return ke({storyId:d,epicId:l,outcome:"integrated",receipt:te,checkpointHeadSha:y,worktreeRealigned:ne})}const N=Object.values(A.storyWorktrees?.entries??{}).filter(y=>y.storyId===d&&y.epicId===l&&y.state==="active"&&(e.leaseId===void 0||y.leaseId===e.leaseId));N.length===0&&o("story-worktree-integration-lease-missing"),N.length>1&&o("story-worktree-integration-lease-ambiguous");const C=N[0];C.executionBranch!==u&&o("story-worktree-integration-lease-invalid");const b=await new xe({projectRoot:r}).probe(C.leaseId);(!b.ok||b.value.ownership!=="proven")&&o("story-worktree-integration-ownership-unproven"),b.value.clean!==!0&&o("story-worktree-integration-worktree-dirty");const F=await h(r,["rev-parse",`refs/heads/${C.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");b.value.headSha!==F&&o("story-worktree-integration-worktree-dirty");const B=await h(r,["show","--no-patch","--format=%B",w],"story-worktree-integration-git-failed"),Q=$(B,ue)===F&&$(B,"Neocortex-Story")===d;let _,j,k,U=!1;if(Q){_=await h(r,["rev-parse",`${w}^`],"story-worktree-integration-git-failed"),j=w;const y=$(B,"Neocortex-Bundle-Digest")??"",R=$(B,"Neocortex-Claim-Revision")??"";k=et({storyId:d,epicId:l,executionBranch:u,baseSha:_,bundleDigest:y,graphRevision:f.graphRevision,claimRevision:R}),le(I,_)}else{le(I,w);const y=await lt(r,f,d,w,F);if(y.kind==="conflict")return await Ge({projectRoot:r,epicId:l,storyId:d,executionBranch:u,epicHead:w,tip:F,conflictPaths:y.conflictPaths,integratedAt:S,chain:P});const R=y.changedPaths;j=y.commitSha,k=y.idempotencyKey,_=w,U=!0,(!await T(r,["diff","--cached","--quiet"])||!await T(r,["diff","--quiet","HEAD","--",...R]))&&o("story-worktree-integration-root-dirty")}const Z=await V(r,{required:!0}),q=Z.epics[l]?.branch_lease,oe=q&&q.ownerStoryId===d&&q.sessionId===k&&q.idempotencyKey===k&&Date.parse(String(q.expiresAt))>Date.now()?q:void 0;q&&!oe&&Date.parse(String(q.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active");const K=oe??{schemaVersion:1,ownerStoryId:d,sessionId:k,idempotencyKey:k,acquiredAt:S,expiresAt:new Date(Date.parse(S)+Ze).toISOString()};t=await Ne(r,{kind:"direct",storyId:d,sessionId:k,idempotencyKey:k,expiresAt:String(K.expiresAt),persistent:!0,createdAt:String(K.acquiredAt)}),t.ok||o(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const Y=t;oe||(await pe(r,y=>{const R=Re(y,l),te=R.branch_lease;te&&Date.parse(String(te.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active"),JSON.stringify(R.origin_binding)!==JSON.stringify(D)&&o("story-worktree-integration-origin-binding-invalid"),R.graph_revision!==f.graphRevision&&o("story-worktree-integration-graph-revision-raced"),R.branch_lease=K},{expectedRevision:Z.revision,preCommit:async y=>{await ot(Y.path,Y.owner)||o("story-worktree-integration-lock-raced");const R=X(y,l);me(R),le(R,_),await h(r,["rev-parse",m],"story-worktree-integration-epic-branch-missing")!==w&&o("story-worktree-integration-epic-head-raced")}}),a=K),U&&((await h(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==w||await h(r,["rev-parse",m],"story-worktree-integration-git-failed")!==w)&&o("story-worktree-integration-epic-head-raced"),await T(r,["merge","--ff-only","--no-edit",j])||o("story-worktree-integration-ff-refused"),await h(r,["rev-parse",m],"story-worktree-integration-git-failed")!==j&&o("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let ee;const ie=await St({projectRoot:r,storyId:d,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,afterCheckpointPersist:async()=>{const y=(await V(r,{required:!0})).stories[d]?.checkpoint;(!y||y.headSha!==j||y.baseSha!==_)&&o("story-worktree-integration-checkpoint-mismatch"),ee=await Ce({projectRoot:r,epicId:l,storyId:d,executionBranch:u,before:_,after:j,checkpointDigest:ze(y),outcome:"integrated",integratedAt:S})}});if(!ie.ok)return{ok:!1,reasonCode:ie.reasonCode};const L=ie.value;(L.headSha!==j||L.baseSha!==_||!ee)&&o("story-worktree-integration-checkpoint-mismatch");const ge=await qe(r,C.leaseId,j);return ke({storyId:d,epicId:l,outcome:"integrated",receipt:ee,checkpointHeadSha:j,worktreeRealigned:ge})}catch(g){if(g instanceof Te)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 Me(t.path,t.owner).catch(()=>{}),a&&s){const g=a;await pe(r,n=>{const f=Re(n,s),l=f.branch_lease;l&&l.sessionId===g.sessionId&&l.idempotencyKey===g.idempotencyKey&&l.acquiredAt===g.acquiredAt&&(f.branch_lease=null)}).catch(()=>{})}}}const je=".neocortex/state.json",De=".neocortex",Oe="state.json",W="story-worktree-integration-state-merge-git-failed";function Pe(e){const t=[];for(const a of e.split("\0")){if(!a)continue;const s=a.indexOf(" "),[r,g,n]=a.slice(0,s).split(" ");(s<0||!r||!g||!n)&&o(W),t.push({mode:r,type:g,oid:n,name:a.slice(s+1)})}return t}function qt(e){return e.map(t=>`${t.mode} ${t.type} ${t.oid} ${t.name}\0`).join("")}async function ft(e,t,a,s){const r=await O(e,["ls-tree","-z",t]);r.code!==0&&o(W);const g=Pe(r.stdout).filter(l=>l.name!==a),n=await st(e,["mktree","-z"],qt([...g,s])),f=n.stdout.trim();return(n.code!==0||!de.test(f))&&o(W),f}async function Le(e,t){const a=await O(e,["ls-tree","-z",t,"--",je]);a.code!==0&&o(W);const s=Pe(a.stdout).find(r=>r.name===je);return s?((s.type!=="blob"||s.mode!=="100644"&&s.mode!=="100755")&&o("state-merge-input-invalid"),de.test(s.oid)||o(W),s.oid):null}async function $e(e,t){t===null&&o("state-merge-input-invalid");const a=await O(e,["cat-file","-s",t]),s=Number.parseInt(a.stdout.trim(),10);(a.code!==0||!Number.isSafeInteger(s)||s<0||s>Pt)&&o(W);const r=await O(e,["cat-file","blob",t]);return r.code!==0&&o(W),r.stdout}async function Gt(e){try{const{projectRoot:t,mergeBase:a,epicHead:s,tip:r,tree:g,storyId:n,epicId:f}=e,l={ok:!0,tree:g,conflictPaths:[...e.conflictPaths],merged:!1},u=await Le(t,a),d=await Le(t,r);if(u===d)return l;const S=await $e(t,u),m=await $e(t,await Le(t,s)),w=await $e(t,d),D=await h(t,["show","--no-patch","--format=%cI",r],W),A=Ot({base:S,epic:m,story:w,storyId:n,epicId:f,aggregateTimestamp:D});if(!A.ok)return{ok:!1,reasonCode:A.reasonCode};const I=e.conflictPaths.filter(b=>b!==je),P=await O(t,["ls-tree","-z",g,"--",De]);P.code!==0&&o(W);const E=Pe(P.stdout).find(b=>b.name===De);if(!E||E.type!=="tree")return{ok:!1,reasonCode:"state-merge-input-invalid"};const G=await O(t,["ls-tree","-z",E.oid,"--",Oe]);G.code!==0&&o(W);const x=Pe(G.stdout).find(b=>b.name===Oe);if(x&&(x.type!=="blob"||x.mode!=="100644"&&x.mode!=="100755"))return{ok:!1,reasonCode:"state-merge-input-invalid"};const H=await st(t,["hash-object","-w","--stdin"],A.bytes),N=H.stdout.trim();if((H.code!==0||!de.test(N))&&o(W),x?.oid===N)return{ok:!0,tree:g,conflictPaths:I,merged:!0};const C=await ft(t,E.oid,Oe,{mode:x?.mode??"100644",type:"blob",oid:N,name:Oe});return{ok:!0,tree:await ft(t,g,De,{mode:E.mode,type:"tree",oid:C,name:De}),conflictPaths:I,merged:!0}}catch(t){return t instanceof Te?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:W}}}async function lt(e,t,a,s,r){const{epicId:g,executionBranch:n}=t;await T(e,["merge-base","--is-ancestor",r,s])&&o("story-worktree-integration-range-empty");const f=await h(e,["merge-base",s,r],"story-worktree-integration-unrelated-history"),l=await O(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${f}`,s,r]);l.code!==0&&l.code!==1&&o("story-worktree-integration-git-unsupported");const u=l.stdout.split("\0"),d=u[0]?.trim()??"";de.test(d)||o("story-worktree-integration-git-unsupported");const S=l.code===1?[...new Set(u.slice(1).filter(ct))].sort():[];l.code===1&&S.length===0&&o("story-worktree-integration-git-failed");const m=await Gt({projectRoot:e,mergeBase:f,epicHead:s,tip:r,tree:d,storyId:a,epicId:g,conflictPaths:S});m.ok||o(m.reasonCode);const w=m.tree;if(m.conflictPaths.length>0)return{kind:"conflict",conflictPaths:m.conflictPaths.slice(0,Wt)};const D=(await h(e,["diff","--name-only","-z",s,w],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),A=Rt(D,t.authorizedWriteSet,a,t.rootMemoryEffect,t.governanceMode);A.ok||o(A.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":A.reasonCode===ce.WRITE_SET_FORBIDDEN?ce.WRITE_SET_FORBIDDEN:"story-worktree-integration-write-set-invalid");const I=t.governanceMode==="runtime-store"?await Ft(e,g,a,r):void 0,P=I?I.review:Dt(e,a,w);P?.verdict!=="approved"&&o("story-worktree-integration-review-not-approved");const E=await O(e,["diff","--binary","--full-index",s,w]);E.code!==0&&o("story-worktree-integration-git-failed");const G=E.stdout;G||o("story-worktree-integration-range-empty");const x=fe(G),H=fe([...t.authorizedWriteSet].sort().join("\0")),N=et({storyId:a,epicId:g,executionBranch:n,baseSha:s,bundleDigest:x,graphRevision:t.graphRevision,claimRevision:H}),C=(await h(e,["show","--no-patch","--format=%s",r],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${a}): integrate story worktree`,z=[`Neocortex-Story: ${a}`,`Neocortex-Epic: ${g}`,`Neocortex-Execution-Branch: ${n}`,`Neocortex-Prepared-Base: ${s}`,`Neocortex-Bundle-Digest: ${x}`,`Neocortex-Review-Artifact-Digest: ${P.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${H}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${Nt(t.rootMemoryEffect)}`]:[],...I?[`${it}: ${I.governanceDigest}`]:[],`${ue}: ${r}`],b=(await h(e,["show","--no-patch","--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI",r],"story-worktree-integration-git-failed")).split("\0");b.length!==6&&o("story-worktree-integration-git-failed");const F=await h(e,["commit-tree",w,"-p",s,"-m",C,"-m",`Story: ${a}`,"-m",z.join(`
|
|
3
|
+
`)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:b[0],GIT_AUTHOR_EMAIL:b[1],GIT_AUTHOR_DATE:b[2],GIT_COMMITTER_NAME:b[3],GIT_COMMITTER_EMAIL:b[4],GIT_COMMITTER_DATE:b[5]});return de.test(F)||o("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:F,changedPaths:D,idempotencyKey:N}}async function Ft(e,t,a,s){const r=await h(e,["show","--no-patch","--format=%B",s],"story-worktree-integration-git-failed"),g=$(r,it);g===void 0&&o("story-worktree-integration-governance-trailer-missing");const n=Ht({projectRoot:e,epicId:t,storyId:a});n.ok||o(n.reasonCode===ce.UNSAFE?n.reasonCode:ce.MISMATCH);const f=n.value.receipt.governanceDigest;g!==f&&o(ce.MISMATCH);const l=n.value.files.get(Bt(a));return l||o(ce.MISMATCH),{governanceDigest:f,review:Ct(a,l)}}async function gt(e,t){const a=JSON.parse(await mt(kt(e,".neocortex","state.json"),"utf8")),r=_t(a,t).stories;return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}async function yt(e,t,a,s){const r=await Ne(e,{kind:"direct",storyId:t,sessionId:a,idempotencyKey:a,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});r.ok||o(r.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");try{return await s()}finally{await Me(r.path,r.owner).catch(()=>{})}}async function qe(e,t,a){const s=await new xe({projectRoot:e}).probe(t);return!s.ok||s.value.ownership!=="proven"||s.value.clean!==!0?!1:T(s.value.entry.worktreePath,["reset","--keep",a])}async function Ge(e){const t=fe(["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 ke({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:a,conflictPaths:Object.freeze([...e.conflictPaths])});const s=()=>Ce({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 s():await yt(e.projectRoot,e.storyId,`conflict-${t.slice(0,48)}`,s);return ke({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:r,conflictPaths:Object.freeze([...e.conflictPaths])})}const Kt=64,Yt="@ornexus/neocortex",Fe=Object.freeze(["dist","packages/shared/dist","packages/client/dist","packages/server/dist"]);for(const e of Fe)if(!ct(e)||/[*?[\]!:]/.test(e))throw new Error("story-worktree-wave-build-output-path-invalid");async function Jt(e){return T(e,["clean","-X","-f","-q","--",...Fe])}async function Ut(e,t){const a=await O(e,["show",`${t}:package.json`]);if(a.code!==0)return[];try{return JSON.parse(a.stdout)?.name===Yt?Fe:[]}catch{return[]}}function Vt(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function cr(e){let t,a,s="",r=0,g;const n=Ee(e.projectRoot);try{const f=e.storyIds;(!Array.isArray(f)||f.length===0||f.length>Kt||new Set(f).size!==f.length||f.some(i=>typeof i!="string"||!_e.test(i)))&&o("story-worktree-wave-stories-invalid");const l=await Ae(await h(n,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),u=await Ae(await h(n,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));l!==u&&o("story-worktree-integration-not-root");const d=new Map;for(const i of f)try{d.set(i,await tt(n,i))}catch(c){o(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:w}=S;for(const i of d.values())(i.epicId!==m||i.executionBranch!==w||i.graphRevision!==S.graphRevision||JSON.stringify(i.originBinding)!==JSON.stringify(S.originBinding))&&o("story-worktree-wave-epic-mixed");s=m;const D=new Date(e.nowIso??Date.now()).toISOString(),A=`refs/heads/${w}`,I=await h(n,["rev-parse",A],"story-worktree-integration-epic-branch-missing");(await h(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==I||await h(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==w)&&o("story-worktree-integration-root-head-mismatch");const P=S.originBinding;(!P||!await T(n,["merge-base","--is-ancestor",P.originHeadSha,I]))&&o("story-worktree-integration-origin-binding-invalid");const E=i=>{const c=d.get(i).story;return Array.isArray(c.depends_on)?c.depends_on.filter(p=>typeof p=="string"):[]},G=new Map(f.map((i,c)=>[i,c]));f.forEach((i,c)=>{for(const p of E(i)){const v=G.get(p);v!==void 0&&v>=c&&o("story-worktree-wave-order-invalid")}});const x=await V(n,{required:!0}),H=X(x,m);me(H);const N=i=>H.filter(c=>c.storyId===i).sort((c,p)=>p.integrationIndex-c.integrationIndex)[0],C=f.filter(i=>N(i)?.outcome!=="integrated"),z=new Map(f.filter(i=>!C.includes(i)).map(i=>{const c=N(i),p=x.stories[i]?.checkpoint;return[i,Object.freeze({storyId:i,outcome:"already-integrated",receiptDigest:We(c),...p?.headSha?{checkpointHeadSha:p.headSha}:{}})]})),b=i=>({ok:!0,value:Object.freeze({epicId:m,...i,gateRuns:r,stories:Object.freeze(f.map(c=>z.get(c)??Object.freeze({storyId:c,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(C.length===0)return b({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:I,epicHeadAfterSha:I,gateRunCap:0});const F=new Set(C),B=[];let Q=I;for(let i=0;i<C.length;i++){const c=await h(n,["show","--no-patch","--format=%B",Q],"story-worktree-integration-git-failed"),p=$(c,"Neocortex-Story");if(!p||!F.has(p)||!$(c,ue))break;B.unshift(Q),Q=await h(n,["rev-parse",`${Q}^`],"story-worktree-integration-git-failed")}const _=Q;le(H,_);const j=await gt(n,x),k=[];let U,Z=_;for(const[i,c]of C.entries()){const p=d.get(c);dt(x,j,m,c,E(c),new Set(C.slice(0,i)));const v=Object.values(x.storyWorktrees?.entries??{}).filter(J=>J.storyId===c&&J.epicId===m&&J.state==="active"),M=x.stories[c]?.checkpoint;if(M&&typeof M.headSha=="string"){const J=M.headSha,Xe=await h(n,["show","--no-patch","--format=%B",J],"story-worktree-integration-git-failed");($(Xe,"Neocortex-Story")!==c||!$(Xe,ue))&&o("story-worktree-integration-checkpoint-not-worktree"),(M.baseSha!==Z||B[i]!==J)&&o("story-worktree-integration-checkpoint-mismatch");const pt=(await h(n,["diff-tree","--no-commit-id","--name-only","-r","-z",J],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);k.push({storyId:c,sha:J,changedPaths:pt,...v.length===1?{leaseId:v[0].leaseId}:{}}),Z=J;continue}v.length===0&&o("story-worktree-integration-lease-missing"),v.length>1&&o("story-worktree-integration-lease-ambiguous");const Se=v[0];Se.executionBranch!==w&&o("story-worktree-integration-lease-invalid");const be=await new xe({projectRoot:n}).probe(Se.leaseId);(!be.ok||be.value.ownership!=="proven")&&o("story-worktree-integration-ownership-unproven"),be.value.clean!==!0&&o("story-worktree-integration-worktree-dirty");const Be=await h(n,["rev-parse",`refs/heads/${Se.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");be.value.headSha!==Be&&o("story-worktree-integration-worktree-dirty");const se=await lt(n,p,c,Z,Be);if(se.kind==="conflict"){i<B.length&&o("story-worktree-wave-resume-mismatch"),U={storyId:c,tip:Be,conflictPaths:se.conflictPaths};break}i<B.length&&B[i]!==se.commitSha&&o("story-worktree-wave-resume-mismatch"),k.push({storyId:c,sha:se.commitSha,changedPaths:se.changedPaths,leaseId:Se.leaseId}),Z=se.commitSha}if(k.length<B.length&&o("story-worktree-wave-resume-mismatch"),k.length===0){const i=U,c=await Ge({projectRoot:n,epicId:m,storyId:i.storyId,executionBranch:w,epicHead:I,tip:i.tip,conflictPaths:i.conflictPaths,integratedAt:D,chain:H.filter(p=>p.storyId===i.storyId).sort((p,v)=>v.integrationIndex-p.integrationIndex)});return c.ok?(z.set(i.storyId,Object.freeze({storyId:i.storyId,outcome:"conflict-reopened",receiptDigest:c.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...i.conflictPaths])})),b({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:I,epicHeadAfterSha:I,gateRunCap:0})):{ok:!1,reasonCode:c.reasonCode,gateRuns:r}}const q=k[k.length-1].sha,oe=[...new Set(k.flatMap(i=>i.changedPaths))].sort();(!await T(n,["diff","--cached","--quiet"])||!await T(n,["diff","--quiet","HEAD","--",...oe]))&&o("story-worktree-integration-root-dirty");const K=Vt(k.length),Y=fe(["p205-wave-lease-v1",m,w,_,...k.map(i=>i.sha)].join("\0")),ee=k[0].storyId,ie=await V(n,{required:!0}),L=ie.epics[m]?.branch_lease,ge=L&&L.ownerStoryId===ee&&L.sessionId===Y&&L.idempotencyKey===Y&&Date.parse(String(L.expiresAt))>Date.now()?L:void 0;L&&!ge&&Date.parse(String(L.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active");const y=ge??{schemaVersion:1,ownerStoryId:ee,sessionId:Y,idempotencyKey:Y,acquiredAt:D,expiresAt:new Date(Date.parse(D)+Ze*K).toISOString()};t=await Ne(n,{kind:"direct",storyId:ee,sessionId:Y,idempotencyKey:Y,expiresAt:String(y.expiresAt),persistent:!0,createdAt:String(y.acquiredAt)}),t.ok||o(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const R=t;ge||await pe(n,i=>{const c=Re(i,m),p=c.branch_lease;p&&Date.parse(String(p.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active"),JSON.stringify(c.origin_binding)!==JSON.stringify(P)&&o("story-worktree-integration-origin-binding-invalid"),c.graph_revision!==S.graphRevision&&o("story-worktree-integration-graph-revision-raced"),c.branch_lease=y},{expectedRevision:ie.revision,preCommit:async i=>{await ot(R.path,R.owner)||o("story-worktree-integration-lock-raced");const c=X(i,m);me(c),le(c,_),await h(n,["rev-parse",A],"story-worktree-integration-epic-branch-missing")!==I&&o("story-worktree-integration-epic-head-raced")}}),a=y;const te=new Set(k.map(i=>i.sha));let ne=!0;if(e.push&&B.length>0){const i=(await O(n,["ls-remote","--heads",e.remote??"origin",A])).stdout.split(/\s+/)[0]??"";de.test(i)&&await T(n,["merge-base","--is-ancestor",B[0],i])&&(ne=!1)}let ae=I;const Ie=async i=>{if((await h(n,["rev-parse",A],"story-worktree-integration-git-failed")!==ae||await h(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==ae||await h(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==w)&&o("story-worktree-integration-epic-head-raced"),ae===i)return;const c=await T(n,["merge-base","--is-ancestor",ae,i]);!c&&(!ne||!te.has(ae))&&o("story-worktree-wave-pushed-immovable"),(!(c?await T(n,["merge","--ff-only","--no-edit",i]):await T(n,["reset","--keep",i]))||await h(n,["rev-parse",A],"story-worktree-integration-git-failed")!==i||await h(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==i)&&o("story-worktree-integration-ff-refused"),ae=i};g=ne?{epicRef:A,base:_,owned:te}:void 0,await Ie(q),await e.afterWaveFastForward?.();const ht=[...new Set([S.graphRevision,...k.map(i=>x.stories[i.storyId]?.checkpoint?.graphRevision).filter(i=>typeof i=="string")])],wt=await Ut(n,_),He=async()=>{wt.length!==0&&(await(e.cleanBuildOutputs??Jt)(n)||o("story-worktree-wave-clean-failed"))},Ke=async i=>{const c=k[i];await Ie(c.sha),r>=K&&o("story-worktree-wave-gate-cap-exceeded"),r>0&&await He(),r++;const p=await Et({projectRoot:n,headSha:c.sha,storyId:c.storyId,graphRevisions:ht,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await h(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==c.sha||await h(n,["rev-parse",A],"story-worktree-integration-git-failed")!==c.sha||!await T(n,["diff","--cached","--quiet"])||!await T(n,["diff","--quiet","HEAD","--",...oe]))&&o("story-worktree-integration-epic-head-raced"),!p.ok&&p.kind==="infrastructure"&&o(p.reasonCode),p},ve=await Ke(k.length-1);let Ye=k.length-1,Je=ve.ok?ve.authorities:void 0,ye,he;if(!ve.ok){ne||o("story-worktree-wave-gate-failed-pushed");let i=-1,c=k.length-1;for(he=ve.reasonCode;c-i>1;){const v=Math.floor((i+c)/2),M=await Ke(v);M.ok?(i=v,Je=M.authorities):(c=v,he=M.reasonCode)}ye=c,Ye=i;const p=k[c].storyId;if(z.set(p,Object.freeze({storyId:p,outcome:"gate-failed",reasonCode:he})),i<0)return await Ie(_),await He(),g=void 0,b({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:p,failureReasonCode:he,epicHeadBeforeSha:I,epicHeadAfterSha:_,gateRunCap:K});await Ie(k[i].sha),await He()}const re=k.slice(0,Ye+1),we=re[re.length-1].sha,Ue=vt({epicId:m,executionBranch:w,waveHeadSha:we,waveStoryIds:re.map(i=>i.storyId),waveCommitShas:re.map(i=>i.sha)});e.push&&(g=void 0,await At(n,e.remote??"origin",w,we)||o("story-worktree-wave-remote-head-mismatch")),g=void 0;const Ve=[];for(const[i,c]of re.entries()){const p=i===0?_:re[i-1].sha,v=await bt({projectRoot:n,storyId:c.storyId,headSha:c.sha,coverage:Ue,authorities:Je,expectedLease:y,physicalLock:R,...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});v.ok||o(v.reasonCode),(v.value.headSha!==c.sha||v.value.baseSha!==p)&&o("story-worktree-integration-checkpoint-mismatch");const M=await Ce({projectRoot:n,epicId:m,storyId:c.storyId,executionBranch:w,before:p,after:c.sha,checkpointDigest:ze(v.value),outcome:"integrated",integratedAt:D,expectedEpicHead:we});Ve.push(c.storyId),z.set(c.storyId,Object.freeze({storyId:c.storyId,outcome:"integrated",checkpointHeadSha:c.sha,receiptDigest:We(M)})),await e.afterWaveStoryPersist?.(c.storyId)}if(U&&ye===void 0){const i=U,c=await V(n,{required:!0}),p=await Ge({projectRoot:n,epicId:m,storyId:i.storyId,executionBranch:w,epicHead:we,tip:i.tip,conflictPaths:i.conflictPaths,integratedAt:D,chain:X(c,m).filter(v=>v.storyId===i.storyId).sort((v,M)=>M.integrationIndex-v.integrationIndex),lockHeld:!0});p.ok||o(p.reasonCode),z.set(i.storyId,Object.freeze({storyId:i.storyId,outcome:"conflict-reopened",receiptDigest:p.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...i.conflictPaths])}))}for(const i of re){if(!i.leaseId)continue;const c=await qe(n,i.leaseId,i.sha);z.set(i.storyId,Object.freeze({...z.get(i.storyId),worktreeRealigned:c}))}return b({outcome:ye!==void 0?"gate-failed":U?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Ve),...ye!==void 0?{failedStoryId:k[ye].storyId,failureReasonCode:he}:{},epicHeadBeforeSha:I,epicHeadAfterSha:we,qaCoverage:Ue,gateRunCap:K})}catch(f){let l=f instanceof Te?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 O(n,["rev-parse",u.epicRef])).stdout.trim(),S=(await O(n,["rev-parse","HEAD"])).stdout.trim();d!==u.base&&(d!==S||!u.owned.has(d)||!await T(n,["reset","--keep",u.base]))&&(l="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:l,gateRuns:r}}finally{if(t?.ok&&await Me(t.path,t.owner).catch(()=>{}),a&&s){const f=a;await pe(n,l=>{const u=Re(l,s),d=u.branch_lease;d&&d.sessionId===f.sessionId&&d.idempotencyKey===f.idempotencyKey&&d.acquiredAt===f.acquiredAt&&(u.branch_lease=null)}).catch(()=>{})}}}async function dr(e){const t=e.integrationOrder;if(!Array.isArray(t)||t.length===0||new Set(t).size!==t.length||t.some(l=>typeof l!="string"||!_e.test(l)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const a=e.integrate??$t,s=new Set(e.readyStoryIds),r=Ee(e.projectRoot);let g;try{const l=await V(r,{required:!0}),u=new Set(t.map(d=>d.split(".")[0]));g=new Set([...u].flatMap(d=>X(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(!s.has(l))return{results:n,integratedStoryIds:f,stoppedAt:l,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:u,readyStoryIds:d,integrate:S,...m}=e,w=await a({...m,projectRoot:r,storyId:l});if(n.push({storyId:l,result:w}),!w.ok)return{results:n,integratedStoryIds:f,stoppedAt:l,reasonCode:w.reasonCode};if(w.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 fr(e){const t=Ee(e.projectRoot),a=e.manager??new xe({projectRoot:t});let s;try{s=await V(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"&&_e.test(n.storyId)?n.storyId:"";if(!f){r.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const l=Object.values(s.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 a.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{Wt as STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS,Mt as STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN,je as STORY_WORKTREE_STATE_JSON_PATH,Fe as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PATHS,Yt as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PROJECT,Kt as STORY_WORKTREE_WAVE_MAX_STORIES,We as digestStoryWorktreeIntegrationReceipt,$t as integrateStoryWorktree,cr as integrateStoryWorktreeWave,dr as integrateStoryWorktreesInOrder,Gt as resolveStoryWorktreeStateJsonMerge,Ut as storyWorktreeWaveBuildOutputPaths,Vt as storyWorktreeWaveGateRunCap,fr as syncReleasedDependents};
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* at runtime. Keep this file in sync with `packages/shared/src/project-memory-*`
|
|
6
6
|
* and enforce drift through the P130.06 release tests.
|
|
7
7
|
*/
|
|
8
|
-
export type ProjectMemoryTargetId = 'canonical' | 'claude-code' | 'codex' | 'grok' | 'gemini-cli' | 'antigravity' | 'vscode' | 'cursor' | 'opencode' | 'openclaw' | 'kimi' | 'github-copilot-cli';
|
|
8
|
+
export type ProjectMemoryTargetId = 'canonical' | 'claude-code' | 'codex' | 'grok' | 'gemini-cli' | 'antigravity' | 'vscode' | 'cursor' | 'opencode' | 'openclaw' | 'kimi' | 'github-copilot-cli' | 'deepseek';
|
|
9
9
|
export type ProjectMemoryTemplateKind = 'neocortex-md' | 'claude-md' | 'agents-md' | 'gemini-md' | 'copilot-instructions' | 'cursor-rule';
|
|
10
10
|
export interface ProjectMemoryBudget {
|
|
11
11
|
readonly maxLines: number;
|
|
@@ -71,7 +71,14 @@ export interface BootstrapArchitectureMemory {
|
|
|
71
71
|
readonly heuristics?: readonly string[];
|
|
72
72
|
}
|
|
73
73
|
export declare const CANONICAL_PROJECT_MEMORY_SOURCE: "NEOCORTEX.md";
|
|
74
|
-
export declare const PROJECT_MEMORY_TARGET_IDS: readonly ["claude-code", "codex", "grok", "gemini-cli", "antigravity", "vscode", "cursor", "opencode", "openclaw", "kimi", "github-copilot-cli"];
|
|
74
|
+
export declare const PROJECT_MEMORY_TARGET_IDS: readonly ["claude-code", "codex", "grok", "gemini-cli", "antigravity", "vscode", "cursor", "opencode", "openclaw", "kimi", "github-copilot-cli", "deepseek"];
|
|
75
|
+
/**
|
|
76
|
+
* P228.20: native per-story child profiles (`neocortex-sentinel`). The child
|
|
77
|
+
* receives only the server-authored per-story prompt, so these paths are never
|
|
78
|
+
* memory wrappers: no target lists them as primary or secondary file. The
|
|
79
|
+
* orchestrator `neocortex` and the alias `neocortex-root` keep their wrappers.
|
|
80
|
+
*/
|
|
81
|
+
export declare const PROJECT_MEMORY_CHILD_PROFILE_PATHS: readonly [".claude/agents/neocortex-sentinel.md", ".gemini/agents/neocortex-sentinel.md", ".opencode/agents/neocortex-sentinel.md", ".codex/agents/neocortex-sentinel.toml"];
|
|
75
82
|
export declare const PROJECT_MEMORY_TARGETS: {
|
|
76
83
|
readonly canonical: {
|
|
77
84
|
readonly targetId: "canonical";
|
|
@@ -400,6 +407,36 @@ export declare const PROJECT_MEMORY_TARGETS: {
|
|
|
400
407
|
readonly requiresWrapperPreservation: true;
|
|
401
408
|
readonly notes: "GitHub Copilot CLI or gh alias instructions. Resolve compact memory back to NEOCORTEX.md without copying private prompt bodies.";
|
|
402
409
|
};
|
|
410
|
+
readonly deepseek: {
|
|
411
|
+
readonly targetId: "deepseek";
|
|
412
|
+
readonly platformName: "DeepSeek Harness";
|
|
413
|
+
readonly canonicalSource: "NEOCORTEX.md";
|
|
414
|
+
readonly primaryFile: ".dsh/skills/neocortex/SKILL.md";
|
|
415
|
+
readonly secondaryFiles: readonly [{
|
|
416
|
+
readonly scope: "user";
|
|
417
|
+
readonly path: ".dsh/skills/neocortex/SKILL.md";
|
|
418
|
+
}];
|
|
419
|
+
readonly ownedBlockName: "NEOCORTEX-MEMORY";
|
|
420
|
+
readonly templateKind: "agents-md";
|
|
421
|
+
readonly budget: {
|
|
422
|
+
readonly maxLines: 220;
|
|
423
|
+
readonly maxBytes: 18000;
|
|
424
|
+
};
|
|
425
|
+
readonly linkRequirement: {
|
|
426
|
+
readonly canonicalSource: "NEOCORTEX.md";
|
|
427
|
+
readonly semanticFileRequired: true;
|
|
428
|
+
readonly symlinkBacked: true;
|
|
429
|
+
readonly wrapperAllowed: true;
|
|
430
|
+
readonly includeFallbackAllowed: true;
|
|
431
|
+
readonly requiresWrapperPreservation: true;
|
|
432
|
+
readonly fallbackIsCompatibilityRemediation: true;
|
|
433
|
+
readonly policy: "safe-include-fallback";
|
|
434
|
+
readonly notes: "Use a safe include/import only for platforms that cannot consume symlinks directly; the include must resolve back to NEOCORTEX.md.";
|
|
435
|
+
};
|
|
436
|
+
readonly bidirectionalReference: ProjectMemoryBidirectionalReference;
|
|
437
|
+
readonly requiresWrapperPreservation: true;
|
|
438
|
+
readonly notes: "DeepSeek Harness Skill thin-client memory entrypoint (P228.04). Use the project Skill path when --create-project is requested and keep memory content public-safe.";
|
|
439
|
+
};
|
|
403
440
|
};
|
|
404
441
|
export declare function getProjectMemoryTarget(targetId: ProjectMemoryTargetId): ProjectMemoryTarget;
|
|
405
442
|
export declare function isProjectMemoryTargetId(value: string): value is ProjectMemoryTargetId;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function i(...
|
|
2
|
-
`)}export{e as CANONICAL_PROJECT_MEMORY_SOURCE,m as PROJECT_MEMORY_TARGETS,s as PROJECT_MEMORY_TARGET_IDS,
|
|
1
|
+
function i(...o){return o.map(a=>({scope:"project",path:a}))}const e="NEOCORTEX.md",r={canonicalSource:e,semanticFileRequired:!0,symlinkBacked:!0,wrapperAllowed:!1,includeFallbackAllowed:!1,requiresWrapperPreservation:!1,fallbackIsCompatibilityRemediation:!0,policy:"mandatory-semantic-symlink",notes:"Semantic platform memory file must resolve to NEOCORTEX.md through a symlink; do not replace it with an unrelated wrapper or copied frontmatter."},l={canonicalSource:e,semanticFileRequired:!0,symlinkBacked:!0,wrapperAllowed:!0,includeFallbackAllowed:!1,requiresWrapperPreservation:!0,fallbackIsCompatibilityRemediation:!0,policy:"symlink-backed-wrapper",notes:"Platform wrapper/frontmatter is allowed only when the semantic memory payload remains symlink-backed by NEOCORTEX.md."},n={canonicalSource:e,semanticFileRequired:!0,symlinkBacked:!0,wrapperAllowed:!0,includeFallbackAllowed:!0,requiresWrapperPreservation:!0,fallbackIsCompatibilityRemediation:!0,policy:"safe-include-fallback",notes:"Use a safe include/import only for platforms that cannot consume symlinks directly; the include must resolve back to NEOCORTEX.md."};function t(o){return{canonicalSource:e,resolvesVia:o.policy,feedbackTrigger:"*update-memory",guidance:"Treat NEOCORTEX.md as canonical project memory; consult it before platform-specific memory, and run *update-memory when durable project context changes should flow back to the canonical source."}}const s=["claude-code","codex","grok","gemini-cli","antigravity","vscode","cursor","opencode","openclaw","kimi","github-copilot-cli","deepseek"],p=Object.freeze([".claude/agents/neocortex-sentinel.md",".gemini/agents/neocortex-sentinel.md",".opencode/agents/neocortex-sentinel.md",".codex/agents/neocortex-sentinel.toml"]),m={canonical:{targetId:"canonical",platformName:"Neocortex Canonical Memory",canonicalSource:e,primaryFile:e,secondaryFiles:i("AGENTS.md","CLAUDE.md","GEMINI.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"neocortex-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:r,bidirectionalReference:t(r),requiresWrapperPreservation:!1,notes:"Canonical compact project memory source for platform symlinks and wrappers. Store only summaries, indexes, and links to architecture docs here."},"claude-code":{targetId:"claude-code",platformName:"Claude Code",canonicalSource:e,primaryFile:"CLAUDE.md",secondaryFiles:i(),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"claude-md",budget:{maxLines:320,maxBytes:28e3},linkRequirement:r,bidirectionalReference:t(r),requiresWrapperPreservation:!1,notes:"Claude Code project memory. Resolve to NEOCORTEX.md; keep root content concise and link deeper docs with @path references."},codex:{targetId:"codex",platformName:"Codex CLI",canonicalSource:e,primaryFile:"AGENTS.md",secondaryFiles:i(".codex/agents/neocortex.toml"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:r,bidirectionalReference:t(r),requiresWrapperPreservation:!0,notes:"Codex root instructions. Uppercase AGENTS.md is required on case-sensitive filesystems."},grok:{targetId:"grok",platformName:"Grok Build",canonicalSource:e,primaryFile:"AGENTS.md",secondaryFiles:i(".grok/skills/neocortex/SKILL.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:r,bidirectionalReference:t(r),requiresWrapperPreservation:!0,notes:"Grok Build reads AGENTS.md and the project-local Neocortex Skill; both resolve to canonical NEOCORTEX.md context."},"gemini-cli":{targetId:"gemini-cli",platformName:"Gemini CLI",canonicalSource:e,primaryFile:"GEMINI.md",secondaryFiles:i(),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"gemini-md",budget:{maxLines:260,maxBytes:22e3},linkRequirement:r,bidirectionalReference:t(r),requiresWrapperPreservation:!1,notes:"Gemini CLI context file. Prefer shallow @file.md imports for detailed architecture docs."},antigravity:{targetId:"antigravity",platformName:"Antigravity",canonicalSource:e,primaryFile:"GEMINI.md",secondaryFiles:i(),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"gemini-md",budget:{maxLines:260,maxBytes:22e3},linkRequirement:r,bidirectionalReference:t(r),requiresWrapperPreservation:!1,notes:"Antigravity currently shares GEMINI.md behavior with the Gemini target stubs."},vscode:{targetId:"vscode",platformName:"VS Code / GitHub Copilot",canonicalSource:e,primaryFile:".github/copilot-instructions.md",secondaryFiles:i(".github/instructions/neocortex.instructions.md",".github/agents/neocortex.agent.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"copilot-instructions",budget:{maxLines:180,maxBytes:14e3},linkRequirement:l,bidirectionalReference:t(l),requiresWrapperPreservation:!0,notes:"VS Code and GitHub Copilot always-on repository instructions."},cursor:{targetId:"cursor",platformName:"Cursor",canonicalSource:e,primaryFile:".cursor/rules/neocortex.mdc",secondaryFiles:i("AGENTS.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"cursor-rule",budget:{maxLines:180,maxBytes:14e3},linkRequirement:l,bidirectionalReference:t(l),requiresWrapperPreservation:!0,notes:"Cursor rule memory. Use AGENTS.md as compatibility fallback when Cursor rules are absent."},opencode:{targetId:"opencode",platformName:"OpenCode",canonicalSource:e,primaryFile:"AGENTS.md",secondaryFiles:i(".opencode/AGENTS.md",".opencode/agents/neocortex-root.md",".opencode/agents/neocortex.md",".agent/skills/neocortex/SKILL.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:r,bidirectionalReference:t(r),requiresWrapperPreservation:!0,notes:"OpenCode agent memory. It consumes AGENTS.md-compatible instructions and must resolve to canonical NEOCORTEX.md."},openclaw:{targetId:"openclaw",platformName:"OpenClaw",canonicalSource:e,primaryFile:".openclaw/skills/neocortex/SKILL.md",secondaryFiles:[{scope:"user",path:".openclaw/skills/neocortex/SKILL.md"}],ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:n,bidirectionalReference:t(n),requiresWrapperPreservation:!0,notes:"OpenClaw Skill thin-client memory entrypoint. Use the project Skill path when --create-project is requested; do not mutate ~/.openclaw/openclaw.json, and keep memory content public-safe."},kimi:{targetId:"kimi",platformName:"Kimi",canonicalSource:e,primaryFile:"KIMI.md",secondaryFiles:i("AGENTS.md",".kimi/skills/neocortex/SKILL.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:n,bidirectionalReference:t(n),requiresWrapperPreservation:!0,notes:"Kimi memory entrypoint. Prefer a symlink to NEOCORTEX.md; use a compact include only if the host cannot follow symlinks."},"github-copilot-cli":{targetId:"github-copilot-cli",platformName:"GitHub Copilot CLI / gh alias",canonicalSource:e,primaryFile:".github/copilot-instructions.md",secondaryFiles:i("AGENTS.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"copilot-instructions",budget:{maxLines:180,maxBytes:14e3},linkRequirement:n,bidirectionalReference:t(n),requiresWrapperPreservation:!0,notes:"GitHub Copilot CLI or gh alias instructions. Resolve compact memory back to NEOCORTEX.md without copying private prompt bodies."},deepseek:{targetId:"deepseek",platformName:"DeepSeek Harness",canonicalSource:e,primaryFile:".dsh/skills/neocortex/SKILL.md",secondaryFiles:[{scope:"user",path:".dsh/skills/neocortex/SKILL.md"}],ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:n,bidirectionalReference:t(n),requiresWrapperPreservation:!0,notes:"DeepSeek Harness Skill thin-client memory entrypoint (P228.04). Use the project Skill path when --create-project is requested and keep memory content public-safe."}};function u(o){return m[o]}function y(o){return o==="canonical"||s.includes(o)}function E(){return s.map(o=>m[o])}function R(o){const a=c=>c.replace(/\|/g,"\\|").replace(/\n/g," ");return["| Path | Title | Purpose | Suggested Usage |","| --- | --- | --- | --- |",...o.map(c=>`| ${a(c.path)} | ${a(c.title)} | ${a(c.purpose)} | ${a(c.suggestedUsage)} |`)].join(`
|
|
2
|
+
`)}export{e as CANONICAL_PROJECT_MEMORY_SOURCE,p as PROJECT_MEMORY_CHILD_PROFILE_PATHS,m as PROJECT_MEMORY_TARGETS,s as PROJECT_MEMORY_TARGET_IDS,u as getProjectMemoryTarget,y as isProjectMemoryTargetId,E as listProjectMemoryTargets,R as renderArchitectureReferenceTable};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const u=1,p="max",s="[P201-EV-MAX-POLICY]",c=new Set(["claude-code","cursor","vscode","gemini","codex","opencode","github-copilot-cli","kimi","antigravity","openclaw","grok","deepseek","runner","unknown"]),r=e=>c.has(e)?e:"unknown",d=Object.freeze({"claude-code":{status:"validated",scope:"child",fallbackMode:"none",fallbackReasonCode:null},opencode:{status:"unvalidated",scope:"child",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},codex:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},gemini:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},vscode:{status:"unvalidated",scope:"session",fallbackMode:"root-inline",fallbackReasonCode:"platform-child-unvalidated"},"github-copilot-cli":{status:"unvalidated",scope:"session",fallbackMode:"root-inline",fallbackReasonCode:"platform-child-unvalidated"},kimi:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},cursor:{status:"unvalidated",scope:"session",fallbackMode:"root-inline",fallbackReasonCode:"platform-child-unvalidated"},antigravity:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},grok:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},openclaw:{status:"
|
|
1
|
+
const u=1,p="max",s="[P201-EV-MAX-POLICY]",c=new Set(["claude-code","cursor","vscode","gemini","codex","opencode","github-copilot-cli","kimi","antigravity","openclaw","grok","deepseek","runner","unknown"]),r=e=>c.has(e)?e:"unknown",d=Object.freeze({"claude-code":{status:"validated",scope:"child",fallbackMode:"none",fallbackReasonCode:null},opencode:{status:"unvalidated",scope:"child",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},codex:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},gemini:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},vscode:{status:"unvalidated",scope:"session",fallbackMode:"root-inline",fallbackReasonCode:"platform-child-unvalidated"},"github-copilot-cli":{status:"unvalidated",scope:"session",fallbackMode:"root-inline",fallbackReasonCode:"platform-child-unvalidated"},kimi:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},cursor:{status:"unvalidated",scope:"session",fallbackMode:"root-inline",fallbackReasonCode:"platform-child-unvalidated"},antigravity:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},grok:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},openclaw:{status:"unvalidated",scope:"inherited",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unvalidated"},deepseek:{status:"unsupported",scope:"none",fallbackMode:"root-inline",fallbackReasonCode:"platform-child-unsupported"},runner:{status:"unsupported",scope:"none",fallbackMode:"shell-loop",fallbackReasonCode:"platform-child-unsupported"},unknown:{status:"unsupported",scope:"none",fallbackMode:"shell-loop",fallbackReasonCode:"platform-target-unknown"}}),n=Object.freeze({disabled:0,standard:1,max:2});function f(e){return e==="max"||e==="standard"||e==="disabled"}function i(e){const o=r(e),a=d[o];return o==="unknown"?Object.freeze({platformTarget:o,maximumMode:"disabled",scope:a.scope,reductionReason:"platform-target-unknown"}):a.status==="unsupported"?Object.freeze({platformTarget:o,maximumMode:"disabled",scope:a.scope,reductionReason:"host-capability-unsupported"}):a.status==="unvalidated"?Object.freeze({platformTarget:o,maximumMode:"standard",scope:a.scope,reductionReason:"host-capability-unvalidated"}):Object.freeze({platformTarget:o,maximumMode:"max",scope:a.scope,reductionReason:"host-policy-reduced"})}function b(e={}){const o=e.userOverride??"max",a=e.hostPolicy??i(e.platformTarget),t=d[a.platformTarget],l=n[o]>n[a.maximumMode];return Object.freeze({schemaVersion:1,requestedMode:o,effectiveMode:l?a.maximumMode:o,source:e.userOverride?"user-override":"managed-default",platformTarget:a.platformTarget,scope:a.scope,effectiveReason:l?a.reductionReason:"requested-mode-honored",fallbackMode:t.fallbackMode,fallbackReasonCode:t.fallbackReasonCode})}function m(e,o,a){return Object.freeze({evidence:s,event:e,occurredAt:a,...o})}export{s as SUBAGENT_APPROVAL_EVIDENCE,p as SUBAGENT_APPROVAL_MANAGED_DEFAULT,u as SUBAGENT_APPROVAL_POLICY_SCHEMA_VERSION,m as createSubagentApprovalAuditEvent,i as deriveSubagentHostApprovalPolicy,f as isSubagentApprovalMode,b as resolveSubagentApprovalPolicy};
|
|
@@ -1,6 +1,13 @@
|
|
|
1
|
+
import type { PRIVATE_EXECUTION_CODEX_HOST_KIND } from '../../../shared/dist/compatibility/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Codex-host attributes of the private-execution envelope (P228.18, ADR-3).
|
|
4
|
+
* The Linux platform, ChatGPT subscription login and the v6 sandbox proof are
|
|
5
|
+
* preconditions of this executor only; the envelope itself is host-neutral and
|
|
6
|
+
* other enum hosts never run this preflight.
|
|
7
|
+
*/
|
|
1
8
|
export interface PrivateCodexPreflightV6 {
|
|
2
9
|
readonly schemaVersion: 6;
|
|
3
|
-
readonly hostKind:
|
|
10
|
+
readonly hostKind: typeof PRIVATE_EXECUTION_CODEX_HOST_KIND;
|
|
4
11
|
readonly hostVersion: string;
|
|
5
12
|
readonly projectRoot: string;
|
|
6
13
|
readonly observedAtMs: number;
|