@ornexus/neocortex 4.61.6 → 4.64.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.
Files changed (99) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +31 -34
  4. package/install.sh +28 -5
  5. package/package.json +6 -4
  6. package/packages/client/dist/agent/refresh-stubs.d.ts +6 -0
  7. package/packages/client/dist/agent/refresh-stubs.js +2 -2
  8. package/packages/client/dist/agent/update-description.d.ts +8 -1
  9. package/packages/client/dist/agent/update-description.js +2 -1
  10. package/packages/client/dist/commands/invoke.d.ts +24 -0
  11. package/packages/client/dist/commands/invoke.js +73 -73
  12. package/packages/client/dist/commands/refresh-memory.d.ts +10 -0
  13. package/packages/client/dist/commands/refresh-memory.js +5 -3
  14. package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +10 -1
  15. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -1
  16. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +110 -10
  17. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -4
  18. package/packages/client/dist/git/git-lifecycle-store.d.ts +96 -2
  19. package/packages/client/dist/git/git-lifecycle-store.js +8 -7
  20. package/packages/client/dist/git/legacy-branch-mode-conversion.d.ts +58 -0
  21. package/packages/client/dist/git/legacy-branch-mode-conversion.js +4 -0
  22. package/packages/client/dist/git/release-gate-env.d.ts +23 -0
  23. package/packages/client/dist/git/release-gate-env.js +1 -0
  24. package/packages/client/dist/git/secure-filesystem-boundary.d.ts +24 -0
  25. package/packages/client/dist/git/secure-filesystem-boundary.js +20 -9
  26. package/packages/client/dist/git/state-json-field-merge.d.ts +76 -0
  27. package/packages/client/dist/git/state-json-field-merge.js +2 -0
  28. package/packages/client/dist/git/story-worktree-cleanup.d.ts +22 -1
  29. package/packages/client/dist/git/story-worktree-cleanup.js +4 -4
  30. package/packages/client/dist/git/story-worktree-integration.d.ts +48 -0
  31. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  32. package/packages/client/dist/git/story-worktree-manager.d.ts +57 -0
  33. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  34. package/packages/client/dist/git/story-worktree-paths.d.ts +23 -1
  35. package/packages/client/dist/git/story-worktree-paths.js +1 -1
  36. package/packages/client/dist/git/story-write-set-extension.d.ts +3 -0
  37. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  38. package/packages/client/dist/private-execution/root-memory-writer.js +1 -1
  39. package/packages/client/dist/runner/headless/child-env.d.ts +92 -0
  40. package/packages/client/dist/runner/headless/child-env.js +1 -0
  41. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -11
  42. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +31 -0
  43. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -10
  44. package/packages/client/dist/runner/headless/run-yolo.d.ts +15 -0
  45. package/packages/client/dist/runner/headless/run-yolo.js +1 -1
  46. package/packages/client/dist/runner/headless/run-yoloop.d.ts +55 -0
  47. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  48. package/packages/client/dist/runner/headless/types.d.ts +9 -1
  49. package/packages/client/dist/runner/headless/types.js +2 -2
  50. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  51. package/packages/client/dist/state/state-json-repair.d.ts +23 -0
  52. package/packages/client/dist/state/state-json-repair.js +4 -3
  53. package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
  54. package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +2 -0
  55. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -1
  56. package/packages/client/dist/yolo/project-manifest-projection-collector.d.ts +28 -0
  57. package/packages/client/dist/yolo/project-manifest-projection-collector.js +1 -0
  58. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +9 -0
  59. package/packages/client/dist/yolo/spec-envelope-collector.js +3 -3
  60. package/packages/client/dist/yoloop/discovery-hook.d.ts +2 -0
  61. package/packages/client/dist/yoloop/discovery-hook.js +2 -2
  62. package/packages/client/dist/yoloop/invoke-hooks.d.ts +17 -0
  63. package/packages/client/dist/yoloop/invoke-hooks.js +14 -10
  64. package/packages/client/dist/yoloop/legacy-story-scope.d.ts +23 -0
  65. package/packages/client/dist/yoloop/legacy-story-scope.js +1 -0
  66. package/packages/client/dist/yoloop/legacy-yoloop-adoption.d.ts +69 -0
  67. package/packages/client/dist/yoloop/legacy-yoloop-adoption.js +1 -0
  68. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +62 -1
  69. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
  70. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +23 -0
  71. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  72. package/packages/client/dist/yoloop/yoloop-start-origin-binding.d.ts +92 -0
  73. package/packages/client/dist/yoloop/yoloop-start-origin-binding.js +1 -0
  74. package/packages/shared/dist/compatibility/index.js +6 -0
  75. package/packages/shared/dist/frontmatter-context-contract.js +164 -52
  76. package/packages/shared/dist/project-manifest-projection.js +202 -0
  77. package/packages/shared/dist/project-validation-commands.js +14 -6
  78. package/packages/shared/dist/release-gate-env-contract.js +129 -0
  79. package/packages/shared/dist/yolo/spec-envelope-rules.js +85 -0
  80. package/packages/shared/dist/yolo/spec-envelope.js +33 -7
  81. package/packages/shared/dist/yoloop/branch-unit.js +119 -3
  82. package/packages/shared/dist/yoloop/epic-terminal-git.js +98 -6
  83. package/packages/shared/dist/yoloop/story-write-scope.js +212 -0
  84. package/targets-stubs/antigravity/gemini.md +1 -1
  85. package/targets-stubs/antigravity/install-antigravity.sh +13 -4
  86. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  87. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  88. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  89. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  90. package/targets-stubs/claude-code/neocortex.md +5 -5
  91. package/targets-stubs/codex/AGENTS.md +1 -1
  92. package/targets-stubs/codex/install-codex.sh +12 -4
  93. package/targets-stubs/cursor/agent.md +2 -2
  94. package/targets-stubs/gemini-cli/agent.md +2 -2
  95. package/targets-stubs/lib/managed-config-merge.js +459 -5
  96. package/targets-stubs/lib/managed-profile.sh +54 -7
  97. package/targets-stubs/opencode/neocortex-root.md +1 -1
  98. package/targets-stubs/vscode/install-vscode.sh +21 -0
  99. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -7,6 +7,8 @@ export interface RefreshMemoryCliOptions {
7
7
  readonly verify?: boolean;
8
8
  readonly backupDirectory?: string;
9
9
  readonly memoryNotes?: readonly string[];
10
+ /** P227.15: set when `--help`/`-h` was requested; such options never cause an effect. */
11
+ readonly help?: boolean;
10
12
  }
