@ornexus/neocortex 4.62.0 → 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.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1193 -1193
- package/install.ps1 +1 -1
- package/install.sh +28 -5
- package/package.json +3 -4
- package/packages/client/dist/agent/refresh-stubs.d.ts +6 -0
- package/packages/client/dist/agent/refresh-stubs.js +2 -2
- package/packages/client/dist/commands/invoke.d.ts +7 -0
- package/packages/client/dist/commands/invoke.js +50 -50
- package/packages/client/dist/commands/refresh-memory.d.ts +10 -0
- package/packages/client/dist/commands/refresh-memory.js +5 -3
- package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +86 -1
- package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -3
- package/packages/client/dist/git/git-lifecycle-store.d.ts +30 -2
- package/packages/client/dist/git/git-lifecycle-store.js +7 -7
- package/packages/client/dist/git/legacy-branch-mode-conversion.d.ts +58 -0
- package/packages/client/dist/git/legacy-branch-mode-conversion.js +4 -0
- package/packages/client/dist/git/release-gate-env.d.ts +2 -41
- package/packages/client/dist/git/release-gate-env.js +1 -1
- package/packages/client/dist/git/state-json-field-merge.d.ts +76 -0
- package/packages/client/dist/git/state-json-field-merge.js +2 -0
- package/packages/client/dist/git/story-worktree-cleanup.d.ts +22 -1
- package/packages/client/dist/git/story-worktree-cleanup.js +4 -4
- package/packages/client/dist/git/story-worktree-integration.d.ts +48 -0
- package/packages/client/dist/git/story-worktree-integration.js +3 -3
- package/packages/client/dist/git/story-worktree-manager.d.ts +57 -0
- package/packages/client/dist/git/story-worktree-manager.js +3 -3
- package/packages/client/dist/git/story-worktree-paths.d.ts +23 -1
- package/packages/client/dist/git/story-worktree-paths.js +1 -1
- package/packages/client/dist/git/story-write-set-extension.d.ts +3 -0
- package/packages/client/dist/git/story-write-set-extension.js +1 -1
- package/packages/client/dist/private-execution/root-memory-writer.js +1 -1
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +30 -0
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +8 -8
- package/packages/client/dist/runner/headless/run-yolo.d.ts +15 -0
- package/packages/client/dist/runner/headless/run-yolo.js +1 -1
- package/packages/client/dist/runner/headless/run-yoloop.d.ts +55 -0
- package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
- package/packages/client/dist/runner/headless/types.d.ts +9 -1
- package/packages/client/dist/runner/headless/types.js +2 -2
- package/packages/client/dist/state/project-state-snapshot.js +1 -1
- package/packages/client/dist/state/state-json-repair.d.ts +23 -0
- package/packages/client/dist/state/state-json-repair.js +4 -3
- package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
- package/packages/client/dist/yoloop/discovery-hook.d.ts +2 -0
- package/packages/client/dist/yoloop/discovery-hook.js +2 -2
- package/packages/client/dist/yoloop/invoke-hooks.d.ts +17 -0
- package/packages/client/dist/yoloop/invoke-hooks.js +14 -10
- package/packages/client/dist/yoloop/legacy-story-scope.d.ts +23 -0
- package/packages/client/dist/yoloop/legacy-story-scope.js +1 -0
- package/packages/client/dist/yoloop/legacy-yoloop-adoption.d.ts +69 -0
- package/packages/client/dist/yoloop/legacy-yoloop-adoption.js +1 -0
- package/packages/client/dist/yoloop/shared-discover-epics.d.ts +46 -1
- package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
- package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +23 -0
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
- package/packages/client/dist/yoloop/yoloop-start-origin-binding.d.ts +92 -0
- package/packages/client/dist/yoloop/yoloop-start-origin-binding.js +1 -0
- package/packages/shared/dist/compatibility/index.js +6 -0
- package/packages/shared/dist/project-manifest-projection.js +6 -3
- package/packages/shared/dist/release-gate-env-contract.js +129 -0
- package/packages/shared/dist/yoloop/branch-unit.js +119 -3
- package/packages/shared/dist/yoloop/epic-terminal-git.js +4 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/codex/install-codex.sh +12 -4
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/lib/managed-config-merge.js +385 -7
- package/targets-stubs/lib/managed-profile.sh +47 -7
- package/targets-stubs/opencode/neocortex-root.md +1 -1
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,12 +1,16 @@
|
|
|
1
|
-
import{statSync as
|
|
2
|
-
`),new
|
|
3
|
-
`),{
|
|
4
|
-
`)
|
|
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
|
|
7
|
-
`),{applied:!0,blocking:!1,reasonCode:"inline-yolo-materialized"}}catch(
|
|
8
|
-
`),{applied:!1,blocking:!0,reasonCode:"inline-yolo-persistence-failed"}}finally{await
|
|
9
|
-
`),{applied:
|
|
10
|
-
`),{applied:!1,blocking:!0,reasonCode:
|
|
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
|
|
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`.
|
|
@@ -230,7 +273,7 @@ export declare function getEpicIdFromDescriptor(filename: string, frontmatter: {
|
|
|
230
273
|
* @param fs optional fs adapter; defaults to `node:fs` wrapper (lazy)
|
|
231
274
|
* @returns DiscoveryResult with epics, warnings, skipped arrays
|
|
232
275
|
*/
|
|
233
|
-
export declare function discoverEpicsFromDir(dir: string, fs: DiscoveryFsAdapter): DiscoveryResult;
|
|
276
|
+
export declare function discoverEpicsFromDir(dir: string, fs: DiscoveryFsAdapter, options?: DiscoveryOptions): DiscoveryResult;
|
|
234
277
|
/**
|
|
235
278
|
* Options for `mergeDiscoveredIntoState`.
|
|
236
279
|
*
|
|
@@ -273,6 +316,8 @@ export interface MergeResult {
|
|
|
273
316
|
}>;
|
|
274
317
|
/** Number of stories added to `state.stories`. */
|
|
275
318
|
readonly storiesAdded: number;
|
|
319
|
+
/** P227.17: existing stories that received at least one fill-only field. */
|
|
320
|
+
readonly storiesFilled: number;
|
|
276
321
|
}
|
|
277
322
|
/**
|
|
278
323
|
* Merge `DiscoveryResult` (from `discoverEpicsFromDir`) into a `state` object,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const ye=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]),F=Object.freeze([/^(P?\d+\.\d+(?:\.\d+)?)\.story\.md$/i,/^story-(P?\d+\.\d+)\.md$/i,/^EPIC-(\d+)\.STORY-(\d+)\.md$/]),B=Object.freeze([".archive","_archive","_archives","_drafts","archive","archives","archived","drafts"]),W=/^---\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 Y(t){if(typeof t!="string"||t.length===0)return{};const e=t.match(W);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:se(i),files_to_modify:N(i,"files_to_modify"),total_stories:R(z(i,"total_stories"))}}const G=32,Z=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 D(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 R(t){if(t===void 0||!/^\d{1,5}$/.test(t.trim()))return;const e=Number(t);return Number.isSafeInteger(e)?e:void 0}function K(t){const e=D(t).toLowerCase().replace(/[_\s]+/g,"-"),n={planned:"planning",complete:"completed",closed:"done",finished:"done"}[e]??e;return U.has(n)?n:void 0}function V(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 X(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 I(t,e,i,n){const c=[...new Set(t.map(D).filter(Boolean))];if(c.length>1){n.push(`legacy metadata ambiguous for '${e}' in '${i}': conflicting values ignored`);return}return c[0]}function q(t,e){const i=[],n=[],c=t.slice(0,Z).split(/\r?\n/,G);for(const g of c){if(n.length>0&&(/^\s*---\s*$/.test(g)||/^##\s+/.test(g)))break;n.push(g)}const r=new Map;for(const g of n){const o=g.match(H);if(!o)continue;const d=V(o[1]);if(!d)continue;const l=r.get(d)??[];l.push(o[2]),r.set(d,l)}const u=I(r.get("id")??[],"id",e,i),f=I(r.get("title")??[],"title",e,i),b=I(r.get("status")??[],"status",e,i),h=I(r.get("total_stories")??[],"total_stories",e,i),p=b===void 0?void 0:K(b);b!==void 0&&p===void 0&&i.push(`legacy metadata status unrecognized in '${e}': value ignored`);const S=R(h);h!==void 0&&S===void 0&&i.push(`legacy metadata total_stories invalid in '${e}': value ignored`);const _=u&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(u)?u:void 0;u!==void 0&&_===void 0&&i.push(`legacy metadata id invalid in '${e}': value ignored`);const s=X(n),a=f??s;return{metadata:{..._?{id:_}:{},...a?{title:a.slice(0,200)}:{},...p?{status:p}:{},...S!==void 0?{total_stories:S}:{}},source:"legacy-metadata",warnings:Object.freeze(i)}}function J(t){return/^[A-Za-z0-9._-]{1,160}$/.test(t)?t:"markdown-target.md"}function A(t){return new TextEncoder().encode(t).length}const Q=Object.freeze({maxBytes:8*1024,maxLines:128,maxListItems:32,budgetField:"files_to_modify",budgetFieldMaxItems:256,extraLines:256,extraBytes:64*1024}),ee=new Set(["files_to_modify","depends_on","related_epics"]);function te(t){const e=Q,i=t.split(/\r?\n/);let n=0,c=0,r=null,u=0;const f=(_,s)=>{const a=_===e.budgetField?e.budgetFieldMaxItems:e.maxListItems;return s<=a?null:`frontmatter-list-too-long:${ee.has(_)?_:"unlisted-field"}:${Math.min(s,999999)}>${a}`};for(const _ of i){if(!_.trim()||_.trimStart().startsWith("#"))continue;if(/^\s+-\s+\S/.test(_)){if(r===null)continue;u+=1,r===e.budgetField&&(n+=1,c+=A(_)+1);continue}if(r!==null){const m=f(r,u);if(m)return m;r=null,u=0}const s=_.match(/^([A-Za-z_][A-Za-z0-9_-]{0,63}):(?:\s*(.*))?$/);if(!s)continue;const a=(s[2]??"").trim();if(!a){r=s[1];continue}if(a.startsWith("[")&&a.endsWith("]")){const m=a.slice(1,-1).trim(),g=m?f(s[1],m.split(",").length):null;if(g)return g;s[1]===e.budgetField&&(c+=A(s[2]??""))}}if(r!==null){const _=f(r,u);if(_)return _}const b=i.length+2,h=A(t)+9,p=e.maxLines+Math.min(e.extraLines,n),S=e.maxBytes+Math.min(e.extraBytes,c);return b>p||h>S?"frontmatter-oversized":null}function ie(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 u=n[1].trim();if(u.startsWith('"')&&!u.endsWith('"')||u.startsWith("'")&&!u.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 r=c[1].trim();if(e=r.length===0,r.startsWith('"')&&!r.endsWith('"')||r.startsWith("'")&&!r.endsWith("'"))return!0}return!1}function ne(t,e,i){const n=J(e),c=t.match(W);if(!c)return Object.freeze([`metadata-frontmatter reason=frontmatter-malformed file='${n}': repair the bounded leading YAML envelope; source content omitted`]);const r=c[1],u=te(r);return u?Object.freeze([`metadata-frontmatter reason=${u} file='${n}': reduce the leading YAML envelope; source content omitted`]):ie(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 M(t,e){if(/^---(?:\s*\r?\n|\s*$)/.test(t)){const i=Y(t);return{metadata:i,source:"frontmatter",warnings:ne(t,e,i)}}return typeof t!="string"||t.length===0?{metadata:{},source:"none",warnings:Object.freeze([])}:q(t,e)}function T(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 se(t){return N(t,"depends_on")}function N(t,e){const i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=t.match(new RegExp(`^${i}:[ \\t]*(.+?)[ \\t]*$`,"mi"))?.[1]?.trim();if(c!==void 0){const h=(c.startsWith("[")&&c.endsWith("]")?c.slice(1,-1).split(","):[c]).map(T).filter(p=>typeof p=="string"&&p.length>0);return h.length>0?Object.freeze(h):void 0}const r=t.split(/\r?\n/),u=[];let f=!1;for(const b of r){if(!f){new RegExp(`^${i}:\\s*$`,"i").test(b.trim())&&(f=!0);continue}if(/^[A-Za-z0-9_-]+:\s*/.test(b))break;const h=b.match(/^\s*-\s*(.+?)\s*$/);if(!h)continue;const p=T(h[1]);p&&u.push(p)}return u.length>0?Object.freeze(u):void 0}function C(t){return t.startsWith("_")||t.startsWith(".")}function re(t){return B.includes(t)}async function be(){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 oe(t,e){let i=!1,n=null,c=null;for(let r=0;r<O.length;r++){const u=O[r],f=t.match(u);if(f){i=!0,n=f[1],c=r===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 ce(t){for(const e of O){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 ae(t){const e=j(t);return/^P\d+(?:\.\d+)?$/i.test(e)?`epic-${e}.md`:`epic-${t}.md`}function de(t){const e=j(t);return/^P\d+\.\d+(?:\.\d+)?$/i.test(e)?`${e}.story.md`:`${t}.story.md`}function P(t,e){return!t||!e?!1:j(t)!==j(e)}function ue(t,e,i){return`frontmatter/filename mismatch: epic '${t}' has frontmatter id '${e}' but filename implies '${i}'. Repair by using generated canonical '${ae(e)}' or changing frontmatter id to '${i}'.`}function le(t,e,i){return`frontmatter/filename mismatch: story '${t}' has frontmatter id '${e}' but filename implies '${i}'. Repair by using generated canonical '${de(e)}' or changing frontmatter id to '${i}'.`}function fe(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 pe(t,e){return e.join(t,"..","stories")}function Se(t,e){const i=[],n=[],c=[],r=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 u=[...e.readdir(t)].sort(),f=[];for(const s of u){const a=e.join(t,s);if(C(s)){n.push(`${s}: ignored (draft or hidden prefix)`);continue}if(e.isDirectory(a)){if(re(s)){n.push(`${s}: ignored subdirectory`);continue}n.push(`${s}: subdirectory not recursed`);continue}if(!s.endsWith(".md"))continue;if(!O.some(y=>y.test(s))){n.push(`${s}: did not match any EPIC_FILE_PATTERNS`);continue}const g=e.readFile(a),o=M(g,s);i.push(...o.warnings);const d=o.metadata,l=ce(s);d.id&&P(d.id,l)&&i.push(o.source==="frontmatter"?ue(s,d.id,l):`legacy metadata/filename mismatch: epic '${s}' id does not match its filename`),f.push({filename:s,fullPath:a,metadata:d,metadataSource:o.source})}const b=new Map,h=[];for(const s of f){const a=oe(s.filename,s.metadata);if(a===null){n.push(`${s.filename}: id resolution returned null`);continue}let m=a.id;const g=m,o=b.get(g)??0;o>0&&(m=`${g}-${o+1}`,i.push(`epic ID collision: '${g}' resolved to '${m}' for ${s.filename}`)),b.set(g,o+1),h.push({candidate:s,finalId:m,idSource:s.metadataSource==="legacy-metadata"&&s.metadata.id?"legacy-metadata":a.source})}const p=new Map,S=pe(t,e);if(e.isDirectory(S)){const s=[...e.readdir(S)].sort();for(const a of s){if(C(a)||!a.endsWith(".md"))continue;const m=e.join(S,a);if(e.isDirectory(m))continue;const g=fe(a);if(!g)continue;const o=e.readFile(m),d=M(o,a);i.push(...d.warnings);const l=d.metadata;l.id&&P(l.id,g.id)&&i.push(d.source==="frontmatter"?le(a,l.id,g.id):`legacy metadata/filename mismatch: story '${a}' id does not match its filename`);const y=l.epic_id??g.epic_id_hint;if(!y){i.push(`story '${a}' has no epic_id (frontmatter or filename pattern)`);continue}const $=Object.freeze({id:g.id,epic_id:y,filename:a,path:m,...l.title?{title:l.title}:{},...l.status?{status:l.status}:{},...l.depends_on?{depends_on:l.depends_on}:{},...l.files_to_modify?{files_to_modify:l.files_to_modify}:{}});p.has(y)||p.set(y,[]),p.get(y).push($)}}for(const s of h){const a=p.get(s.finalId)??[],m=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:r,stories:Object.freeze([...a]),t:s.idSource,e:s.candidate.metadataSource});c.push(m)}const _=new Set(c.map(s=>s.id));for(const[s,a]of p.entries())if(!_.has(s))for(const m of a)i.push(`orphan story '${m.filename}' references unknown epic '${s}'`);return Object.freeze({epics:Object.freeze(c),warnings:Object.freeze(i),skipped:Object.freeze(n)})}function k(t){const e=me(t);return e==="done"||e==="completed"||e==="merged"}function L(t){return k(t)}function me(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 ge(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 _e(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 he(t,e,i,n,c){const r=e[t];E(r)||w("epic_aggregate_epic_not_object"),r.id!==t&&w("epic_aggregate_epic_id_conflict"),Array.isArray(r.stories)||w("epic_aggregate_story_list_not_array");const u=ge(r.stories),f=u.length,b=u.filter(a=>k(_e(t,a,i).status)).length,h=c?.total_stories,p=c?.e==="legacy-metadata"&&L(r.status),S=p?h??f:f>0?f:h??0,_=p||f===0&&S>0&&L(r.status)?S:b,s=f>0&&b===f;L(r.status)&&!p&&!s&&f>0&&w("epic_aggregate_terminal_incomplete_conflict"),r.total_stories=S,r.completed_stories=_,!L(r.status)&&s&&(r.status="done",(r.completed_at===void 0||r.completed_at===null)&&(r.completed_at=n))}function $e(t,e,i){const n=t??{},c=E(n.epics)?n.epics:{},r=E(n.stories)?n.stories:{},u=structuredClone(c),f=structuredClone(r),b=[],h=[],p=new Set,S=new Map;let _=0;const s=i?.forceOverwrite===!0,a=i?.nowIso??new Date().toISOString(),m=new Set,g=new Map;for(const o of e.epics){if(!o.id||m.has(o.id))throw new Error("discovery_epic_identity_conflict");m.add(o.id),S.set(o.id,o);const d=u[o.id];if(d!==void 0&&(!E(d)||d.id!==void 0&&d.id!==o.id))throw new Error("discovery_epic_identity_conflict");for(const l of o.stories){if(!l.id||l.epic_id!==o.id||g.has(l.id))throw new Error("discovery_story_identity_conflict");g.set(l.id,o.id);const y=f[l.id];if(y!==void 0&&(!E(y)||y.id!==void 0&&y.id!==l.id||y.epic_id!==void 0&&y.epic_id!==o.id))throw new Error("discovery_story_identity_conflict")}}for(const o of e.epics){const d=u[o.id],l=d;if(l&&(l.branch_mode==="epic"||typeof l.execution_branch=="string")){h.push({id:o.id,reason:"epic Git lifecycle preserved"});continue}if(d&&d.source==="create-epic"&&!s){h.push({id:o.id,reason:"create-epic source preserved (defense)"});continue}if(d){const $=d;$.depends_on=o.depends_on??[];const v=Array.isArray($.stories)?$.stories.filter(x=>typeof x=="string"):[];$.stories=[...new Set([...v,...o.stories.map(x=>x.id)])],o.title!==void 0&&($.title=o.title),d.source!=="create-epic"&&p.add(o.id);continue}const y={id:o.id,title:o.title??"",status:o.status??"planning",source:"discovered",discovered_at:a,merged_at:a,stories:o.stories.map($=>$.id),depends_on:o.depends_on??[]};u[o.id]=y,p.add(o.id),b.push(o.id)}for(const o of e.epics)for(const d of o.stories){const l=f[d.id],y=u[o.id];if(l&&y&&(y.branch_mode==="epic"||typeof y.execution_branch=="string")){h.push({id:d.id,reason:"story Git lifecycle preserved"});continue}if(l&&l.source==="create-epic"&&!s){h.push({id:d.id,reason:"create-epic source preserved (defense, story)"});continue}if(l){const v=l;d.title!==void 0&&(v.title=d.title),v.depends_on=d.depends_on??[],v.files_to_modify=d.files_to_modify??[];continue}const $={id:d.id,epic_id:d.epic_id,title:d.title??"",status:"backlog",source:"discovered",discovered_at:a,depends_on:d.depends_on??[],files_to_modify:d.files_to_modify??[]};f[d.id]=$,_++}for(const o of p)he(o,u,f,a,S.get(o));return n.epics=u,n.stories=f,{state:n,added:Object.freeze([...b]),skipped:Object.freeze([...h]),storiesAdded:_}}export{Q as DISCOVERY_FRONTMATTER_LIMITS,O as EPIC_FILE_PATTERNS,ye as GENERATED_NAMING_CONTRACT,F as STORY_FILE_PATTERNS,be as buildDefaultDiscoveryFs,Se as discoverEpicsFromDir,oe as getEpicIdFromDescriptor,$e 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
|