@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
@@ -56,6 +56,8 @@ export interface DiscoveryHookResult {
56
56
  /** Reason hook was a no-op (only present if !applied). */
57
57
  readonly reason?: string;
58
58
  }
59
+ /** P227.17 DEC-05: discovery backup of `.neocortex/state.json` (git-ignored). */
60
+ export declare const DISCOVERY_STATE_BACKUP_SUFFIX = "backup-discovery";
59
61
  /**
60
62
  * Run discovery + merge if hook conditions are met.
61
63
  *
@@ -1,2 +1,2 @@
1
- import{existsSync as f,readFileSync as h,renameSync as m,statSync as y,writeFileSync as j}from"node:fs";import{basename as p,dirname as b,resolve as l,isAbsolute as O}from"node:path";import{discoverEpicsFromDir as w,mergeDiscoveredIntoState as g,buildDefaultDiscoveryFs as k}from"./shared-discover-epics.js";import{extractYoloopTargetPath as z,isYoloopInvocation as S}from"./target-normalization.js";function v(e,o){return O(e)?e:l(o,e)}function $(e,o,t){if(o.epics.length===0)return;const s=l(e,".neocortex","state.json");if(f(s))try{const i=h(s,"utf8"),r=JSON.parse(i),n=g(r,o);if(n.added.length===0&&n.storiesAdded===0)return;r.last_updated=new Date().toISOString();const a=`${s}.tmp.${process.pid}.${Date.now()}`;j(a,`${JSON.stringify(r,null,2)}
2
- `,"utf8"),m(a,s)}catch(i){const r=i instanceof Error?i.message:String(i);t?.warn?.(`[neocortex] discovery hook: failed to persist .neocortex/state.json: ${r}. Proceeding with request snapshot only.`)}}function A(e,o){const t=p(o),s=e.epics.filter(r=>r.path===o||r.filename===t),i=new Set(s.map(r=>r.id));return{epics:Object.freeze(s),warnings:Object.freeze([...e.warnings,...s.length===0?[`single-file discovery found no matching epic descriptor for ${t}`]:[]]),skipped:Object.freeze([...e.skipped,...e.epics.filter(r=>!i.has(r.id)).map(r=>`${r.filename}: skipped (not requested file)`)])}}async function D(e){if(!e.featureFlag)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"flag off"};if(!S(e.args))return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"not a yoloop trigger"};const o=z(e.args,e.projectRoot);if(!o)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"no path arg"};let t;try{t=v(o,e.projectRoot)}catch(r){const n=r instanceof Error?r.message:String(r);return e.logger?.warn?.(`[neocortex] discovery hook: path resolution failed: ${n}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"path resolution failed"}}let s=!1,i=!1;try{if(f(t)){const r=y(t);s=r.isDirectory(),i=r.isFile()}}catch{s=!1,i=!1}if(!s&&!i)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"path not found"};try{const r=await k(),n=s?t:b(t),a=w(n,r),c=i?A(a,t):a,d=g(e.stateSnapshot,c);$(e.projectRoot,c,e.logger),(d.added.length>0||d.storiesAdded>0)&&e.logger?.info?.(`[neocortex] discovered ${d.added.length} epic(s), ${d.storiesAdded} story-ies from ${s?t:p(t)}`);for(const u of c.warnings)e.logger?.warn?.(`[neocortex] discovery: ${u}`);return{applied:!0,added:d.added,skipped:d.skipped,storiesAdded:d.storiesAdded}}catch(r){const n=r instanceof Error?r.message:String(r);return e.logger?.warn?.(`[neocortex] discovery hook failed: ${n}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`error: ${n}`}}}async function I(e){if(!e.featureFlag)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"flag off"};try{return await D(e)}catch(o){const t=o instanceof Error?o.message:String(o);return e.logger?.warn?.(`[neocortex] discovery hook (outer) failed: ${t}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`outer error: ${t}`}}}export{I as maybeRunDiscoveryHook,D as runDiscoveryHook};
1
+ import{closeSync as k,existsSync as u,fchmodSync as O,fsyncSync as $,openSync as z,readFileSync as y,renameSync as h,statSync as m,unlinkSync as A,writeSync as v}from"node:fs";import{basename as S,dirname as D,resolve as p,isAbsolute as g,relative as F,sep as E}from"node:path";import{discoverEpicsFromDir as P,mergeDiscoveredIntoState as j,buildDefaultDiscoveryFs as R}from"./shared-discover-epics.js";import{createLegacyStoryScopeExtractor as I}from"./legacy-story-scope.js";import{extractYoloopTargetPath as T,isYoloopInvocation as x}from"./target-normalization.js";function B(e,s){return g(e)?e:p(s,e)}function _(e,s,t){if(s.epics.length===0)return;const r=p(e,".neocortex","state.json");if(u(r))try{const n=y(r,"utf8"),o=JSON.parse(n),i=j(o,s);if(i.added.length===0&&i.storiesAdded===0&&i.storiesFilled===0)return;o.last_updated=new Date().toISOString();const f=`tmp.${process.pid}.${Date.now()}`,c=`${r}.${f}`,a=`${r}.${Y}`,d=`${a}.${f}`;b(c,Buffer.from(`${JSON.stringify(o,null,2)}
2
+ `,"utf8"),J(r));try{if(b(d,Buffer.from(n,"utf8"),384),y(r,"utf8")!==n){l(c),l(d),t?.warn?.("[neocortex] discovery hook: legacy-scope-state-cas-mismatch; state.json left unchanged.");return}h(d,a),h(c,r)}catch(w){throw l(c),l(d),w}}catch(n){t?.warn?.(`[neocortex] discovery hook: failed to persist .neocortex/state.json (${C(n)}). Proceeding with request snapshot only.`)}}function C(e){const s=e?.code;return typeof s=="string"&&/^[A-Z][A-Z0-9_]{1,31}$/.test(s)?s:e instanceof SyntaxError?"state-json-invalid":"discovery-state-persist-failed"}function l(e){try{A(e)}catch{}}function J(e){try{return m(e).mode&511}catch{return 420}}function b(e,s,t){const r=z(e,"w",t);try{O(r,t),v(r,s),$(r)}finally{k(r)}}const Y="backup-discovery";function q(e){const s=p(e);return t=>{if(typeof t!="string"||t.length===0||g(t))return!1;const r=p(s,t.endsWith("/")?t.slice(0,-1):t),n=F(s,r);return n.length===0||n===".."||n.startsWith(`..${E}`)||g(n)?!1:u(r)}}function H(e,s){const t=S(s),r=e.epics.filter(o=>o.path===s||o.filename===t),n=new Set(r.map(o=>o.id));return{epics:Object.freeze(r),warnings:Object.freeze([...e.warnings,...r.length===0?[`single-file discovery found no matching epic descriptor for ${t}`]:[]]),skipped:Object.freeze([...e.skipped,...e.epics.filter(o=>!n.has(o.id)).map(o=>`${o.filename}: skipped (not requested file)`)])}}async function N(e){if(!e.featureFlag)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"flag off"};if(!x(e.args))return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"not a yoloop trigger"};const s=T(e.args,e.projectRoot);if(!s)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"no path arg"};let t;try{t=B(s,e.projectRoot)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger?.warn?.(`[neocortex] discovery hook: path resolution failed: ${i}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"path resolution failed"}}let r=!1,n=!1;try{if(u(t)){const o=m(t);r=o.isDirectory(),n=o.isFile()}}catch{r=!1,n=!1}if(!r&&!n)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"path not found"};try{const o=await R(),i=r?t:D(t),f=P(i,o,{legacyStoryScope:I(q(e.projectRoot))}),c=n?H(f,t):f,a=j(e.stateSnapshot,c);_(e.projectRoot,c,e.logger),(a.added.length>0||a.storiesAdded>0)&&e.logger?.info?.(`[neocortex] discovered ${a.added.length} epic(s), ${a.storiesAdded} story-ies from ${r?t:S(t)}`);for(const d of c.warnings)e.logger?.warn?.(`[neocortex] discovery: ${d}`);return{applied:!0,added:a.added,skipped:a.skipped,storiesAdded:a.storiesAdded}}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger?.warn?.(`[neocortex] discovery hook failed: ${i}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`error: ${i}`}}}async function M(e){if(!e.featureFlag)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"flag off"};try{return await N(e)}catch(s){const t=s instanceof Error?s.message:String(s);return e.logger?.warn?.(`[neocortex] discovery hook (outer) failed: ${t}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`outer error: ${t}`}}}export{Y as DISCOVERY_STATE_BACKUP_SUFFIX,M as maybeRunDiscoveryHook,N as runDiscoveryHook};
@@ -84,6 +84,23 @@ export declare function maybeAutoResolveYoloopArgs(ctx: AutoResolveYoloopContext
84
84
  * reinterpret corrupt/unavailable persisted state as a fresh session.
85
85
  */
86
86
  export declare function readYoloopForRequest(args: string, projectRoot: string, nowIso?: string): Promise<YoloopPersistedState | undefined>;