11
13
  export interface ProjectMemoryVerification {
12
14
  readonly schemaVersion: 'ProjectMemoryVerification/1';
@@ -15,6 +17,14 @@ export interface ProjectMemoryVerification {
15
17
  readonly fileCount: number;
16
18
  readonly publicSafe: true;
17
19
  }
20
+ export type RefreshMemoryArgumentReasonCode = 'refresh-memory-argument-unknown' | 'refresh-memory-argument-value-missing';
21
+ /** P227.15 ADR-2: typed argument failure; the message is the reason code, never the rejected input. */
22
+ export declare class RefreshMemoryArgumentError extends Error {
23
+ readonly reasonCode: RefreshMemoryArgumentReasonCode;
24
+ constructor(reasonCode: RefreshMemoryArgumentReasonCode);
25
+ }
26
+ export declare const REFRESH_MEMORY_HELP_NO_EFFECT = "refresh-memory-help-no-effect";
27
+ export declare const REFRESH_MEMORY_HELP_TEXT: string;
18
28
  export declare function parseRefreshMemoryArgs(args: readonly string[]): RefreshMemoryCliOptions;
19
29
  export declare function refreshProjectMemoryTargets(options: RefreshMemoryCliOptions): readonly WriteProjectMemoryTargetFilesResult[];
20
30
  /** Deduplicated (by path) tracked legacy wrappers that refresh refused to delete. */
@@ -1,3 +1,5 @@
1
- import{createHash as h}from"node:crypto";import{lstatSync as E,readFileSync as f}from"node:fs";import{join as u,resolve as $}from"node:path";import{getProjectMemoryTarget as P,isProjectMemoryTargetId as k,listProjectMemoryTargets as y}from"../memory/shared-project-memory-types.js";import{LEGACY_AGENT_PATH_WRAPPER_TRACKED_REASON as j,writeProjectMemoryTargetFiles as M}from"../memory/project-memory-writer.js";function g(t){return(t??"").split(",").map(e=>e.trim()).filter(Boolean)}function C(t){let e=process.cwd(),i=!1,s=!1;const c=[],l=[];for(let r=0;r<t.length;r++){const o=t[r];if(o==="--dry-run"||o==="--preview")i=!0;else if(o==="--verify")s=!0,i=!0;else if(o==="--project-root")e=t[++r]??e;else if(o.startsWith("--project-root="))e=o.slice(15);else if(o==="--target"||o==="--targets")c.push(...g(t[++r]));else if(o.startsWith("--target="))c.push(...g(o.slice(9)));else if(o.startsWith("--targets="))c.push(...g(o.slice(10)));else if(o==="--note"||o==="--memory-note"||o==="--change"){const m=t[++r];m&&l.push(m)}else o.startsWith("--note=")?l.push(o.slice(7)):o.startsWith("--memory-note=")?l.push(o.slice(14)):o.startsWith("--change=")&&l.push(o.slice(9))}if(s&&(c.length>0||l.length>0))throw new Error("Project memory verification requires all targets and no update notes.");const a=c.length>0?c.map(r=>{if(!k(r))throw new Error(`Unknown project-memory target: ${r}`);return r}):["canonical",...y().map(r=>r.targetId)];return{projectRoot:$(e),targetIds:Array.from(new Set(a)),dryRun:i,verify:s,memoryNotes:l}}function p(t){return t.targetIds.map(e=>M({projectRoot:t.projectRoot,targetId:e,dryRun:t.dryRun,memoryNotes:t.memoryNotes??[],backupDirectory:t.backupDirectory}))}function w(t){const e=new Map;for(const i of t.flatMap(s=>s.legacyAgentPathWrappers??[]))i.status==="tracked-blocked"&&!e.has(i.relativeFile)&&e.set(i.relativeFile,i);return[...e.values()].sort((i,s)=>i.relativeFile.localeCompare(s.relativeFile))}function T(t){if(!t.verify||!t.dryRun||t.memoryNotes?.length||t.targetIds.join(",")!==["canonical",...y().map(n=>n.targetId)].join(","))throw new Error("Project memory verification requires the complete read-only target set.");const e=u(t.projectRoot,"NEOCORTEX.md");let i;try{i=E(e)}catch{throw new Error("Canonical project memory is missing or unsafe.")}if(!i.isFile()||i.isSymbolicLink())throw new Error("Canonical project memory must be a regular file.");const s=f(e,"utf8"),c="<!-- NEOCORTEX-MEMORY-START -->",l="<!-- NEOCORTEX-MEMORY-END -->",a=P("canonical").budget;if(s.split(c).length!==2||s.split(l).length!==2||s.indexOf(c)>=s.indexOf(l)||Buffer.byteLength(s,"utf8")>a.maxBytes||s.split(`
2
- `).length>a.maxLines)throw new Error("Canonical project memory markers or budget are invalid.");const r=p(t),o=r.flatMap(n=>n.files),m=w(r);if(m.length>0)throw new Error(`Project memory verification blocked: ${j} ${m.map(n=>`${n.relativeFile} hint=${n.remediation??`git rm ${n.relativeFile}`}`).join("; ")}`);if(r.some(n=>(n.retiredFiles?.length??0)>0)||o.some(n=>n.changed||n.mode==="compatibility-materialized-fallback"||n.fallbackReason||n.remediationDebt))throw new Error("Project memory verification found stale or fallback targets.");let d;try{if(d=[...new Set(o.map(n=>n.relativeFile))].sort().map(n=>{const R=f(u(t.projectRoot,n)),v=o.find(b=>b.relativeFile===n).mode;return`${n}:${v}:${h("sha256").update(R).digest("hex")}`}),f(e,"utf8")!==s||p(t).some(n=>n.changed))throw new Error("project-memory-verification-race")}catch{throw new Error("Project memory changed during verification.")}return{schemaVersion:"ProjectMemoryVerification/1",canonicalSha256:h("sha256").update(s).digest("hex"),projectionSha256:h("sha256").update(d.join(`
3
- `)).digest("hex"),fileCount:d.length,publicSafe:!0}}async function N(t){try{const e=C(t);if(e.verify){const a=T(e);return console.log(`Project memory verified: files=${a.fileCount} canonical_sha256=${a.canonicalSha256} projection_sha256=${a.projectionSha256}`),0}const i=p(e),s=i.flatMap(a=>a.files.map(r=>[r.changed?e.dryRun?"would-change":"changed":"unchanged",r.mode,r.relativeFile,r.fallbackReason?`warning=${r.fallbackReason}`:void 0,r.remediationDebt?`debt=${r.remediationDebt}`:void 0,r.reasonCodes&&r.reasonCodes.length>0?`reasons=${r.reasonCodes.join(",")}`:void 0].filter(Boolean).join(" "))),c=[...new Set(i.flatMap(a=>a.retiredFiles??[]))].map(a=>`${e.dryRun?"would-retire":"retired"} legacy-agent-path-wrapper ${a}`),l=w(i).map(a=>`blocked ${j} ${a.relativeFile} hint=${a.remediation??`git rm ${a.relativeFile}`}`);console.log(`${e.dryRun?"Project memory preview":"Project memory refreshed"}: ${e.projectRoot}`);for(const a of[...s,...c,...l])console.log(a);return 0}catch(e){return console.error(e instanceof Error?e.message:String(e)),1}}export{C as parseRefreshMemoryArgs,N as refreshMemoryCliHandler,p as refreshProjectMemoryTargets,w as trackedLegacyAgentPathWrappers,T as verifyProjectMemoryTargets};
1
+ import{createHash as d}from"node:crypto";import{lstatSync as C,readFileSync as u}from"node:fs";import{join as w,resolve as j}from"node:path";import{getProjectMemoryTarget as k,isProjectMemoryTargetId as S,listProjectMemoryTargets as E}from"../memory/shared-project-memory-types.js";import{LEGACY_AGENT_PATH_WRAPPER_TRACKED_REASON as R,writeProjectMemoryTargetFiles as T}from"../memory/project-memory-writer.js";class h extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e,this.name="RefreshMemoryArgumentError"}}const v="refresh-memory-help-no-effect",F=["Usage: neocortex-client refresh-memory [options]","","Create or repair canonical project memory (NEOCORTEX.md) and its platform wrappers.","","Options:"," --project-root <path>, --project-root=<path> Project root (default: current directory)"," --target <ids>, --targets <ids> Comma-separated target ids (also --target=<ids>, --targets=<ids>)"," --dry-run, --preview Show what would change without writing"," --verify Check every target without writes"," --note <text>, --memory-note <text>, --change <text>"," Add a memory update note (also --note=<text>, --memory-note=<text>, --change=<text>)"," --help, -h Show this help without any effect"].join(`
2
+ `),O=new Set(["--help","-h"]);function A(r){return(r??"").split(",").map(e=>e.trim()).filter(Boolean)}function g(r,e){const n=r[e];if(n===void 0||n.startsWith("--"))throw new h("refresh-memory-argument-value-missing");return n}function P(r){if(r.trim()==="")throw new h("refresh-memory-argument-value-missing");return r}function p(r){const e=A(r);if(e.length===0)throw new h("refresh-memory-argument-value-missing");return e}function _(r){if(r.some(t=>O.has(t)))return{projectRoot:j(process.cwd()),targetIds:[],dryRun:!0,verify:!1,memoryNotes:[],help:!0};let e=process.cwd(),n=!1,s=!1;const c=[],l=[];for(let t=0;t<r.length;t++){const o=r[t];if(o==="--dry-run"||o==="--preview")n=!0;else if(o==="--verify")s=!0,n=!0;else if(o==="--project-root")e=P(g(r,++t));else if(o.startsWith("--project-root="))e=P(o.slice(15));else if(o==="--target"||o==="--targets")c.push(...p(g(r,++t)));else if(o.startsWith("--target="))c.push(...p(o.slice(9)));else if(o.startsWith("--targets="))c.push(...p(o.slice(10)));else if(o==="--note"||o==="--memory-note"||o==="--change"){const m=g(r,++t);m&&l.push(m)}else if(o.startsWith("--note="))l.push(o.slice(7));else if(o.startsWith("--memory-note="))l.push(o.slice(14));else if(o.startsWith("--change="))l.push(o.slice(9));else throw new h("refresh-memory-argument-unknown")}if(s&&(c.length>0||l.length>0))throw new Error("Project memory verification requires all targets and no update notes.");const i=c.length>0?c.map(t=>{if(!S(t))throw new Error(`Unknown project-memory target: ${t}`);return t}):["canonical",...E().map(t=>t.targetId)];return{projectRoot:j(e),targetIds:Array.from(new Set(i)),dryRun:n,verify:s,memoryNotes:l}}function y(r){if(r.help)throw new Error(v);return r.targetIds.map(e=>T({projectRoot:r.projectRoot,targetId:e,dryRun:r.dryRun,memoryNotes:r.memoryNotes??[],backupDirectory:r.backupDirectory}))}function b(r){const e=new Map;for(const n of r.flatMap(s=>s.legacyAgentPathWrappers??[]))n.status==="tracked-blocked"&&!e.has(n.relativeFile)&&e.set(n.relativeFile,n);return[...e.values()].sort((n,s)=>n.relativeFile.localeCompare(s.relativeFile))}function N(r){if(r.help)throw new Error(v);if(!r.verify||!r.dryRun||r.memoryNotes?.length||r.targetIds.join(",")!==["canonical",...E().map(a=>a.targetId)].join(","))throw new Error("Project memory verification requires the complete read-only target set.");const e=w(r.projectRoot,"NEOCORTEX.md");let n;try{n=C(e)}catch{throw new Error("Canonical project memory is missing or unsafe.")}if(!n.isFile()||n.isSymbolicLink())throw new Error("Canonical project memory must be a regular file.");const s=u(e,"utf8"),c="<!-- NEOCORTEX-MEMORY-START -->",l="<!-- NEOCORTEX-MEMORY-END -->",i=k("canonical").budget;if(s.split(c).length!==2||s.split(l).length!==2||s.indexOf(c)>=s.indexOf(l)||Buffer.byteLength(s,"utf8")>i.maxBytes||s.split(`
3
+ `).length>i.maxLines)throw new Error("Canonical project memory markers or budget are invalid.");const t=y(r),o=t.flatMap(a=>a.files),m=b(t);if(m.length>0)throw new Error(`Project memory verification blocked: ${R} ${m.map(a=>`${a.relativeFile} hint=${a.remediation??`git rm ${a.relativeFile}`}`).join("; ")}`);if(t.some(a=>(a.retiredFiles?.length??0)>0)||o.some(a=>a.changed||a.mode==="compatibility-materialized-fallback"||a.fallbackReason||a.remediationDebt))throw new Error("Project memory verification found stale or fallback targets.");let f;try{if(f=[...new Set(o.map(a=>a.relativeFile))].sort().map(a=>{const x=u(w(r.projectRoot,a)),M=o.find($=>$.relativeFile===a).mode;return`${a}:${M}:${d("sha256").update(x).digest("hex")}`}),u(e,"utf8")!==s||y(r).some(a=>a.changed))throw new Error("project-memory-verification-race")}catch{throw new Error("Project memory changed during verification.")}return{schemaVersion:"ProjectMemoryVerification/1",canonicalSha256:d("sha256").update(s).digest("hex"),projectionSha256:d("sha256").update(f.join(`
4
+ `)).digest("hex"),fileCount:f.length,publicSafe:!0}}async function q(r){try{const e=_(r);if(e.help)return console.log(F),0;if(e.verify){const i=N(e);return console.log(`Project memory verified: files=${i.fileCount} canonical_sha256=${i.canonicalSha256} projection_sha256=${i.projectionSha256}`),0}const n=y(e),s=n.flatMap(i=>i.files.map(t=>[t.changed?e.dryRun?"would-change":"changed":"unchanged",t.mode,t.relativeFile,t.fallbackReason?`warning=${t.fallbackReason}`:void 0,t.remediationDebt?`debt=${t.remediationDebt}`:void 0,t.reasonCodes&&t.reasonCodes.length>0?`reasons=${t.reasonCodes.join(",")}`:void 0].filter(Boolean).join(" "))),c=[...new Set(n.flatMap(i=>i.retiredFiles??[]))].map(i=>`${e.dryRun?"would-retire":"retired"} legacy-agent-path-wrapper ${i}`),l=b(n).map(i=>`blocked ${R} ${i.relativeFile} hint=${i.remediation??`git rm ${i.relativeFile}`}`);console.log(`${e.dryRun?"Project memory preview":"Project memory refreshed"}: ${e.projectRoot}`);for(const i of[...s,...c,...l])console.log(i);return 0}catch(e){return e instanceof h?(console.error(`${e.reasonCode}
5
+ Run: neocortex-client refresh-memory --help`),1):(console.error(e instanceof Error?e.message:String(e)),1)}}export{v as REFRESH_MEMORY_HELP_NO_EFFECT,F as REFRESH_MEMORY_HELP_TEXT,h as RefreshMemoryArgumentError,_ as parseRefreshMemoryArgs,q as refreshMemoryCliHandler,y as refreshProjectMemoryTargets,b as trackedLegacyAgentPathWrappers,N as verifyProjectMemoryTargets};
@@ -9,9 +9,18 @@ export declare const FRONTMATTER_DIAGNOSTIC_CATEGORIES: readonly ["payload-selec
9
9
  export type FrontmatterDiagnosticCategory = (typeof FRONTMATTER_DIAGNOSTIC_CATEGORIES)[number];
10
10
  export declare const FRONTMATTER_DIAGNOSTIC_REASON_CODES: readonly ["payload-selection-ambiguous", "payload-selection-unavailable", "markdown-link-target-malformed", "markdown-link-target-ambiguous", "markdown-link-target-external", "markdown-link-target-unsafe-path", "raw-target-malformed", "raw-target-external", "raw-target-unsafe-path", "frontmatter-malformed", "frontmatter-oversized", "frontmatter-unsupported-value", "frontmatter-explicit-selection-required"];
11
11
  export type FrontmatterDiagnosticReasonCode = (typeof FRONTMATTER_DIAGNOSTIC_REASON_CODES)[number];
12
+ /**
13
+ * P226.04: dynamic per-field list limit code emitted by the shared frontmatter
14
+ * contract. Only known list-field names (or a fixed label) and integers can
15
+ * match, so a matching code never carries rejected values. The standalone
16
+ * client cannot import `@neocortex/shared` here; this pattern mirrors
17
+ * `FRONTMATTER_LIST_TOO_LONG_PATTERN` and is pinned by tests.
18
+ */
19
+ export type FrontmatterListTooLongDiagnosticCode = `frontmatter-list-too-long:${string}:${number}>${number}`;
20
+ export declare const FRONTMATTER_LIST_TOO_LONG_DIAGNOSTIC_PATTERN: RegExp;
12
21
  export interface PublicFrontmatterDiagnostic {
13
22
  readonly category: FrontmatterDiagnosticCategory;
14
- readonly reasonCode: FrontmatterDiagnosticReasonCode | 'frontmatter-diagnostic-unclassified';
23
+ readonly reasonCode: FrontmatterDiagnosticReasonCode | FrontmatterListTooLongDiagnosticCode | 'frontmatter-diagnostic-unclassified';
15
24
  readonly summary: string;
16
25
  readonly remediation: string;
17
26
  readonly example?: string;
@@ -1 +1 @@
1
- const l=["payload-selection","target-normalization","metadata-frontmatter"],d=["payload-selection-ambiguous","payload-selection-unavailable","markdown-link-target-malformed","markdown-link-target-ambiguous","markdown-link-target-external","markdown-link-target-unsafe-path","raw-target-malformed","raw-target-external","raw-target-unsafe-path","frontmatter-malformed","frontmatter-oversized","frontmatter-unsupported-value","frontmatter-explicit-selection-required"],t="*yoloop @docs/epics/epic-P204.md",a="docs/epics/epic-P204.md",n=Object.freeze({"payload-selection-ambiguous":Object.freeze({category:"payload-selection",summary:"The explicit Neocortex command could not be selected unambiguously.",remediation:"Pass exactly one explicit trigger and its project-local arguments; keep host wrapper metadata outside the selected payload."}),"payload-selection-unavailable":Object.freeze({category:"payload-selection",summary:"The explicit Neocortex command could not be selected safely.",remediation:"Retry with one explicit trigger. Do not include wrapper frontmatter, conversation history or delegated prompt text."}),"markdown-link-target-malformed":Object.freeze({category:"target-normalization",summary:"The Markdown target is malformed or is not a supported Markdown path.",remediation:"Use one complete Markdown link to a project-relative .md file or a trailing-slash directory.",example:t}),"markdown-link-target-ambiguous":Object.freeze({category:"target-normalization",summary:"More than one target or mixed target syntax was supplied.",remediation:"Pass exactly one raw path or one Markdown link target.",example:t}),"markdown-link-target-external":Object.freeze({category:"target-normalization",summary:"External Markdown targets are not supported.",remediation:"Reference a file already inside the project with a project-relative path.",example:t}),"markdown-link-target-unsafe-path":Object.freeze({category:"target-normalization",summary:"The Markdown target is outside the supported project-relative path boundary.",remediation:"Remove absolute, home, drive, backslash or traversal segments and use a project-relative path.",example:t}),"raw-target-malformed":Object.freeze({category:"target-normalization",summary:"The raw target is not a supported Markdown path.",remediation:"Use one project-relative .md file or a trailing-slash directory.",example:t}),"raw-target-external":Object.freeze({category:"target-normalization",summary:"External raw targets are not supported.",remediation:"Reference a file already inside the project with a project-relative path.",example:t}),"raw-target-unsafe-path":Object.freeze({category:"target-normalization",summary:"The raw target is outside the supported project-relative path boundary.",remediation:"Remove absolute, home, drive, backslash or traversal segments and use a project-relative path.",example:t}),"frontmatter-malformed":Object.freeze({category:"metadata-frontmatter",summary:"The leading YAML frontmatter envelope is malformed.",remediation:"Repair the bounded leading --- envelope and keep generated metadata fields scalar or string-list values.",example:a}),"frontmatter-oversized":Object.freeze({category:"metadata-frontmatter",summary:"The leading YAML frontmatter exceeds the public parsing limits.",remediation:"Reduce the metadata header and keep descriptive content in the Markdown body.",example:a}),"frontmatter-unsupported-value":Object.freeze({category:"metadata-frontmatter",summary:"A frontmatter field uses an unsupported value shape.",remediation:"Use allowlisted scalar fields and bounded string lists only.",example:a}),"frontmatter-explicit-selection-required":Object.freeze({category:"metadata-frontmatter",summary:"Target metadata cannot be projected before explicit file selection.",remediation:"Select one project-relative epic or story target before metadata discovery.",example:a})}),i=Object.freeze({category:"metadata-frontmatter",reasonCode:"frontmatter-diagnostic-unclassified",summary:"The frontmatter operation could not be classified safely.",remediation:"Retry with one explicit project-relative target and a bounded YAML header.",example:a});function m(r){const e=n[r];return e?Object.freeze({reasonCode:r,...e}):i}function s(r){const e=m(r),o=e.example?` Example: ${e.example}.`:"";return`${e.reasonCode} [${e.category}]: ${e.summary} Remediation: ${e.remediation}${o}`}export{l as FRONTMATTER_DIAGNOSTIC_CATEGORIES,d as FRONTMATTER_DIAGNOSTIC_REASON_CODES,s as formatFrontmatterDiagnostic,m as getFrontmatterDiagnostic};
1
+ const d=["payload-selection","target-normalization","metadata-frontmatter"],c=["payload-selection-ambiguous","payload-selection-unavailable","markdown-link-target-malformed","markdown-link-target-ambiguous","markdown-link-target-external","markdown-link-target-unsafe-path","raw-target-malformed","raw-target-external","raw-target-unsafe-path","frontmatter-malformed","frontmatter-oversized","frontmatter-unsupported-value","frontmatter-explicit-selection-required"],i=/^frontmatter-list-too-long:(files_to_modify|depends_on|related_epics|unlisted-field):[0-9]{1,6}>[0-9]{1,6}$/,a="*yoloop @docs/epics/epic-P204.md",r="docs/epics/epic-P204.md",n=Object.freeze({"payload-selection-ambiguous":Object.freeze({category:"payload-selection",summary:"The explicit Neocortex command could not be selected unambiguously.",remediation:"Pass exactly one explicit trigger and its project-local arguments; keep host wrapper metadata outside the selected payload."}),"payload-selection-unavailable":Object.freeze({category:"payload-selection",summary:"The explicit Neocortex command could not be selected safely.",remediation:"Retry with one explicit trigger. Do not include wrapper frontmatter, conversation history or delegated prompt text."}),"markdown-link-target-malformed":Object.freeze({category:"target-normalization",summary:"The Markdown target is malformed or is not a supported Markdown path.",remediation:"Use one complete Markdown link to a project-relative .md file or a trailing-slash directory.",example:a}),"markdown-link-target-ambiguous":Object.freeze({category:"target-normalization",summary:"More than one target or mixed target syntax was supplied.",remediation:"Pass exactly one raw path or one Markdown link target.",example:a}),"markdown-link-target-external":Object.freeze({category:"target-normalization",summary:"External Markdown targets are not supported.",remediation:"Reference a file already inside the project with a project-relative path.",example:a}),"markdown-link-target-unsafe-path":Object.freeze({category:"target-normalization",summary:"The Markdown target is outside the supported project-relative path boundary.",remediation:"Remove absolute, home, drive, backslash or traversal segments and use a project-relative path.",example:a}),"raw-target-malformed":Object.freeze({category:"target-normalization",summary:"The raw target is not a supported Markdown path.",remediation:"Use one project-relative .md file or a trailing-slash directory.",example:a}),"raw-target-external":Object.freeze({category:"target-normalization",summary:"External raw targets are not supported.",remediation:"Reference a file already inside the project with a project-relative path.",example:a}),"raw-target-unsafe-path":Object.freeze({category:"target-normalization",summary:"The raw target is outside the supported project-relative path boundary.",remediation:"Remove absolute, home, drive, backslash or traversal segments and use a project-relative path.",example:a}),"frontmatter-malformed":Object.freeze({category:"metadata-frontmatter",summary:"The leading YAML frontmatter envelope is malformed.",remediation:"Repair the bounded leading --- envelope and keep generated metadata fields scalar or string-list values.",example:r}),"frontmatter-oversized":Object.freeze({category:"metadata-frontmatter",summary:"The leading YAML frontmatter exceeds the public parsing limits.",remediation:"Reduce the metadata header and keep descriptive content in the Markdown body.",example:r}),"frontmatter-unsupported-value":Object.freeze({category:"metadata-frontmatter",summary:"A frontmatter field uses an unsupported value shape.",remediation:"Use allowlisted scalar fields and bounded string lists only.",example:r}),"frontmatter-explicit-selection-required":Object.freeze({category:"metadata-frontmatter",summary:"Target metadata cannot be projected before explicit file selection.",remediation:"Select one project-relative epic or story target before metadata discovery.",example:r})}),m=Object.freeze({category:"metadata-frontmatter",reasonCode:"frontmatter-diagnostic-unclassified",summary:"The frontmatter operation could not be classified safely.",remediation:"Retry with one explicit project-relative target and a bounded YAML header.",example:r}),l=Object.freeze({category:"metadata-frontmatter",summary:"A frontmatter list exceeds its per-field item limit; the code reports the field, the item count and the limit.",remediation:"Trim the list to the reported limit (files_to_modify allows 256 items, other lists allow 32) and keep descriptive content in the Markdown body.",example:r});function s(t){if(typeof t=="string"&&i.test(t))return Object.freeze({reasonCode:t,...l});const e=n[t];return e?Object.freeze({reasonCode:t,...e}):m}function p(t){const e=s(t),o=e.example?` Example: ${e.example}.`:"";return`${e.reasonCode} [${e.category}]: ${e.summary} Remediation: ${e.remediation}${o}`}export{d as FRONTMATTER_DIAGNOSTIC_CATEGORIES,c as FRONTMATTER_DIAGNOSTIC_REASON_CODES,i as FRONTMATTER_LIST_TOO_LONG_DIAGNOSTIC_PATTERN,p as formatFrontmatterDiagnostic,s as getFrontmatterDiagnostic};
@@ -1,12 +1,15 @@
1
1
  import type { RootProjectMemoryEffect } from '@neocortex/shared';
2
- import type { StoryCommitCheckpoint } from '../../../shared/dist/yoloop/branch-unit.js';
2
+ import { type StoryCommitCheckpoint } from '../../../shared/dist/yoloop/branch-unit.js';
3
3
  import { type GitLifecyclePhysicalIntegrationLockOwner, type P205TransientExecutionAuthority } from './git-lifecycle-store.js';
4
+ /** P226.08 CON-ORIGIN-08-03: closed public remediation hints; never free text. */
5
+ export type DirectYoloFailureHint = 'fetch-origin-branch' | 'checkout-origin-or-rebase';
4
6
  export type DirectYoloCheckpointResult<T> = {
5
7
  readonly ok: true;
6
8
  readonly value: T;
7
9
  } | {
8
10
  readonly ok: false;
9
11
  readonly reasonCode: string;
12
+ readonly hint?: DirectYoloFailureHint;
10
13
  };
11
14
  export interface DirectYoloCommitPlan {
12
15
  readonly schemaVersion: 1;
@@ -113,14 +116,7 @@ export declare function recoverLegacyDirectYoloStoryCheckpoint(options: DirectYo
113
116
  * C08, required from the root checkout on the execution branch.
114
117
  */
115
118
  export declare function resolveDirectYoloIntegrationAuthority(projectRootInput: string, storyId: string): Promise<{
116
- originBinding: {
117
- schemaVersion: 1;
118
- originBranch: string;
119
- originHeadSha: string;
120
- executionBranch: string;
121
- capturedFromCurrentCheckout: true;
122
- capturedAt: string;
123
- } | undefined;
119
+ originBinding: OriginBinding | undefined;
124
120
  projectRoot: string;
125
121
  storyId: string;
126
122
  story: Record<string, unknown>;
@@ -128,7 +124,7 @@ export declare function resolveDirectYoloIntegrationAuthority(projectRootInput:
128
124
  executionBranch: string;
129
125
  originBranch: string;
130
126
  graphRevision: string;
131
- authorizedWriteSet: string[];
127
+ authorizedWriteSet: readonly string[];
132
128
  rootMemoryEffect: import("../private-execution/shared-root-memory-types.js").RootProjectMemoryEffect | undefined;
133
129
  }>;
134
130
  /** P225.07: the direct C08 write-set rule, shared with root integration. */
@@ -218,9 +214,113 @@ export declare function persistDirectYoloWaveStoryCheckpoint(input: {
218
214
  readonly remote?: string;
219
215
  readonly nowIso?: string;
220
216
  }): Promise<DirectYoloCheckpointResult<StoryCommitCheckpoint>>;
217
+ /**
218
+ * P227.03 (P227.06 DEBT-1, C11 F1/F2): a root write-set extension scope
219
+ * admitted by the direct checkpoint. It follows the shared P226.05 grammar
220
+ * (exact path, `dir/`, bounded glob) with the P227.06 store refusals: no
221
+ * governance surface (`.neocortex`, `.claude`, `.git*`, case-insensitive) and
222
+ * no `docs/stories` in any form; no glob in the first segment (`**`, `*.ts`
223
+ * would widen to repository-wide scopes); no traversal, absolute path, brace,
224
+ * negation or unbounded wildcard; at most 512 characters. DEC-03: P227.06
225
+ * should replace this with delegation to the store validator.
226
+ */
227
+ export declare function isDirectYoloWriteSetExtensionScope(value: unknown): value is string;
228
+ /** P226.08 CON-ORIGIN-08-01: v1 is unchanged; v2 is additive and closed. */
229
+ interface OriginBindingV1 {
230
+ schemaVersion: 1;
231
+ originBranch: string;
232
+ originHeadSha: string;
233
+ executionBranch: string;
234
+ capturedFromCurrentCheckout: true;
235
+ capturedAt: string;
236
+ }
237
+ interface OriginBindingV2 {
238
+ schemaVersion: 2;
239
+ originBranch: string;
240
+ originHeadSha: string;
241
+ executionBranch: string;
242
+ capturedFrom: 'current-checkout' | 'branch-ref';
243
+ capturedAt: string;
244
+ }
245
+ type OriginBinding = OriginBindingV1 | OriginBindingV2;
246
+ /** P227.21 R7: public-safe receipt of the root `*yoloop` start capture (SHAs, enums, branch names, ISO time only). */
247
+ export interface OriginBindingStartReceipt {
248
+ readonly schemaVersion: 1;
249
+ readonly kind: 'origin-binding-start';
250
+ readonly epicId: string;
251
+ readonly executionBranch?: string;
252
+ readonly originBranch?: string;
253
+ readonly originHeadSha?: string;
254
+ readonly outcome: 'captured' | 'already-bound' | 'refused';
255
+ readonly reasonCode?: string;
256
+ readonly executionRefCreated: boolean;
257
+ readonly capturedAt: string;
258
+ }
259
+ export declare const ORIGIN_BINDING_START_FETCH_TIMEOUT_MS = 30000;
260
+ /**
261
+ * P227.21 C11 F1: bounded, non-interactive execFile options for the start
262
+ * fetch (same contract as P227.12 `gitNetworkExecOptions`): SIGKILL on the
263
+ * budget, no terminal or credential-manager prompt, low-speed abort and a
264
+ * batch-mode SSH command unless the user configured one.
265
+ */
266
+ export declare function yoloopStartGitNetworkExecOptions(baseEnv: NodeJS.ProcessEnv, timeoutMs?: number): {
267
+ readonly timeout: number;
268
+ readonly killSignal: 'SIGKILL';
269
+ readonly env: NodeJS.ProcessEnv;
270
+ };
271
+ export type YoloopStartFetchReasonCode = 'origin-binding-start-fetch-unavailable' | 'origin-binding-start-fetch-non-fast-forward';
272
+ export type YoloopStartFetchResult = {
273
+ readonly ok: true;
274
+ } | {
275
+ readonly ok: false;
276
+ readonly reasonCode: YoloopStartFetchReasonCode;
277
+ };
278
+ /**
279
+ * P227.21 F6/F8: the single fetch of `refs/heads/<origin>` into
280
+ * `refs/remotes/origin/<origin>` per `*yoloop` start. The refspec has no `+`,
281
+ * so a rewritten remote origin is refused with its own reason code.
282
+ */
283
+ export declare function fetchOriginForYoloopStart(options: {
284
+ readonly projectRoot: string;
285
+ readonly originBranch: string;
286
+ readonly fetchTimeoutMs?: number;
287
+ }): Promise<YoloopStartFetchResult>;
288
+ /** P227.21: effective (tracked + runtime overlay) view of one epic at `*yoloop` start; only enums and branch names leave it. */
289
+ export interface YoloopStartEpicView {
290
+ readonly exists: boolean;
291
+ /** `recorded-epic`: `branch_mode: epic`; `resolved-epic`: unset mode that resolves to epic with no legacy evidence (F2). */
292
+ readonly mode: 'recorded-epic' | 'resolved-epic' | 'not-epic';
293
+ readonly terminal: boolean;
294
+ readonly bound: boolean;
295
+ readonly executionBranch?: string;
296
+ readonly originBranch?: string;
297
+ }
298
+ export declare function readYoloopStartEpic(projectRootInput: string, epicId: string): Promise<YoloopStartEpicView>;
299
+ /**
300
+ * P227.21 (R1-R7, ADR-1/2): root capture of `epics[<id>].origin_binding` at
301
+ * `*yoloop` start, before any story C01. It fetches the recorded origin once
302
+ * (or reuses the caller's start fetch), requires the local origin branch to
303
+ * equal the fetched remote-tracking ref, reuses the P226.08 `branch-ref` rule
304
+ * (origin ancestor of the execution branch, execution branch not checked out
305
+ * elsewhere) and persists only the closed V2 binding under revision CAS. It
306
+ * accepts a recorded `branch_mode: epic` or an unset mode that resolves to
307
+ * epic with no legacy evidence (C11 F2). It never writes `branch_lease`,
308
+ * stories, tracked state or the checkout; an absent execution ref is created
309
+ * at the origin SHA with a must-not-exist `update-ref` and removed again if
310
+ * the runtime write does not commit.
311
+ */
312
+ export declare function captureEpicOriginBindingAtYoloopStart(options: {
313
+ readonly projectRoot: string;
314
+ readonly epicId: string;
315
+ readonly nowIso?: string;
316
+ readonly fetchTimeoutMs?: number;
317
+ /** F6/F8: result of the start's single fetch; absent means this call fetches once itself. */
318
+ readonly originFetch?: YoloopStartFetchResult;
319
+ }): Promise<OriginBindingStartReceipt>;
221
320
  /** Physical observation for a private YOLO agent step; this is not actor attribution. */
222
321
  export declare function captureDirectYoloCheckoutEvidence(projectRootInput: string): Promise<{
223
322
  readonly headSha: string;
224
323
  readonly branch: string;
225
324
  readonly payloadDigest: string;
226
325
  }>;
326
+ export {};
@@ -1,4 +1,3 @@
1
- import{execFile as Je}from"node:child_process";import{createHash as Ze,randomBytes as He,timingSafeEqual as Qe}from"node:crypto";import{existsSync as Ce}from"node:fs";import{readFile as N,realpath as ce}from"node:fs/promises";import{join as Q,resolve as M}from"node:path";import{promisify as Ue}from"node:util";import{readRootMemoryEffectForCheckpoint as Xe}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as et,verifyRootMemoryPhysicalWriteSet as se}from"../private-execution/root-memory-git-evidence.js";import{acquireGitLifecyclePhysicalIntegrationLock as V,applyGitLifecycleRuntimeOverlay as tt,computeImmutableStoryQaEvidenceDigest as rt,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as de,computeP205StoryQaEvidenceDigest as ot,computeLegacyDirectYoloRecoveryReceiptRef as it,ensureRuntimeEpic as W,ensureRuntimeStory as he,ensureGitLifecyclePrivateChildDirectory as Le,executeP205TransientAuthorities as at,executeP205TransientAuthority as nt,projectP205TransientExecutionEvidence as Oe,publicStoryReviewArtifactFromGit as ee,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as ct,mutateGitLifecycleRuntime as C,P205_COMPLETE_COMMAND as Pe,readGitLifecycleRuntime as H,gitLifecycleRuntimeDirectory as $e,STORY_WRITE_SET_MAX_ENTRIES as st,storyWriteSetExtensionPaths as dt,assertGitLifecyclePrivateFile as te,releaseGitLifecyclePhysicalIntegrationLock as G,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as ht,verifyGitLifecyclePhysicalIntegrationLock as re,verifyAcceptedGitLifecycleStoryCheckpoint as fe}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as qe,anchoredRemoveFile as ft}from"./secure-filesystem-boundary.js";import{parseNeocortexTrailers as pt,trailerReasonKey as pe,trailerValue as le}from"./neocortex-trailers.js";import{StoryWorktreeManager as lt}from"./story-worktree-manager.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as ut,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as ze,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as P}from"./git-lifecycle-step-ids.js";const ue=Ue(Je),oe=3600*1e3;async function Wt(e){let t,o=!1;try{const r=await ye(e.projectRoot,e.storyId);if(await We(r.projectRoot)){if(e.expiredSetupRecovery)return n("direct-yolo-expired-setup-recovery-invalid");const b=await Ke(r);return{ok:!0,value:Te(r,b,!1)}}const i=$(e.nowIso),a=Date.parse(i),h=await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),s=await p(r.projectRoot,["rev-parse","HEAD"]),d=await H(r.projectRoot,{required:!0}),c=g(d.epics[r.epicId]),l=g(c?.branch_lease),m=e.expiredSetupRecovery;if(m&&!Dt(m,d.revision,l,e.storyId,a))return n("direct-yolo-expired-setup-recovery-invalid");const y=l&&Number.isFinite(Date.parse(String(l.expiresAt)))&&Date.parse(String(l.expiresAt))>a;if(y&&l?.ownerStoryId!==e.storyId)return n("direct-yolo-writer-active");let f=X(c?.origin_binding,r.executionBranch,r.originBranch);if(h===r.executionBranch){if(!f)return n("direct-yolo-origin-binding-invalid")}else{if(h!==r.originBranch)return n("direct-yolo-current-branch-mismatch");if(f&&f.originHeadSha!==s){if(!m||!await B(r.projectRoot,["merge-base","--is-ancestor",f.originHeadSha,s]))return n("direct-yolo-origin-binding-conflict");const u=`refs/heads/${r.executionBranch}`;if(!await B(r.projectRoot,["show-ref","--verify","--quiet",u]))return n("direct-yolo-execution-branch-missing");const S=await p(r.projectRoot,["rev-parse",u]);if(!await B(r.projectRoot,["merge-base","--is-ancestor",S,s]))return n("direct-yolo-execution-branch-diverged")}if(f??={schemaVersion:1,originBranch:r.originBranch,originHeadSha:s,executionBranch:r.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:i},(await Ae(r.projectRoot)).some(u=>u.branch===r.executionBranch&&M(u.path)!==r.projectRoot))return n("direct-yolo-execution-branch-checked-out-elsewhere");const w=await O(r.projectRoot),I=`refs/heads/${r.executionBranch}`;if(await B(r.projectRoot,["show-ref","--verify","--quiet",I])){const u=await p(r.projectRoot,["rev-parse",I]);if(u!==s){if(!await B(r.projectRoot,["merge-base","--is-ancestor",u,s]))return n("direct-yolo-execution-branch-diverged");m||await p(r.projectRoot,["update-ref",I,s,u])}m?t={checkoutBefore:w,executionRef:I,executionBranch:r.executionBranch,executionHead:u,originBranch:r.originBranch,originHead:s}:await p(r.projectRoot,["switch",r.executionBranch])}else{if(m)return n("direct-yolo-execution-branch-missing");await p(r.projectRoot,["switch","-c",r.executionBranch])}if(!t&&await O(r.projectRoot)!==w)return n("direct-yolo-checkout-payload-raced")}const v=t?.originHead??await p(r.projectRoot,["rev-parse","HEAD"]);if(!t&&await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)return n("direct-yolo-current-branch-mismatch");if(y&&l?.ownerStoryId===e.storyId)return l.setupHeadSha!==v?n("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:ae(r,f,String(l.expiresAt),!0)};const x=i,k=new Date(a+3600*1e3).toISOString(),D=`setup-${He(32).toString("hex")}`,j=m?d:await H(r.projectRoot,{required:!0});return await C(r.projectRoot,b=>{const w=W(b,r.epicId),I=g(w.branch_lease);if(m&&JSON.stringify(I)!==JSON.stringify(m.expectedLease))throw new Error("direct-yolo-expired-setup-recovery-raced");if(I&&Date.parse(String(I.expiresAt))>a&&I.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const u=X(w.origin_binding,r.executionBranch,r.originBranch);if(w.origin_binding&&!u)throw new Error("direct-yolo-origin-binding-conflict");if(u&&JSON.stringify(u)!==JSON.stringify(f))throw new Error("direct-yolo-origin-binding-conflict");w.branch_mode="epic",w.execution_branch=r.executionBranch,w.origin_branch=r.originBranch,w.graph_revision=r.graphRevision,w.origin_binding=f,w.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:D,idempotencyKey:D,acquiredAt:x,expiresAt:k,setupHeadSha:v}},{expectedRevision:m?.expectedRuntimeRevision??j.revision,preCommit:async()=>{if(t){if((await Ae(r.projectRoot)).some(w=>w.branch===r.executionBranch&&M(w.path)!==r.projectRoot)||await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.originBranch||await p(r.projectRoot,["rev-parse","HEAD"])!==t.originHead||await O(r.projectRoot)!==t.checkoutBefore||!await B(r.projectRoot,["show-ref","--verify","--quiet",t.executionRef])||await p(r.projectRoot,["rev-parse",t.executionRef])!==t.executionHead)throw new Error("direct-yolo-expired-setup-recovery-raced");if(o=!0,t.executionHead!==t.originHead&&await p(r.projectRoot,["update-ref",t.executionRef,t.originHead,t.executionHead]),await p(r.projectRoot,["switch",r.executionBranch]),await O(r.projectRoot)!==t.checkoutBefore)throw new Error("direct-yolo-checkout-payload-raced")}if(await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await p(r.projectRoot,["rev-parse","HEAD"])!==v)throw new Error("direct-yolo-setup-physical-state-raced")}}),{ok:!0,value:ae(r,f,k,!1)}}catch(r){return o&&t&&await jt(M(e.projectRoot),t).catch(()=>{}),n(Z(r,"direct-yolo-setup-failed"))}}async function Kt(e){let t;try{const o=await ye(e.projectRoot,e.storyId);if(await We(o.projectRoot))return await yt(o);const r=await K(e.projectRoot,e.storyId),i=$(e.nowIso),a=Q(r.projectRoot,".neocortex/state.json"),h=await N(a,"utf8"),s=await O(r.projectRoot),d=await p(r.projectRoot,["rev-parse","HEAD"]),c=`refs/heads/${r.executionBranch}`,l=await H(r.projectRoot,{required:!0}),m=g(l.epics[r.epicId]),y=X(m?.origin_binding,r.executionBranch,r.originBranch),f=g(m?.branch_lease);if(!y)return n("direct-yolo-origin-binding-invalid");if(!f||!Re(f,e.storyId,i)||f?.sessionId!==f?.idempotencyKey)return n("direct-yolo-setup-lease-invalid");const v=await V(r.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:String(f.sessionId),idempotencyKey:String(f.idempotencyKey),expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1});if(!v.ok)return n(v.reasonCode);if(t=v,d!==f.setupHeadSha||!await B(r.projectRoot,["merge-base","--is-ancestor",y.originHeadSha,d])||await p(r.projectRoot,["rev-parse",c])!==d)return n("direct-yolo-setup-head-mismatch");if((await Ae(r.projectRoot)).some(I=>I.branch===r.executionBranch&&M(I.path)!==r.projectRoot))return n("direct-yolo-execution-branch-checked-out-elsewhere");const k=g(JSON.parse(h)),D=g(g(k?.stories)?.[e.storyId]),j=g(l.stories[e.storyId]);if(!D||!["backlog","ready_to_start"].includes(String(D.status))||D.steps_completed!==void 0&&(!Array.isArray(D.steps_completed)||D.steps_completed.length>0)||D.branch_name||D.checkpoint)return n("direct-yolo-setup-story-progress-conflict");const b=j?.status==="branch-ready"&&j.last_step===P&&Array.isArray(j.steps_completed)&&j.steps_completed.length===1&&j.steps_completed[0]===P&&J(j).sort().join(",")==="last_step,status,steps_completed";if(j&&J(j).length>0&&!b)return n("direct-yolo-setup-story-progress-conflict");const w=async()=>{if(Date.parse(String(f.expiresAt))<=(e.nowIso?Date.parse(i):Date.now())||!t||!await re(t.path,t.owner)||await N(a,"utf8")!==h||await O(r.projectRoot)!==s||await p(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await p(r.projectRoot,["rev-parse","HEAD"])!==d||!await B(r.projectRoot,["merge-base","--is-ancestor",y.originHeadSha,d])||await p(r.projectRoot,["rev-parse",c])!==d)throw new Error("direct-yolo-setup-physical-state-raced")};return b?await w():await C(r.projectRoot,I=>{const u=g(I.epics[r.epicId]),S=he(I,e.storyId);if(JSON.stringify(u?.branch_lease)!==JSON.stringify(f)||JSON.stringify(u?.origin_binding)!==JSON.stringify(y)||u?.graph_revision!==r.graphRevision||J(S).length>0)throw new Error("direct-yolo-setup-runtime-raced");S.status="branch-ready",S.last_step=P,S.steps_completed=[P]},{expectedRevision:l.revision,preCommit:w}),{ok:!0,value:Object.freeze({...ae(r,y,String(f.expiresAt),b),checkpointAccepted:!0,graphRevision:r.graphRevision,headSha:d})}}catch(o){return n(Z(o,"direct-yolo-setup-acceptance-failed"))}finally{t&&await G(t.path,t.owner).catch(()=>{})}}async function Tt(e){try{const t=await K(e.projectRoot,e.storyId),o=L(await A(t.projectRoot,["diff","--cached","--name-only","-z"])),r=Y(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!r.ok)return n(r.reasonCode);if(t.rootMemoryEffect&&se(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:await p(t.projectRoot,["rev-parse","HEAD"]),headRef:":",childPaths:t.authorizedWriteSet}),ee(t.projectRoot,e.storyId,":")?.verdict!=="approved")return n("direct-yolo-review-artifact-not-approved");if(L(await A(t.projectRoot,["diff","--name-only","-z"])).some(S=>o.includes(S)))return n("direct-yolo-user-overlap");const h=await A(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!h)return n("direct-yolo-staged-diff-empty");const s=E(h),d=E([...t.authorizedWriteSet].sort().join("\0")),c=$(e.nowIso),l=await H(t.projectRoot,{required:!0}),m=g(l.epics[t.epicId]?.branch_lease);if(!Re(m,e.storyId,c))return n("direct-yolo-setup-handoff-owner-invalid");const y=String(m.sessionId),f=String(m.expiresAt),v=new Date(Math.min(Date.parse(f),Date.parse(c)+300*1e3)).toISOString(),x=await F(t.projectRoot,e.storyId),k=x?.state==="issued"&&x.fromSessionId===y&&x.bundleDigest===s&&x.claimRevision===d&&Date.parse(x.expiresAt)>Date.parse(c),D=k?x.expiresAt:v,j=k?x.token:He(32).toString("base64url"),b=E(j),w=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:y,tokenDigest:b,bundleDigest:s,claimRevision:d,expiresAt:D}),I=E(JSON.stringify(w)),u=await V(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:y,idempotencyKey:y,expiresAt:D,persistent:!1,createdAt:c});if(!u.ok)return n(u.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await Ie(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:y,token:j,tokenDigest:b,bundleDigest:s,claimRevision:d,grantDigest:I,expiresAt:D}),await C(t.projectRoot,S=>{const R=g(W(S,t.epicId).branch_lease);if(!Re(R,e.storyId,c)||R?.sessionId!==y||R.idempotencyKey!==y)throw new Error("direct-yolo-setup-handoff-owner-raced");R.handoffGrant=w},{expectedRevision:l.revision,preCommit:async()=>{if(!await re(u.path,u.owner))throw new Error("direct-yolo-integration-lock-raced");const S=await F(t.projectRoot,e.storyId);if(!S||S.state!=="issued"||S.grantDigest!==I||S.tokenDigest!==b)throw new Error("direct-yolo-setup-handoff-token-raced")}})}finally{await G(u.path,u.owner).catch(()=>{})}return{ok:!0,value:Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff-receipt",storyId:e.storyId,sessionId:y,bundleDigest:s,claimRevision:d,grantDigest:I,expiresAt:D,reused:k,publicSafe:!0})}}catch(t){return n(t instanceof Error&&/^direct-yolo-/.test(t.message)?t.message:"direct-yolo-setup-handoff-failed")}}async function Mt(e){try{const t=await K(e.projectRoot,e.storyId),o=await p(t.projectRoot,["rev-parse","HEAD"]),r=L(await A(t.projectRoot,["diff","--cached","--name-only","-z"])),i=Y(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!i.ok)return n(i.reasonCode);t.rootMemoryEffect&&se(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:o,headRef:":",childPaths:t.authorizedWriteSet});const a=ee(t.projectRoot,e.storyId,":");if(a?.verdict!=="approved")return n("direct-yolo-review-artifact-not-approved");if(L(await A(t.projectRoot,["diff","--name-only","-z"])).some(R=>r.includes(R)))return n("direct-yolo-user-overlap");const s=await A(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!s)return n("direct-yolo-staged-diff-empty");const d=E(s),c=E([...t.authorizedWriteSet].sort().join("\0")),l=await Ve(t.projectRoot,e.storyId),m=l.state==="valid"&&l.plan.epicId===t.epicId&&l.plan.executionBranch===t.executionBranch&&l.plan.preparedBase===o&&l.plan.bundleDigest===d&&l.plan.claimRevision===c?l.plan:void 0,y=m?.graphRevision??t.graphRevision,f=ge({storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:d,graphRevision:y,claimRevision:c}),v=$(e.nowIso),x={schemaVersion:1,kind:"direct-yolo-commit-plan",storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:y,preparedBase:o,bundleDigest:d,claimRevision:c,idempotencyKey:f,issuedAt:m?.issuedAt??v};let k=e.setupLeaseHandoff??await Rt(t.projectRoot,e.storyId,d,c,v);const D=await H(t.projectRoot,{required:!0}),j=g(D.epics[t.epicId]?.branch_lease),b=j?.ownerStoryId===e.storyId&&j.sessionId===f&&j.idempotencyKey===f&&typeof j.expiresAt=="string"&&Date.parse(j.expiresAt)>Date.parse(v)?j:void 0;if(b&&e.setupLeaseHandoff)return n("direct-yolo-setup-handoff-replayed");const w=g(b?.handoffConsumption);if(w){const R=await F(t.projectRoot,e.storyId);if(!R||!["consuming","consumed"].includes(R.state)||R.fromSessionId!==w.fromSessionId||R.tokenDigest!==w.tokenDigest||R.bundleDigest!==d||R.claimRevision!==c||w.bundleDigest!==d||w.claimRevision!==c||R.consumedBySessionId!==f||w.consumedBySessionId!==f)return n("direct-yolo-setup-handoff-consume-invalid");if(R.state==="consuming"){if(!R.token||E(R.token)!==R.tokenDigest)return n("direct-yolo-setup-handoff-consume-invalid");k={sessionId:R.fromSessionId,token:R.token}}}const I=b?String(b.expiresAt):new Date(Date.parse(v)+oe).toISOString(),u=await V(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:f,idempotencyKey:f,expiresAt:I,persistent:!0,createdAt:b&&typeof b.acquiredAt=="string"?b.acquiredAt:v});if(!u.ok)return n(u.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{k&&e.setupLeaseHandoff===void 0&&(await It(t.projectRoot,e.storyId,k.sessionId,k.token,f,v),await e.setupHandoffFault?.("after-consuming-persisted")),await C(t.projectRoot,R=>{const q=W(R,t.epicId),_=g(q.branch_lease),z=_&&Date.parse(String(_.expiresAt))>Date.parse(v),T=_?.ownerStoryId===e.storyId&&_.sessionId===f&&_.idempotencyKey===f,Ye=_?.ownerStoryId===e.storyId&&_.sessionId===_.idempotencyKey&&typeof _.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(_.idempotencyKey),ne=z&&Ye&&xt({current:_,handoff:k,storyId:e.storyId,bundleDigest:d,claimRevision:c,nowIso:v});if(k&&z&&!T&&!ne)throw new Error("direct-yolo-setup-handoff-invalid");if(z&&!T&&!ne)throw new Error("direct-yolo-writer-active");const Be=ne?g(_?.handoffGrant):void 0,_e=Be?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(_?.sessionId),tokenDigest:String(Be.tokenDigest),bundleDigest:d,claimRevision:c,consumedBySessionId:f,consumedAt:v}:void 0;q.branch_mode="epic",q.execution_branch=t.executionBranch,q.origin_branch=t.originBranch,q.graph_revision=t.graphRevision,q.branch_lease=z&&T?_:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:f,idempotencyKey:f,acquiredAt:v,expiresAt:I,..._e?{handoffConsumption:_e}:{}}},{expectedRevision:D.revision,preCommit:async()=>{if(!await re(u.path,u.owner))throw new Error("direct-yolo-integration-lock-raced");await vt(t.projectRoot,x)}})}catch(R){throw await G(u.path,u.owner).catch(()=>{}),R}k&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await St(t.projectRoot,t.epicId,e.storyId,k.sessionId,k.token,d,c,f,v));const S=Object.freeze([`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${t.epicId}`,`Neocortex-Execution-Branch: ${t.executionBranch}`,`Neocortex-Prepared-Base: ${o}`,`Neocortex-Bundle-Digest: ${d}`,`Neocortex-Review-Artifact-Digest: ${a.digest}`,`Neocortex-Graph-Revision: ${y}`,`Neocortex-Claim-Revision: ${c}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${et(t.rootMemoryEffect)}`]:[]]);return{ok:!0,value:Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:d,reviewArtifactDigest:a.digest,graphRevision:y,claimRevision:c,idempotencyKey:f,changedPaths:Object.freeze(r),trailers:S})}}catch(t){return n(Z(t,"direct-yolo-begin-failed"))}}async function Vt(e){let t,o,r;try{const i=await K(e.projectRoot,e.storyId);t=i;const a=await p(i.projectRoot,["rev-parse","HEAD"]);let h=await H(i.projectRoot,{required:!0});const s=g(h.stories[e.storyId]?.checkpoint);if(s){const I=typeof s.headSha=="string"?s.headSha:"",u=typeof s.graphRevision=="string"?s.graphRevision:"",S=/^[a-f0-9]{40,64}$/.test(I)?L(await A(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",I])):[],R=Y(S,i.authorizedWriteSet,e.storyId,i.rootMemoryEffect);if(!(/^[a-f0-9]{40,64}$/.test(I)&&await B(i.projectRoot,["merge-base","--is-ancestor",I,a]))||!/^[a-f0-9]{64}$/.test(u)||!R.ok)return n("direct-yolo-replay-invalid");const _=await ke(e,i.projectRoot,a,u);if(!await fe(i.projectRoot,s,e.storyId,i.epicId,i.executionBranch,_.transientAuthority,i.authorizedWriteSet))return n("direct-yolo-replay-invalid");if(!await be(i.projectRoot,i.executionBranch,a,S))return n("direct-yolo-replay-head-raced");if(e.push&&!await Me(i.projectRoot,e.remote??"origin",i.executionBranch,I))return n("direct-yolo-remote-head-mismatch");const z=Array.isArray(s.receiptRefs)?s.receiptRefs.find(T=>typeof T=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(T)):void 0;return z&&typeof s.idempotencyKey=="string"&&await ht(i.projectRoot,{storyId:e.storyId,idempotencyKey:s.idempotencyKey,ownerDigest:z.slice(20)}),await ie(i.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:s}}const d=a,c=await Ne(i,e.storyId,d);if(!c.ok)return n(c.reasonCode);const{baseSha:l,changedPaths:m,bundleDigest:y,graphRevision:f,claimRevision:v,idempotencyKey:x}=c.value,k=g(h.epics[i.epicId]?.branch_lease),D=$(e.nowIso),j=k?.ownerStoryId===e.storyId&&k.idempotencyKey===x&&k.sessionId===x&&Date.parse(String(k.expiresAt))>Date.now()?k:void 0;if(k&&Date.parse(String(k.expiresAt))>Date.now()&&!j)return n("direct-yolo-writer-active");const b=j??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:x,idempotencyKey:x,acquiredAt:D,expiresAt:new Date(Date.parse(D)+oe).toISOString()},w=await V(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:x,idempotencyKey:x,expiresAt:String(b.expiresAt),persistent:!0,createdAt:String(b.acquiredAt)});if(!w.ok)return n(w.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");r=w,j||(h=(await C(i.projectRoot,u=>{const S=W(u,i.epicId),R=g(S.branch_lease);if(R&&Date.parse(String(R.expiresAt))>Date.parse(D))throw new Error("direct-yolo-writer-active");if(S.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");S.branch_lease=b},{expectedRevision:h.revision})).document),o=b;{const I=await ke(e,i.projectRoot,d,f);if(!await be(i.projectRoot,i.executionBranch,d,m))return n("direct-yolo-head-raced");if(e.push){const R=U(e.remote??"origin");if(await p(i.projectRoot,["push",R,i.executionBranch]),!await De(i.projectRoot,R,i.executionBranch,d))return n("direct-yolo-remote-head-mismatch")}const u=await me({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:l,headSha:d,bundleDigest:y,graphRevision:f,claimRevision:v,idempotencyKey:x,qaExecution:I,physicalLockOwnerDigest:de(w.owner),nowIso:$(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect});return await e.beforeCheckpointPersist?.(),await we({projectRoot:i.projectRoot,checkpoint:u,remote:e.push?e.remote??"origin":void 0,expectedRevision:h.revision,expectedLease:b,expectedGraphRevision:i.graphRevision,expectedCheckpointGraphRevision:f,physicalLockPath:w.path,physicalLockOwner:w.owner,transientAuthority:I.transientAuthority,authorizedWriteSet:i.authorizedWriteSet})?(await ie(i.projectRoot,e.storyId).catch(()=>{}),await e.afterCheckpointPersist?.(),{ok:!0,value:u}):n("direct-yolo-checkpoint-persist-failed")}}catch(i){return n(Z(i,"direct-yolo-finalize-failed"))}finally{r&&await G(r.path,r.owner).catch(()=>{}),t&&o?await xe(t.projectRoot,t.epicId,o).catch(()=>{}):t&&await bt(t,e.storyId).catch(()=>{})}}async function Ne(e,t,o){const r=await p(e.projectRoot,["rev-parse",`${o}^`]),i=await A(e.projectRoot,["show","--no-patch","--format=%B",o]),a=L(await A(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o])),h=Y(a,e.authorizedWriteSet,t,e.rootMemoryEffect);if(!h.ok)return n(h.reasonCode);e.rootMemoryEffect&&se(e.projectRoot,e.rootMemoryEffect,{storyId:t,executionBranch:e.executionBranch,baseSha:r,headRef:o,childPaths:e.authorizedWriteSet});const s=E([...e.authorizedWriteSet].sort().join("\0")),d=await Ve(e.projectRoot,t);if(d.state==="invalid")return n("direct-yolo-commit-plan-invalid");const c=d.state==="valid"?d.plan:void 0;if(c&&(c.epicId!==e.epicId||c.executionBranch!==e.executionBranch))return n("direct-yolo-commit-plan-invalid");if(c&&c.claimRevision!==s)return n("direct-yolo-commit-plan-claim-changed");if(c&&c.preparedBase!==r)return n("direct-yolo-commit-plan-base-mismatch");const l=pt(i);if(!l.ok)return n(`direct-yolo-trailer-duplicate:${l.key}`);const m=l.values,y=c?.graphRevision??e.graphRevision,f=s,v=[["Neocortex-Story",t],["Neocortex-Epic",e.epicId],["Neocortex-Execution-Branch",e.executionBranch],["Neocortex-Prepared-Base",r],["Neocortex-Bundle-Digest",c?.bundleDigest??""],["Neocortex-Graph-Revision",y],["Neocortex-Claim-Revision",f]];for(const[w,I]of v){const u=le(m,w);if(u===void 0)return n(`direct-yolo-trailer-missing:${pe(w)}`);if(w==="Neocortex-Bundle-Digest"&&!c){if(!/^[a-f0-9]{64}$/.test(u))return n(`direct-yolo-trailer-mismatch:${pe(w)}`);continue}if(u!==I)return n(`direct-yolo-trailer-mismatch:${pe(w)}`)}const x=le(m,"Neocortex-Bundle-Digest"),k=ee(e.projectRoot,t,o);if(k?.verdict!=="approved")return n("direct-yolo-review-artifact-not-approved");const D=le(m,"Neocortex-Review-Artifact-Digest");if(D!==void 0&&D!==k.digest)return n("direct-yolo-review-artifact-digest-mismatch");const j=E(await A(e.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]));if(x!==j)return n("direct-yolo-bundle-digest-mismatch");const b=ge({storyId:t,epicId:e.epicId,executionBranch:e.executionBranch,baseSha:r,bundleDigest:x,graphRevision:y,claimRevision:f});return c&&c.idempotencyKey!==b?n("direct-yolo-commit-plan-invalid"):{ok:!0,value:{baseSha:r,changedPaths:a,bundleDigest:x,graphRevision:y,claimRevision:f,idempotencyKey:b}}}async function Gt(e){try{const t=await K(e.projectRoot,e.storyId);if(!/^[a-f0-9]{40,64}$/.test(e.commitSha))return n("direct-yolo-recovery-commit-invalid");const o=await p(t.projectRoot,["rev-parse",e.commitSha]);if(ct[e.storyId]!==o)return n("direct-yolo-recovery-not-allowlisted");if(await p(t.projectRoot,["rev-parse","HEAD"])!==o)return n("direct-yolo-recovery-head-mismatch");await p(t.projectRoot,["merge-base","--is-ancestor",o,`refs/heads/${t.executionBranch}`]);const r=await p(t.projectRoot,["rev-parse",`${o}^`]),i=await A(t.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]),a=L(await A(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!Y(a,t.authorizedWriteSet.length>0?t.authorizedWriteSet:a,e.storyId).ok)return n("direct-yolo-recovery-write-set-invalid");const s=E(i),d=E([...a].sort().join("\0")),c=E(["legacy-direct-yolo-recovery-v1",e.storyId,o].join("\0")),l=$(e.nowIso),m=new Date(Date.parse(l)+oe).toISOString(),y=await H(t.projectRoot,{required:!0}),f=await V(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:c,idempotencyKey:c,expiresAt:m,persistent:!0,createdAt:l});if(!f.ok)return n(f.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const v={schemaVersion:1,ownerStoryId:e.storyId,sessionId:c,idempotencyKey:c,acquiredAt:l,expiresAt:m};let x=!1;try{const k=await C(t.projectRoot,u=>{const S=W(u,t.epicId),R=g(S.branch_lease);if(R&&Date.parse(String(R.expiresAt))>Date.parse(l)&&!Se(R,v))throw new Error("direct-yolo-recovery-writer-active");if(S.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");S.branch_mode="epic",S.execution_branch=t.executionBranch,S.origin_branch=t.originBranch,S.branch_lease=v},{expectedRevision:y.revision});x=!0;const D=await ke(e,t.projectRoot,o,t.graphRevision);if(!await be(t.projectRoot,t.executionBranch,o,a))return n("direct-yolo-recovery-head-raced");if(e.push){const u=U(e.remote??"origin"),S=(await p(t.projectRoot,["ls-remote","--heads",u,`refs/heads/${t.executionBranch}`])).split(/\s+/)[0];if(!S||!await B(t.projectRoot,["merge-base","--is-ancestor",o,S]))return n("direct-yolo-recovery-remote-proof-missing")}const j=await me({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:s,graphRevision:t.graphRevision,claimRevision:d,idempotencyKey:c,qaExecution:D,physicalLockOwnerDigest:de(f.owner),nowIso:l,legacyReceiptRef:void 0}),b=await it(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:s,graphRevision:t.graphRevision});if(!b)return n("direct-yolo-recovery-evidence-invalid");const w=Object.freeze({...j,receiptRefs:Object.freeze([...j.receiptRefs,b])});return await we({projectRoot:t.projectRoot,checkpoint:w,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:k.document.revision,expectedLease:v,expectedGraphRevision:t.graphRevision,physicalLockPath:f.path,physicalLockOwner:f.owner,transientAuthority:D.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:w}:n("direct-yolo-recovery-persist-failed")}finally{await G(f.path,f.owner).catch(()=>{}),x&&await xe(t.projectRoot,t.epicId,v).catch(()=>{})}}catch(t){return n(Z(t,"direct-yolo-recovery-failed"))}}async function We(e){const t=await ce(await p(e,["rev-parse","--absolute-git-dir"])),o=await ce(await p(e,["rev-parse","--path-format=absolute","--git-common-dir"]));return t!==o}async function Ke(e){const t=await H(e.projectRoot,{required:!0}),o=Object.values(t.storyWorktrees?.entries??{}).filter(m=>m.storyId===e.storyId&&m.epicId===e.epicId&&m.state==="active");if(o.length===0)throw new Error("direct-yolo-worktree-lease-missing");if(o.length>1)throw new Error("direct-yolo-worktree-lease-ambiguous");const r=o[0];if(r.executionBranch!==e.executionBranch)throw new Error("direct-yolo-worktree-branch-mismatch");if(await ce(await p(e.projectRoot,["rev-parse","--show-toplevel"]))!==r.worktreePath)throw new Error("direct-yolo-worktree-path-mismatch");if(await p(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]).catch(()=>"")!==r.temporaryBranch)throw new Error("direct-yolo-worktree-branch-mismatch");const h=await new lt({projectRoot:e.projectRoot}).probe(r.leaseId);if(!h.ok||h.value.ownership!=="proven")throw new Error("direct-yolo-worktree-ownership-unproven");const s=X(g(t.epics[e.epicId])?.origin_binding,e.executionBranch,e.originBranch);if(!s)throw new Error("direct-yolo-origin-binding-invalid");const d=r.syncedSha??r.baseSha,c=await p(e.projectRoot,["rev-parse","HEAD"]),l=`refs/heads/${e.executionBranch}`;if(c!==d||!await B(e.projectRoot,["merge-base","--is-ancestor",d,l])||!await B(e.projectRoot,["merge-base","--is-ancestor",s.originHeadSha,d]))throw new Error("direct-yolo-worktree-base-divergent");if(h.value.clean!==!0||(await A(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-worktree-dirty");return{leaseId:r.leaseId,temporaryBranch:r.temporaryBranch,authorizedBase:d,headSha:c,expiresAt:r.expiresAt,binding:s}}function Te(e,t,o){return Object.freeze({...ae(e,t.binding,t.expiresAt,o),workspace:"story-worktree",temporaryBranch:t.temporaryBranch,baseSha:t.authorizedBase})}async function yt(e){const t=await Ke(e),o=Q(e.projectRoot,".neocortex/state.json"),r=await N(o,"utf8"),i=g(JSON.parse(r)),a=g(g(i?.stories)?.[e.storyId]),h=await H(e.projectRoot,{required:!0}),s=g(h.stories[e.storyId]);if(!a||!["backlog","ready_to_start"].includes(String(a.status))||a.steps_completed!==void 0&&(!Array.isArray(a.steps_completed)||a.steps_completed.length>0)||a.branch_name||a.checkpoint)return n("direct-yolo-setup-story-progress-conflict");const d=s?.status==="branch-ready"&&s.last_step===P&&Array.isArray(s.steps_completed)&&s.steps_completed.length===1&&s.steps_completed[0]===P&&J(s).sort().join(",")==="last_step,status,steps_completed";return s&&J(s).length>0&&!d?n("direct-yolo-setup-story-progress-conflict"):(d||await C(e.projectRoot,c=>{const l=he(c,e.storyId);if(J(l).length>0)throw new Error("direct-yolo-setup-runtime-raced");l.status="branch-ready",l.last_step=P,l.steps_completed=[P]},{expectedRevision:h.revision,preCommit:async()=>{if(await N(o,"utf8")!==r||await p(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==t.temporaryBranch||await p(e.projectRoot,["rev-parse","HEAD"])!==t.headSha||(await A(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-setup-physical-state-raced")}}),{ok:!0,value:Object.freeze({...Te(e,t,d),checkpointAccepted:!0,graphRevision:e.graphRevision,headSha:t.headSha})})}async function Ft(e,t){const o=await K(e,t),r=await H(o.projectRoot,{required:!0}),i=X(g(r.epics[o.epicId])?.origin_binding,o.executionBranch,o.originBranch);return{...o,originBinding:i}}function Yt(e,t,o,r){return Y(e,t,o,r)}function Jt(e){return E(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const Zt=oe,mt="p205-wave:";function Qt(e){if(e.waveStoryIds.length===0||e.waveStoryIds.length!==e.waveCommitShas.length||e.waveCommitShas[e.waveCommitShas.length-1]!==e.waveHeadSha||e.waveCommitShas.some(o=>!/^[a-f0-9]{40,64}$/.test(o)))throw new Error("direct-yolo-wave-coverage-invalid");const t=E(["p205-wave-coverage-v1",e.epicId,e.executionBranch,e.waveHeadSha,...e.waveStoryIds.map((o,r)=>`${o}=${e.waveCommitShas[r]}`)].join("\0"));return Object.freeze({kind:"wave",waveHeadSha:e.waveHeadSha,waveStoryIds:Object.freeze([...e.waveStoryIds]),waveCommitShas:Object.freeze([...e.waveCommitShas]),waveDigest:t})}function wt(e){return`${mt}${e.waveHeadSha}:${e.waveDigest}`}async function Ut(e){let t;try{t=await at(e.projectRoot,{headSha:e.headSha,graphRevisions:e.graphRevisions,...e.nowIso!==void 0?{nowIso:e.nowIso}:{}})}catch(o){const r=o instanceof Error?o.message:"";return/^p205-transient-[a-z0-9-]{1,64}$/.test(r)?{ok:!1,headSha:e.headSha,kind:"infrastructure",reasonCode:r}:{ok:!1,headSha:e.headSha,kind:"gate-failed",reasonCode:"p205-complete-gate-failed"}}try{await e.qaRunner?.({projectRoot:e.projectRoot,storyId:e.storyId,headSha:e.headSha})}catch(o){const r=o instanceof Error?o.message:"";return{ok:!1,headSha:e.headSha,kind:"gate-failed",reasonCode:/^p205-[a-z0-9-]{1,64}$/.test(r)?r:"p205-complete-gate-failed"}}return{ok:!0,headSha:e.headSha,authorities:t}}async function Xt(e,t,o,r){const i=U(t);return await p(e,["push",i,o]),De(e,i,o,r)}async function er(e){try{const t=await K(e.projectRoot,e.storyId),o=e.coverage.waveHeadSha,r=e.coverage.waveStoryIds.indexOf(e.storyId);if(r<0||e.coverage.waveCommitShas[r]!==e.headSha)return n("direct-yolo-wave-coverage-invalid");if(await p(t.projectRoot,["rev-parse","HEAD"])!==o||await p(t.projectRoot,["rev-parse",`refs/heads/${t.executionBranch}`])!==o||!await B(t.projectRoot,["merge-base","--is-ancestor",e.headSha,o]))return n("direct-yolo-wave-head-raced");const i=await H(t.projectRoot,{required:!0}),a=g(i.stories[e.storyId]?.checkpoint);if(a){if(a.headSha!==e.headSha)return n("direct-yolo-checkpoint-conflict");const D=e.authorities.get(String(a.graphRevision));return await fe(t.projectRoot,a,e.storyId,t.epicId,t.executionBranch,D??null,t.authorizedWriteSet)?(await ie(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:a}):n("direct-yolo-replay-invalid")}const h=await Ne(t,e.storyId,e.headSha);if(!h.ok)return n(h.reasonCode);const{baseSha:s,bundleDigest:d,graphRevision:c,claimRevision:l,idempotencyKey:m}=h.value,y=r===0?void 0:e.coverage.waveCommitShas[r-1];if(y!==void 0&&s!==y)return n("direct-yolo-wave-chain-invalid");const f=e.authorities.get(c),v=Oe(f);if(!f||!v||v.executionHeadSha!==o||v.graphRevision!==c)return n("direct-yolo-wave-qa-unbound");const x=await me({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:s,headSha:e.headSha,bundleDigest:d,graphRevision:c,claimRevision:l,idempotencyKey:m,qaExecution:{contract:"P205-CI-02",command:Pe,manifestDigest:v.manifestDigest,gateIds:v.gateIds,resultDigest:v.resultDigest,transientAuthority:f},physicalLockOwnerDigest:de(e.physicalLock.owner),nowIso:$(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:t.rootMemoryEffect,extraReceiptRefs:[wt(e.coverage)]});return await we({projectRoot:t.projectRoot,checkpoint:x,remote:e.remote,expectedRevision:i.revision,expectedLease:e.expectedLease,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:c,physicalLockPath:e.physicalLock.path,physicalLockOwner:e.physicalLock.owner,transientAuthority:f,authorizedWriteSet:t.authorizedWriteSet,expectedHeadSha:o,keepLease:!0})?(await ie(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:x}):n("direct-yolo-checkpoint-persist-failed")}catch(t){return n(Z(t,"direct-yolo-wave-persist-failed"))}}async function ye(e,t){if(!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(t))throw new Error("direct-yolo-story-id-invalid");const o=M(e),r=g(JSON.parse(await N(Q(o,".neocortex/state.json"),"utf8"))),i=await H(o,{required:!0}),a=tt(r,i),h=g(a.stories),s=g(a.epics),d=g(h?.[t]),c=String(d?.epic_id??t.split(".")[0]),l=g(s?.[c]),m=String(l?.execution_branch??""),y=String(l?.origin_branch??""),f=String(l?.graph_revision??""),v=dt(d),x=Array.isArray(d?.files_to_modify)||v.length>0?[...new Set([...Array.isArray(d?.files_to_modify)?d.files_to_modify:[],...v].filter(D=>typeof D=="string"&&je(D)))].sort():[];if(!d)throw new Error("direct-yolo-story-state-missing");if(v.length>0&&x.length>st)throw new Error("direct-yolo-write-set-too-large");if(l?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!Ee(m)||!await B(o,["check-ref-format","--branch",m]))throw new Error("direct-yolo-execution-branch-invalid");if(!Ee(y)||!await B(o,["check-ref-format","--branch",y]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(f))throw new Error("direct-yolo-graph-revision-invalid");const k=await Xe({projectRoot:o,storyId:t,graphRevision:f,executionBranch:m,childPaths:x});return{projectRoot:o,storyId:t,story:d,epicId:c,executionBranch:m,originBranch:y,graphRevision:f,authorizedWriteSet:x,rootMemoryEffect:k}}async function K(e,t){const o=await ye(e,t);if(await p(o.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return o}async function me(e){const t=e.nowIso,o=await A(e.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),r=L(await A(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=rt({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),a=ot({gitEvidenceDigest:i,headSha:e.headSha,graphRevision:e.graphRevision,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest}),h=`story-qa:${a}`,s=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,contract:e.qaExecution.contract,command:e.qaExecution.command,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest,sourceEvidenceDigest:a,verdict:"passed",checkedAt:t,receiptRef:h}),d=ee(e.projectRoot,e.storyId,e.headSha);if(d?.verdict!=="approved")throw new Error("direct-yolo-review-artifact-not-approved");const c=E(["root-commit-range-review-v2",e.storyId,e.baseSha,e.headSha,e.bundleDigest,e.graphRevision,h,E(o),[...r].sort().join(","),d.digest].join("\0")),l=`story-review:${c}`,m=Object.freeze({schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,sourceEvidenceDigest:c,reviewArtifactDigest:d.digest,qaReceiptRef:h,verdict:"approved",reviewedAt:t,receiptRef:l}),y=[`.neocortex/stories/${e.storyId}/qa-gate-result.json`,`.neocortex/stories/${e.storyId}/validation-evidence.md`,h,l,...e.physicalLockOwnerDigest?[`physical-lock-owner:${e.physicalLockOwnerDigest}`]:[],...e.legacyReceiptRef?[e.legacyReceiptRef]:[],...e.extraReceiptRefs??[]];return Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:e.epicId,branch:e.executionBranch,baseSha:e.baseSha,headSha:e.headSha,commits:Object.freeze([e.headSha]),idempotencyKey:e.idempotencyKey,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,claimRevision:e.claimRevision,receiptRefs:Object.freeze(y),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:s,reviewReceipt:m,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function we(e){const{projectRoot:t,checkpoint:o,remote:r}=e;let i=!1;return await C(t,a=>{const h=W(a,o.epicId);if(e.expectedLease){const l=g(h.branch_lease);if(!Se(l,e.expectedLease))throw new Error("direct-yolo-runtime-revision-conflict");if(Date.parse(String(l?.expiresAt))<=Date.now())throw new Error("direct-yolo-writer-lease-expired");if(h.graph_revision!==e.expectedGraphRevision||o.graphRevision!==(e.expectedCheckpointGraphRevision??e.expectedGraphRevision))throw new Error("direct-yolo-graph-revision-raced")}const s=he(a,o.storyId),d=g(s.checkpoint);if(d&&d.headSha!==o.headSha){i=!0;return}s.checkpoint=o,s.status="done",s.last_step=ze;const c=Array.isArray(s.steps_completed)?s.steps_completed.filter(l=>typeof l=="string"):[];s.steps_completed=[...new Set([...c,ut,ze])],e.keepLease||(h.branch_lease=null)},{expectedRevision:e.expectedRevision,preCommit:async()=>{if(i)throw new Error("direct-yolo-checkpoint-conflict");const a=e.expectedHeadSha??o.headSha;if(await p(t,["symbolic-ref","--quiet","--short","HEAD"])!==o.branch||await p(t,["rev-parse","HEAD"])!==a||await p(t,["rev-parse",`refs/heads/${o.branch}`])!==a||!await B(t,["merge-base","--is-ancestor",o.headSha,a]))throw new Error("direct-yolo-checkpoint-head-raced");if(!await fe(t,o,o.storyId,o.epicId,o.branch,e.transientAuthority,e.authorizedWriteSet))throw new Error("direct-yolo-checkpoint-physical-invalid");if(e.physicalLockPath&&e.physicalLockOwner&&!await re(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(r&&!(e.remotePolicy==="ancestor-recovery"?await Me(t,r,o.branch,o.headSha):await De(t,r,o.branch,a)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function Me(e,t,o,r){const i=U(t),a=(await p(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0];return!!(a&&await B(e,["merge-base","--is-ancestor",r,a]))}function ge(e){return E(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const gt=["schemaVersion","kind","storyId","epicId","executionBranch","graphRevision","preparedBase","bundleDigest","claimRevision","idempotencyKey","issuedAt"];async function ve(e,t){const o=await $e(e),r=await Le(o,"commit-plans"),i=`direct-${E(t)}.json`;return{parent:r,name:i,path:Q(r,i)}}async function vt(e,t){const o=await ve(e,t.storyId);await qe(o.parent,o.name,`${JSON.stringify(t,null,2)}
2
- `),await te(o.path,o.parent)}async function Ve(e,t){let o;try{o=await ve(e,t)}catch{return{state:"invalid"}}try{if(!Ce(o.path))return{state:"absent"};await te(o.path,o.parent);const r=await N(o.path,"utf8");if(r.length>16*1024)return{state:"invalid"};const i=g(JSON.parse(r));if(!i||Object.keys(i).sort().join("\0")!==[...gt].sort().join("\0")||i.schemaVersion!==1||i.kind!=="direct-yolo-commit-plan"||i.storyId!==t||typeof i.epicId!="string"||typeof i.executionBranch!="string"||!Ee(i.executionBranch)||typeof i.preparedBase!="string"||!/^[a-f0-9]{40,64}$/.test(i.preparedBase)||![i.graphRevision,i.bundleDigest,i.claimRevision,i.idempotencyKey].every(h=>typeof h=="string"&&/^[a-f0-9]{64}$/.test(h))||typeof i.issuedAt!="string"||!Number.isFinite(Date.parse(i.issuedAt)))return{state:"invalid"};const a=i;return a.idempotencyKey!==ge({...a,baseSha:a.preparedBase})?{state:"invalid"}:{state:"valid",plan:a}}catch{return{state:"invalid"}}}async function ie(e,t){const o=await ve(e,t);Ce(o.path)&&await ft(o.parent,o.name)}function Re(e,t,o){return!!(e?.ownerStoryId===t&&e.sessionId===e.idempotencyKey&&typeof e.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(e.idempotencyKey)&&typeof e.expiresAt=="string"&&Date.parse(e.expiresAt)>Date.parse(o))}async function Ge(e,t){const o=await $e(e),r=await Le(o,"handoffs"),i=`direct-${E(t)}.json`;return{parent:r,name:i,path:Q(r,i)}}async function Ie(e,t){const o=await Ge(e,t.storyId);await qe(o.parent,o.name,`${JSON.stringify(t,null,2)}
3
- `),await te(o.path,o.parent)}async function F(e,t){try{const o=await Ge(e,t);await te(o.path,o.parent);const r=JSON.parse(await N(o.path,"utf8")),i=r.state==="issued"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt"]:r.state==="consuming"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumeStartedAt"]:["schemaVersion","kind","state","storyId","fromSessionId","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumedAt"];return Object.keys(r).sort().join("\0")!==[...i].sort().join("\0")||r.schemaVersion!==1||r.kind!=="direct-yolo-setup-handoff-token"||r.state!=="issued"&&r.state!=="consuming"&&r.state!=="consumed"||r.storyId!==t||typeof r.fromSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(r.fromSessionId)||![r.tokenDigest,r.bundleDigest,r.claimRevision,r.grantDigest].every(a=>typeof a=="string"&&/^[a-f0-9]{64}$/.test(a))||typeof r.expiresAt!="string"||!Number.isFinite(Date.parse(r.expiresAt))||(r.state==="issued"||r.state==="consuming")&&(typeof r.token!="string"||!/^[A-Za-z0-9_-]{32,256}$/.test(r.token))||r.state==="consuming"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumeStartedAt!="string"||!Number.isFinite(Date.parse(r.consumeStartedAt)))||r.state==="consumed"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumedAt!="string"||!Number.isFinite(Date.parse(r.consumedAt)))?void 0:r}catch{return}}async function Rt(e,t,o,r,i){const a=await F(e,t);if(!(!a||a.state==="consumed"||!a.token||a.bundleDigest!==o||a.claimRevision!==r||Date.parse(a.expiresAt)<=Date.parse(i)||E(a.token)!==a.tokenDigest))return{sessionId:a.fromSessionId,token:a.token}}async function It(e,t,o,r,i,a){const h=await F(e,t);if(!h||h.state==="consumed"||h.fromSessionId!==o||h.token!==r||h.tokenDigest!==E(r))throw new Error("direct-yolo-setup-handoff-consume-invalid");if(h.state==="consuming"){if(h.consumedBySessionId!==i)throw new Error("direct-yolo-setup-handoff-consume-raced");return}await Ie(e,{...h,state:"consuming",consumedBySessionId:i,consumeStartedAt:a})}async function St(e,t,o,r,i,a,h,s,d){const c=await F(e,o);if(c?.state==="consumed"&&c.fromSessionId===r&&c.consumedBySessionId===s)return;const l=await H(e,{required:!0}),m=g(l.epics[t]?.branch_lease),y=g(m?.handoffConsumption);if(!c||c.state!=="consuming"||c.fromSessionId!==r||c.token!==i||c.tokenDigest!==E(i)||c.bundleDigest!==a||c.claimRevision!==h||c.consumedBySessionId!==s||m?.ownerStoryId!==o||m.sessionId!==s||y?.kind!=="direct-yolo-setup-handoff-consumption"||y.state!=="consumed"||y.fromSessionId!==r||y.tokenDigest!==c.tokenDigest||y.bundleDigest!==a||y.claimRevision!==h||y.consumedBySessionId!==s)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await Ie(e,{schemaVersion:1,kind:c.kind,state:"consumed",storyId:o,fromSessionId:r,tokenDigest:c.tokenDigest,bundleDigest:c.bundleDigest,claimRevision:c.claimRevision,grantDigest:c.grantDigest,expiresAt:c.expiresAt,consumedBySessionId:s,consumedAt:d})}catch{throw new Error("direct-yolo-setup-handoff-consume-persist-failed")}}function xt(e){const t=g(e.current?.handoffGrant),o=e.handoff?.token,r=typeof o=="string"&&/^[A-Za-z0-9_-]{32,256}$/.test(o)?E(o):void 0;return!!(t&&r&&e.handoff&&e.handoff.sessionId===e.current?.sessionId&&t.schemaVersion===1&&t.kind==="direct-yolo-setup-handoff"&&t.storyId===e.storyId&&t.fromSessionId===e.current?.sessionId&&t.bundleDigest===e.bundleDigest&&t.claimRevision===e.claimRevision&&typeof t.expiresAt=="string"&&Date.parse(t.expiresAt)>Date.parse(e.nowIso)&&typeof t.tokenDigest=="string"&&/^[a-f0-9]{64}$/.test(t.tokenDigest)&&kt(t.tokenDigest,r))}function kt(e,t){const o=Buffer.from(e,"hex"),r=Buffer.from(t,"hex");return o.length===32&&r.length===32&&Qe(o,r)}function Se(e,t){return!!(e&&["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt"].every(o=>e[o]===t[o]))}async function xe(e,t,o){await C(e,r=>{const i=W(r,t),a=g(i.branch_lease);Se(a,o)&&(i.branch_lease=null)})}async function bt(e,t){const o=await H(e.projectRoot,{required:!0}),r=g(o.epics[e.epicId]?.branch_lease);if(!r||r.ownerStoryId!==t||!Fe(r.sessionId)||!Fe(r.idempotencyKey)||!Number.isFinite(Date.parse(String(r.acquiredAt)))||!Number.isFinite(Date.parse(String(r.expiresAt))))return;const i=await V(e.projectRoot,{kind:"direct",storyId:t,sessionId:String(r.sessionId),idempotencyKey:String(r.idempotencyKey),createdAt:String(r.acquiredAt),expiresAt:String(r.expiresAt),persistent:!0});if(!i.ok)return;await G(i.path,i.owner)&&await xe(e.projectRoot,e.epicId,r)}async function ke(e,t,o,r){const i=await nt(t,{headSha:o,graphRevision:r,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:o});const a=Oe(i);if(!a)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:Pe,manifestDigest:a.manifestDigest,gateIds:a.gateIds,resultDigest:a.resultDigest,transientAuthority:i}}async function be(e,t,o,r){return await p(e,["rev-parse","HEAD"])!==o||await p(e,["symbolic-ref","--quiet","--short","HEAD"])!==t||!await B(e,["diff","--cached","--quiet"])?!1:B(e,["diff","--quiet","HEAD","--",...r])}async function De(e,t,o,r){const i=U(t);return(await p(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0]===r}function Y(e,t,o,r){if(e.length===0||e.some(a=>!je(a)))return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};const i=[".neocortex/state.json",`docs/stories/${o}.story.md`,`.neocortex/stories/${o}/qa-gate-result.json`,`.neocortex/stories/${o}/validation-evidence.md`,`.neocortex/stories/${o}/review.md`];return!i.every(a=>e.includes(a))||!i.every(a=>t.includes(a))?{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}:r&&(r.storyId!==o||r.childClaimRevision!==E([...t].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(a=>!t.includes(a)&&!r?.files.some(h=>h.path===a))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}}function J(e){return Object.keys(e).filter(t=>t!=="write_set_extension")}function je(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").includes("..")&&!e.startsWith(".git/")&&!e.includes("\0")}function Fe(e){return typeof e=="string"&&e.length>0&&e.length<=512&&/^[A-Za-z0-9._:@/+\-=]+$/.test(e)}function Ee(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!/[\s~^:?*[\\]/.test(e)&&!e.includes("..")}function U(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function E(e){return Ze("sha256").update(e).digest("hex")}function L(e){return e.split("\0").filter(Boolean)}function $(e){return e&&Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function g(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Dt(e,t,o,r,i){const a=g(e.expectedLease),h=a?.sessionId,s=Date.parse(String(a?.expiresAt??""));return e.schemaVersion===1&&Number.isSafeInteger(e.expectedRuntimeRevision)&&e.expectedRuntimeRevision===t&&!!o&&JSON.stringify(o)===JSON.stringify(a)&&a?.schemaVersion===1&&a.ownerStoryId===r&&typeof h=="string"&&/^setup-[a-f0-9]{64}$/.test(h)&&a.idempotencyKey===h&&Number.isFinite(s)&&s<=i}async function jt(e,t){let o=await p(e,["symbolic-ref","--quiet","--short","HEAD"]);if(o===t.executionBranch){if(await p(e,["rev-parse","HEAD"])!==t.originHead||await O(e)!==t.checkoutBefore)return;await p(e,["switch",t.originBranch]),o=t.originBranch}if(o!==t.originBranch||await p(e,["rev-parse","HEAD"])!==t.originHead||await O(e)!==t.checkoutBefore||t.executionHead===t.originHead||!await B(e,["show-ref","--verify","--quiet",t.executionRef]))return;await p(e,["rev-parse",t.executionRef])===t.originHead&&await p(e,["update-ref",t.executionRef,t.executionHead,t.originHead])}function X(e,t,o){const r=g(e);if(!(!r||r.schemaVersion!==1||r.originBranch!==o||r.executionBranch!==t||r.capturedFromCurrentCheckout!==!0||typeof r.originHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(r.originHeadSha)||typeof r.capturedAt!="string"||!Number.isFinite(Date.parse(r.capturedAt))))return r}function ae(e,t,o,r){return Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-receipt",storyId:e.storyId,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,originHeadSha:t.originHeadSha,leaseExpiresAt:o,reused:r,publicSafe:!0})}async function O(e){const t=L(await A(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=await Promise.all(t.map(async r=>{if(!je(r))throw new Error("direct-yolo-checkout-payload-invalid");return`${r}\0${await p(e,["hash-object","--no-filters","--",r])}`}));return E([await A(e,["diff","--cached","--binary","--full-index"]),await A(e,["diff","--binary","--full-index"]),await A(e,["status","--porcelain=v1","-z","--untracked-files=all"]),...o].join("\0"))}async function tr(e){const t=M(e),o=await p(t,["rev-parse","HEAD"]),r=await p(t,["symbolic-ref","--quiet","--short","HEAD"]),i=await O(t);if(await p(t,["rev-parse","HEAD"])!==o||await p(t,["symbolic-ref","--quiet","--short","HEAD"])!==r)throw new Error("direct-yolo-checkout-observation-raced");return Object.freeze({headSha:o,branch:r,payloadDigest:i})}async function Ae(e){const t=[];let o;for(const r of(await A(e,["worktree","list","--porcelain"])).split(`
4
- `))r.startsWith("worktree ")?(o={path:r.slice(9)},t.push(o)):o&&r.startsWith("branch refs/heads/")&&(o.branch=r.slice(18));return t}function Z(e,t){return e instanceof Error&&e.message==="git-lifecycle-runtime-revision-conflict"?"direct-yolo-runtime-revision-conflict":e instanceof Error&&/^direct-yolo-[a-z0-9-]+(?::[a-z0-9-]+)?$/.test(e.message)?e.message:t}function n(e){return{ok:!1,reasonCode:e}}async function p(e,t){return String((await ue("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function A(e,t){return String((await ue("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function B(e,t){try{return await ue("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{Zt as DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS,mt as DIRECT_YOLO_WAVE_RECEIPT_REF_PREFIX,Kt as acceptDirectYoloSetupCheckpoint,Mt as beginDirectYoloStoryCommit,tr as captureDirectYoloCheckoutEvidence,Jt as directYoloCommitIdempotencyKey,Qt as directYoloWaveQaCoverage,wt as directYoloWaveReceiptRef,Vt as finalizeDirectYoloStoryCheckpoint,Tt as issueDirectYoloSetupLeaseHandoff,er as persistDirectYoloWaveStoryCheckpoint,Wt as prepareDirectYoloSetup,Xt as pushDirectYoloWaveHead,Gt as recoverLegacyDirectYoloStoryCheckpoint,Ft as resolveDirectYoloIntegrationAuthority,Ut as runDirectYoloWaveP205,Yt as validateDirectYoloWriteSet};
1
+ import{execFile as ot}from"node:child_process";import{createHash as it,randomBytes as $e,timingSafeEqual as nt}from"node:crypto";import{existsSync as Pe}from"node:fs";import{readFile as P,realpath as he}from"node:fs/promises";import{join as G,resolve as O}from"node:path";import{promisify as at}from"node:util";import{readRootMemoryEffectForCheckpoint as ct}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as st,verifyRootMemoryPhysicalWriteSet as ue}from"../private-execution/root-memory-git-evidence.js";import{resolveBranchUnit as dt,resolveEpicStoryIds as ft}from"../../../shared/dist/yoloop/branch-unit.js";import{expandStoryWriteScope as qe,storyWriteSetCovers as ht,validateStoryWriteScope as ut}from"../../../shared/dist/yoloop/story-write-scope.js";import{acquireGitLifecyclePhysicalIntegrationLock as F,applyGitLifecycleRuntimeOverlay as le,computeImmutableStoryQaEvidenceDigest as lt,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as pe,computeP205StoryQaEvidenceDigest as pt,computeLegacyDirectYoloRecoveryReceiptRef as yt,ensureRuntimeEpic as M,ensureRuntimeStory as ye,ensureGitLifecyclePrivateChildDirectory as Ne,executeP205TransientAuthorities as gt,executeP205TransientAuthority as mt,isP226GateReasonCode as ge,projectP205TransientExecutionEvidence as ze,publicStoryReviewArtifactFromGit as oe,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as wt,mutateGitLifecycleRuntime as L,P205_COMPLETE_COMMAND as Te,readGitLifecycleRuntime as C,gitLifecycleRuntimeDirectory as Me,STORY_WRITE_SET_MAX_ENTRIES as vt,storyWriteSetExtensionPaths as Rt,assertGitLifecyclePrivateFile as ie,releaseGitLifecyclePhysicalIntegrationLock as Y,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as It,verifyGitLifecyclePhysicalIntegrationLock as ne,verifyAcceptedGitLifecycleStoryCheckpoint as me}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as We,anchoredRemoveFile as St}from"./secure-filesystem-boundary.js";import{parseNeocortexTrailers as xt,trailerReasonKey as we,trailerValue as ve}from"./neocortex-trailers.js";import{StoryWorktreeManager as bt}from"./story-worktree-manager.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as kt,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as Ge,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as W}from"./git-lifecycle-step-ids.js";const ee=at(ot),ae=3600*1e3;async function dr(e){let t,o=!1;try{const r=await Re(e.projectRoot,e.storyId);if(await Ke(r.projectRoot)){if(e.expiredSetupRecovery)return s("direct-yolo-expired-setup-recovery-invalid");const m=await Fe(r);return{ok:!0,value:Ye(r,m,!1)}}const i=N(e.nowIso),n=Date.parse(i),f=await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),c=await l(r.projectRoot,["rev-parse","HEAD"]),d=await C(r.projectRoot,{required:!0}),a=p(d.epics[r.epicId]),u=p(a?.branch_lease),g=e.expiredSetupRecovery;if(g&&!qt(g,d.revision,u,e.storyId,n))return s("direct-yolo-expired-setup-recovery-invalid");const w=u&&Number.isFinite(Date.parse(String(u.expiresAt)))&&Date.parse(String(u.expiresAt))>n;if(w&&u?.ownerStoryId!==e.storyId)return s("direct-yolo-writer-active");let h=K(a?.origin_binding,r.executionBranch,r.originBranch),v;if(f===r.executionBranch){if(!h){if(a?.origin_binding!==void 0&&a?.origin_binding!==null||w)return s("direct-yolo-origin-binding-invalid");const m=await Mt(r,c,i);if(!m.ok)return m;h=m.value.binding,v={originRef:m.value.originRef,originHeadSha:m.value.binding.originHeadSha}}}else{if(f!==r.originBranch)return s("direct-yolo-current-branch-mismatch");if(h&&h.originHeadSha!==c){if(!g||!await B(r.projectRoot,["merge-base","--is-ancestor",h.originHeadSha,c]))return s("direct-yolo-origin-binding-conflict");const y=`refs/heads/${r.executionBranch}`;if(!await B(r.projectRoot,["show-ref","--verify","--quiet",y]))return s("direct-yolo-execution-branch-missing");const x=await l(r.projectRoot,["rev-parse",y]);if(!await B(r.projectRoot,["merge-base","--is-ancestor",x,c]))return s("direct-yolo-execution-branch-diverged")}if(h??={schemaVersion:1,originBranch:r.originBranch,originHeadSha:c,executionBranch:r.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:i},(await re(r.projectRoot)).some(y=>y.branch===r.executionBranch&&O(y.path)!==r.projectRoot))return s("direct-yolo-execution-branch-checked-out-elsewhere");const S=await z(r.projectRoot),I=`refs/heads/${r.executionBranch}`;if(await B(r.projectRoot,["show-ref","--verify","--quiet",I])){const y=await l(r.projectRoot,["rev-parse",I]);if(y!==c){if(!await B(r.projectRoot,["merge-base","--is-ancestor",y,c]))return s("direct-yolo-execution-branch-diverged");g||await l(r.projectRoot,["update-ref",I,c,y])}g?t={checkoutBefore:S,executionRef:I,executionBranch:r.executionBranch,executionHead:y,originBranch:r.originBranch,originHead:c}:await l(r.projectRoot,["switch",r.executionBranch])}else{if(g)return s("direct-yolo-execution-branch-missing");await l(r.projectRoot,["switch","-c",r.executionBranch])}if(!t&&await z(r.projectRoot)!==S)return s("direct-yolo-checkout-payload-raced")}const R=t?.originHead??await l(r.projectRoot,["rev-parse","HEAD"]);if(!t&&await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)return s("direct-yolo-current-branch-mismatch");if(w&&u?.ownerStoryId===e.storyId)return u.setupHeadSha!==R?s("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:de(r,h,String(u.expiresAt),!0)};const b=i,k=new Date(n+3600*1e3).toISOString(),D=`setup-${$e(32).toString("hex")}`,j=g?d:await C(r.projectRoot,{required:!0});return await L(r.projectRoot,m=>{const S=M(m,r.epicId),I=p(S.branch_lease);if(g&&JSON.stringify(I)!==JSON.stringify(g.expectedLease))throw new Error("direct-yolo-expired-setup-recovery-raced");if(I&&Date.parse(String(I.expiresAt))>n&&I.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const y=K(S.origin_binding,r.executionBranch,r.originBranch);if(S.origin_binding&&!y)throw new Error("direct-yolo-origin-binding-conflict");if(y&&JSON.stringify(y)!==JSON.stringify(h))throw new Error("direct-yolo-origin-binding-conflict");S.branch_mode="epic",S.execution_branch=r.executionBranch,S.origin_branch=r.originBranch,S.graph_revision=r.graphRevision,S.origin_binding=h,S.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:D,idempotencyKey:D,acquiredAt:b,expiresAt:k,setupHeadSha:R}},{expectedRevision:g?.expectedRuntimeRevision??j.revision,preCommit:async()=>{if(t){if((await re(r.projectRoot)).some(S=>S.branch===r.executionBranch&&O(S.path)!==r.projectRoot)||await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.originBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==t.originHead||await z(r.projectRoot)!==t.checkoutBefore||!await B(r.projectRoot,["show-ref","--verify","--quiet",t.executionRef])||await l(r.projectRoot,["rev-parse",t.executionRef])!==t.executionHead)throw new Error("direct-yolo-expired-setup-recovery-raced");if(o=!0,t.executionHead!==t.originHead&&await l(r.projectRoot,["update-ref",t.executionRef,t.originHead,t.executionHead]),await l(r.projectRoot,["switch",r.executionBranch]),await z(r.projectRoot)!==t.checkoutBefore)throw new Error("direct-yolo-checkout-payload-raced")}if(await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==R)throw new Error("direct-yolo-setup-physical-state-raced");if(v&&(await l(r.projectRoot,["rev-parse","--verify","--quiet",`${v.originRef}^{commit}`]).catch(()=>"")!==v.originHeadSha||await He(r.projectRoot,["merge-base","--is-ancestor",v.originHeadSha,R])!==0))throw new Error("direct-yolo-origin-ref-raced")}}),{ok:!0,value:de(r,h,k,!1)}}catch(r){return o&&t&&await Nt(O(e.projectRoot),t).catch(()=>{}),s(X(r,"direct-yolo-setup-failed"))}}async function fr(e){let t;try{const o=await Re(e.projectRoot,e.storyId);if(await Ke(o.projectRoot))return await Dt(o);const r=await V(e.projectRoot,e.storyId),i=N(e.nowIso),n=G(r.projectRoot,".neocortex/state.json"),f=await P(n,"utf8"),c=await z(r.projectRoot),d=await l(r.projectRoot,["rev-parse","HEAD"]),a=`refs/heads/${r.executionBranch}`,u=await C(r.projectRoot,{required:!0}),g=p(u.epics[r.epicId]),w=K(g?.origin_binding,r.executionBranch,r.originBranch),h=p(g?.branch_lease);if(!w)return s("direct-yolo-origin-binding-invalid");if(!h||!ke(h,e.storyId,i)||h?.sessionId!==h?.idempotencyKey)return s("direct-yolo-setup-lease-invalid");const v=await F(r.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:String(h.sessionId),idempotencyKey:String(h.idempotencyKey),expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1});if(!v.ok)return s(v.reasonCode);if(t=v,d!==h.setupHeadSha||!await B(r.projectRoot,["merge-base","--is-ancestor",w.originHeadSha,d])||await l(r.projectRoot,["rev-parse",a])!==d)return s("direct-yolo-setup-head-mismatch");if((await re(r.projectRoot)).some(S=>S.branch===r.executionBranch&&O(S.path)!==r.projectRoot))return s("direct-yolo-execution-branch-checked-out-elsewhere");const b=p(JSON.parse(f)),k=p(p(b?.stories)?.[e.storyId]),D=p(u.stories[e.storyId]);if(!k||!["backlog","ready_to_start"].includes(String(k.status))||k.steps_completed!==void 0&&(!Array.isArray(k.steps_completed)||k.steps_completed.length>0)||k.branch_name||k.checkpoint)return s("direct-yolo-setup-story-progress-conflict");const j=D?.status==="branch-ready"&&D.last_step===W&&Array.isArray(D.steps_completed)&&D.steps_completed.length===1&&D.steps_completed[0]===W&&U(D).sort().join(",")==="last_step,status,steps_completed";if(D&&U(D).length>0&&!j)return s("direct-yolo-setup-story-progress-conflict");const m=async()=>{if(Date.parse(String(h.expiresAt))<=(e.nowIso?Date.parse(i):Date.now())||!t||!await ne(t.path,t.owner)||await P(n,"utf8")!==f||await z(r.projectRoot)!==c||await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==d||!await B(r.projectRoot,["merge-base","--is-ancestor",w.originHeadSha,d])||await l(r.projectRoot,["rev-parse",a])!==d)throw new Error("direct-yolo-setup-physical-state-raced")};return j?await m():await L(r.projectRoot,S=>{const I=p(S.epics[r.epicId]),y=ye(S,e.storyId);if(JSON.stringify(I?.branch_lease)!==JSON.stringify(h)||JSON.stringify(I?.origin_binding)!==JSON.stringify(w)||I?.graph_revision!==r.graphRevision||U(y).length>0)throw new Error("direct-yolo-setup-runtime-raced");y.status="branch-ready",y.last_step=W,y.steps_completed=[W]},{expectedRevision:u.revision,preCommit:m}),{ok:!0,value:Object.freeze({...de(r,w,String(h.expiresAt),j),checkpointAccepted:!0,graphRevision:r.graphRevision,headSha:d})}}catch(o){return s(X(o,"direct-yolo-setup-acceptance-failed"))}finally{t&&await Y(t.path,t.owner).catch(()=>{})}}async function hr(e){try{const t=await V(e.projectRoot,e.storyId),o=q(await _(t.projectRoot,["diff","--cached","--name-only","-z"])),r=Z(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!r.ok)return s(r.reasonCode);if(t.rootMemoryEffect&&ue(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:await l(t.projectRoot,["rev-parse","HEAD"]),headRef:":",childPaths:t.authorizedWriteSet}),oe(t.projectRoot,e.storyId,":")?.verdict!=="approved")return s("direct-yolo-review-artifact-not-approved");if(q(await _(t.projectRoot,["diff","--name-only","-z"])).some(y=>o.includes(y)))return s("direct-yolo-user-overlap");const f=await _(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!f)return s("direct-yolo-staged-diff-empty");const c=A(f),d=A([...t.authorizedWriteSet].sort().join("\0")),a=N(e.nowIso),u=await C(t.projectRoot,{required:!0}),g=p(u.epics[t.epicId]?.branch_lease);if(!ke(g,e.storyId,a))return s("direct-yolo-setup-handoff-owner-invalid");const w=String(g.sessionId),h=String(g.expiresAt),v=new Date(Math.min(Date.parse(h),Date.parse(a)+300*1e3)).toISOString(),R=await J(t.projectRoot,e.storyId),b=R?.state==="issued"&&R.fromSessionId===w&&R.bundleDigest===c&&R.claimRevision===d&&Date.parse(R.expiresAt)>Date.parse(a),k=b?R.expiresAt:v,D=b?R.token:$e(32).toString("base64url"),j=A(D),m=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:w,tokenDigest:j,bundleDigest:c,claimRevision:d,expiresAt:k}),S=A(JSON.stringify(m)),I=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:w,idempotencyKey:w,expiresAt:k,persistent:!1,createdAt:a});if(!I.ok)return s(I.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await De(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:w,token:D,tokenDigest:j,bundleDigest:c,claimRevision:d,grantDigest:S,expiresAt:k}),await L(t.projectRoot,y=>{const x=p(M(y,t.epicId).branch_lease);if(!ke(x,e.storyId,a)||x?.sessionId!==w||x.idempotencyKey!==w)throw new Error("direct-yolo-setup-handoff-owner-raced");x.handoffGrant=m},{expectedRevision:u.revision,preCommit:async()=>{if(!await ne(I.path,I.owner))throw new Error("direct-yolo-integration-lock-raced");const y=await J(t.projectRoot,e.storyId);if(!y||y.state!=="issued"||y.grantDigest!==S||y.tokenDigest!==j)throw new Error("direct-yolo-setup-handoff-token-raced")}})}finally{await Y(I.path,I.owner).catch(()=>{})}return{ok:!0,value:Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff-receipt",storyId:e.storyId,sessionId:w,bundleDigest:c,claimRevision:d,grantDigest:S,expiresAt:k,reused:b,publicSafe:!0})}}catch(t){return s(t instanceof Error&&/^direct-yolo-/.test(t.message)?t.message:"direct-yolo-setup-handoff-failed")}}async function ur(e){try{const t=await V(e.projectRoot,e.storyId),o=await l(t.projectRoot,["rev-parse","HEAD"]),r=q(await _(t.projectRoot,["diff","--cached","--name-only","-z"])),i=Z(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!i.ok)return s(i.reasonCode);t.rootMemoryEffect&&ue(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:o,headRef:":",childPaths:t.authorizedWriteSet});const n=oe(t.projectRoot,e.storyId,":");if(n?.verdict!=="approved")return s("direct-yolo-review-artifact-not-approved");if(q(await _(t.projectRoot,["diff","--name-only","-z"])).some(x=>r.includes(x)))return s("direct-yolo-user-overlap");const c=await _(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!c)return s("direct-yolo-staged-diff-empty");const d=A(c),a=A([...t.authorizedWriteSet].sort().join("\0")),u=await Ze(t.projectRoot,e.storyId),g=u.state==="valid"&&u.plan.epicId===t.epicId&&u.plan.executionBranch===t.executionBranch&&u.plan.preparedBase===o&&u.plan.bundleDigest===d&&u.plan.claimRevision===a?u.plan:void 0,w=g?.graphRevision??t.graphRevision,h=xe({storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:d,graphRevision:w,claimRevision:a}),v=N(e.nowIso),R={schemaVersion:1,kind:"direct-yolo-commit-plan",storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:w,preparedBase:o,bundleDigest:d,claimRevision:a,idempotencyKey:h,issuedAt:g?.issuedAt??v};let b=e.setupLeaseHandoff??await _t(t.projectRoot,e.storyId,d,a,v);const k=await C(t.projectRoot,{required:!0}),D=p(k.epics[t.epicId]?.branch_lease),j=D?.ownerStoryId===e.storyId&&D.sessionId===h&&D.idempotencyKey===h&&typeof D.expiresAt=="string"&&Date.parse(D.expiresAt)>Date.parse(v)?D:void 0;if(j&&e.setupLeaseHandoff)return s("direct-yolo-setup-handoff-replayed");const m=p(j?.handoffConsumption);if(m){const x=await J(t.projectRoot,e.storyId);if(!x||!["consuming","consumed"].includes(x.state)||x.fromSessionId!==m.fromSessionId||x.tokenDigest!==m.tokenDigest||x.bundleDigest!==d||x.claimRevision!==a||m.bundleDigest!==d||m.claimRevision!==a||x.consumedBySessionId!==h||m.consumedBySessionId!==h)return s("direct-yolo-setup-handoff-consume-invalid");if(x.state==="consuming"){if(!x.token||A(x.token)!==x.tokenDigest)return s("direct-yolo-setup-handoff-consume-invalid");b={sessionId:x.fromSessionId,token:x.token}}}const S=j?String(j.expiresAt):new Date(Date.parse(v)+ae).toISOString(),I=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:h,idempotencyKey:h,expiresAt:S,persistent:!0,createdAt:j&&typeof j.acquiredAt=="string"?j.acquiredAt:v});if(!I.ok)return s(I.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{b&&e.setupLeaseHandoff===void 0&&(await Ct(t.projectRoot,e.storyId,b.sessionId,b.token,h,v),await e.setupHandoffFault?.("after-consuming-persisted")),await L(t.projectRoot,x=>{const $=M(x,t.epicId),E=p($.branch_lease),H=E&&Date.parse(String(E.expiresAt))>Date.parse(v),T=E?.ownerStoryId===e.storyId&&E.sessionId===h&&E.idempotencyKey===h,rt=E?.ownerStoryId===e.storyId&&E.sessionId===E.idempotencyKey&&typeof E.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(E.idempotencyKey),fe=H&&rt&&Ot({current:E,handoff:b,storyId:e.storyId,bundleDigest:d,claimRevision:a,nowIso:v});if(b&&H&&!T&&!fe)throw new Error("direct-yolo-setup-handoff-invalid");if(H&&!T&&!fe)throw new Error("direct-yolo-writer-active");const Oe=fe?p(E?.handoffGrant):void 0,Le=Oe?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(E?.sessionId),tokenDigest:String(Oe.tokenDigest),bundleDigest:d,claimRevision:a,consumedBySessionId:h,consumedAt:v}:void 0;$.branch_mode="epic",$.execution_branch=t.executionBranch,$.origin_branch=t.originBranch,$.graph_revision=t.graphRevision,$.branch_lease=H&&T?E:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:h,idempotencyKey:h,acquiredAt:v,expiresAt:S,...Le?{handoffConsumption:Le}:{}}},{expectedRevision:k.revision,preCommit:async()=>{if(!await ne(I.path,I.owner))throw new Error("direct-yolo-integration-lock-raced");await Bt(t.projectRoot,R)}})}catch(x){throw await Y(I.path,I.owner).catch(()=>{}),x}b&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await Ht(t.projectRoot,t.epicId,e.storyId,b.sessionId,b.token,d,a,h,v));const y=Object.freeze([`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${t.epicId}`,`Neocortex-Execution-Branch: ${t.executionBranch}`,`Neocortex-Prepared-Base: ${o}`,`Neocortex-Bundle-Digest: ${d}`,`Neocortex-Review-Artifact-Digest: ${n.digest}`,`Neocortex-Graph-Revision: ${w}`,`Neocortex-Claim-Revision: ${a}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${st(t.rootMemoryEffect)}`]:[]]);return{ok:!0,value:Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:d,reviewArtifactDigest:n.digest,graphRevision:w,claimRevision:a,idempotencyKey:h,changedPaths:Object.freeze(r),trailers:y})}}catch(t){return s(X(t,"direct-yolo-begin-failed"))}}async function lr(e){let t,o,r;try{const i=await V(e.projectRoot,e.storyId);t=i;const n=await l(i.projectRoot,["rev-parse","HEAD"]);let f=await C(i.projectRoot,{required:!0});const c=p(f.stories[e.storyId]?.checkpoint);if(c){const S=typeof c.headSha=="string"?c.headSha:"",I=typeof c.graphRevision=="string"?c.graphRevision:"",y=/^[a-f0-9]{40,64}$/.test(S)?q(await _(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",S])):[],x=Z(y,i.authorizedWriteSet,e.storyId,i.rootMemoryEffect);if(!(/^[a-f0-9]{40,64}$/.test(S)&&await B(i.projectRoot,["merge-base","--is-ancestor",S,n]))||!/^[a-f0-9]{64}$/.test(I)||!x.ok)return s("direct-yolo-replay-invalid");const E=await Ae(e,i.projectRoot,n,I);if(!await me(i.projectRoot,c,e.storyId,i.epicId,i.executionBranch,E.transientAuthority,i.authorizedWriteSet))return s("direct-yolo-replay-invalid");if(!await Be(i.projectRoot,i.executionBranch,n,y))return s("direct-yolo-replay-head-raced");if(e.push&&!await Je(i.projectRoot,e.remote??"origin",i.executionBranch,S))return s("direct-yolo-remote-head-mismatch");const H=Array.isArray(c.receiptRefs)?c.receiptRefs.find(T=>typeof T=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(T)):void 0;return H&&typeof c.idempotencyKey=="string"&&await It(i.projectRoot,{storyId:e.storyId,idempotencyKey:c.idempotencyKey,ownerDigest:H.slice(20)}),await ce(i.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:c}}const d=n,a=await Ve(i,e.storyId,d);if(!a.ok)return s(a.reasonCode);const{baseSha:u,changedPaths:g,bundleDigest:w,graphRevision:h,claimRevision:v,idempotencyKey:R}=a.value,b=p(f.epics[i.epicId]?.branch_lease),k=N(e.nowIso),D=b?.ownerStoryId===e.storyId&&b.idempotencyKey===R&&b.sessionId===R&&Date.parse(String(b.expiresAt))>Date.now()?b:void 0;if(b&&Date.parse(String(b.expiresAt))>Date.now()&&!D)return s("direct-yolo-writer-active");const j=D??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:R,idempotencyKey:R,acquiredAt:k,expiresAt:new Date(Date.parse(k)+ae).toISOString()},m=await F(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:R,idempotencyKey:R,expiresAt:String(j.expiresAt),persistent:!0,createdAt:String(j.acquiredAt)});if(!m.ok)return s(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");r=m,D||(f=(await L(i.projectRoot,I=>{const y=M(I,i.epicId),x=p(y.branch_lease);if(x&&Date.parse(String(x.expiresAt))>Date.parse(k))throw new Error("direct-yolo-writer-active");if(y.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");y.branch_lease=j},{expectedRevision:f.revision})).document),o=j;{const S=await Ae(e,i.projectRoot,d,h);if(!await Be(i.projectRoot,i.executionBranch,d,g))return s("direct-yolo-head-raced");if(e.push){const x=te(e.remote??"origin");if(await l(i.projectRoot,["push",x,i.executionBranch]),!await _e(i.projectRoot,x,i.executionBranch,d))return s("direct-yolo-remote-head-mismatch")}const I=await Ie({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:u,headSha:d,bundleDigest:w,graphRevision:h,claimRevision:v,idempotencyKey:R,qaExecution:S,physicalLockOwnerDigest:pe(m.owner),nowIso:N(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect});return await e.beforeCheckpointPersist?.(),await Se({projectRoot:i.projectRoot,checkpoint:I,remote:e.push?e.remote??"origin":void 0,expectedRevision:f.revision,expectedLease:j,expectedGraphRevision:i.graphRevision,expectedCheckpointGraphRevision:h,physicalLockPath:m.path,physicalLockOwner:m.owner,transientAuthority:S.transientAuthority,authorizedWriteSet:i.authorizedWriteSet})?(await ce(i.projectRoot,e.storyId).catch(()=>{}),await e.afterCheckpointPersist?.(),{ok:!0,value:I}):s("direct-yolo-checkpoint-persist-failed")}}catch(i){return s(X(i,"direct-yolo-finalize-failed"))}finally{r&&await Y(r.path,r.owner).catch(()=>{}),t&&o?await Ee(t.projectRoot,t.epicId,o).catch(()=>{}):t&&await $t(t,e.storyId).catch(()=>{})}}async function Ve(e,t,o){const r=await l(e.projectRoot,["rev-parse",`${o}^`]),i=await _(e.projectRoot,["show","--no-patch","--format=%B",o]),n=q(await _(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o])),f=Z(n,e.authorizedWriteSet,t,e.rootMemoryEffect);if(!f.ok)return s(f.reasonCode);e.rootMemoryEffect&&ue(e.projectRoot,e.rootMemoryEffect,{storyId:t,executionBranch:e.executionBranch,baseSha:r,headRef:o,childPaths:e.authorizedWriteSet});const c=A([...e.authorizedWriteSet].sort().join("\0")),d=await Ze(e.projectRoot,t);if(d.state==="invalid")return s("direct-yolo-commit-plan-invalid");const a=d.state==="valid"?d.plan:void 0;if(a&&(a.epicId!==e.epicId||a.executionBranch!==e.executionBranch))return s("direct-yolo-commit-plan-invalid");if(a&&a.claimRevision!==c)return s("direct-yolo-commit-plan-claim-changed");if(a&&a.preparedBase!==r)return s("direct-yolo-commit-plan-base-mismatch");const u=xt(i);if(!u.ok)return s(`direct-yolo-trailer-duplicate:${u.key}`);const g=u.values,w=a?.graphRevision??e.graphRevision,h=c,v=[["Neocortex-Story",t],["Neocortex-Epic",e.epicId],["Neocortex-Execution-Branch",e.executionBranch],["Neocortex-Prepared-Base",r],["Neocortex-Bundle-Digest",a?.bundleDigest??""],["Neocortex-Graph-Revision",w],["Neocortex-Claim-Revision",h]];for(const[m,S]of v){const I=ve(g,m);if(I===void 0)return s(`direct-yolo-trailer-missing:${we(m)}`);if(m==="Neocortex-Bundle-Digest"&&!a){if(!/^[a-f0-9]{64}$/.test(I))return s(`direct-yolo-trailer-mismatch:${we(m)}`);continue}if(I!==S)return s(`direct-yolo-trailer-mismatch:${we(m)}`)}const R=ve(g,"Neocortex-Bundle-Digest"),b=oe(e.projectRoot,t,o);if(b?.verdict!=="approved")return s("direct-yolo-review-artifact-not-approved");const k=ve(g,"Neocortex-Review-Artifact-Digest");if(k!==void 0&&k!==b.digest)return s("direct-yolo-review-artifact-digest-mismatch");const D=A(await _(e.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]));if(R!==D)return s("direct-yolo-bundle-digest-mismatch");const j=xe({storyId:t,epicId:e.epicId,executionBranch:e.executionBranch,baseSha:r,bundleDigest:R,graphRevision:w,claimRevision:h});return a&&a.idempotencyKey!==j?s("direct-yolo-commit-plan-invalid"):{ok:!0,value:{baseSha:r,changedPaths:n,bundleDigest:R,graphRevision:w,claimRevision:h,idempotencyKey:j}}}async function pr(e){try{const t=await V(e.projectRoot,e.storyId);if(!/^[a-f0-9]{40,64}$/.test(e.commitSha))return s("direct-yolo-recovery-commit-invalid");const o=await l(t.projectRoot,["rev-parse",e.commitSha]);if(wt[e.storyId]!==o)return s("direct-yolo-recovery-not-allowlisted");if(await l(t.projectRoot,["rev-parse","HEAD"])!==o)return s("direct-yolo-recovery-head-mismatch");await l(t.projectRoot,["merge-base","--is-ancestor",o,`refs/heads/${t.executionBranch}`]);const r=await l(t.projectRoot,["rev-parse",`${o}^`]),i=await _(t.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]),n=q(await _(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!Z(n,t.authorizedWriteSet.length>0?t.authorizedWriteSet:n,e.storyId).ok)return s("direct-yolo-recovery-write-set-invalid");const c=A(i),d=A([...n].sort().join("\0")),a=A(["legacy-direct-yolo-recovery-v1",e.storyId,o].join("\0")),u=N(e.nowIso),g=new Date(Date.parse(u)+ae).toISOString(),w=await C(t.projectRoot,{required:!0}),h=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:a,idempotencyKey:a,expiresAt:g,persistent:!0,createdAt:u});if(!h.ok)return s(h.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const v={schemaVersion:1,ownerStoryId:e.storyId,sessionId:a,idempotencyKey:a,acquiredAt:u,expiresAt:g};let R=!1;try{const b=await L(t.projectRoot,I=>{const y=M(I,t.epicId),x=p(y.branch_lease);if(x&&Date.parse(String(x.expiresAt))>Date.parse(u)&&!je(x,v))throw new Error("direct-yolo-recovery-writer-active");if(y.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");y.branch_mode="epic",y.execution_branch=t.executionBranch,y.origin_branch=t.originBranch,y.branch_lease=v},{expectedRevision:w.revision});R=!0;const k=await Ae(e,t.projectRoot,o,t.graphRevision);if(!await Be(t.projectRoot,t.executionBranch,o,n))return s("direct-yolo-recovery-head-raced");if(e.push){const I=te(e.remote??"origin"),y=(await l(t.projectRoot,["ls-remote","--heads",I,`refs/heads/${t.executionBranch}`])).split(/\s+/)[0];if(!y||!await B(t.projectRoot,["merge-base","--is-ancestor",o,y]))return s("direct-yolo-recovery-remote-proof-missing")}const D=await Ie({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision,claimRevision:d,idempotencyKey:a,qaExecution:k,physicalLockOwnerDigest:pe(h.owner),nowIso:u,legacyReceiptRef:void 0}),j=await yt(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision});if(!j)return s("direct-yolo-recovery-evidence-invalid");const m=Object.freeze({...D,receiptRefs:Object.freeze([...D.receiptRefs,j])});return await Se({projectRoot:t.projectRoot,checkpoint:m,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:b.document.revision,expectedLease:v,expectedGraphRevision:t.graphRevision,physicalLockPath:h.path,physicalLockOwner:h.owner,transientAuthority:k.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:m}:s("direct-yolo-recovery-persist-failed")}finally{await Y(h.path,h.owner).catch(()=>{}),R&&await Ee(t.projectRoot,t.epicId,v).catch(()=>{})}}catch(t){return s(X(t,"direct-yolo-recovery-failed"))}}async function Ke(e){const t=await he(await l(e,["rev-parse","--absolute-git-dir"])),o=await he(await l(e,["rev-parse","--path-format=absolute","--git-common-dir"]));return t!==o}async function Fe(e){const t=await C(e.projectRoot,{required:!0}),o=Object.values(t.storyWorktrees?.entries??{}).filter(g=>g.storyId===e.storyId&&g.epicId===e.epicId&&g.state==="active");if(o.length===0)throw new Error("direct-yolo-worktree-lease-missing");if(o.length>1)throw new Error("direct-yolo-worktree-lease-ambiguous");const r=o[0];if(r.executionBranch!==e.executionBranch)throw new Error("direct-yolo-worktree-branch-mismatch");if(await he(await l(e.projectRoot,["rev-parse","--show-toplevel"]))!==r.worktreePath)throw new Error("direct-yolo-worktree-path-mismatch");if(await l(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]).catch(()=>"")!==r.temporaryBranch)throw new Error("direct-yolo-worktree-branch-mismatch");const f=await new bt({projectRoot:e.projectRoot}).probe(r.leaseId);if(!f.ok||f.value.ownership!=="proven")throw new Error("direct-yolo-worktree-ownership-unproven");const c=K(p(t.epics[e.epicId])?.origin_binding,e.executionBranch,e.originBranch);if(!c)throw new Error("direct-yolo-origin-binding-invalid");const d=r.syncedSha??r.baseSha,a=await l(e.projectRoot,["rev-parse","HEAD"]),u=`refs/heads/${e.executionBranch}`;if(a!==d||!await B(e.projectRoot,["merge-base","--is-ancestor",d,u])||!await B(e.projectRoot,["merge-base","--is-ancestor",c.originHeadSha,d]))throw new Error("direct-yolo-worktree-base-divergent");if(f.value.clean!==!0||(await _(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-worktree-dirty");return{leaseId:r.leaseId,temporaryBranch:r.temporaryBranch,authorizedBase:d,headSha:a,expiresAt:r.expiresAt,binding:c}}function Ye(e,t,o){return Object.freeze({...de(e,t.binding,t.expiresAt,o),workspace:"story-worktree",temporaryBranch:t.temporaryBranch,baseSha:t.authorizedBase})}async function Dt(e){const t=await Fe(e),o=G(e.projectRoot,".neocortex/state.json"),r=await P(o,"utf8"),i=p(JSON.parse(r)),n=p(p(i?.stories)?.[e.storyId]),f=await C(e.projectRoot,{required:!0}),c=p(f.stories[e.storyId]);if(!n||!["backlog","ready_to_start"].includes(String(n.status))||n.steps_completed!==void 0&&(!Array.isArray(n.steps_completed)||n.steps_completed.length>0)||n.branch_name||n.checkpoint)return s("direct-yolo-setup-story-progress-conflict");const d=c?.status==="branch-ready"&&c.last_step===W&&Array.isArray(c.steps_completed)&&c.steps_completed.length===1&&c.steps_completed[0]===W&&U(c).sort().join(",")==="last_step,status,steps_completed";return c&&U(c).length>0&&!d?s("direct-yolo-setup-story-progress-conflict"):(d||await L(e.projectRoot,a=>{const u=ye(a,e.storyId);if(U(u).length>0)throw new Error("direct-yolo-setup-runtime-raced");u.status="branch-ready",u.last_step=W,u.steps_completed=[W]},{expectedRevision:f.revision,preCommit:async()=>{if(await P(o,"utf8")!==r||await l(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==t.temporaryBranch||await l(e.projectRoot,["rev-parse","HEAD"])!==t.headSha||(await _(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-setup-physical-state-raced")}}),{ok:!0,value:Object.freeze({...Ye(e,t,d),checkpointAccepted:!0,graphRevision:e.graphRevision,headSha:t.headSha})})}async function yr(e,t){const o=await V(e,t),r=await C(o.projectRoot,{required:!0}),i=K(p(r.epics[o.epicId])?.origin_binding,o.executionBranch,o.originBranch);return{...o,originBinding:i}}function gr(e,t,o,r){return Z(e,t,o,r)}function mr(e){return A(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const wr=ae,jt="p205-wave:";function vr(e){if(e.waveStoryIds.length===0||e.waveStoryIds.length!==e.waveCommitShas.length||e.waveCommitShas[e.waveCommitShas.length-1]!==e.waveHeadSha||e.waveCommitShas.some(o=>!/^[a-f0-9]{40,64}$/.test(o)))throw new Error("direct-yolo-wave-coverage-invalid");const t=A(["p205-wave-coverage-v1",e.epicId,e.executionBranch,e.waveHeadSha,...e.waveStoryIds.map((o,r)=>`${o}=${e.waveCommitShas[r]}`)].join("\0"));return Object.freeze({kind:"wave",waveHeadSha:e.waveHeadSha,waveStoryIds:Object.freeze([...e.waveStoryIds]),waveCommitShas:Object.freeze([...e.waveCommitShas]),waveDigest:t})}function Et(e){return`${jt}${e.waveHeadSha}:${e.waveDigest}`}async function Rr(e){let t;try{t=await gt(e.projectRoot,{headSha:e.headSha,graphRevisions:e.graphRevisions,...e.nowIso!==void 0?{nowIso:e.nowIso}:{}})}catch(o){const r=o instanceof Error?o.message:"";return/^p205-transient-[a-z0-9-]{1,64}$/.test(r)?{ok:!1,headSha:e.headSha,kind:"infrastructure",reasonCode:r}:{ok:!1,headSha:e.headSha,kind:"gate-failed",reasonCode:ge(r)?r:"p205-complete-gate-failed"}}try{await e.qaRunner?.({projectRoot:e.projectRoot,storyId:e.storyId,headSha:e.headSha})}catch(o){const r=o instanceof Error?o.message:"";return/^p205-transient-[a-z0-9-]{1,64}$/.test(r)?{ok:!1,headSha:e.headSha,kind:"infrastructure",reasonCode:r}:{ok:!1,headSha:e.headSha,kind:"gate-failed",reasonCode:ge(r)||/^p205-[a-z0-9-]{1,64}$/.test(r)?r:"p205-complete-gate-failed"}}return{ok:!0,headSha:e.headSha,authorities:t}}async function Ir(e,t,o,r){const i=te(t);return await l(e,["push",i,o]),_e(e,i,o,r)}async function Sr(e){try{const t=await V(e.projectRoot,e.storyId),o=e.coverage.waveHeadSha,r=e.coverage.waveStoryIds.indexOf(e.storyId);if(r<0||e.coverage.waveCommitShas[r]!==e.headSha)return s("direct-yolo-wave-coverage-invalid");if(await l(t.projectRoot,["rev-parse","HEAD"])!==o||await l(t.projectRoot,["rev-parse",`refs/heads/${t.executionBranch}`])!==o||!await B(t.projectRoot,["merge-base","--is-ancestor",e.headSha,o]))return s("direct-yolo-wave-head-raced");const i=await C(t.projectRoot,{required:!0}),n=p(i.stories[e.storyId]?.checkpoint);if(n){if(n.headSha!==e.headSha)return s("direct-yolo-checkpoint-conflict");const k=e.authorities.get(String(n.graphRevision));return await me(t.projectRoot,n,e.storyId,t.epicId,t.executionBranch,k??null,t.authorizedWriteSet)?(await ce(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:n}):s("direct-yolo-replay-invalid")}const f=await Ve(t,e.storyId,e.headSha);if(!f.ok)return s(f.reasonCode);const{baseSha:c,bundleDigest:d,graphRevision:a,claimRevision:u,idempotencyKey:g}=f.value,w=r===0?void 0:e.coverage.waveCommitShas[r-1];if(w!==void 0&&c!==w)return s("direct-yolo-wave-chain-invalid");const h=e.authorities.get(a),v=ze(h);if(!h||!v||v.executionHeadSha!==o||v.graphRevision!==a)return s("direct-yolo-wave-qa-unbound");const R=await Ie({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:c,headSha:e.headSha,bundleDigest:d,graphRevision:a,claimRevision:u,idempotencyKey:g,qaExecution:{contract:"P205-CI-02",command:Te,manifestDigest:v.manifestDigest,gateIds:v.gateIds,resultDigest:v.resultDigest,transientAuthority:h},physicalLockOwnerDigest:pe(e.physicalLock.owner),nowIso:N(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:t.rootMemoryEffect,extraReceiptRefs:[Et(e.coverage)]});return await Se({projectRoot:t.projectRoot,checkpoint:R,remote:e.remote,expectedRevision:i.revision,expectedLease:e.expectedLease,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:a,physicalLockPath:e.physicalLock.path,physicalLockOwner:e.physicalLock.owner,transientAuthority:h,authorizedWriteSet:t.authorizedWriteSet,expectedHeadSha:o,keepLease:!0})?(await ce(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:R}):s("direct-yolo-checkpoint-persist-failed")}catch(t){return s(X(t,"direct-yolo-wave-persist-failed"))}}async function Re(e,t){if(!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(t))throw new Error("direct-yolo-story-id-invalid");const o=O(e),r=p(JSON.parse(await P(G(o,".neocortex/state.json"),"utf8"))),i=await C(o,{required:!0}),n=le(r,i),f=p(n.stories),c=p(n.epics),d=p(f?.[t]),a=String(d?.epic_id??t.split(".")[0]),u=p(c?.[a]),g=String(u?.execution_branch??""),w=String(u?.origin_branch??""),h=String(u?.graph_revision??""),v=Array.isArray(d?.files_to_modify)?d.files_to_modify:[],R=Rt(d).filter(Pt),b=[...v,...R],k=b.length>0?qe(t,b):void 0,D=k?.ok?k.scopes:[];if(!d)throw new Error("direct-yolo-story-state-missing");if(R.length>0&&D.length>vt)throw new Error("direct-yolo-write-set-too-large");if(u?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!Q(g)||!await B(o,["check-ref-format","--branch",g]))throw new Error("direct-yolo-execution-branch-invalid");if(!Q(w)||!await B(o,["check-ref-format","--branch",w]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(h))throw new Error("direct-yolo-graph-revision-invalid");const j=await ct({projectRoot:o,storyId:t,graphRevision:h,executionBranch:g,childPaths:D});return{projectRoot:o,storyId:t,story:d,epicId:a,executionBranch:g,originBranch:w,graphRevision:h,authorizedWriteSet:D,rootMemoryEffect:j}}async function V(e,t){const o=await Re(e,t);if(await l(o.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return o}async function Ie(e){const t=e.nowIso,o=await _(e.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),r=q(await _(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=lt({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),n=pt({gitEvidenceDigest:i,headSha:e.headSha,graphRevision:e.graphRevision,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest}),f=`story-qa:${n}`,c=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,contract:e.qaExecution.contract,command:e.qaExecution.command,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest,sourceEvidenceDigest:n,verdict:"passed",checkedAt:t,receiptRef:f}),d=oe(e.projectRoot,e.storyId,e.headSha);if(d?.verdict!=="approved")throw new Error("direct-yolo-review-artifact-not-approved");const a=A(["root-commit-range-review-v2",e.storyId,e.baseSha,e.headSha,e.bundleDigest,e.graphRevision,f,A(o),[...r].sort().join(","),d.digest].join("\0")),u=`story-review:${a}`,g=Object.freeze({schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,sourceEvidenceDigest:a,reviewArtifactDigest:d.digest,qaReceiptRef:f,verdict:"approved",reviewedAt:t,receiptRef:u}),w=[`.neocortex/stories/${e.storyId}/qa-gate-result.json`,`.neocortex/stories/${e.storyId}/validation-evidence.md`,f,u,...e.physicalLockOwnerDigest?[`physical-lock-owner:${e.physicalLockOwnerDigest}`]:[],...e.legacyReceiptRef?[e.legacyReceiptRef]:[],...e.extraReceiptRefs??[]];return Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:e.epicId,branch:e.executionBranch,baseSha:e.baseSha,headSha:e.headSha,commits:Object.freeze([e.headSha]),idempotencyKey:e.idempotencyKey,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,claimRevision:e.claimRevision,receiptRefs:Object.freeze(w),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:c,reviewReceipt:g,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function Se(e){const{projectRoot:t,checkpoint:o,remote:r}=e;let i=!1;return await L(t,n=>{const f=M(n,o.epicId);if(e.expectedLease){const u=p(f.branch_lease);if(!je(u,e.expectedLease))throw new Error("direct-yolo-runtime-revision-conflict");if(Date.parse(String(u?.expiresAt))<=Date.now())throw new Error("direct-yolo-writer-lease-expired");if(f.graph_revision!==e.expectedGraphRevision||o.graphRevision!==(e.expectedCheckpointGraphRevision??e.expectedGraphRevision))throw new Error("direct-yolo-graph-revision-raced")}const c=ye(n,o.storyId),d=p(c.checkpoint);if(d&&d.headSha!==o.headSha){i=!0;return}c.checkpoint=o,c.status="done",c.last_step=Ge;const a=Array.isArray(c.steps_completed)?c.steps_completed.filter(u=>typeof u=="string"):[];c.steps_completed=[...new Set([...a,kt,Ge])],e.keepLease||(f.branch_lease=null)},{expectedRevision:e.expectedRevision,preCommit:async()=>{if(i)throw new Error("direct-yolo-checkpoint-conflict");const n=e.expectedHeadSha??o.headSha;if(await l(t,["symbolic-ref","--quiet","--short","HEAD"])!==o.branch||await l(t,["rev-parse","HEAD"])!==n||await l(t,["rev-parse",`refs/heads/${o.branch}`])!==n||!await B(t,["merge-base","--is-ancestor",o.headSha,n]))throw new Error("direct-yolo-checkpoint-head-raced");if(!await me(t,o,o.storyId,o.epicId,o.branch,e.transientAuthority,e.authorizedWriteSet))throw new Error("direct-yolo-checkpoint-physical-invalid");if(e.physicalLockPath&&e.physicalLockOwner&&!await ne(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(r&&!(e.remotePolicy==="ancestor-recovery"?await Je(t,r,o.branch,o.headSha):await _e(t,r,o.branch,n)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function Je(e,t,o,r){const i=te(t),n=(await l(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0];return!!(n&&await B(e,["merge-base","--is-ancestor",r,n]))}function xe(e){return A(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const At=["schemaVersion","kind","storyId","epicId","executionBranch","graphRevision","preparedBase","bundleDigest","claimRevision","idempotencyKey","issuedAt"];async function be(e,t){const o=await Me(e),r=await Ne(o,"commit-plans"),i=`direct-${A(t)}.json`;return{parent:r,name:i,path:G(r,i)}}async function Bt(e,t){const o=await be(e,t.storyId);await We(o.parent,o.name,`${JSON.stringify(t,null,2)}
2
+ `),await ie(o.path,o.parent)}async function Ze(e,t){let o;try{o=await be(e,t)}catch{return{state:"invalid"}}try{if(!Pe(o.path))return{state:"absent"};await ie(o.path,o.parent);const r=await P(o.path,"utf8");if(r.length>16*1024)return{state:"invalid"};const i=p(JSON.parse(r));if(!i||Object.keys(i).sort().join("\0")!==[...At].sort().join("\0")||i.schemaVersion!==1||i.kind!=="direct-yolo-commit-plan"||i.storyId!==t||typeof i.epicId!="string"||typeof i.executionBranch!="string"||!Q(i.executionBranch)||typeof i.preparedBase!="string"||!/^[a-f0-9]{40,64}$/.test(i.preparedBase)||![i.graphRevision,i.bundleDigest,i.claimRevision,i.idempotencyKey].every(f=>typeof f=="string"&&/^[a-f0-9]{64}$/.test(f))||typeof i.issuedAt!="string"||!Number.isFinite(Date.parse(i.issuedAt)))return{state:"invalid"};const n=i;return n.idempotencyKey!==xe({...n,baseSha:n.preparedBase})?{state:"invalid"}:{state:"valid",plan:n}}catch{return{state:"invalid"}}}async function ce(e,t){const o=await be(e,t);Pe(o.path)&&await St(o.parent,o.name)}function ke(e,t,o){return!!(e?.ownerStoryId===t&&e.sessionId===e.idempotencyKey&&typeof e.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(e.idempotencyKey)&&typeof e.expiresAt=="string"&&Date.parse(e.expiresAt)>Date.parse(o))}async function Ue(e,t){const o=await Me(e),r=await Ne(o,"handoffs"),i=`direct-${A(t)}.json`;return{parent:r,name:i,path:G(r,i)}}async function De(e,t){const o=await Ue(e,t.storyId);await We(o.parent,o.name,`${JSON.stringify(t,null,2)}
3
+ `),await ie(o.path,o.parent)}async function J(e,t){try{const o=await Ue(e,t);await ie(o.path,o.parent);const r=JSON.parse(await P(o.path,"utf8")),i=r.state==="issued"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt"]:r.state==="consuming"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumeStartedAt"]:["schemaVersion","kind","state","storyId","fromSessionId","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumedAt"];return Object.keys(r).sort().join("\0")!==[...i].sort().join("\0")||r.schemaVersion!==1||r.kind!=="direct-yolo-setup-handoff-token"||r.state!=="issued"&&r.state!=="consuming"&&r.state!=="consumed"||r.storyId!==t||typeof r.fromSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(r.fromSessionId)||![r.tokenDigest,r.bundleDigest,r.claimRevision,r.grantDigest].every(n=>typeof n=="string"&&/^[a-f0-9]{64}$/.test(n))||typeof r.expiresAt!="string"||!Number.isFinite(Date.parse(r.expiresAt))||(r.state==="issued"||r.state==="consuming")&&(typeof r.token!="string"||!/^[A-Za-z0-9_-]{32,256}$/.test(r.token))||r.state==="consuming"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumeStartedAt!="string"||!Number.isFinite(Date.parse(r.consumeStartedAt)))||r.state==="consumed"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumedAt!="string"||!Number.isFinite(Date.parse(r.consumedAt)))?void 0:r}catch{return}}async function _t(e,t,o,r,i){const n=await J(e,t);if(!(!n||n.state==="consumed"||!n.token||n.bundleDigest!==o||n.claimRevision!==r||Date.parse(n.expiresAt)<=Date.parse(i)||A(n.token)!==n.tokenDigest))return{sessionId:n.fromSessionId,token:n.token}}async function Ct(e,t,o,r,i,n){const f=await J(e,t);if(!f||f.state==="consumed"||f.fromSessionId!==o||f.token!==r||f.tokenDigest!==A(r))throw new Error("direct-yolo-setup-handoff-consume-invalid");if(f.state==="consuming"){if(f.consumedBySessionId!==i)throw new Error("direct-yolo-setup-handoff-consume-raced");return}await De(e,{...f,state:"consuming",consumedBySessionId:i,consumeStartedAt:n})}async function Ht(e,t,o,r,i,n,f,c,d){const a=await J(e,o);if(a?.state==="consumed"&&a.fromSessionId===r&&a.consumedBySessionId===c)return;const u=await C(e,{required:!0}),g=p(u.epics[t]?.branch_lease),w=p(g?.handoffConsumption);if(!a||a.state!=="consuming"||a.fromSessionId!==r||a.token!==i||a.tokenDigest!==A(i)||a.bundleDigest!==n||a.claimRevision!==f||a.consumedBySessionId!==c||g?.ownerStoryId!==o||g.sessionId!==c||w?.kind!=="direct-yolo-setup-handoff-consumption"||w.state!=="consumed"||w.fromSessionId!==r||w.tokenDigest!==a.tokenDigest||w.bundleDigest!==n||w.claimRevision!==f||w.consumedBySessionId!==c)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await De(e,{schemaVersion:1,kind:a.kind,state:"consumed",storyId:o,fromSessionId:r,tokenDigest:a.tokenDigest,bundleDigest:a.bundleDigest,claimRevision:a.claimRevision,grantDigest:a.grantDigest,expiresAt:a.expiresAt,consumedBySessionId:c,consumedAt:d})}catch{throw new Error("direct-yolo-setup-handoff-consume-persist-failed")}}function Ot(e){const t=p(e.current?.handoffGrant),o=e.handoff?.token,r=typeof o=="string"&&/^[A-Za-z0-9_-]{32,256}$/.test(o)?A(o):void 0;return!!(t&&r&&e.handoff&&e.handoff.sessionId===e.current?.sessionId&&t.schemaVersion===1&&t.kind==="direct-yolo-setup-handoff"&&t.storyId===e.storyId&&t.fromSessionId===e.current?.sessionId&&t.bundleDigest===e.bundleDigest&&t.claimRevision===e.claimRevision&&typeof t.expiresAt=="string"&&Date.parse(t.expiresAt)>Date.parse(e.nowIso)&&typeof t.tokenDigest=="string"&&/^[a-f0-9]{64}$/.test(t.tokenDigest)&&Lt(t.tokenDigest,r))}function Lt(e,t){const o=Buffer.from(e,"hex"),r=Buffer.from(t,"hex");return o.length===32&&r.length===32&&nt(o,r)}function je(e,t){return!!(e&&["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt"].every(o=>e[o]===t[o]))}async function Ee(e,t,o){await L(e,r=>{const i=M(r,t),n=p(i.branch_lease);je(n,o)&&(i.branch_lease=null)})}async function $t(e,t){const o=await C(e.projectRoot,{required:!0}),r=p(o.epics[e.epicId]?.branch_lease);if(!r||r.ownerStoryId!==t||!Qe(r.sessionId)||!Qe(r.idempotencyKey)||!Number.isFinite(Date.parse(String(r.acquiredAt)))||!Number.isFinite(Date.parse(String(r.expiresAt))))return;const i=await F(e.projectRoot,{kind:"direct",storyId:t,sessionId:String(r.sessionId),idempotencyKey:String(r.idempotencyKey),createdAt:String(r.acquiredAt),expiresAt:String(r.expiresAt),persistent:!0});if(!i.ok)return;await Y(i.path,i.owner)&&await Ee(e.projectRoot,e.epicId,r)}async function Ae(e,t,o,r){const i=await mt(t,{headSha:o,graphRevision:r,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:o});const n=ze(i);if(!n)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:Te,manifestDigest:n.manifestDigest,gateIds:n.gateIds,resultDigest:n.resultDigest,transientAuthority:i}}async function Be(e,t,o,r){return await l(e,["rev-parse","HEAD"])!==o||await l(e,["symbolic-ref","--quiet","--short","HEAD"])!==t||!await B(e,["diff","--cached","--quiet"])?!1:B(e,["diff","--quiet","HEAD","--",...r])}async function _e(e,t,o,r){const i=te(t);return(await l(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0]===r}function Z(e,t,o,r){if(e.length===0||e.some(f=>!Ce(f)))return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};const i=t.length>0?qe(o,t):void 0;return i?.ok?[".neocortex/state.json",`docs/stories/${o}.story.md`,`.neocortex/stories/${o}/qa-gate-result.json`,`.neocortex/stories/${o}/validation-evidence.md`,`.neocortex/stories/${o}/review.md`].every(f=>e.includes(f))?r&&(r.storyId!==o||r.childClaimRevision!==A([...i.scopes].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(f=>!ht(i.scopes,f)&&!r?.files.some(c=>c.path===f))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}:{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}:{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}}function U(e){return Object.keys(e).filter(t=>t!=="write_set_extension")}function Pt(e){return typeof e!="string"||e.length>512||!Ce(e)||!ut(e).ok||/^(?:\.neocortex|\.claude|\.git[^/]*)(?:\/|$)/i.test(e)||/^docs\/stories(?:\/|$)/i.test(e)?!1:!e.split("/")[0].includes("*")}function Ce(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").includes("..")&&!e.startsWith(".git/")&&!e.includes("\0")}function Qe(e){return typeof e=="string"&&e.length>0&&e.length<=512&&/^[A-Za-z0-9._:@/+\-=]+$/.test(e)}function Q(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!/[\s~^:?*[\\]/.test(e)&&!e.includes("..")}function te(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function A(e){return it("sha256").update(e).digest("hex")}function q(e){return e.split("\0").filter(Boolean)}function N(e){return e&&Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function p(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function qt(e,t,o,r,i){const n=p(e.expectedLease),f=n?.sessionId,c=Date.parse(String(n?.expiresAt??""));return e.schemaVersion===1&&Number.isSafeInteger(e.expectedRuntimeRevision)&&e.expectedRuntimeRevision===t&&!!o&&JSON.stringify(o)===JSON.stringify(n)&&n?.schemaVersion===1&&n.ownerStoryId===r&&typeof f=="string"&&/^setup-[a-f0-9]{64}$/.test(f)&&n.idempotencyKey===f&&Number.isFinite(c)&&c<=i}async function Nt(e,t){let o=await l(e,["symbolic-ref","--quiet","--short","HEAD"]);if(o===t.executionBranch){if(await l(e,["rev-parse","HEAD"])!==t.originHead||await z(e)!==t.checkoutBefore)return;await l(e,["switch",t.originBranch]),o=t.originBranch}if(o!==t.originBranch||await l(e,["rev-parse","HEAD"])!==t.originHead||await z(e)!==t.checkoutBefore||t.executionHead===t.originHead||!await B(e,["show-ref","--verify","--quiet",t.executionRef]))return;await l(e,["rev-parse",t.executionRef])===t.originHead&&await l(e,["update-ref",t.executionRef,t.executionHead,t.originHead])}const zt=["capturedAt","capturedFromCurrentCheckout","executionBranch","originBranch","originHeadSha","schemaVersion"],Tt=["capturedAt","capturedFrom","executionBranch","originBranch","originHeadSha","schemaVersion"];function K(e,t,o){const r=p(e);if(!r||r.originBranch!==o||r.executionBranch!==t||typeof r.originHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(r.originHeadSha)||typeof r.capturedAt!="string"||!Number.isFinite(Date.parse(r.capturedAt)))return;const i=Object.keys(r).sort().join("\0");if(r.schemaVersion===1)return r.capturedFromCurrentCheckout!==!0||i!==zt.join("\0")?void 0:r;if(r.schemaVersion===2)return r.capturedFrom!=="current-checkout"&&r.capturedFrom!=="branch-ref"||i!==Tt.join("\0")?void 0:r}async function Mt(e,t,o){const r=`refs/heads/${e.originBranch}`;if(!await B(e.projectRoot,["show-ref","--verify","--quiet",r]))return s("direct-yolo-origin-ref-missing","fetch-origin-branch");const i=await l(e.projectRoot,["rev-parse","--verify","--quiet",`${r}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(i))return s("direct-yolo-origin-ref-missing","fetch-origin-branch");if((await re(e.projectRoot)).some(d=>d.branch===e.executionBranch&&O(d.path)!==e.projectRoot))return s("direct-yolo-execution-branch-checked-out-elsewhere");const f=`refs/heads/${e.executionBranch}`;if(await l(e.projectRoot,["rev-parse","--verify","--quiet",f]).catch(()=>"")!==t)return s("direct-yolo-setup-physical-state-raced");const c=await He(e.projectRoot,["merge-base","--is-ancestor",i,t]);return c===1?s("direct-yolo-origin-not-ancestor","checkout-origin-or-rebase"):c!==0?s("direct-yolo-origin-ancestry-unverifiable"):{ok:!0,value:{originRef:r,binding:{schemaVersion:2,originBranch:e.originBranch,originHeadSha:i,executionBranch:e.executionBranch,capturedFrom:"branch-ref",capturedAt:o}}}}const Xe=3e4,Wt=3,Gt="ssh -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=2";class se extends Error{}function Vt(e,t=Xe){return{timeout:t,killSignal:"SIGKILL",env:{...e,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",GIT_HTTP_LOW_SPEED_LIMIT:"1000",GIT_HTTP_LOW_SPEED_TIME:"30",...e.GIT_SSH_COMMAND?{}:{GIT_SSH_COMMAND:Gt}}}}async function Kt(e){if(!Q(e.originBranch))return{ok:!1,reasonCode:"origin-binding-start-fetch-unavailable"};try{return await ee("git",["fetch","--no-tags","origin",`refs/heads/${e.originBranch}:refs/remotes/origin/${e.originBranch}`],{cwd:O(e.projectRoot),maxBuffer:1024*1024,encoding:"utf8",...Vt(process.env,e.fetchTimeoutMs??Xe)}),{ok:!0}}catch(t){const o=String(t.stderr??"");return{ok:!1,reasonCode:/non-fast-forward|\[rejected\]/.test(o)?"origin-binding-start-fetch-non-fast-forward":"origin-binding-start-fetch-unavailable"}}}const Ft=new Set(["done","completed","complete","closed","cancelled","canceled","archived","terminal"]);async function xr(e,t){const o=Object.freeze({exists:!1,mode:"not-epic",terminal:!1,bound:!1});try{const r=O(e),i=p(JSON.parse(await P(G(r,".neocortex/state.json"),"utf8")));if(!i)return o;const n=await C(r),f=le(i,n),c=p(p(f.epics)?.[t]);if(!c)return o;const d=et(f,t,c),a=typeof c.execution_branch=="string"&&c.execution_branch.length>0?c.execution_branch:`epic/${t}`,u=typeof c.origin_branch=="string"&&c.origin_branch.length>0?c.origin_branch:String(p(i.config)?.default_branch??""),g=p(n.epics[t])?.origin_binding??c.origin_binding;return Object.freeze({exists:!0,mode:d,terminal:Ft.has(String(c.status??"").toLowerCase()),bound:!!K(g,a,u),executionBranch:a,originBranch:u})}catch{return o}}function et(e,t,o){if(o.branch_mode==="epic")return"recorded-epic";if(o.branch_mode!==void 0&&o.branch_mode!==null)return"not-epic";const r=p(e.stories)??{},n=ft(t,Array.isArray(o.stories)?o.stories:void 0,Object.keys(r)).flatMap(c=>{const d=p(r[c]);return d?[{...d,id:c}]:[]}),f=dt({...o,id:t},n);return f.mode==="epic"&&(f.source==="new-epic-default"||f.source==="epic-boundary")?"resolved-epic":"not-epic"}function tt(e,t){if(!e)return!1;const o=Date.parse(String(e.expiresAt));return!(Number.isFinite(o)&&o<=t)}async function br(e){const t=N(e.nowIso),o=Date.parse(t),r=(c,d={})=>Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...d,outcome:"refused",reasonCode:c,executionRefCreated:!1,capturedAt:t});if(!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(e.epicId))return r("origin-binding-start-target-ambiguous");const i=O(e.projectRoot);let n=e.originFetch,f="origin-binding-start-raced";for(let c=0;c<Wt;c+=1){let d,a={};try{const u=p(JSON.parse(await P(G(i,".neocortex/state.json"),"utf8")));if(!u)return r("origin-binding-start-state-invalid");const g=await C(i),w=le(u,g),h=p(p(w.epics)?.[e.epicId]);if(!h)return r("origin-binding-start-target-ambiguous");if(et(w,e.epicId,h)==="not-epic")return r("origin-binding-start-branch-mode-not-epic");const v=typeof h.execution_branch=="string"&&h.execution_branch.length>0?h.execution_branch:`epic/${e.epicId}`,R=typeof h.origin_branch=="string"&&h.origin_branch.length>0?h.origin_branch:String(p(u.config)?.default_branch??"");if(a={executionBranch:v,originBranch:R},!Q(v)||!Q(R)||v===R||!await B(i,["check-ref-format","--branch",v])||!await B(i,["check-ref-format","--branch",R]))return r("origin-binding-start-branch-invalid",a);const b=p(g.epics[e.epicId]),k=b?.origin_binding??h.origin_binding;if(k!=null){const E=K(k,v,R);return E?Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...a,originHeadSha:E.originHeadSha,outcome:"already-bound",executionRefCreated:!1,capturedAt:t}):r("origin-binding-start-binding-invalid",a)}if(tt(p(b?.branch_lease??h.branch_lease),o))return r("origin-binding-start-lease-inconsistent",a);if(n??=await Kt({projectRoot:i,originBranch:R,...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}),!n.ok)return r(n.reasonCode,a);const D=`refs/remotes/origin/${R}`,j=`refs/heads/${R}`,m=await l(i,["rev-parse","--verify","--quiet",`${j}^{commit}`]).catch(()=>""),S=await l(i,["rev-parse","--verify","--quiet",`${D}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(m)||m!==S)return r("origin-binding-start-origin-stale",a);if((await re(i)).some(E=>E.branch===v&&O(E.path)!==i))return r("direct-yolo-execution-branch-checked-out-elsewhere",a);const y=`refs/heads/${v}`,x=await l(i,["rev-parse","--verify","--quiet",`${y}^{commit}`]).catch(()=>"");if(x){const E=await He(i,["merge-base","--is-ancestor",m,x]);if(E===1)return r("direct-yolo-origin-not-ancestor",a);if(E!==0)return r("direct-yolo-origin-ancestry-unverifiable",a)}const $={schemaVersion:2,originBranch:R,originHeadSha:m,executionBranch:v,capturedFrom:"branch-ref",capturedAt:t};return await L(i,E=>{const H=M(E,e.epicId);if(H.origin_binding!==void 0&&H.origin_binding!==null)throw new se("origin-binding-start-raced");if(tt(p(H.branch_lease),o))throw new se("origin-binding-start-lease-inconsistent");H.origin_binding=$},{expectedRevision:g.revision,preCommit:async()=>{const E=await l(i,["rev-parse","--verify","--quiet",`${j}^{commit}`]).catch(()=>""),H=await l(i,["rev-parse","--verify","--quiet",`${D}^{commit}`]).catch(()=>""),T=await l(i,["rev-parse","--verify","--quiet",`${y}^{commit}`]).catch(()=>"");if(E!==m||H!==m||T!==x)throw new se("origin-binding-start-raced");x||(await l(i,["update-ref",y,m,""]),d={ref:y,sha:m})}}),Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...a,originHeadSha:m,outcome:"captured",executionRefCreated:d!==void 0,capturedAt:t})}catch(u){if(d&&await l(i,["update-ref","-d",d.ref,d.sha]).catch(()=>{}),u instanceof Error&&u.message==="git-lifecycle-runtime-revision-conflict"){f="origin-binding-start-raced";continue}return u instanceof se?r(u.message,a):r("origin-binding-start-failed",a)}}return r(f)}function de(e,t,o,r){return Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-receipt",storyId:e.storyId,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,originHeadSha:t.originHeadSha,leaseExpiresAt:o,reused:r,publicSafe:!0})}async function z(e){const t=q(await _(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=await Promise.all(t.map(async r=>{if(!Ce(r))throw new Error("direct-yolo-checkout-payload-invalid");return`${r}\0${await l(e,["hash-object","--no-filters","--",r])}`}));return A([await _(e,["diff","--cached","--binary","--full-index"]),await _(e,["diff","--binary","--full-index"]),await _(e,["status","--porcelain=v1","-z","--untracked-files=all"]),...o].join("\0"))}async function kr(e){const t=O(e),o=await l(t,["rev-parse","HEAD"]),r=await l(t,["symbolic-ref","--quiet","--short","HEAD"]),i=await z(t);if(await l(t,["rev-parse","HEAD"])!==o||await l(t,["symbolic-ref","--quiet","--short","HEAD"])!==r)throw new Error("direct-yolo-checkout-observation-raced");return Object.freeze({headSha:o,branch:r,payloadDigest:i})}async function re(e){const t=[];let o;for(const r of(await _(e,["worktree","list","--porcelain","-z"])).split("\0"))r.startsWith("worktree ")?(o={path:r.slice(9)},t.push(o)):o&&r.startsWith("branch refs/heads/")&&(o.branch=r.slice(18));return t}function X(e,t){return e instanceof Error&&e.message==="git-lifecycle-runtime-revision-conflict"?"direct-yolo-runtime-revision-conflict":e instanceof Error&&ge(e.message)||e instanceof Error&&/^direct-yolo-[a-z0-9-]+(?::[a-z0-9-]+)?$/.test(e.message)?e.message:t}function s(e,t){return t?{ok:!1,reasonCode:e,hint:t}:{ok:!1,reasonCode:e}}async function He(e,t){try{return await ee("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),0}catch(o){const r=o.code;return typeof r=="number"?r:-1}}async function l(e,t){return String((await ee("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function _(e,t){return String((await ee("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function B(e,t){try{return await ee("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{wr as DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS,jt as DIRECT_YOLO_WAVE_RECEIPT_REF_PREFIX,Xe as ORIGIN_BINDING_START_FETCH_TIMEOUT_MS,fr as acceptDirectYoloSetupCheckpoint,ur as beginDirectYoloStoryCommit,kr as captureDirectYoloCheckoutEvidence,br as captureEpicOriginBindingAtYoloopStart,mr as directYoloCommitIdempotencyKey,vr as directYoloWaveQaCoverage,Et as directYoloWaveReceiptRef,Kt as fetchOriginForYoloopStart,lr as finalizeDirectYoloStoryCheckpoint,Pt as isDirectYoloWriteSetExtensionScope,hr as issueDirectYoloSetupLeaseHandoff,Sr as persistDirectYoloWaveStoryCheckpoint,dr as prepareDirectYoloSetup,Ir as pushDirectYoloWaveHead,xr as readYoloopStartEpic,pr as recoverLegacyDirectYoloStoryCheckpoint,yr as resolveDirectYoloIntegrationAuthority,Rr as runDirectYoloWaveP205,gr as validateDirectYoloWriteSet,Vt as yoloopStartGitNetworkExecOptions};