87
+ /**
88
+ * P227.21 (R8, DEC-06, DEC-15): `*yoloop` start hook, run by `invoke.ts` before the
89
+ * state snapshot is projected. It runs the P227.20 branch-mode conversion and
90
+ * then the origin-binding capture for the resolved target epic. The order of the start adaptations is: policy (P227.16),
91
+ * then branch-mode conversion (P227.20), then the origin binding (this hook), then the plan
92
+ * request. Only yoloop triggers do I/O. The hook never throws and never aborts
93
+ * the request: it reports one public stderr line (outcome and reason code only)
94
+ * and returns the receipt.
95
+ */
96
+ export declare function maybeCaptureYoloopStartOriginBinding(args: string, projectRoot: string, options?: {
97
+ readonly nowIso?: string;
98
+ readonly fetchTimeoutMs?: number;
99
+ readonly quiet?: boolean;
100
+ /** DEC-15 test seams forwarded to the P227.20 conversion. */
101
+ readonly prProvider?: import('../git/legacy-branch-mode-conversion.js').LegacyBranchModeConversionPrProvider;
102
+ readonly repository?: string;
103
+ }): Promise<import('./yoloop-start-origin-binding.js').OriginBindingStartReceipt | undefined>;
87
104
  /**
88
105
  * Post-response hook: apply server-provided operations to local state.
89
106
  * Safe to call for any response — no-op if no yoloopStateUpdate present.
@@ -1,12 +1,16 @@
1
- import{statSync as q}from"node:fs";import{join as J}from"node:path";import{YoloopClientStateStore as U}from"./yoloop-client-state-store.js";import{isYoloopInvocation as X}from"./target-normalization.js";import{applyStateMigration as Q,StateMigrationApplyError as ee}from"../migrations/state-json.js";function te(e){return X(e)}const N=Object.freeze({stateReadFailed:"YOLOOP_STATE_READ_FAILED",authoritativeWritebackFailed:"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED",auxiliaryWritebackFailed:"YOLOOP_AUXILIARY_WRITEBACK_FAILED"});class oe extends Error{reasonCode;constructor(o){super(o),this.reasonCode=o,this.name="YoloopStateReadError"}}function L(e,o){return(e instanceof Error?e.message:String(e)).match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??o}const W=new Set(["YOLOOP_RUN_REVISION_CONFLICT","YOLOOP_RUN_SNAPSHOT_CONFLICT","YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT","EAGAIN","EBUSY","EMFILE","ENFILE"]);function re(e){const o=L(e,"");if(W.has(o))return!0;const r=e?.code;return typeof r=="string"&&W.has(r)}const ie=/^\s*\*?(yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i;function fe(e){if(typeof e.args!="string"||e.args.length===0)return;const o=e.args.match(ie);if(!o)return;const r=o[0];if(e.args.slice(r.length).trim()!=="")return;let n=!1;try{const t=J(e.projectRoot,"docs","epics");n=q(t).isDirectory()}catch(t){const l=t instanceof Error?t.message:String(t);e.logger?.warn?.(`[Neocortex] Zero-config *yoloop hook (P121.05): could not stat docs/epics/: ${l}. Proceeding with raw args.`);return}n&&(e.args=`${r} @docs/epics/`,e.logger?.info?.("[Neocortex] Zero-config *yoloop (P121.05): auto-resolved empty args to @docs/epics/"))}async function ge(e,o,r){if(te(e))try{return await new U(o).readAll(r)}catch(i){const n=L(i,N.stateReadFailed);throw process.stderr.write(`[yoloop] ${n}. Local yoloop authority was not read; no request was sent.
2
- `),new oe(n)}}async function he(e,o,r){if(!e)return{ok:!0,authoritative:!1,reasonCodes:[]};const i=e.yoloopStateUpdate;if(!i||!Array.isArray(i.operations)||i.operations.length===0)return{ok:!0,authoritative:!1,reasonCodes:[]};const n=i.operations.some(p=>p.type==="rollover_session"||p.type==="commit_successor_transition");let t;const l=n?3:1;for(let p=0;p<l;p+=1)try{return await new U(o).applyUpdate(i,r),{ok:!0,authoritative:n,reasonCodes:[]}}catch(u){if(t=u,!n||p+1>=l||!re(u))break}{const u=L(t,n?N.authoritativeWritebackFailed:N.auxiliaryWritebackFailed);return n?(process.stderr.write(`[yoloop] ${u}. Authoritative yoloop transition was not persisted; no continuation instructions were released.
3
- `),{ok:!1,authoritative:!0,reasonCodes:[u]}):(process.stderr.write(`[yoloop] ${u}. Auxiliary state update was not persisted; retry the same command.
4
- `),{ok:!0,authoritative:!1,reasonCodes:[u]})}}function a(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function j(e,o){return Array.isArray(e)&&e.length<=o&&e.every(r=>typeof r=="string"&&r.length>0&&r.length<=160&&/^[A-Za-z0-9_.:+-]+$/.test(r))}function G(e){return a(e.scope)?e.scope.kind==="projected"||typeof e.scope.omittedStoryCount=="number"&&e.scope.omittedStoryCount>0||typeof e.scope.omittedEpicCount=="number"&&e.scope.omittedEpicCount>0:!1}function ne(e){const o={...e};return delete o.scope,delete o.stateSummary,delete o.graphRetrieval,delete o.runnerBootstrap,delete o.projectEvidence,delete o.continuity,delete o.implementCheckpoint,o}function ae(e){return typeof e=="string"&&["done","completed","merged"].includes(e.trim().toLowerCase())}function se(e){return/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(e)&&!e.includes("..")&&!e.includes("//")&&!e.includes("@{")&&!e.endsWith("/")&&!e.endsWith(".")&&!e.endsWith(".lock")}async function ce(e,o){const r=e.syntheticStory;if(!a(r))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-missing"};const i=r.schemaVersion,n=r.epicId,t=r.storyId,l=r.storyPath,p=r.deterministicKey,u=r.storyContent,A=r.storyContentSha256,y=r.lifecycle;if(i!==2||typeof n!="string"||!/^P9\d{18}$/.test(n)||typeof t!="string"||t!==`${n}.01.000001`||typeof l!="string"||l!==`docs/stories/${t}.story.md`||typeof p!="string"||!/^[a-f0-9]{16}$/.test(p)||typeof A!="string"||!/^[a-f0-9]{64}$/.test(A)||typeof u!="string"||u.length===0||u.length>131072||!a(y)||y.branchMode!=="epic"||y.executionBranch!==`epic/${n}`||typeof y.originBranch!="string"||!se(y.originBranch)||typeof y.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(y.graphRevision)||y.isolatedSyntheticEpic!==!0||r.publicSafe!==!0||r.sanitized!==!0)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-invalid"};const d=await import("node:fs/promises"),S=await import("node:path"),O=await import("node:crypto");if(O.createHash("sha256").update(u).digest("hex")!==A)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-content-integrity-invalid"};const C=S.join(o,".neocortex"),I=S.join(C,"state.json"),w=S.join(o,...l.split("/"));let $;try{$=await d.readFile(I,"utf8")}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-missing"}}const P=O.createHash("sha256").update($).digest("hex");let f;try{f=JSON.parse($)}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-corrupt"}}if(!a(f)||!a(f.stories)||!a(f.epics)||G(f))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-not-full"};if(!a(f.config)||f.config.default_branch!==y.originBranch)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-origin-branch-conflict"};const c=f.stories[t];if(c!==void 0&&(!a(c)||c.epic_id!==n||c.story_file!==l||!a(c.inlineYolo)||c.inlineYolo.deterministicKey!==p))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-conflict"};const g=f.epics[n];if(g!==void 0&&(!a(g)||g.id!==n||g.source!=="inline-yolo-materialization"||g.branch_mode!=="epic"||g.execution_branch!==y.executionBranch||g.origin_branch!==y.originBranch||g.graph_revision!==y.graphRevision||!a(g.inlineYoloLifecycle)||g.inlineYoloLifecycle.deterministicKey!==p||g.inlineYoloLifecycle.isolatedSyntheticEpic!==!0||!Array.isArray(g.stories)))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-conflict"};const E=a(g)?g:{},b=Array.isArray(E.stories)?E.stories:[];if(b.some(s=>typeof s!="string")||new Set(b).size!==b.length)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-story-list-invalid"};for(const s of b){const h=f.stories[s];if(!a(h)||h.id!==s||h.epic_id!==n)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-ownership-conflict"}}try{const s=await d.readFile(w,"utf8"),h=s.includes(`id: ${t}`)&&s.includes(`synthetic_key: ${p}`);if(s!==u&&!h)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-conflict"}}catch(s){if(s.code!=="ENOENT")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-unreadable"}}const k=b.includes(t)?[...b]:[...b,t],T={...f.stories,[t]:{...a(c)?c:{},id:t,epic_id:n,title:"Synthetic inline USER STORY for yolo",status:a(c)&&typeof c.status=="string"?c.status:"backlog",steps_completed:a(c)&&Array.isArray(c.steps_completed)?c.steps_completed:[],last_step:a(c)?c.last_step??null:null,branch_name:a(c)?c.branch_name??null:null,story_file:l,source:"inline-yolo-materialization",inlineYolo:{...a(c)&&a(c.inlineYolo)?c.inlineYolo:{},schemaVersion:2,deterministicKey:p,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0}}},v=k.filter(s=>a(T[s])&&ae(T[s].status)).length,Y=a(f.inlineYolo)?f.inlineYolo:{},K=a(Y.materializations)?Y.materializations:{},Z=ne({...f,stories:T,epics:{...f.epics,[n]:{...E,id:n,title:typeof E.title=="string"?E.title:"Isolated synthetic inline yolo lifecycle",status:v===k.length&&k.length>0?"done":"in-progress",source:"inline-yolo-materialization",branch_mode:"epic",execution_branch:y.executionBranch,origin_branch:y.originBranch,graph_revision:y.graphRevision,stories:k,total_stories:k.length,completed_stories:v,...v===k.length&&k.length>0?{}:{completed_at:null},inlineYoloLifecycle:{schemaVersion:2,deterministicKey:p,isolatedSyntheticEpic:!0}}},inlineYolo:{...Y,schemaVersion:2,materializations:{...K,[t]:{schemaVersion:2,epicId:n,storyId:t,storyPath:l,deterministicKey:p,storyContentSha256:A,sourceStateSha256:P,lifecycle:y,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0,pipelineTrigger:`*yolo @${l}`,reasonCodes:Array.isArray(r.reasonCodes)?r.reasonCodes:[]}}},last_updated:new Date().toISOString()}),B=`${Date.now()}-${O.randomBytes(6).toString("hex")}`,z=S.join(C,`state.json.tmp.${B}`),x=`${w}.tmp.${B}`,F=S.join(C,`state.json.backup-${new Date().toISOString().replace(/[:.]/g,"-")}`),V=S.join(C,"state.json.inline-yolo.lock");let D=!1,_;const H=async s=>{let h;try{h=await d.open(s,"r"),await h.sync()}catch(m){const R=m.code;if(!["EINVAL","ENOTSUP","EPERM","EISDIR"].includes(R??""))throw m}finally{await h?.close().catch(()=>{})}},M=async(s,h)=>{const m=await d.open(s,"wx",384);try{await m.writeFile(h,"utf8"),await m.sync()}finally{await m.close()}};try{await d.mkdir(C,{recursive:!0}),await d.mkdir(S.dirname(w),{recursive:!0});try{_=await d.open(V,"wx",384),await _.writeFile(`${process.pid}
1
+ import{statSync as J}from"node:fs";import{join as X}from"node:path";import{YoloopClientStateStore as L}from"./yoloop-client-state-store.js";import{LEGACY_ADOPTION_RECEIPT_SCHEMA as Q,LEGACY_ADOPTION_TARGET_POLICY as ee,runLegacyYoloopAdoption as te}from"./legacy-yoloop-adoption.js";import{isYoloopInvocation as oe}from"./target-normalization.js";import{applyStateMigration as re,StateMigrationApplyError as ie}from"../migrations/state-json.js";function W(e){return oe(e)}const N=Object.freeze({stateReadFailed:"YOLOOP_STATE_READ_FAILED",authoritativeWritebackFailed:"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED",auxiliaryWritebackFailed:"YOLOOP_AUXILIARY_WRITEBACK_FAILED"});class ne extends Error{reasonCode;constructor(r){super(r),this.reasonCode=r,this.name="YoloopStateReadError"}}function j(e,r){return(e instanceof Error?e.message:String(e)).match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??r}const G=new Set(["YOLOOP_RUN_REVISION_CONFLICT","YOLOOP_RUN_SNAPSHOT_CONFLICT","YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT","EAGAIN","EBUSY","EMFILE","ENFILE"]);function ae(e){const r=j(e,"");if(G.has(r))return!0;const t=e?.code;return typeof t=="string"&&G.has(t)}const se=/^\s*\*?(yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i;function we(e){if(typeof e.args!="string"||e.args.length===0)return;const r=e.args.match(se);if(!r)return;const t=r[0];if(e.args.slice(t.length).trim()!=="")return;let n=!1;try{const o=X(e.projectRoot,"docs","epics");n=J(o).isDirectory()}catch(o){const a=o instanceof Error?o.message:String(o);e.logger?.warn?.(`[Neocortex] Zero-config *yoloop hook (P121.05): could not stat docs/epics/: ${a}. Proceeding with raw args.`);return}n&&(e.args=`${t} @docs/epics/`,e.logger?.info?.("[Neocortex] Zero-config *yoloop (P121.05): auto-resolved empty args to @docs/epics/"))}async function be(e,r,t){if(W(e))try{const i=await te(r,t?{nowIso:t}:{});return i.written&&process.stderr.write(`[yoloop] ${i.receipt.reasonCode}: continuation policy ${ee} (${Q}).
2
+ `),await new L(r).readAll(t)}catch(i){const n=j(i,N.stateReadFailed);throw process.stderr.write(`[yoloop] ${n}. Local yoloop authority was not read; no request was sent.
3
+ `),new ne(n)}}async function Se(e,r,t={}){if(W(e))try{let i;try{i=(await new L(r).readAll(t.nowIso))?.state?.currentEpicId}catch{i=void 0}const{runYoloopStartAdaptations:n}=await import("./yoloop-start-origin-binding.js"),o=await n({args:e,projectRoot:r,persistedCurrentEpicId:i,...t.nowIso?{nowIso:t.nowIso}:{},...t.fetchTimeoutMs?{fetchTimeoutMs:t.fetchTimeoutMs}:{},...t.prProvider?{prProvider:t.prProvider}:{},...t.repository?{repository:t.repository}:{}}),a=o.branchModeConversion;!t.quiet&&a&&(a.outcome==="converted"||a.outcome==="refused"&&a.reasonCode!=="branch-mode-conversion-epic-missing")&&process.stderr.write(`[yoloop] branch-mode-conversion-start ${a.outcome}${a.reasonCode?` ${a.reasonCode}`:""}.
4
+ `);const s=o.originBinding,p=s.reasonCode==="origin-binding-start-target-ambiguous"||s.reasonCode==="origin-binding-start-target-terminal"||s.reasonCode==="origin-binding-start-branch-mode-not-epic"||s.reasonCode==="origin-binding-start-state-invalid"||s.reasonCode==="origin-binding-start-failed";return!t.quiet&&s.outcome!=="already-bound"&&!p&&process.stderr.write(`[yoloop] origin-binding-start ${s.outcome}${s.reasonCode?` ${s.reasonCode}`:""}.
5
+ `),s}catch{t.quiet||process.stderr.write(`[yoloop] origin-binding-start refused origin-binding-start-failed.
6
+ `);return}}async function Ce(e,r,t){if(!e)return{ok:!0,authoritative:!1,reasonCodes:[]};const i=e.yoloopStateUpdate;if(!i||!Array.isArray(i.operations)||i.operations.length===0)return{ok:!0,authoritative:!1,reasonCodes:[]};const n=i.operations.some(s=>s.type==="rollover_session"||s.type==="commit_successor_transition");let o;const a=n?3:1;for(let s=0;s<a;s+=1)try{return await new L(r).applyUpdate(i,t),{ok:!0,authoritative:n,reasonCodes:[]}}catch(p){if(o=p,!n||s+1>=a||!ae(p))break}{const p=j(o,n?N.authoritativeWritebackFailed:N.auxiliaryWritebackFailed);return n?(process.stderr.write(`[yoloop] ${p}. Authoritative yoloop transition was not persisted; no continuation instructions were released.
7
+ `),{ok:!1,authoritative:!0,reasonCodes:[p]}):(process.stderr.write(`[yoloop] ${p}. Auxiliary state update was not persisted; retry the same command.
8
+ `),{ok:!0,authoritative:!1,reasonCodes:[p]})}}function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function M(e,r){return Array.isArray(e)&&e.length<=r&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=160&&/^[A-Za-z0-9_.:+-]+$/.test(t))}function K(e){return c(e.scope)?e.scope.kind==="projected"||typeof e.scope.omittedStoryCount=="number"&&e.scope.omittedStoryCount>0||typeof e.scope.omittedEpicCount=="number"&&e.scope.omittedEpicCount>0:!1}function ce(e){const r={...e};return delete r.scope,delete r.stateSummary,delete r.graphRetrieval,delete r.runnerBootstrap,delete r.projectEvidence,delete r.continuity,delete r.implementCheckpoint,r}function le(e){return typeof e=="string"&&["done","completed","merged"].includes(e.trim().toLowerCase())}function de(e){return/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(e)&&!e.includes("..")&&!e.includes("//")&&!e.includes("@{")&&!e.endsWith("/")&&!e.endsWith(".")&&!e.endsWith(".lock")}async function pe(e,r){const t=e.syntheticStory;if(!c(t))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-missing"};const i=t.schemaVersion,n=t.epicId,o=t.storyId,a=t.storyPath,s=t.deterministicKey,p=t.storyContent,E=t.storyContentSha256,f=t.lifecycle;if(i!==2||typeof n!="string"||!/^P9\d{18}$/.test(n)||typeof o!="string"||o!==`${n}.01.000001`||typeof a!="string"||a!==`docs/stories/${o}.story.md`||typeof s!="string"||!/^[a-f0-9]{16}$/.test(s)||typeof E!="string"||!/^[a-f0-9]{64}$/.test(E)||typeof p!="string"||p.length===0||p.length>131072||!c(f)||f.branchMode!=="epic"||f.executionBranch!==`epic/${n}`||typeof f.originBranch!="string"||!de(f.originBranch)||typeof f.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(f.graphRevision)||f.isolatedSyntheticEpic!==!0||t.publicSafe!==!0||t.sanitized!==!0)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-invalid"};const u=await import("node:fs/promises"),w=await import("node:path"),I=await import("node:crypto");if(I.createHash("sha256").update(p).digest("hex")!==E)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-content-integrity-invalid"};const k=w.join(r,".neocortex"),O=w.join(k,"state.json"),b=w.join(r,...a.split("/"));let R;try{R=await u.readFile(O,"utf8")}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-missing"}}const P=I.createHash("sha256").update(R).digest("hex");let y;try{y=JSON.parse(R)}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-corrupt"}}if(!c(y)||!c(y.stories)||!c(y.epics)||K(y))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-not-full"};if(!c(y.config)||y.config.default_branch!==f.originBranch)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-origin-branch-conflict"};const d=y.stories[o];if(d!==void 0&&(!c(d)||d.epic_id!==n||d.story_file!==a||!c(d.inlineYolo)||d.inlineYolo.deterministicKey!==s))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-conflict"};const g=y.epics[n];if(g!==void 0&&(!c(g)||g.id!==n||g.source!=="inline-yolo-materialization"||g.branch_mode!=="epic"||g.execution_branch!==f.executionBranch||g.origin_branch!==f.originBranch||g.graph_revision!==f.graphRevision||!c(g.inlineYoloLifecycle)||g.inlineYoloLifecycle.deterministicKey!==s||g.inlineYoloLifecycle.isolatedSyntheticEpic!==!0||!Array.isArray(g.stories)))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-conflict"};const _=c(g)?g:{},S=Array.isArray(_.stories)?_.stories:[];if(S.some(l=>typeof l!="string")||new Set(S).size!==S.length)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-story-list-invalid"};for(const l of S){const m=y.stories[l];if(!c(m)||m.id!==l||m.epic_id!==n)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-ownership-conflict"}}try{const l=await u.readFile(b,"utf8"),m=l.includes(`id: ${o}`)&&l.includes(`synthetic_key: ${s}`);if(l!==p&&!m)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-conflict"}}catch(l){if(l.code!=="ENOENT")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-unreadable"}}const C=S.includes(o)?[...S]:[...S,o],T={...y.stories,[o]:{...c(d)?d:{},id:o,epic_id:n,title:"Synthetic inline USER STORY for yolo",status:c(d)&&typeof d.status=="string"?d.status:"backlog",steps_completed:c(d)&&Array.isArray(d.steps_completed)?d.steps_completed:[],last_step:c(d)?d.last_step??null:null,branch_name:c(d)?d.branch_name??null:null,story_file:a,source:"inline-yolo-materialization",inlineYolo:{...c(d)&&c(d.inlineYolo)?d.inlineYolo:{},schemaVersion:2,deterministicKey:s,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0}}},v=C.filter(l=>c(T[l])&&le(T[l].status)).length,Y=c(y.inlineYolo)?y.inlineYolo:{},Z=c(Y.materializations)?Y.materializations:{},q=ce({...y,stories:T,epics:{...y.epics,[n]:{..._,id:n,title:typeof _.title=="string"?_.title:"Isolated synthetic inline yolo lifecycle",status:v===C.length&&C.length>0?"done":"in-progress",source:"inline-yolo-materialization",branch_mode:"epic",execution_branch:f.executionBranch,origin_branch:f.originBranch,graph_revision:f.graphRevision,stories:C,total_stories:C.length,completed_stories:v,...v===C.length&&C.length>0?{}:{completed_at:null},inlineYoloLifecycle:{schemaVersion:2,deterministicKey:s,isolatedSyntheticEpic:!0}}},inlineYolo:{...Y,schemaVersion:2,materializations:{...Z,[o]:{schemaVersion:2,epicId:n,storyId:o,storyPath:a,deterministicKey:s,storyContentSha256:E,sourceStateSha256:P,lifecycle:f,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0,pipelineTrigger:`*yolo @${a}`,reasonCodes:Array.isArray(t.reasonCodes)?t.reasonCodes:[]}}},last_updated:new Date().toISOString()}),B=`${Date.now()}-${I.randomBytes(6).toString("hex")}`,x=w.join(k,`state.json.tmp.${B}`),z=`${b}.tmp.${B}`,F=w.join(k,`state.json.backup-${new Date().toISOString().replace(/[:.]/g,"-")}`),D=w.join(k,"state.json.inline-yolo.lock");let H=!1,A;const V=async l=>{let m;try{m=await u.open(l,"r"),await m.sync()}catch(h){const $=h.code;if(!["EINVAL","ENOTSUP","EPERM","EISDIR"].includes($??""))throw h}finally{await m?.close().catch(()=>{})}},U=async(l,m)=>{const h=await u.open(l,"wx",384);try{await h.writeFile(m,"utf8"),await h.sync()}finally{await h.close()}};try{await u.mkdir(k,{recursive:!0}),await u.mkdir(w.dirname(b),{recursive:!0});try{A=await u.open(D,"wx",384),await A.writeFile(`${process.pid}
5
9
  ${P}
6
- `,"utf8"),await _.sync()}catch(R){if(R.code==="EEXIST")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-writeback-locked"};throw R}const s=await d.readFile(I,"utf8");if(O.createHash("sha256").update(s).digest("hex")!==P)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-cas-conflict"};try{await d.access(w)}catch{await M(x,u),await d.rename(x,w),await H(S.dirname(w)),D=!0}await d.copyFile(I,F);const m=await d.open(F,"r");try{await m.sync()}finally{await m.close()}return await M(z,JSON.stringify(Z,null,2)),await d.rename(z,I),await H(C),process.stderr.write(`[Neocortex] inline yolo story materialized with bounded full-state merge; story=${t}; backup=${S.basename(F)}.
7
- `),{applied:!0,blocking:!1,reasonCode:"inline-yolo-materialized"}}catch(s){await Promise.allSettled([d.unlink(z),d.unlink(x)]),D&&await d.readFile(w,"utf8").catch(()=>{})===u&&await d.unlink(w).catch(()=>{});const h=s.message??String(s);return process.stderr.write(`[Neocortex] inline yolo materialization failed: ${h}.
8
- `),{applied:!1,blocking:!0,reasonCode:"inline-yolo-persistence-failed"}}finally{await _?.close().catch(()=>{}),_&&await d.unlink(V).catch(()=>{})}}async function me(e,o){if(!e||e.stateMutated!==!0)return{applied:!1,blocking:!1,reasonCode:"state-writeback-not-requested"};if(e.stateMutationStrategy==="merge-inline-yolo-v2"||e.stateMutationReason==="inline-yolo-materialized-synthetic-story")return ce(e,o);if(e.stateMutationStrategy==="state-migration-v1"||e.stateMigrationPlan!==void 0){const i=e.stateMigrationPlan,n=new Set(["schemaVersion","operationId","sourceSchemaVersion","targetSchemaVersion","sourceCanonicalHash","targetCanonicalHash","steps","migratedEpicIds","migratedStoryIds","preservedUnknownFieldCount","reasonCodes","sourceByteDigest"]);if(!a(i)||Object.keys(i).some(t=>!n.has(t))||i.schemaVersion!=="StateMigrationPlan/1.0"||typeof i.operationId!="string"||!/^smig_[a-f0-9]{32}$/.test(i.operationId)||typeof i.sourceCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(i.sourceCanonicalHash)||typeof i.targetCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(i.targetCanonicalHash)||typeof i.sourceByteDigest!="string"||!/^[a-f0-9]{64}$/.test(i.sourceByteDigest)||![0,1,"absent"].includes(i.sourceSchemaVersion)||i.targetSchemaVersion!==1||!Array.isArray(i.steps)||i.steps.length>8192||i.steps.some(t=>!a(t)||Object.keys(t).some(l=>!["kind","source","target"].includes(l))||!["initialize-collection","merge-epic","merge-story","preserve-legacy","remove-legacy","set-schema-version"].includes(String(t.kind))||typeof t.target!="string"||t.target.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(t.target)||t.source!==void 0&&(typeof t.source!="string"||t.source.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(t.source)))||!j(i.migratedEpicIds,4096)||!j(i.migratedStoryIds,4096)||!j(i.reasonCodes,32)||!Number.isSafeInteger(i.preservedUnknownFieldCount)||i.preservedUnknownFieldCount<0)return{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"};try{const t=Q(o,i),l=`.neocortex/state.json.migration-backup-${t.operationId}`;return process.stderr.write(`[P220-EV-STATE-MIGRATION] outcome=${t.outcome}; operation=${t.operationId}; backup=${t.backupHash?l:"none"}.
9
- `),{applied:t.outcome==="applied",blocking:!1,reasonCode:t.outcome==="applied"?"state-migration-applied":"state-migration-replay-verified"}}catch(t){const l=t instanceof ee?t.reasonCode:"state-migration-apply-failed";return process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=${l}.
10
- `),{applied:!1,blocking:!0,reasonCode:l}}}const r=e.migratedState;return!r||typeof r!="object"||Array.isArray(r)?{applied:!1,blocking:!0,reasonCode:"state-writeback-payload-missing"}:G(r)?(process.stderr.write(`[Neocortex] Refused projected/partial state replacement; canonical state was not modified.
10
+ `,"utf8"),await A.sync()}catch($){if($.code==="EEXIST")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-writeback-locked"};throw $}const l=await u.readFile(O,"utf8");if(I.createHash("sha256").update(l).digest("hex")!==P)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-cas-conflict"};try{await u.access(b)}catch{await U(z,p),await u.rename(z,b),await V(w.dirname(b)),H=!0}await u.copyFile(O,F);const h=await u.open(F,"r");try{await h.sync()}finally{await h.close()}return await U(x,JSON.stringify(q,null,2)),await u.rename(x,O),await V(k),process.stderr.write(`[Neocortex] inline yolo story materialized with bounded full-state merge; story=${o}; backup=${w.basename(F)}.
11
+ `),{applied:!0,blocking:!1,reasonCode:"inline-yolo-materialized"}}catch(l){await Promise.allSettled([u.unlink(x),u.unlink(z)]),H&&await u.readFile(b,"utf8").catch(()=>{})===p&&await u.unlink(b).catch(()=>{});const m=l.message??String(l);return process.stderr.write(`[Neocortex] inline yolo materialization failed: ${m}.
12
+ `),{applied:!1,blocking:!0,reasonCode:"inline-yolo-persistence-failed"}}finally{await A?.close().catch(()=>{}),A&&await u.unlink(D).catch(()=>{})}}async function ke(e,r){if(!e||e.stateMutated!==!0)return{applied:!1,blocking:!1,reasonCode:"state-writeback-not-requested"};if(e.stateMutationStrategy==="merge-inline-yolo-v2"||e.stateMutationReason==="inline-yolo-materialized-synthetic-story")return pe(e,r);if(e.stateMutationStrategy==="state-migration-v1"||e.stateMigrationPlan!==void 0){const i=e.stateMigrationPlan,n=new Set(["schemaVersion","operationId","sourceSchemaVersion","targetSchemaVersion","sourceCanonicalHash","targetCanonicalHash","steps","migratedEpicIds","migratedStoryIds","preservedUnknownFieldCount","reasonCodes","sourceByteDigest"]);if(!c(i)||Object.keys(i).some(o=>!n.has(o))||i.schemaVersion!=="StateMigrationPlan/1.0"||typeof i.operationId!="string"||!/^smig_[a-f0-9]{32}$/.test(i.operationId)||typeof i.sourceCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(i.sourceCanonicalHash)||typeof i.targetCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(i.targetCanonicalHash)||typeof i.sourceByteDigest!="string"||!/^[a-f0-9]{64}$/.test(i.sourceByteDigest)||![0,1,"absent"].includes(i.sourceSchemaVersion)||i.targetSchemaVersion!==1||!Array.isArray(i.steps)||i.steps.length>8192||i.steps.some(o=>!c(o)||Object.keys(o).some(a=>!["kind","source","target"].includes(a))||!["initialize-collection","merge-epic","merge-story","preserve-legacy","remove-legacy","set-schema-version"].includes(String(o.kind))||typeof o.target!="string"||o.target.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(o.target)||o.source!==void 0&&(typeof o.source!="string"||o.source.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(o.source)))||!M(i.migratedEpicIds,4096)||!M(i.migratedStoryIds,4096)||!M(i.reasonCodes,32)||!Number.isSafeInteger(i.preservedUnknownFieldCount)||i.preservedUnknownFieldCount<0)return{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"};try{const o=re(r,i),a=`.neocortex/state.json.migration-backup-${o.operationId}`;return process.stderr.write(`[P220-EV-STATE-MIGRATION] outcome=${o.outcome}; operation=${o.operationId}; backup=${o.backupHash?a:"none"}.
13
+ `),{applied:o.outcome==="applied",blocking:!1,reasonCode:o.outcome==="applied"?"state-migration-applied":"state-migration-replay-verified"}}catch(o){const a=o instanceof ie?o.reasonCode:"state-migration-apply-failed";return process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=${a}.
14
+ `),{applied:!1,blocking:!0,reasonCode:a}}}const t=e.migratedState;return!t||typeof t!="object"||Array.isArray(t)?{applied:!1,blocking:!0,reasonCode:"state-writeback-payload-missing"}:K(t)?(process.stderr.write(`[Neocortex] Refused projected/partial state replacement; canonical state was not modified.
11
15
  `),{applied:!1,blocking:!0,reasonCode:"state-writeback-partial-rejected"}):(process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=state-migration-plan-missing-or-invalid; canonical state was not modified.
12
- `),{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"})}async function Se(e){if(!e.featureFlag)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"flag off"};try{return await(await import("./discovery-hook.js")).runDiscoveryHook(e)}catch(o){const r=o instanceof Error?o.message:String(o);return e.logger?.warn?.(`[neocortex] discovery hook (lazy load) failed: ${r}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`lazy load error: ${r}`}}}async function we(e){if(!e.featureFlag)return{applied:!1,reason:"flag_off"};try{return await(await import("../graph-retrieval/pre-command-hook.js")).runGraphRetrievalHook(e)}catch(o){const r=o instanceof Error?o.message:String(o);return e.logger?.warn?.(`[neocortex] graph retrieval hook (lazy load) failed: ${r}. Proceeding without enrichment.`),{applied:!1,reason:"hook_error",warning:r}}}export{N as YOLOOP_PERSISTENCE_REASON_CODES,oe as YoloopStateReadError,te as isYoloopTrigger,fe as maybeAutoResolveYoloopArgs,Se as maybeRunDiscoveryHook,we as maybeRunGraphRetrievalHook,me as persistMigratedStateFromResponse,he as persistYoloopFromResponse,ge as readYoloopForRequest};
16
+ `),{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"})}async function Ee(e){if(!e.featureFlag)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"flag off"};try{return await(await import("./discovery-hook.js")).runDiscoveryHook(e)}catch(r){const t=r instanceof Error?r.message:String(r);return e.logger?.warn?.(`[neocortex] discovery hook (lazy load) failed: ${t}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`lazy load error: ${t}`}}}async function _e(e){if(!e.featureFlag)return{applied:!1,reason:"flag_off"};try{return await(await import("../graph-retrieval/pre-command-hook.js")).runGraphRetrievalHook(e)}catch(r){const t=r instanceof Error?r.message:String(r);return e.logger?.warn?.(`[neocortex] graph retrieval hook (lazy load) failed: ${t}. Proceeding without enrichment.`),{applied:!1,reason:"hook_error",warning:t}}}export{N as YOLOOP_PERSISTENCE_REASON_CODES,ne as YoloopStateReadError,W as isYoloopTrigger,we as maybeAutoResolveYoloopArgs,Se as maybeCaptureYoloopStartOriginBinding,Ee as maybeRunDiscoveryHook,_e as maybeRunGraphRetrievalHook,ke as persistMigratedStateFromResponse,Ce as persistYoloopFromResponse,be as readYoloopForRequest};
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ * This file is part of Neocortex CLI, licensed under the
5
+ * Functional Source License, Version 1.1 (FSL-1.1).
6
+ * Change Date: February 20, 2029
7
+ * Change License: MIT
8
+ * See the LICENSE file in the project root for full license text.
9
+ */
10
+ import type { LegacyStoryScopeExtractor, LegacyStoryScopeInput, LegacyStoryScopeResult } from './shared-discover-epics.js';
11
+ export declare const LEGACY_STORY_SCOPE_RECEIPT_SCHEMA: "LegacyStoryScopeReceipt/1";
12
+ export declare const LEGACY_STORY_SCOPE_MAX_STORY_BYTES = 131072;
13
+ export declare const LEGACY_STORY_SCOPE_MAX_EPIC_BYTES = 524288;
14
+ export declare const LEGACY_STORY_SCOPE_MAX_TABLE_ROWS = 512;
15
+ export declare const LEGACY_STORY_SCOPE_MAX_SCOPES = 256;
16
+ export interface LegacyStoryScopeExtractionInput extends LegacyStoryScopeInput {
17
+ /** Injected predicate over project-relative paths (Mover/Remover rows). */
18
+ readonly pathExists: (relativePath: string) => boolean;
19
+ }
20
+ /** Pure extraction for one story (P227.17-R1..R9). */
21
+ export declare function extractLegacyStoryScope(input: LegacyStoryScopeExtractionInput): LegacyStoryScopeResult;
22
+ /** Bind `pathExists` once and expose the canonical discovery extractor shape. */
23
+ export declare function createLegacyStoryScopeExtractor(pathExists: (relativePath: string) => boolean): LegacyStoryScopeExtractor;
@@ -0,0 +1 @@
1
+ import{createHash as T}from"node:crypto";import{isStoryWriteScopeGovernancePath as g,validateStoryWriteScope as b}from"../../../shared/dist/yoloop/story-write-scope.js";const v="LegacyStoryScopeReceipt/1",N=131072,R=524288,Y=512,z=256,I=/^---\s*\n([\s\S]*?)\n---/,P=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,W=/^[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+-[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+$/,M=new Set(["arquivos a criar/modificar","files to create/modify"]),D=new Set(["arquivo","arquivos","file","files","path"]),$=new Set(["a\xE7\xE3o","acao","action"]),G=new Set(["story","hist\xF3ria","historia","id"]),j=new Set(["depends_on","depende de"]),B=new Set(["criar","create","modificar","modify","atualizar","update"]),U=new Set(["remover","remove","excluir","delete"]),Z=new Set(["mover","move"]),q=new Set(["\u2014","\u2013","-","","nenhuma","none"]),m=/^(?:null|Null|NULL|~)$/;class H{counts=new Map;add(e,t=1){t>0&&this.counts.set(e,(this.counts.get(e)??0)+t)}codes(){return[...this.counts.keys()]}toArray(){return[...this.counts.entries()].sort(([e],[t])=>_(e,t)).map(([e,t])=>({reason_code:e,count:t}))}}function X(o){const e=typeof o.content=="string"?o.content:"",t=new Set,n=new H,r=e.match(I)?.[1];let s="none",c=[];if(Buffer.byteLength(e,"utf8")>N)t.add("legacy-scope-input-too-large");else{const d=r===void 0?void 0:x(r,"files_to_modify");if(d?.declared)s="frontmatter",c=h(d.items.map(p=>({token:p})),n,o.pathExists);else{const p=J(e);p==="too-large"?t.add("legacy-scope-input-too-large"):p?(s="table",c=F(p,n,o.pathExists)):t.add("legacy-scope-undeclared")}}let i=[...new Set(c)].sort(_);i.length>z?(t.add("legacy-scope-limit-exceeded"),i=void 0):i.length===0&&(s!=="none"&&t.add("legacy-scope-no-valid-paths"),i=void 0),i&&t.add(`legacy-scope-source-${s}`);let a="none",l,u=!1;const y=r===void 0?void 0:x(r,"depends_on");if(y?.declared)a="frontmatter",l=A(y.items,t);else if(typeof o.epicContent=="string"){u=!0;const d=ee(o.epicContent,o.storyId);d.kind==="found"?(a="epic-table",l=Q(d.cell,t)):d.kind==="ambiguous"?t.add("legacy-dependency-ambiguous"):t.add(d.kind==="too-large"?"legacy-scope-input-too-large":"legacy-dependency-undeclared")}else t.add("legacy-dependency-undeclared");l&&t.add("legacy-dependency-declared");for(const d of n.codes())t.add(d);const k=Object.freeze({schema:v,story_id:o.storyId,story_sha256:L(e),...u&&typeof o.epicContent=="string"?{epic_sha256:L(o.epicContent)}:{},scope_source:s,scope_basis:i?"validated":"unknown",accepted_count:i?.length??0,discarded:Object.freeze(n.toArray().map(d=>Object.freeze(d))),dependency_source:a,dependency_basis:l?"declared":"unknown",reason_codes:Object.freeze([...t].sort(_))});return Object.freeze({...i?{files_to_modify:Object.freeze(i)}:{},...l?{depends_on:Object.freeze(l)}:{},receipt:k})}function oe(o){return e=>X({...e,pathExists:o})}function h(o,e,t,n="none"){const r=[];for(const c of o){const i=c.token.startsWith("./")?c.token.slice(2):c.token;if(i.includes("|")||m.test(i)){e.add("legacy-scope-path-invalid");continue}const a=b(i);if(!a.ok){e.add("legacy-scope-path-invalid"),e.add(a.reasonCode);continue}if(V(i)){e.add("legacy-scope-governance");continue}r.push(i)}return n==="none"||r.length===0||(n==="all"?r:r.slice(0,1)).every(c=>K(t,c))?r:(e.add("legacy-scope-move-remove-missing",r.length),[])}function F(o,e,t){const n=[];for(const r of o){const s=[...r.pathCell.matchAll(/`([^`]+)`/g)].map(a=>a[1].trim()).filter(Boolean);if(s.length===0){e.add("legacy-scope-path-unquoted");continue}const c=s.map(a=>({token:a})),i=f(r.action);B.has(i)?n.push(...h(c,e,t)):U.has(i)?n.push(...h(c,e,t,"all")):Z.has(i)?n.push(...h(c,e,t,"first")):e.add("legacy-scope-action-unknown",s.length)}return n}function V(o){const e=(o.endsWith("/")?o.slice(0,-1):o).split("/"),t=[];for(const r of e){if(r.includes("*"))break;t.push(r)}const n=t.join("/");return g(o)||n.length>0&&(g(n)||g(`${n}/`))}function K(o,e){try{return o(e)===!0}catch{return!1}}function J(o){const e=o.split(/\r?\n/),t=E(e);for(let n=0;n<e.length;n++){if(t[n])continue;const r=/^(#{2,4})\s+(.+?)\s*#*\s*$/.exec(e[n].trim());if(!r||!M.has(r[2].trim().toLowerCase()))continue;const s=S(e,n+1,t);if(s==="too-large")return s;if(!s)return;const c=s.header.findIndex(a=>D.has(f(a))),i=s.header.findIndex(a=>$.has(f(a)));return c<0||i<0?void 0:s.rows.map(a=>({pathCell:a[c]??"",action:a[i]??""}))}}function S(o,e,t){let n=e;for(;n<o.length&&!t[n]&&o[n].trim()==="";)n++;const r=[];for(;n<o.length&&!t[n]&&o[n].trim().startsWith("|");)r.push(o[n].trim()),n++;if(r.length<2||!/^\|?\s*:?-{3,}/.test(r[1]))return;const s=r.slice(2);return s.length>Y?"too-large":{header:C(r[0]),rows:s.map(C)}}function E(o){const e=new Array(o.length).fill(!1);let t;for(let n=0;n<o.length;n++){const r=o[n].trim();if(t){e[n]=!0;const c=/^(`{3,}|~{3,})\s*$/.exec(r);c&&c[1][0]===t.char&&c[1].length>=t.length&&(t=void 0);continue}const s=/^(`{3,}|~{3,})/.exec(r);s&&!(s[1][0]==="`"&&r.slice(s[1].length).includes("`"))&&(t={char:s[1][0],length:s[1].length},e[n]=!0)}return e}function C(o){const e=o.replace(/^\|/,"").replace(/\|$/,""),t=[];let n="",r=!1;for(const s of e){if(s==="`"&&(r=!r),s==="|"&&!r){t.push(n.trim()),n="";continue}n+=s}return t.push(n.trim()),t}function f(o){return o.replace(/[*`]/g,"").trim().toLowerCase()}function x(o,e){const t=o.split(/\r?\n/);for(let n=0;n<t.length;n++){const r=new RegExp(`^${e}:[ \\t]*(.*?)[ \\t]*$`,"i").exec(t[n]);if(!r)continue;const s=O(r[1]);if(s.length>0)return m.test(s)?{declared:!1,items:[]}:{declared:!0,items:(s.startsWith("[")&&s.endsWith("]")?s.slice(1,-1).split(","):[s]).map(w).filter(l=>l.length>0)};const c=[];for(let a=n+1;a<t.length;a++){const l=t[a];if(/^[A-Za-z0-9_-]+:\s*/.test(l))break;const u=/^\s*-\s*(.+?)\s*$/.exec(l);u&&c.push(w(O(u[1])))}const i=c.filter(a=>a.length>0);return i.length>0?{declared:!0,items:i}:{declared:!1,items:[]}}return{declared:!1,items:[]}}function O(o){const e=o.trim();if(e.startsWith('"')||e.startsWith("'"))return e;const t=e.search(/\s#/);return(t>=0?e.slice(0,t):e).trim()}function w(o){let e=o.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function A(o,e){const t=[];for(const n of o){if(!P.test(n)||W.test(n)||n.includes("..")||m.test(n)){e.add("legacy-dependency-token-unsupported");return}t.includes(n)||t.push(n)}return t}function Q(o,e){const t=o.replace(/[*`]/g,"").trim();return q.has(t.toLowerCase())?[]:A(t.split(/[\s,;]+/).filter(Boolean),e)}function ee(o,e){if(Buffer.byteLength(o,"utf8")>R)return{kind:"too-large"};const t=o.split(/\r?\n/),n=E(t),r=[];for(let s=0;s<t.length;s++){if(n[s]||!t[s].trim().startsWith("|")||s>0&&!n[s-1]&&t[s-1].trim().startsWith("|"))continue;const c=S(t,s,n);if(c==="too-large")return{kind:"too-large"};if(!c)continue;const i=c.header.findIndex(l=>G.has(f(l))),a=c.header.findIndex(l=>j.has(f(l)));if(!(i<0||a<0))for(const l of c.rows)f(l[i]??"")===e.toLowerCase()&&r.push(l[a]??"")}return r.length===0?{kind:"none"}:r.length>1?{kind:"ambiguous"}:{kind:"found",cell:r[0]}}function L(o){return T("sha256").update(o,"utf8").digest("hex")}function _(o,e){return o<e?-1:o>e?1:0}export{R as LEGACY_STORY_SCOPE_MAX_EPIC_BYTES,z as LEGACY_STORY_SCOPE_MAX_SCOPES,N as LEGACY_STORY_SCOPE_MAX_STORY_BYTES,Y as LEGACY_STORY_SCOPE_MAX_TABLE_ROWS,v as LEGACY_STORY_SCOPE_RECEIPT_SCHEMA,oe as createLegacyStoryScopeExtractor,X as extractLegacyStoryScope};
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Epic P227.16 -- legacy *yoloop continuation-policy adoption.
3
+ *
4
+ * Single legacy adapter run at the start of `*yoloop` (ADR-P227-02). A state
5
+ * without `continuationPolicy` resolves to the p137 legacy default, whose
6
+ * frontier admits one story at a time. At the safe boundary (no session, lock,
7
+ * pending authority or pending transition manifest) the adapter persists
8
+ * `p205-finite-resume-v2` with a `LegacyAdoptionReceipt/1`, an exact-bytes
9
+ * backup and source-byte CAS. It never writes `continuationSession`: the
10
+ * server freezes the p205 session itself. Replay and explicit opt-out are
11
+ * byte-for-byte no-ops. The receipt is evidence, never merge/release authority.
12
+ *
13
+ * The client stays standalone at runtime (P117.07): the policy classification
14
+ * mirrors `packages/shared/src/yoloop/policy.ts#classifyYoloopPolicyAdoption`
15
+ * and a contract test enforces parity.
16
+ */
17
+ import { type LegacyAdoptionSourceV1 } from './yoloop-client-state-store.js';
18
+ export declare const LEGACY_ADOPTION_RECEIPT_SCHEMA: "LegacyAdoptionReceipt/1";
19
+ export declare const LEGACY_ADOPTION_TARGET_POLICY: "p205-finite-resume-v2";
20
+ export declare const LEGACY_ADOPTION_SOURCE_LIMIT_BYTES: number;
21
+ export declare const LEGACY_ADOPTION_RECEIPT_CAP = 16;
22
+ export type LegacyYoloopPolicyClass = 'legacy-migratable' | 'explicit-opt-out' | 'explicit-current' | 'unsupported';
23
+ export type LegacyAdoptionOutcome = 'policy-switched' | 'policy-switch-deferred' | 'policy-already-explicit' | 'policy-opt-out-preserved' | 'policy-switch-blocked' | 'policy-switch-not-applicable' | 'no-legacy-state';
24
+ export type LegacyAdoptionReasonCode = 'legacy-policy-migrated' | 'yoloop-session-active' | 'yoloop-session-ambiguous' | 'yoloop-lock-present' | 'yoloop-authority-pending' | 'yoloop-transition-pending' | 'policy-explicit-current' | 'policy-explicit-opt-out' | 'legacy-state-corrupt' | 'legacy-state-oversized' | 'yoloop-policy-version-unsupported' | 'yoloop-common-authority' | 'legacy-state-absent';
25
+ export interface LegacyAdoptionReceiptV1 {
26
+ readonly schemaVersion: typeof LEGACY_ADOPTION_RECEIPT_SCHEMA;
27
+ readonly adoption: 'continuation-policy';
28
+ readonly outcome: LegacyAdoptionOutcome;
29
+ readonly reasonCode: LegacyAdoptionReasonCode;
30
+ readonly fromPolicy: 'implicit-p137-resume-first-v1' | 'p137-resume-first-v1' | 'p205-finite-resume-v2' | null;
31
+ readonly toPolicy: typeof LEGACY_ADOPTION_TARGET_POLICY | null;
32
+ readonly sourceSha256: string | null;
33
+ readonly idempotencyKey: string | null;
34
+ readonly recordedAt: string;
35
+ readonly publicSafe: true;
36
+ }
37
+ export interface LegacyAdoptionPlanInput extends LegacyAdoptionSourceV1 {
38
+ readonly nowIso: string;
39
+ }
40
+ export interface LegacyAdoptionPlan {
41
+ readonly receipt: LegacyAdoptionReceiptV1;
42
+ /** Present only for `policy-switched`. */
43
+ readonly nextBytes?: string;
44
+ }
45
+ export interface LegacyYoloopAdoptionResult {
46
+ readonly receipt: LegacyAdoptionReceiptV1;
47
+ readonly written: boolean;
48
+ readonly resultSha256: string | null;
49
+ }
50
+ export interface RunLegacyYoloopAdoptionOptions {
51
+ readonly nowIso?: string;
52
+ /** Test seam: runs between planning and the CAS commit. */
53
+ readonly beforeCommit?: () => void | Promise<void>;
54
+ }
55
+ /** Client mirror of shared `classifyYoloopPolicyAdoption` (parity-tested). */
56
+ export declare function classifyLegacyYoloopPolicy(policy: unknown): LegacyYoloopPolicyClass;
57
+ /**
58
+ * Pure planner (no I/O, no clock read). Only a `policy-switched` plan carries
59
+ * `nextBytes`: the parsed source object (unknown fields and key order kept)
60
+ * plus the explicit policy and the bounded receipt list.
61
+ */
62
+ export declare function planLegacyYoloopPolicyAdoption(input: LegacyAdoptionPlanInput): LegacyAdoptionPlan;
63
+ /**
64
+ * Adapter entry point, called by `readYoloopForRequest` before `readAll`.
65
+ * Writes only for `policy-switched`; CAS divergence throws
66
+ * `YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT` and a boundary taken between plan and
67
+ * commit throws `YOLOOP_POLICY_SWITCH_ACTIVE` (both fail closed upstream).
68
+ */
69
+ export declare function runLegacyYoloopAdoption(projectRoot: string, options?: RunLegacyYoloopAdoptionOptions): Promise<LegacyYoloopAdoptionResult>;
@@ -0,0 +1 @@
1
+ import{createHash as m}from"node:crypto";import{YoloopClientStateStore as h}from"./yoloop-client-state-store.js";const S="LegacyAdoptionReceipt/1",p="p205-finite-resume-v2",O=4*1024*1024,x=16,P="p227-legacy-policy-adoption-v1:";function b(e){return e===void 0?"legacy-migratable":e==="p137-resume-first-v1"?"explicit-opt-out":e===p?"explicit-current":"unsupported"}function d(e){return m("sha256").update(e).digest("hex")}function C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function c(e,t,i,r,o,n=null){return Object.freeze({schemaVersion:S,adoption:"continuation-policy",outcome:e,reasonCode:t,fromPolicy:o,toPolicy:n,sourceSha256:r,idempotencyKey:r===null?null:d(`${P}${r}`),recordedAt:i,publicSafe:!0})}function s(e,t){return Object.freeze(t===void 0?{receipt:e}:{receipt:e,nextBytes:t})}function w(e){const{nowIso:t}=e;if(e.sourceBytes===null)return s(c("no-legacy-state","legacy-state-absent",t,null,null));const i=d(e.sourceBytes),r=y=>s(c("policy-switch-blocked",y,t,i,null));if(e.sourceBytes.byteLength>O)return r("legacy-state-oversized");let o;try{o=JSON.parse(Buffer.from(e.sourceBytes).toString("utf8"))}catch{return r("legacy-state-corrupt")}if(!C(o))return r("legacy-state-corrupt");const n=b(o.continuationPolicy);if(n==="unsupported")return r("yoloop-policy-version-unsupported");if(n==="explicit-current")return s(c("policy-already-explicit","policy-explicit-current",t,i,p));if(n==="explicit-opt-out")return s(c("policy-opt-out-preserved","policy-explicit-opt-out",t,i,"p137-resume-first-v1"));const l=o.pendingContinuationAuthorities,a=o.legacyAdoptionReceipts;if(l!==void 0&&!Array.isArray(l)||a!==void 0&&!Array.isArray(a))return r("legacy-state-corrupt");const u=y=>s(c("policy-switch-deferred",y,t,i,"implicit-p137-resume-first-v1"));if(o.currentSession!==void 0&&o.currentSession!==null)return u("yoloop-session-active");if(o.continuationSession!==void 0&&o.continuationSession!==null)return u("yoloop-session-ambiguous");if(e.lockPresent)return u("yoloop-lock-present");if((l?.length??0)>0)return u("yoloop-authority-pending");if(e.rolloverManifestPresent||e.successorTransitionManifestPresent)return u("yoloop-transition-pending");const f=c("policy-switched","legacy-policy-migrated",t,i,"implicit-p137-resume-first-v1",p),g=[...(a??[]).slice(-(x-1)),f],A=JSON.stringify({...o,continuationPolicy:p,legacyAdoptionReceipts:g},null,2);return s(f,A)}async function _(e,t={}){const i=t.nowIso??new Date().toISOString(),r=new h(e);if(r.usesCommonAuthority())return Object.freeze({receipt:c("policy-switch-not-applicable","yoloop-common-authority",i,null,null),written:!1,resultSha256:null});const o=await r.readLegacyAdoptionSource(),n=w({...o,nowIso:i});if(n.nextBytes===void 0||n.receipt.sourceSha256===null)return Object.freeze({receipt:n.receipt,written:!1,resultSha256:n.receipt.sourceSha256});await t.beforeCommit?.();const{resultSha256:l}=await r.commitLegacyPolicyAdoption({sourceSha256:n.receipt.sourceSha256,nextBytes:n.nextBytes});return Object.freeze({receipt:n.receipt,written:!0,resultSha256:l})}export{x as LEGACY_ADOPTION_RECEIPT_CAP,S as LEGACY_ADOPTION_RECEIPT_SCHEMA,O as LEGACY_ADOPTION_SOURCE_LIMIT_BYTES,p as LEGACY_ADOPTION_TARGET_POLICY,b as classifyLegacyYoloopPolicy,w as planLegacyYoloopPolicyAdoption,_ as runLegacyYoloopAdoption};
@@ -96,6 +96,49 @@ export interface StoryDescriptor {
96
96
  readonly status?: string;
97
97
  readonly depends_on?: readonly string[];
98
98
  readonly files_to_modify?: readonly string[];
99
+ /** P227.17: validated legacy scope/dependency extraction, when injected. */
100
+ readonly legacy_scope?: LegacyStoryScopeResult;
101
+ }
102
+ /**
103
+ * P227.17 (P227-CON-LEGACY-BACKFILL): receipt bound to the story bytes.
104
+ * Carries counts and reason codes only, never rejected path text.
105
+ */
106
+ export interface LegacyStoryScopeReceipt {
107
+ readonly schema: 'LegacyStoryScopeReceipt/1';
108
+ readonly story_id: string;
109
+ readonly story_sha256: string;
110
+ readonly epic_sha256?: string;
111
+ readonly scope_source: 'frontmatter' | 'table' | 'none';
112
+ readonly scope_basis: 'validated' | 'unknown';
113
+ readonly accepted_count: number;
114
+ readonly discarded: ReadonlyArray<{
115
+ readonly reason_code: string;
116
+ readonly count: number;
117
+ }>;
118
+ readonly dependency_source: 'frontmatter' | 'epic-table' | 'none';
119
+ readonly dependency_basis: 'declared' | 'unknown';
120
+ readonly reason_codes: readonly string[];
121
+ }
122
+ /** P227.17: extractor output; absent fields mean "not declared / unknown". */
123
+ export interface LegacyStoryScopeResult {
124
+ readonly files_to_modify?: readonly string[];
125
+ readonly depends_on?: readonly string[];
126
+ readonly receipt: LegacyStoryScopeReceipt;
127
+ }
128
+ /** P227.17: pure extractor input (story bytes plus owner epic bytes). */
129
+ export interface LegacyStoryScopeInput {
130
+ readonly storyId: string;
131
+ readonly epicId: string;
132
+ readonly content: string;
133
+ readonly epicContent?: string;
134
+ }
135
+ export type LegacyStoryScopeExtractor = (input: LegacyStoryScopeInput) => LegacyStoryScopeResult;
136
+ /**
137
+ * P227.17: optional discovery behavior. Without `legacyStoryScope` the
138
+ * discovery output is unchanged (the canonical body stays dependency-free).
139
+ */
140
+ export interface DiscoveryOptions {
141
+ readonly legacyStoryScope?: LegacyStoryScopeExtractor;
99
142
  }
100
143
  /**
101
144
  * Output shape for `discoverEpicsFromDir`.
@@ -164,6 +207,22 @@ export declare const EPIC_FILE_PATTERNS: readonly [RegExp, RegExp, RegExp];
164
207
  * (numeric only) -- the `P?` prefix is optional.
165
208
  */
166
209
  export declare const STORY_FILE_PATTERNS: readonly [RegExp, RegExp, RegExp];
210
+ /**
211
+ * P226.04: frontmatter limits mirrored from
212
+ * `packages/shared/src/frontmatter-context-contract.ts` (`FRONTMATTER_LIMITS`,
213
+ * `FRONTMATTER_FIELD_LIMITS`, `FRONTMATTER_FIELD_BUDGET`). This module and its
214
+ * byte-identical server/client mirrors must stay import-free, so the values are
215
+ * inlined and pinned to the contract by `discover-epics-legacy-metadata.test.ts`.
216
+ */
217
+ export declare const DISCOVERY_FRONTMATTER_LIMITS: Readonly<{
218
+ readonly maxBytes: number;
219
+ readonly maxLines: 128;
220
+ readonly maxListItems: 32;
221
+ readonly budgetField: "files_to_modify";
222
+ readonly budgetFieldMaxItems: 256;
223
+ readonly extraLines: 256;
224
+ readonly extraBytes: number;
225
+ }>;
167
226
  /**
168
227
  * Default filesystem adapter wrapping `node:fs` synchronous APIs.
169
228
  * Lazy-loaded via dynamic require so this module is safe to import in
@@ -214,7 +273,7 @@ export declare function getEpicIdFromDescriptor(filename: string, frontmatter: {
214
273
  * @param fs optional fs adapter; defaults to `node:fs` wrapper (lazy)
215
274
  * @returns DiscoveryResult with epics, warnings, skipped arrays
216
275
  */
217
- export declare function discoverEpicsFromDir(dir: string, fs: DiscoveryFsAdapter): DiscoveryResult;
276
+ export declare function discoverEpicsFromDir(dir: string, fs: DiscoveryFsAdapter, options?: DiscoveryOptions): DiscoveryResult;
218
277
  /**
219
278
  * Options for `mergeDiscoveredIntoState`.
220
279
  *
@@ -257,6 +316,8 @@ export interface MergeResult {
257
316
  }>;
258
317
  /** Number of stories added to `state.stories`. */
259
318
  readonly storiesAdded: number;
319
+ /** P227.17: existing stories that received at least one fill-only field. */
320
+ readonly storiesFilled: number;
260
321
  }
261
322
  /**
262
323
  * Merge `DiscoveryResult` (from `discoverEpicsFromDir`) into a `state` object,
@@ -1 +1 @@
1
- const ge=Object.freeze({epicId:"P{number}",epicFilename:"docs/epics/epic-P{number}.md",storyId:"P{number}.NN",storyFilename:"docs/stories/P{number}.NN.story.md",acceptedOnly:Object.freeze({epicFilenames:Object.freeze(["docs/epics/epic-{number}.md","docs/epics/EPIC-{number}-{slug}.md","docs/epics/EPIC-{number}_{slug}.md","docs/epics/epic-{slug}.md"]),storyFilenames:Object.freeze(["docs/stories/{number}.NN.story.md","docs/stories/story-P{number}.NN.md","docs/stories/story-{number}.NN.md","docs/stories/EPIC-{number}.STORY-{number}.md"])})}),O=Object.freeze([/^epic-(P?\d+(?:\.\d+)?)\.md$/i,/^EPIC-(\d+)(?:[-_].*)?\.md$/,/^epic-([a-z0-9][a-z0-9_-]*)\.md$/i]),D=Object.freeze([/^(P?\d+\.\d+(?:\.\d+)?)\.story\.md$/i,/^story-(P?\d+\.\d+)\.md$/i,/^EPIC-(\d+)\.STORY-(\d+)\.md$/]),k=Object.freeze([".archive","_archive","_archives","_drafts","archive","archives","archived","drafts"]),F=/^---\s*\n([\s\S]*?)\n---/;function z(t,e){const i=new RegExp(`^${e}:\\s*(.+?)\\s*$`,"mi"),n=t.match(i);if(!n)return;let c=n[1].trim();return(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),c||void 0}function G(t){if(typeof t!="string"||t.length===0)return{};const e=t.match(F);if(!e)return{};const i=e[1];return{id:z(i,"id"),title:z(i,"title"),status:z(i,"status"),epic_id:z(i,"epic_id"),depends_on:te(i),files_to_modify:P(i,"files_to_modify"),total_stories:x(z(i,"total_stories"))}}const Y=32,B=4096,H=/^\s*\*\*([^*\r\n]+?):\*\*\s*(.*?)\s*$/,U=new Set(["backlog","pending","ready","planning","in-progress","done","completed","merged","cancelled","canceled","abandoned","draft","template","archived","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","partial"]);function L(t){let e=t.trim();return e.startsWith("`")&&e.endsWith("`")&&e.length>=2&&(e=e.slice(1,-1).trim()),(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function x(t){if(t===void 0||!/^\d{1,5}$/.test(t.trim()))return;const e=Number(t);return Number.isSafeInteger(e)?e:void 0}function Z(t){const e=L(t).toLowerCase().replace(/[_\s]+/g,"-"),n={planned:"planning",complete:"completed",closed:"done",finished:"done"}[e]??e;return U.has(n)?n:void 0}function X(t){const e=t.trim().toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ");if(e==="id"||e==="epic id")return"id";if(e==="title"||e==="titulo")return"title";if(e==="status")return"status";if(e==="total stories"||e==="total de stories")return"total_stories"}function q(t){const e=t.find(c=>/^#\s+\S/.test(c));if(!e)return;const i=e.replace(/^#\s+/,"").trim();return(i.replace(/^(?:Epic|Story)\s+\S+\s*(?:(?:--?|:)|[\u2013\u2014])\s*/i,"")||i).slice(0,200)}function j(t,e,i,n){const c=[...new Set(t.map(L).filter(Boolean))];if(c.length>1){n.push(`legacy metadata ambiguous for '${e}' in '${i}': conflicting values ignored`);return}return c[0]}function K(t,e){const i=[],n=[],c=t.slice(0,B).split(/\r?\n/,Y);for(const m of c){if(n.length>0&&(/^\s*---\s*$/.test(m)||/^##\s+/.test(m)))break;n.push(m)}const o=new Map;for(const m of n){const r=m.match(H);if(!r)continue;const a=X(r[1]);if(!a)continue;const d=o.get(a)??[];d.push(r[2]),o.set(a,d)}const f=j(o.get("id")??[],"id",e,i),l=j(o.get("title")??[],"title",e,i),_=j(o.get("status")??[],"status",e,i),g=j(o.get("total_stories")??[],"total_stories",e,i),p=_===void 0?void 0:Z(_);_!==void 0&&p===void 0&&i.push(`legacy metadata status unrecognized in '${e}': value ignored`);const b=x(g);g!==void 0&&b===void 0&&i.push(`legacy metadata total_stories invalid in '${e}': value ignored`);const $=f&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(f)?f:void 0;f!==void 0&&$===void 0&&i.push(`legacy metadata id invalid in '${e}': value ignored`);const s=q(n),u=l??s;return{metadata:{...$?{id:$}:{},...u?{title:u.slice(0,200)}:{},...p?{status:p}:{},...b!==void 0?{total_stories:b}:{}},source:"legacy-metadata",warnings:Object.freeze(i)}}function V(t){return/^[A-Za-z0-9._-]{1,160}$/.test(t)?t:"markdown-target.md"}function J(t){return new TextEncoder().encode(t).length}function Q(t){let e=!1;for(const i of t.split(/\r?\n/)){if(!i.trim()||i.trimStart().startsWith("#"))continue;const n=i.match(/^\s+-\s+(.+?)\s*$/);if(n){if(!e)return!0;const f=n[1].trim();if(f.startsWith('"')&&!f.endsWith('"')||f.startsWith("'")&&!f.endsWith("'"))return!0;continue}if(/^\s+/.test(i))return!0;const c=i.match(/^[A-Za-z0-9_-]+:\s*(.*?)\s*$/);if(!c)return!0;const o=c[1].trim();if(e=o.length===0,o.startsWith('"')&&!o.endsWith('"')||o.startsWith("'")&&!o.endsWith("'"))return!0}return!1}function ee(t,e,i){const n=V(e),c=t.match(F);if(!c)return Object.freeze([`metadata-frontmatter reason=frontmatter-malformed file='${n}': repair the bounded leading YAML envelope; source content omitted`]);const o=c[1];return J(o)>8*1024||o.split(/\r?\n/).length>128?Object.freeze([`metadata-frontmatter reason=frontmatter-oversized file='${n}': reduce the leading YAML envelope; source content omitted`]):Q(o)||o.trim().length>0&&Object.keys(i).length===0?Object.freeze([`metadata-frontmatter reason=frontmatter-unsupported-value file='${n}': use bounded scalar fields or string lists; source content omitted`]):Object.freeze([])}function N(t,e){if(/^---(?:\s*\r?\n|\s*$)/.test(t)){const i=G(t);return{metadata:i,source:"frontmatter",warnings:ee(t,e,i)}}return typeof t!="string"||t.length===0?{metadata:{},source:"none",warnings:Object.freeze([])}:K(t,e)}function R(t){let e=t.trim();if((e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),!!e&&!/^(null|undefined|true|false)$/i.test(e))return e}function te(t){return P(t,"depends_on")}function P(t,e){const i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=t.match(new RegExp(`^${i}:[ \\t]*(.+?)[ \\t]*$`,"mi"))?.[1]?.trim();if(c!==void 0){const g=(c.startsWith("[")&&c.endsWith("]")?c.slice(1,-1).split(","):[c]).map(R).filter(p=>typeof p=="string"&&p.length>0);return g.length>0?Object.freeze(g):void 0}const o=t.split(/\r?\n/),f=[];let l=!1;for(const _ of o){if(!l){new RegExp(`^${i}:\\s*$`,"i").test(_.trim())&&(l=!0);continue}if(/^[A-Za-z0-9_-]+:\s*/.test(_))break;const g=_.match(/^\s*-\s*(.+?)\s*$/);if(!g)continue;const p=R(g[1]);p&&f.push(p)}return f.length>0?Object.freeze(f):void 0}function T(t){return t.startsWith("_")||t.startsWith(".")}function ie(t){return k.includes(t)}async function he(){const t=await import("node:fs"),e=await import("node:path");return{isDirectory(i){try{return t.statSync(i).isDirectory()}catch{return!1}},readdir(i){try{return t.readdirSync(i)}catch{return[]}},readFile(i){try{return t.readFileSync(i,"utf8")}catch{return""}},join(...i){try{return e.join(...i)}catch{return i.join("/")}}}}function ne(t,e){let i=!1,n=null,c=null;for(let o=0;o<O.length;o++){const f=O[o],l=t.match(f);if(l){i=!0,n=l[1],c=o===2?"filename-slug":"filename-canonical";break}}return i?e.id&&e.id.length>0?{id:e.id,source:"frontmatter"}:{id:n,source:c}:null}function se(t){for(const e of O){const i=t.match(e);if(i)return i[1]}return null}function I(t){const e=t.trim();return/^\d+(?:\.\d+)*$/i.test(e)?`P${e}`.toUpperCase():e.toUpperCase()}function re(t){const e=I(t);return/^P\d+(?:\.\d+)?$/i.test(e)?`epic-${e}.md`:`epic-${t}.md`}function oe(t){const e=I(t);return/^P\d+\.\d+(?:\.\d+)?$/i.test(e)?`${e}.story.md`:`${t}.story.md`}function C(t,e){return!t||!e?!1:I(t)!==I(e)}function ce(t,e,i){return`frontmatter/filename mismatch: epic '${t}' has frontmatter id '${e}' but filename implies '${i}'. Repair by using generated canonical '${re(e)}' or changing frontmatter id to '${i}'.`}function ae(t,e,i){return`frontmatter/filename mismatch: story '${t}' has frontmatter id '${e}' but filename implies '${i}'. Repair by using generated canonical '${oe(e)}' or changing frontmatter id to '${i}'.`}function de(t){let e=t.match(D[0]);if(e){const i=e[1],n=i.indexOf(".");return{id:i,epic_id_hint:n>0?i.slice(0,n):null}}if(e=t.match(D[1]),e){const i=e[1],n=i.indexOf(".");return{id:i,epic_id_hint:n>0?i.slice(0,n):null}}if(e=t.match(D[2]),e){const i=e[1],n=e[2];return{id:`${i}.${n}`,epic_id_hint:i}}return null}function ue(t,e){return e.join(t,"..","stories")}function _e(t,e){const i=[],n=[],c=[],o=new Date().toISOString();if(typeof t!="string"||t.length===0)return Object.freeze({epics:Object.freeze([]),warnings:Object.freeze([]),skipped:Object.freeze([])});if(!e.isDirectory(t))return Object.freeze({epics:Object.freeze([]),warnings:Object.freeze([]),skipped:Object.freeze([])});const f=[...e.readdir(t)].sort(),l=[];for(const s of f){const u=e.join(t,s);if(T(s)){n.push(`${s}: ignored (draft or hidden prefix)`);continue}if(e.isDirectory(u)){if(ie(s)){n.push(`${s}: ignored subdirectory`);continue}n.push(`${s}: subdirectory not recursed`);continue}if(!s.endsWith(".md"))continue;if(!O.some(h=>h.test(s))){n.push(`${s}: did not match any EPIC_FILE_PATTERNS`);continue}const m=e.readFile(u),r=N(m,s);i.push(...r.warnings);const a=r.metadata,d=se(s);a.id&&C(a.id,d)&&i.push(r.source==="frontmatter"?ce(s,a.id,d):`legacy metadata/filename mismatch: epic '${s}' id does not match its filename`),l.push({filename:s,fullPath:u,metadata:a,metadataSource:r.source})}const _=new Map,g=[];for(const s of l){const u=ne(s.filename,s.metadata);if(u===null){n.push(`${s.filename}: id resolution returned null`);continue}let y=u.id;const m=y,r=_.get(m)??0;r>0&&(y=`${m}-${r+1}`,i.push(`epic ID collision: '${m}' resolved to '${y}' for ${s.filename}`)),_.set(m,r+1),g.push({candidate:s,finalId:y,idSource:s.metadataSource==="legacy-metadata"&&s.metadata.id?"legacy-metadata":u.source})}const p=new Map,b=ue(t,e);if(e.isDirectory(b)){const s=[...e.readdir(b)].sort();for(const u of s){if(T(u)||!u.endsWith(".md"))continue;const y=e.join(b,u);if(e.isDirectory(y))continue;const m=de(u);if(!m)continue;const r=e.readFile(y),a=N(r,u);i.push(...a.warnings);const d=a.metadata;d.id&&C(d.id,m.id)&&i.push(a.source==="frontmatter"?ae(u,d.id,m.id):`legacy metadata/filename mismatch: story '${u}' id does not match its filename`);const h=d.epic_id??m.epic_id_hint;if(!h){i.push(`story '${u}' has no epic_id (frontmatter or filename pattern)`);continue}const S=Object.freeze({id:m.id,epic_id:h,filename:u,path:y,...d.title?{title:d.title}:{},...d.status?{status:d.status}:{},...d.depends_on?{depends_on:d.depends_on}:{},...d.files_to_modify?{files_to_modify:d.files_to_modify}:{}});p.has(h)||p.set(h,[]),p.get(h).push(S)}}for(const s of g){const u=p.get(s.finalId)??[],y=Object.freeze({id:s.finalId,filename:s.candidate.filename,path:s.candidate.fullPath,...s.candidate.metadata.title?{title:s.candidate.metadata.title}:{},...s.candidate.metadata.status?{status:s.candidate.metadata.status}:{},...s.candidate.metadata.total_stories!==void 0?{total_stories:s.candidate.metadata.total_stories}:{},...s.candidate.metadata.depends_on?{depends_on:s.candidate.metadata.depends_on}:{},source:"discovered",discovered_at:o,stories:Object.freeze([...u]),t:s.idSource,e:s.candidate.metadataSource});c.push(y)}const $=new Set(c.map(s=>s.id));for(const[s,u]of p.entries())if(!$.has(s))for(const y of u)i.push(`orphan story '${y.filename}' references unknown epic '${s}'`);return Object.freeze({epics:Object.freeze(c),warnings:Object.freeze(i),skipped:Object.freeze(n)})}function M(t){const e=fe(t);return e==="done"||e==="completed"||e==="merged"}function A(t){return M(t)}function fe(t){return typeof t=="string"?t.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}function E(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function w(t){throw new Error(`epic-aggregate-writer:${t}`)}function le(t){const e=[],i=new Set;for(const n of t)(typeof n!="string"||n.length===0)&&w("epic_aggregate_story_ref_invalid"),i.has(n)&&w("epic_aggregate_story_ref_duplicate"),i.add(n),e.push(n);return e}function pe(t,e,i){const n=i[e];return n===void 0&&w("epic_aggregate_story_missing"),E(n)||w("epic_aggregate_story_not_object"),n.id!==e&&w("epic_aggregate_story_id_conflict"),n.epic_id!==t&&w("epic_aggregate_story_epic_conflict"),n}function me(t,e,i,n,c){const o=e[t];E(o)||w("epic_aggregate_epic_not_object"),o.id!==t&&w("epic_aggregate_epic_id_conflict"),Array.isArray(o.stories)||w("epic_aggregate_story_list_not_array");const f=le(o.stories),l=f.length,_=f.filter(u=>M(pe(t,u,i).status)).length,g=c?.total_stories,p=c?.e==="legacy-metadata"&&A(o.status),b=p?g??l:l>0?l:g??0,$=p||l===0&&b>0&&A(o.status)?b:_,s=l>0&&_===l;A(o.status)&&!p&&!s&&l>0&&w("epic_aggregate_terminal_incomplete_conflict"),o.total_stories=b,o.completed_stories=$,!A(o.status)&&s&&(o.status="done",(o.completed_at===void 0||o.completed_at===null)&&(o.completed_at=n))}function ye(t,e,i){const n=t??{},c=E(n.epics)?n.epics:{},o=E(n.stories)?n.stories:{},f=structuredClone(c),l=structuredClone(o),_=[],g=[],p=new Set,b=new Map;let $=0;const s=i?.forceOverwrite===!0,u=i?.nowIso??new Date().toISOString(),y=new Set,m=new Map;for(const r of e.epics){if(!r.id||y.has(r.id))throw new Error("discovery_epic_identity_conflict");y.add(r.id),b.set(r.id,r);const a=f[r.id];if(a!==void 0&&(!E(a)||a.id!==void 0&&a.id!==r.id))throw new Error("discovery_epic_identity_conflict");for(const d of r.stories){if(!d.id||d.epic_id!==r.id||m.has(d.id))throw new Error("discovery_story_identity_conflict");m.set(d.id,r.id);const h=l[d.id];if(h!==void 0&&(!E(h)||h.id!==void 0&&h.id!==d.id||h.epic_id!==void 0&&h.epic_id!==r.id))throw new Error("discovery_story_identity_conflict")}}for(const r of e.epics){const a=f[r.id],d=a;if(d&&(d.branch_mode==="epic"||typeof d.execution_branch=="string")){g.push({id:r.id,reason:"epic Git lifecycle preserved"});continue}if(a&&a.source==="create-epic"&&!s){g.push({id:r.id,reason:"create-epic source preserved (defense)"});continue}if(a){const S=a;S.depends_on=r.depends_on??[];const v=Array.isArray(S.stories)?S.stories.filter(W=>typeof W=="string"):[];S.stories=[...new Set([...v,...r.stories.map(W=>W.id)])],r.title!==void 0&&(S.title=r.title),a.source!=="create-epic"&&p.add(r.id);continue}const h={id:r.id,title:r.title??"",status:r.status??"planning",source:"discovered",discovered_at:u,merged_at:u,stories:r.stories.map(S=>S.id),depends_on:r.depends_on??[]};f[r.id]=h,p.add(r.id),_.push(r.id)}for(const r of e.epics)for(const a of r.stories){const d=l[a.id],h=f[r.id];if(d&&h&&(h.branch_mode==="epic"||typeof h.execution_branch=="string")){g.push({id:a.id,reason:"story Git lifecycle preserved"});continue}if(d&&d.source==="create-epic"&&!s){g.push({id:a.id,reason:"create-epic source preserved (defense, story)"});continue}if(d){const v=d;a.title!==void 0&&(v.title=a.title),v.depends_on=a.depends_on??[],v.files_to_modify=a.files_to_modify??[];continue}const S={id:a.id,epic_id:a.epic_id,title:a.title??"",status:"backlog",source:"discovered",discovered_at:u,depends_on:a.depends_on??[],files_to_modify:a.files_to_modify??[]};l[a.id]=S,$++}for(const r of p)me(r,f,l,u,b.get(r));return n.epics=f,n.stories=l,{state:n,added:Object.freeze([..._]),skipped:Object.freeze([...g]),storiesAdded:$}}export{O as EPIC_FILE_PATTERNS,ge as GENERATED_NAMING_CONTRACT,D as STORY_FILE_PATTERNS,he as buildDefaultDiscoveryFs,_e as discoverEpicsFromDir,ne as getEpicIdFromDescriptor,ye as mergeDiscoveredIntoState};
1
+ const ze=Object.freeze({epicId:"P{number}",epicFilename:"docs/epics/epic-P{number}.md",storyId:"P{number}.NN",storyFilename:"docs/stories/P{number}.NN.story.md",acceptedOnly:Object.freeze({epicFilenames:Object.freeze(["docs/epics/epic-{number}.md","docs/epics/EPIC-{number}-{slug}.md","docs/epics/EPIC-{number}_{slug}.md","docs/epics/epic-{slug}.md"]),storyFilenames:Object.freeze(["docs/stories/{number}.NN.story.md","docs/stories/story-P{number}.NN.md","docs/stories/story-{number}.NN.md","docs/stories/EPIC-{number}.STORY-{number}.md"])})}),A=Object.freeze([/^epic-(P?\d+(?:\.\d+)?)\.md$/i,/^EPIC-(\d+)(?:[-_].*)?\.md$/,/^epic-([a-z0-9][a-z0-9_-]*)\.md$/i]),F=Object.freeze([/^(P?\d+\.\d+(?:\.\d+)?)\.story\.md$/i,/^story-(P?\d+\.\d+)\.md$/i,/^EPIC-(\d+)\.STORY-(\d+)\.md$/]),J=Object.freeze([".archive","_archive","_archives","_drafts","archive","archives","archived","drafts"]),M=/^---\s*\n([\s\S]*?)\n---/;function z(t,e){const i=new RegExp(`^${e}:\\s*(.+?)\\s*$`,"mi"),n=t.match(i);if(!n)return;let o=n[1].trim();return(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),o||void 0}function X(t){if(typeof t!="string"||t.length===0)return{};const e=t.match(M);if(!e)return{};const i=e[1];return{id:z(i,"id"),title:z(i,"title"),status:z(i,"status"),epic_id:z(i,"epic_id"),depends_on:le(i),files_to_modify:B(i,"files_to_modify"),total_stories:C(z(i,"total_stories"))}}const q=32,Q=4096,ee=/^\s*\*\*([^*\r\n]+?):\*\*\s*(.*?)\s*$/,te=new Set(["backlog","pending","ready","planning","in-progress","done","completed","merged","cancelled","canceled","abandoned","draft","template","archived","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","partial"]);function N(t){let e=t.trim();return e.startsWith("`")&&e.endsWith("`")&&e.length>=2&&(e=e.slice(1,-1).trim()),(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function C(t){if(t===void 0||!/^\d{1,5}$/.test(t.trim()))return;const e=Number(t);return Number.isSafeInteger(e)?e:void 0}function ie(t){const e=N(t).toLowerCase().replace(/[_\s]+/g,"-"),n={planned:"planning",complete:"completed",closed:"done",finished:"done"}[e]??e;return te.has(n)?n:void 0}function ne(t){const e=t.trim().toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ");if(e==="id"||e==="epic id")return"id";if(e==="title"||e==="titulo")return"title";if(e==="status")return"status";if(e==="total stories"||e==="total de stories")return"total_stories"}function se(t){const e=t.find(o=>/^#\s+\S/.test(o));if(!e)return;const i=e.replace(/^#\s+/,"").trim();return(i.replace(/^(?:Epic|Story)\s+\S+\s*(?:(?:--?|:)|[\u2013\u2014])\s*/i,"")||i).slice(0,200)}function L(t,e,i,n){const o=[...new Set(t.map(N).filter(Boolean))];if(o.length>1){n.push(`legacy metadata ambiguous for '${e}' in '${i}': conflicting values ignored`);return}return o[0]}function re(t,e){const i=[],n=[],o=t.slice(0,Q).split(/\r?\n/,q);for(const v of o){if(n.length>0&&(/^\s*---\s*$/.test(v)||/^##\s+/.test(v)))break;n.push(v)}const r=new Map;for(const v of n){const c=v.match(ee);if(!c)continue;const s=ne(c[1]);if(!s)continue;const a=r.get(s)??[];a.push(c[2]),r.set(s,a)}const d=L(r.get("id")??[],"id",e,i),l=L(r.get("title")??[],"title",e,i),b=L(r.get("status")??[],"status",e,i),h=L(r.get("total_stories")??[],"total_stories",e,i),y=b===void 0?void 0:ie(b);b!==void 0&&y===void 0&&i.push(`legacy metadata status unrecognized in '${e}': value ignored`);const E=C(h);h!==void 0&&E===void 0&&i.push(`legacy metadata total_stories invalid in '${e}': value ignored`);const u=d&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(d)?d:void 0;d!==void 0&&u===void 0&&i.push(`legacy metadata id invalid in '${e}': value ignored`);const g=se(n),S=l??g;return{metadata:{...u?{id:u}:{},...S?{title:S.slice(0,200)}:{},...y?{status:y}:{},...E!==void 0?{total_stories:E}:{}},source:"legacy-metadata",warnings:Object.freeze(i)}}function T(t){return/^[A-Za-z0-9._-]{1,160}$/.test(t)?t:"markdown-target.md"}function W(t){return new TextEncoder().encode(t).length}const oe=Object.freeze({maxBytes:8*1024,maxLines:128,maxListItems:32,budgetField:"files_to_modify",budgetFieldMaxItems:256,extraLines:256,extraBytes:64*1024}),ce=new Set(["files_to_modify","depends_on","related_epics"]);function ae(t){const e=oe,i=t.split(/\r?\n/);let n=0,o=0,r=null,d=0;const l=(u,g)=>{const S=u===e.budgetField?e.budgetFieldMaxItems:e.maxListItems;return g<=S?null:`frontmatter-list-too-long:${ce.has(u)?u:"unlisted-field"}:${Math.min(g,999999)}>${S}`};for(const u of i){if(!u.trim()||u.trimStart().startsWith("#"))continue;if(/^\s+-\s+\S/.test(u)){if(r===null)continue;d+=1,r===e.budgetField&&(n+=1,o+=W(u)+1);continue}if(r!==null){const w=l(r,d);if(w)return w;r=null,d=0}const g=u.match(/^([A-Za-z_][A-Za-z0-9_-]{0,63}):(?:\s*(.*))?$/);if(!g)continue;const S=(g[2]??"").trim();if(!S){r=g[1];continue}if(S.startsWith("[")&&S.endsWith("]")){const w=S.slice(1,-1).trim(),v=w?l(g[1],w.split(",").length):null;if(v)return v;g[1]===e.budgetField&&(o+=W(g[2]??""))}}if(r!==null){const u=l(r,d);if(u)return u}const b=i.length+2,h=W(t)+9,y=e.maxLines+Math.min(e.extraLines,n),E=e.maxBytes+Math.min(e.extraBytes,o);return b>y||h>E?"frontmatter-oversized":null}function de(t){let e=!1;for(const i of t.split(/\r?\n/)){if(!i.trim()||i.trimStart().startsWith("#"))continue;const n=i.match(/^\s+-\s+(.+?)\s*$/);if(n){if(!e)return!0;const d=n[1].trim();if(d.startsWith('"')&&!d.endsWith('"')||d.startsWith("'")&&!d.endsWith("'"))return!0;continue}if(/^\s+/.test(i))return!0;const o=i.match(/^[A-Za-z0-9_-]+:\s*(.*?)\s*$/);if(!o)return!0;const r=o[1].trim();if(e=r.length===0,r.startsWith('"')&&!r.endsWith('"')||r.startsWith("'")&&!r.endsWith("'"))return!0}return!1}function fe(t,e,i){const n=T(e),o=t.match(M);if(!o)return Object.freeze([`metadata-frontmatter reason=frontmatter-malformed file='${n}': repair the bounded leading YAML envelope; source content omitted`]);const r=o[1],d=ae(r);return d?Object.freeze([`metadata-frontmatter reason=${d} file='${n}': reduce the leading YAML envelope; source content omitted`]):de(r)||r.trim().length>0&&Object.keys(i).length===0?Object.freeze([`metadata-frontmatter reason=frontmatter-unsupported-value file='${n}': use bounded scalar fields or string lists; source content omitted`]):Object.freeze([])}function P(t,e){if(/^---(?:\s*\r?\n|\s*$)/.test(t)){const i=X(t);return{metadata:i,source:"frontmatter",warnings:fe(t,e,i)}}return typeof t!="string"||t.length===0?{metadata:{},source:"none",warnings:Object.freeze([])}:re(t,e)}function k(t){let e=t.trim();if((e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),!!e&&!/^(null|undefined|true|false)$/i.test(e))return e}function le(t){return B(t,"depends_on")}function B(t,e){const i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=t.match(new RegExp(`^${i}:[ \\t]*(.+?)[ \\t]*$`,"mi"))?.[1]?.trim();if(o!==void 0){const h=(o.startsWith("[")&&o.endsWith("]")?o.slice(1,-1).split(","):[o]).map(k).filter(y=>typeof y=="string"&&y.length>0);return h.length>0?Object.freeze(h):void 0}const r=t.split(/\r?\n/),d=[];let l=!1;for(const b of r){if(!l){new RegExp(`^${i}:\\s*$`,"i").test(b.trim())&&(l=!0);continue}if(/^[A-Za-z0-9_-]+:\s*/.test(b))break;const h=b.match(/^\s*-\s*(.+?)\s*$/);if(!h)continue;const y=k(h[1]);y&&d.push(y)}return d.length>0?Object.freeze(d):void 0}function ue(t,e,i,n){if(!t)return{};try{const o=t(e);if(!I(o)||!I(o.receipt))throw new Error("invalid");return{legacy_scope:o}}catch{return n.push(`legacy story scope extractor failed: ${T(i)}`),{}}}function Y(t){return t.startsWith("_")||t.startsWith(".")}function pe(t){return J.includes(t)}async function Ae(){const t=await import("node:fs"),e=await import("node:path");return{isDirectory(i){try{return t.statSync(i).isDirectory()}catch{return!1}},readdir(i){try{return t.readdirSync(i)}catch{return[]}},readFile(i){try{return t.readFileSync(i,"utf8")}catch{return""}},join(...i){try{return e.join(...i)}catch{return i.join("/")}}}}function me(t,e){let i=!1,n=null,o=null;for(let r=0;r<A.length;r++){const d=A[r],l=t.match(d);if(l){i=!0,n=l[1],o=r===2?"filename-slug":"filename-canonical";break}}return i?e.id&&e.id.length>0?{id:e.id,source:"frontmatter"}:{id:n,source:o}:null}function ge(t){for(const e of A){const i=t.match(e);if(i)return i[1]}return null}function j(t){const e=t.trim();return/^\d+(?:\.\d+)*$/i.test(e)?`P${e}`.toUpperCase():e.toUpperCase()}function _e(t){const e=j(t);return/^P\d+(?:\.\d+)?$/i.test(e)?`epic-${e}.md`:`epic-${t}.md`}function he(t){const e=j(t);return/^P\d+\.\d+(?:\.\d+)?$/i.test(e)?`${e}.story.md`:`${t}.story.md`}function G(t,e){return!t||!e?!1:j(t)!==j(e)}function ye(t,e,i){return`frontmatter/filename mismatch: epic '${t}' has frontmatter id '${e}' but filename implies '${i}'. Repair by using generated canonical '${_e(e)}' or changing frontmatter id to '${i}'.`}function Se(t,e,i){return`frontmatter/filename mismatch: story '${t}' has frontmatter id '${e}' but filename implies '${i}'. Repair by using generated canonical '${he(e)}' or changing frontmatter id to '${i}'.`}function be(t){let e=t.match(F[0]);if(e){const i=e[1],n=i.indexOf(".");return{id:i,epic_id_hint:n>0?i.slice(0,n):null}}if(e=t.match(F[1]),e){const i=e[1],n=i.indexOf(".");return{id:i,epic_id_hint:n>0?i.slice(0,n):null}}if(e=t.match(F[2]),e){const i=e[1],n=e[2];return{id:`${i}.${n}`,epic_id_hint:i}}return null}function $e(t,e){return e.join(t,"..","stories")}function Le(t,e,i){const n=typeof i?.legacyStoryScope=="function"?i.legacyStoryScope:void 0,o=[],r=[],d=[],l=new Date().toISOString();if(typeof t!="string"||t.length===0)return Object.freeze({epics:Object.freeze([]),warnings:Object.freeze([]),skipped:Object.freeze([])});if(!e.isDirectory(t))return Object.freeze({epics:Object.freeze([]),warnings:Object.freeze([]),skipped:Object.freeze([])});const b=[...e.readdir(t)].sort(),h=[],y=new Map;for(const c of b){const s=e.join(t,c);if(Y(c)){r.push(`${c}: ignored (draft or hidden prefix)`);continue}if(e.isDirectory(s)){if(pe(c)){r.push(`${c}: ignored subdirectory`);continue}r.push(`${c}: subdirectory not recursed`);continue}if(!c.endsWith(".md"))continue;if(!A.some($=>$.test(c))){r.push(`${c}: did not match any EPIC_FILE_PATTERNS`);continue}const f=e.readFile(s),p=P(f,c);o.push(...p.warnings);const m=p.metadata,_=ge(c);m.id&&G(m.id,_)&&o.push(p.source==="frontmatter"?ye(c,m.id,_):`legacy metadata/filename mismatch: epic '${c}' id does not match its filename`),n&&y.set(s,f),h.push({filename:c,fullPath:s,metadata:m,metadataSource:p.source})}const E=new Map,u=[];for(const c of h){const s=me(c.filename,c.metadata);if(s===null){r.push(`${c.filename}: id resolution returned null`);continue}let a=s.id;const f=a,p=E.get(f)??0;p>0&&(a=`${f}-${p+1}`,o.push(`epic ID collision: '${f}' resolved to '${a}' for ${c.filename}`)),E.set(f,p+1),u.push({candidate:c,finalId:a,idSource:c.metadataSource==="legacy-metadata"&&c.metadata.id?"legacy-metadata":s.source})}const g=new Map;if(n)for(const c of u){const s=y.get(c.candidate.fullPath);s!==void 0&&g.set(c.finalId,s)}const S=new Map,w=$e(t,e);if(e.isDirectory(w)){const c=[...e.readdir(w)].sort();for(const s of c){if(Y(s)||!s.endsWith(".md"))continue;const a=e.join(w,s);if(e.isDirectory(a))continue;const f=be(s);if(!f)continue;const p=e.readFile(a),m=P(p,s);o.push(...m.warnings);const _=m.metadata;_.id&&G(_.id,f.id)&&o.push(m.source==="frontmatter"?Se(s,_.id,f.id):`legacy metadata/filename mismatch: story '${s}' id does not match its filename`);const $=_.epic_id??f.epic_id_hint;if(!$){o.push(`story '${s}' has no epic_id (frontmatter or filename pattern)`);continue}const V=Object.freeze({id:f.id,epic_id:$,filename:s,path:a,..._.title?{title:_.title}:{},..._.status?{status:_.status}:{},..._.depends_on?{depends_on:_.depends_on}:{},..._.files_to_modify?{files_to_modify:_.files_to_modify}:{},...ue(n,{storyId:f.id,epicId:$,content:p,...g.has($)?{epicContent:g.get($)}:{}},s,o)});S.has($)||S.set($,[]),S.get($).push(V)}}for(const c of u){const s=S.get(c.finalId)??[],a=Object.freeze({id:c.finalId,filename:c.candidate.filename,path:c.candidate.fullPath,...c.candidate.metadata.title?{title:c.candidate.metadata.title}:{},...c.candidate.metadata.status?{status:c.candidate.metadata.status}:{},...c.candidate.metadata.total_stories!==void 0?{total_stories:c.candidate.metadata.total_stories}:{},...c.candidate.metadata.depends_on?{depends_on:c.candidate.metadata.depends_on}:{},source:"discovered",discovered_at:l,stories:Object.freeze([...s]),t:c.idSource,e:c.candidate.metadataSource});d.push(a)}const v=new Set(d.map(c=>c.id));for(const[c,s]of S.entries())if(!v.has(c))for(const a of s)o.push(`orphan story '${a.filename}' references unknown epic '${c}'`);return Object.freeze({epics:Object.freeze(d),warnings:Object.freeze(o),skipped:Object.freeze(r)})}function D(t){const e=t.legacy_scope;if(!e)return{...t.files_to_modify?{files:t.files_to_modify}:{},filesSource:t.files_to_modify?"frontmatter":"none",...t.depends_on?{deps:t.depends_on}:{}};const i=e.receipt,n=i.scope_basis==="validated"&&Array.isArray(e.files_to_modify)&&e.files_to_modify.length>0?e.files_to_modify:void 0,o=i.dependency_basis==="declared"&&Array.isArray(e.depends_on)?e.depends_on:void 0;return{...n?{files:n}:{},filesSource:n?i.scope_source:"none",...o?{deps:o}:{},receipt:i}}function Z(t){return t.files_to_modify!==void 0&&!(Array.isArray(t.files_to_modify)&&t.files_to_modify.length===0)}function H(t,e){const i=t.legacy_scope_receipt;return e!==void 0&&I(i)&&i.story_sha256===e.story_sha256&&(i.epic_sha256??null)===(e.epic_sha256??null)}function R(t,e){e&&(t.legacy_scope_receipt=JSON.parse(JSON.stringify(e)))}function U(t,e){const i=D(e);if(!i.receipt||H(t,i.receipt))return!1;let n=!1;return!Z(t)&&i.files&&i.files.length>0&&(t.files_to_modify=[...i.files],n=!0),t.depends_on===void 0&&i.deps!==void 0&&(t.depends_on=[...i.deps],n=!0),n&&R(t,i.receipt),n}function we(t,e){const i=D(e);if(H(t,i.receipt))return!1;let n=!1;return i.deps!==void 0&&(t.depends_on=[...i.deps]),i.filesSource==="frontmatter"&&i.files?t.files_to_modify=[...i.files]:i.filesSource==="table"&&i.files&&!Z(t)&&(t.files_to_modify=[...i.files],n=!0),n&&R(t,i.receipt),n}function K(t){const e=Ee(t);return e==="done"||e==="completed"||e==="merged"}function x(t){return K(t)}function Ee(t){return typeof t=="string"?t.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}function I(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function O(t){throw new Error(`epic-aggregate-writer:${t}`)}function ve(t){const e=[],i=new Set;for(const n of t)(typeof n!="string"||n.length===0)&&O("epic_aggregate_story_ref_invalid"),i.has(n)&&O("epic_aggregate_story_ref_duplicate"),i.add(n),e.push(n);return e}function Ie(t,e,i){const n=i[e];return n===void 0&&O("epic_aggregate_story_missing"),I(n)||O("epic_aggregate_story_not_object"),n.id!==e&&O("epic_aggregate_story_id_conflict"),n.epic_id!==t&&O("epic_aggregate_story_epic_conflict"),n}function Oe(t,e,i,n,o){const r=e[t];I(r)||O("epic_aggregate_epic_not_object"),r.id!==t&&O("epic_aggregate_epic_id_conflict"),Array.isArray(r.stories)||O("epic_aggregate_story_list_not_array");const d=ve(r.stories),l=d.length,b=d.filter(S=>K(Ie(t,S,i).status)).length,h=o?.total_stories,y=o?.e==="legacy-metadata"&&x(r.status),E=y?h??l:l>0?l:h??0,u=y||l===0&&E>0&&x(r.status)?E:b,g=l>0&&b===l;x(r.status)&&!y&&!g&&l>0&&O("epic_aggregate_terminal_incomplete_conflict"),r.total_stories=E,r.completed_stories=u,!x(r.status)&&g&&(r.status="done",(r.completed_at===void 0||r.completed_at===null)&&(r.completed_at=n))}function je(t,e,i){const n=t??{},o=I(n.epics)?n.epics:{},r=I(n.stories)?n.stories:{},d=structuredClone(o),l=structuredClone(r),b=[],h=[],y=new Set,E=new Map;let u=0,g=0;const S=i?.forceOverwrite===!0,w=i?.nowIso??new Date().toISOString(),v=new Set,c=new Map;for(const s of e.epics){if(!s.id||v.has(s.id))throw new Error("discovery_epic_identity_conflict");v.add(s.id),E.set(s.id,s);const a=d[s.id];if(a!==void 0&&(!I(a)||a.id!==void 0&&a.id!==s.id))throw new Error("discovery_epic_identity_conflict");for(const f of s.stories){if(!f.id||f.epic_id!==s.id||c.has(f.id))throw new Error("discovery_story_identity_conflict");c.set(f.id,s.id);const p=l[f.id];if(p!==void 0&&(!I(p)||p.id!==void 0&&p.id!==f.id||p.epic_id!==void 0&&p.epic_id!==s.id))throw new Error("discovery_story_identity_conflict")}}for(const s of e.epics){const a=d[s.id],f=a;if(f&&(f.branch_mode==="epic"||typeof f.execution_branch=="string")){h.push({id:s.id,reason:"epic Git lifecycle preserved"});continue}if(a&&a.source==="create-epic"&&!S){h.push({id:s.id,reason:"create-epic source preserved (defense)"});continue}if(a){const m=a;m.depends_on=s.depends_on??[];const _=Array.isArray(m.stories)?m.stories.filter($=>typeof $=="string"):[];m.stories=[...new Set([..._,...s.stories.map($=>$.id)])],s.title!==void 0&&(m.title=s.title),a.source!=="create-epic"&&y.add(s.id);continue}const p={id:s.id,title:s.title??"",status:s.status??"planning",source:"discovered",discovered_at:w,merged_at:w,stories:s.stories.map(m=>m.id),depends_on:s.depends_on??[]};d[s.id]=p,y.add(s.id),b.push(s.id)}for(const s of e.epics)for(const a of s.stories){const f=l[a.id],p=d[s.id];if(f&&p&&(p.branch_mode==="epic"||typeof p.execution_branch=="string")){h.push({id:a.id,reason:"story Git lifecycle preserved"}),I(f)&&U(f,a)&&g++;continue}if(f&&f.source==="create-epic"&&!S){h.push({id:a.id,reason:"create-epic source preserved (defense, story)"}),I(f)&&U(f,a)&&g++;continue}if(f){const $=f;a.title!==void 0&&($.title=a.title),we($,a)&&g++;continue}const m=D(a),_={id:a.id,epic_id:a.epic_id,title:a.title??"",status:"backlog",source:"discovered",discovered_at:w};m.receipt?m.deps!==void 0&&(_.depends_on=[...m.deps]):_.depends_on=a.depends_on??[],_.files_to_modify=m.receipt?[...m.files??[]]:a.files_to_modify??[],m.receipt&&R(_,m.receipt),l[a.id]=_,u++}for(const s of y)Oe(s,d,l,w,E.get(s));return n.epics=d,n.stories=l,{state:n,added:Object.freeze([...b]),skipped:Object.freeze([...h]),storiesAdded:u,storiesFilled:g}}export{oe as DISCOVERY_FRONTMATTER_LIMITS,A as EPIC_FILE_PATTERNS,ze as GENERATED_NAMING_CONTRACT,F as STORY_FILE_PATTERNS,Ae as buildDefaultDiscoveryFs,Le as discoverEpicsFromDir,me as getEpicIdFromDescriptor,je as mergeDiscoveredIntoState};
@@ -30,6 +30,13 @@ type YoloopSessionRolloverOperation = Extract<YoloopStateOperation, {
30
30
  type YoloopSuccessorTransitionOperation = Extract<YoloopStateOperation, {
31
31
  readonly type: 'commit_successor_transition';
32
32
  }>;
33
+ /** P227.16: exact legacy source bytes and boundary evidence for adoption planning. */
34
+ export interface LegacyAdoptionSourceV1 {
35
+ readonly sourceBytes: Uint8Array | null;
36
+ readonly lockPresent: boolean;
37
+ readonly rolloverManifestPresent: boolean;
38
+ readonly successorTransitionManifestPresent: boolean;
39
+ }
33
40
  /** Minimal Pino-compatible logger subset. */
34
41
  export interface ClientYoloopLogger {
35
42
  warn(payload: object, msg?: string): void;
@@ -90,6 +97,22 @@ export declare class YoloopClientStateStore {
90
97
  private acknowledgeContinuationAuthority;
91
98
  private repairContinuationAuthority;
92
99
  private switchContinuationPolicy;
100
+ /** True when the common v2 operational authority owns yoloop state; a corrupt v2 throws. */
101
+ usesCommonAuthority(): boolean;
102
+ /** Exact source bytes plus boundary evidence for the pure adoption planner. */
103
+ readLegacyAdoptionSource(): Promise<LegacyAdoptionSourceV1>;
104
+ /**
105
+ * Commit a planned adoption under the mutation lock: the source bytes must
106
+ * still hash to `sourceSha256` and the boundary must still be free. The
107
+ * exact source bytes are backed up before the state rename.
108
+ */
109
+ commitLegacyPolicyAdoption(input: {
110
+ readonly sourceSha256: string;
111
+ readonly nextBytes: string;
112
+ }): Promise<{
113
+ readonly resultSha256: string;
114
+ }>;
115
+ private writeBytesAtomically;
93
116
  private replanContinuationSession;
94
117
  /**
95
118
  * Append a new recovery attempt to `state.recovery_history[]`. FIFO cap