@ornexus/neocortex 4.60.23 → 4.60.25
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/sbom.cdx.json +23 -23
- package/install.js +67 -10
- package/install.ps1 +39 -8
- package/install.sh +18 -6
- package/package.json +5 -2
- package/packages/client/dist/adapters/adapter-registry.d.ts +2 -2
- package/packages/client/dist/adapters/adapter-registry.js +1 -1
- package/packages/client/dist/adapters/grok-adapter.d.ts +11 -0
- package/packages/client/dist/adapters/grok-adapter.js +2 -0
- package/packages/client/dist/adapters/index.d.ts +1 -0
- package/packages/client/dist/adapters/index.js +1 -1
- package/packages/client/dist/adapters/platform-detector.d.ts +1 -1
- package/packages/client/dist/adapters/platform-detector.js +1 -1
- package/packages/client/dist/agent/refresh-stubs.js +2 -2
- package/packages/client/dist/cli.js +21 -2
- package/packages/client/dist/commands/invoke.d.ts +20 -21
- package/packages/client/dist/commands/invoke.js +59 -55
- package/packages/client/dist/commands/story-checkpoint.d.ts +15 -0
- package/packages/client/dist/commands/story-checkpoint.js +1 -0
- package/packages/client/dist/config.js +1 -1
- package/packages/client/dist/generated/command-registry.generated.d.ts +18 -52
- package/packages/client/dist/generated/command-registry.generated.js +1 -1
- package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +67 -0
- package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -0
- package/packages/client/dist/git/git-lifecycle-step-ids.d.ts +2 -0
- package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -0
- package/packages/client/dist/git/git-lifecycle-store.d.ts +198 -0
- package/packages/client/dist/git/git-lifecycle-store.js +4 -0
- package/packages/client/dist/git/secure-filesystem-boundary.d.ts +26 -0
- package/packages/client/dist/git/secure-filesystem-boundary.js +123 -0
- package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -1
- package/packages/client/dist/index.d.ts +2 -0
- package/packages/client/dist/index.js +1 -1
- package/packages/client/dist/memory/shared-project-memory-types.d.ts +29 -2
- package/packages/client/dist/memory/shared-project-memory-types.js +2 -2
- package/packages/client/dist/policy/subagent-approval-policy.js +1 -1
- package/packages/client/dist/runner/headless/continuous-story-workspace.d.ts +131 -0
- package/packages/client/dist/runner/headless/continuous-story-workspace.js +58 -0
- package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.d.ts +23 -0
- package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -0
- package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +15 -0
- package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +28 -0
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +12 -0
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +8 -0
- package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +134 -0
- package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -0
- package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -1
- package/packages/client/dist/runner/headless/run-yolo.js +1 -1
- package/packages/client/dist/runner/headless/run-yoloop.d.ts +7 -2
- package/packages/client/dist/runner/headless/run-yoloop.js +8 -1
- package/packages/client/dist/runner/headless/types.d.ts +1 -1
- package/packages/client/dist/runner/headless/types.js +2 -2
- package/packages/client/dist/runner-cli.js +0 -0
- package/packages/client/dist/state/project-state-snapshot.js +1 -1
- package/packages/client/dist/state/state-json-repair.d.ts +9 -0
- package/packages/client/dist/state/state-json-repair.js +3 -3
- package/packages/client/dist/tier/tier-aware-client.js +1 -1
- package/packages/client/dist/yoloop/invoke-hooks.d.ts +13 -10
- package/packages/client/dist/yoloop/invoke-hooks.js +8 -5
- package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
- package/packages/shared/dist/generated/command-registry.generated.js +18 -66
- package/packages/shared/dist/generated/invocation-schema.generated.js +5 -25
- package/packages/shared/dist/invocation/index.d.ts +1 -1
- package/packages/shared/dist/yoloop/epic-terminal-git.js +227 -0
- package/packages/shared/dist/yoloop/planning-graph.js +119 -0
- package/packages/shared/dist/yoloop/public-story-write-set.js +27 -0
- package/packages/shared/dist/yoloop/wave-decision-receipt.js +19 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/neocortex.md +18 -0
- 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 +21 -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 +20 -1
- package/targets-stubs/cursor/agent.md +20 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/gemini-cli/gemini.md +18 -0
- package/targets-stubs/grok/README.md +13 -0
- package/targets-stubs/grok/SKILL.md +50 -0
- package/targets-stubs/grok/config-mcp.toml +22 -0
- package/targets-stubs/grok/install-grok.sh +31 -0
- package/targets-stubs/kimi/neocortex.md +18 -0
- package/targets-stubs/openclaw/SKILL.md +18 -0
- package/targets-stubs/opencode/neocortex-root.md +20 -1
- package/targets-stubs/vscode/neocortex.agent.md +20 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{analyzeDependencyDag as I,StructuralDagError as f}from"./structural-dag-projection.js";import{classifyInvocationShapeV2 as E}from"./invocation-shape.js";const P=12,$=16,_=["active","archived","rolled-back","synthetic","orphan"],n=(i,e,t={})=>({commandId:i,stateProjectionPolicy:e,...t}),A=Object.freeze({status:n("status","full"),init:n("init","epic-targeted"),"arch-plan":n("arch-plan","full"),"arch-prd":n("arch-prd","full"),"arch-architecture":n("arch-architecture","epic-targeted"),"arch-api-contracts":n("arch-api-contracts","epic-targeted"),"arch-api-integrations":n("arch-api-integrations","epic-targeted"),"arch-database":n("arch-database","epic-targeted"),"arch-security":n("arch-security","epic-targeted"),"arch-design-system":n("arch-design-system","epic-targeted"),"arch-ux-design":n("arch-ux-design","epic-targeted"),"arch-performance":n("arch-performance","epic-targeted"),"arch-testing":n("arch-testing","epic-targeted"),"arch-infrastructure":n("arch-infrastructure","epic-targeted"),"arch-review":n("arch-review","epic-targeted"),"arch-fitness-functions":n("arch-fitness-functions","epic-targeted"),"create-epic":n("create-epic","epic-summary"),"idea-diagnose":n("idea-diagnose","full"),"idea-research":n("idea-research","epic-targeted"),"generate-epic":n("generate-epic","epic-targeted"),exec:n("exec","story-targeted",{structuralRequired:!0}),yolo:n("yolo","story-targeted",{structuralRequired:!0}),"yolo-inline":n("yolo-inline","story-targeted",{structuralRequired:!0}),epic:n("epic","epic-targeted",{structuralRequired:!0}),"setup-branch":n("setup-branch","story-targeted",{structuralRequired:!0}),diagnose:n("diagnose","adaptive-targeted"),"diagnose-inline":n("diagnose-inline","full"),research:n("research","adaptive-targeted"),"research-inline":n("research-inline","full"),"write-spec":n("write-spec","story-targeted",{structuralRequired:!0}),"create-tasks":n("create-tasks","story-targeted",{structuralRequired:!0}),implement:n("implement","story-targeted",{structuralRequired:!0}),commit:n("commit","story-targeted",{structuralRequired:!0}),"commit-push":n("commit","story-targeted",{structuralRequired:!0}),sync:n("sync","story-targeted",{structuralRequired:!0}),"sync-main":n("sync","story-targeted",{structuralRequired:!0}),"create-pr":n("create-pr","story-targeted",{structuralRequired:!0}),review:n("review","story-targeted"),"review-pr":n("review","story-targeted"),merge:n("merge","story-targeted",{structuralRequired:!0}),"merge-pr":n("merge","story-targeted",{structuralRequired:!0}),"fix-blocked":n("fix-blocked","story-targeted"),"finalize-epic":n("finalize-epic","epic-targeted"),"resolve-conflicts":n("resolve-conflicts","story-targeted"),"update-memory":n("update-memory","full"),"update-project-memory":n("update-memory","story-targeted",{structuralRequired:!0}),refactor:n("refactor","adaptive-targeted"),"refactor-suggest":n("refactor","story-targeted",{structuralRequired:!0}),cleanup:n("cleanup","full"),audit:n("audit","full"),"tech-debt":n("tech-debt","full"),menu:n("menu","full"),plans:n("plans","full"),billing:n("billing","full"),subscribe:n("subscribe","full"),"qa-scan":n("qa-scan","full"),yoloop:n("yoloop","yoloop-targeted",{structuralRequired:!0}),"migrate-state":n("migrate-state","full"),"migrate-project-id":n("migrate-project-id","full"),"policy-audit":n("policy-audit","full"),"mutation-test":n("mutation-test","full"),"sync-openapi":n("sync-openapi","full"),"generate-pacts":n("generate-pacts","full"),"verify-pacts":n("verify-pacts","full"),"property-test":n("property-test","full"),"property-tests":n("property-test","story-targeted",{structuralRequired:!0}),"chaos-plan":n("chaos-plan","full"),"ui-ux-review":n("ui-ux-review","adaptive-targeted"),"solyd-system":n("solyd-system","adaptive-targeted"),goal:n("goal","continuity-scoped"),loop:n("loop","continuity-scoped"),jobs:n("jobs","continuity-scoped"),runner:n("runner","continuity-scoped"),"goal-tick":n("goal-tick","continuity-scoped"),"loop-tick":n("loop-tick","continuity-scoped"),"validate-tests":n("validate-tests","story-targeted",{structuralRequired:!0}),"qa-gate":n("qa-gate","story-targeted",{structuralRequired:!0})}),Y=Object.freeze({st:"status",inicializar:"init",arquitetura:"arch-plan",architecture:"arch-plan",arch:"arch-plan",prd:"arch-prd","product-requirements":"arch-prd","arch-doc":"arch-architecture","tech-architecture":"arch-architecture","api-contracts":"arch-api-contracts","api-contract":"arch-api-contracts","api-integrations":"arch-api-integrations","api-int":"arch-api-integrations","database-schema":"arch-database","db-schema":"arch-database",db:"arch-database","cyber-security":"arch-security",security:"arch-security",sec:"arch-security","design-system":"arch-design-system",ds:"arch-design-system","atomic-design":"arch-design-system","ux-design":"arch-ux-design",ux:"arch-ux-design",wireframes:"arch-ux-design",wireframe:"arch-ux-design","user-flows":"arch-ux-design",performance:"arch-performance",perf:"arch-performance","capacity-planning":"arch-performance",capacity:"arch-performance","arch-perf":"arch-performance","performance-strategy":"arch-performance","testing-strategy":"arch-testing","test-plan":"arch-testing","test-strategy":"arch-testing","arch-test":"arch-testing",infrastructure:"arch-infrastructure",infra:"arch-infrastructure","deploy-plan":"arch-infrastructure",deployment:"arch-infrastructure","arch-infra":"arch-infrastructure","arch-deploy":"arch-infrastructure","review-consolidation":"arch-review",consolidation:"arch-review","architecture-review":"arch-review","arch-consolidation":"arch-review",fitness:"arch-fitness-functions","fitness-functions":"arch-fitness-functions",archfit:"arch-fitness-functions","arch-fit":"arch-fitness-functions","fit-funcs":"arch-fitness-functions","criar-epic":"create-epic",planejamento:"create-epic","idea-diag":"idea-diagnose","idea-pesq":"idea-research","gerar-epic":"generate-epic",executar:"exec",pipeline:"exec","parallel-epic":"epic",setup:"setup-branch",branch:"setup-branch",diag:"diagnose",diagnostico:"diagnose",c02:"diagnose",pesquisar:"research",pesq:"research","research-fix":"research",c03:"research",spec:"write-spec",especificacao:"write-spec",c04:"write-spec",tasks:"create-tasks",tarefas:"create-tasks",c05:"create-tasks",impl:"implement",implementar:"implement",c06:"implement",push:"commit",commit_push:"commit",cp:"commit",c07:"commit",sincronizar:"sync",c08:"sync",pr:"create-pr",c09:"create-pr",revisar:"review",c11:"review",mesclar:"merge",c12:"merge",fix:"fix-blocked",corrigir:"fix-blocked",finalizar:"finalize-epic",conflitos:"resolve-conflicts",memoria:"update-memory",refactoring:"refactor",refact:"refactor",refac:"refactor",rf:"refactor","cleanup-code":"refactor","code-cleanup":"refactor","code-quality":"refactor","improve-code":"refactor",modernize:"refactor",modernization:"refactor",legacy:"refactor","legacy-code":"refactor","debt-pay":"refactor","pay-debt":"refactor","debt-reduction":"refactor","smell-fix":"refactor","fix-smells":"refactor","code-smells":"refactor",strangler:"refactor","strangler-fig":"refactor",limpar:"cleanup",limpeza:"cleanup",auditar:"audit",auditoria:"audit",debt:"tech-debt",debts:"tech-debt","debt-list":"tech-debt","tech-debts":"tech-debt",td:"tech-debt",help:"menu",ajuda:"menu","?":"menu",commands:"menu",cmds:"menu",planos:"plans",pricing:"plans",bill:"billing",subscription:"billing",sub:"billing",upgrade:"subscribe",checkout:"subscribe",qa:"qa-scan","qa-test":"qa-scan","visual-qa":"qa-scan","e2e-scan":"qa-scan",troubleshoot:"qa-scan","debug-ui":"qa-scan",scan:"qa-scan",a11y:"qa-scan",accessibility:"qa-scan",wcag:"qa-scan","auto-yolo":"yoloop","epic-runner":"yoloop","story-runner":"yoloop","loop-yolo":"yoloop","auto-epic":"yoloop",migrate:"migrate-state","state-migrate":"migrate-state","schema-migrate":"migrate-state",policy:"policy-audit","audit-policy":"policy-audit","policy-history":"policy-audit",policies:"policy-audit",mutation:"mutation-test",stryker:"mutation-test","kill-mutants":"mutation-test","openapi-sync":"sync-openapi","api-sync":"sync-openapi","spec-sync":"sync-openapi","regen-openapi":"sync-openapi",pacts:"generate-pacts","gen-pacts":"generate-pacts","regen-pacts":"generate-pacts","create-pacts":"generate-pacts","verify-pact":"verify-pacts","pact-verify":"verify-pacts","check-pacts":"verify-pacts","pact-check":"verify-pacts",property:"property-test",pbt:"property-test",proptest:"property-test","invariant-test":"property-test",chaos:"chaos-plan",gameday:"chaos-plan","resilience-test":"chaos-plan","ux-review":"ui-ux-review","design-review":"ui-ux-review","visual-review":"ui-ux-review","product-polish":"ui-ux-review","security-system":"solyd-system","authorized-security":"solyd-system","sec-system":"solyd-system",goals:"goal","durable-goal":"goal","continuity-goal":"goal",loops:"loop","durable-loop":"loop","continuity-loop":"loop",job:"jobs","continuity-jobs":"jobs","neocortex-runner":"runner","continuity-runner":"runner"}),K=Object.freeze({1:"status",2:"init",3:"arch-plan",4:"arch-prd",5:"arch-architecture",6:"arch-api-contracts",7:"arch-api-integrations",8:"arch-database",9:"arch-security",10:"arch-design-system",11:"arch-ux-design",12:"arch-performance",13:"arch-testing",14:"arch-infrastructure",15:"arch-review",16:"arch-fitness-functions",17:"create-epic",18:"idea-diagnose",19:"idea-research",20:"generate-epic",21:"exec",22:"yolo",23:"epic",24:"setup-branch",25:"diagnose",26:"research",27:"write-spec",28:"create-tasks",29:"implement",30:"commit",31:"sync",32:"create-pr",33:"review",34:"merge",35:"fix-blocked",36:"finalize-epic",37:"resolve-conflicts",38:"update-memory",39:"refactor",40:"cleanup",41:"audit",42:"tech-debt",43:"menu",44:"plans",45:"billing",46:"subscribe",47:"qa-scan",48:"yoloop",49:"migrate-state",50:"policy-audit",51:"mutation-test",52:"sync-openapi",53:"generate-pacts",54:"verify-pacts",55:"property-test",56:"chaos-plan",57:"ui-ux-review",58:"solyd-system",59:"goal",60:"loop",61:"jobs",62:"runner"});function a(i,e=120){if(typeof i!="string")return;const t=i.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,e)}function C(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)}function m(...i){const e=new Set,t=[];for(const r of i)for(const o of r??[]){const c=a(o,80);if(!(!c||e.has(c))&&(e.add(c),t.push(c),t.length>=$))return t}return t}function V(i){return i.trim().replace(/^@?\*/,"").replace(/^@/,"").toLowerCase()}function Z(i){return i.trim().split(/\s+/,1)[0]??""}function q(i){const e=Z(i);if(!e)return A.menu;const t=V(e),r=K[t]??Y[t]??t;return A[r]??null}function B(i,e,t,r="full-compatible",o=["full-state"]){return{kind:"full",commandId:t?.commandId??null,stateProjectionPolicy:t?.stateProjectionPolicy??null,projectionMode:r,trigger:i,targetEpicId:null,targetStoryId:null,includedStoryCount:Object.keys(e.stories).length,includedEpicCount:Object.keys(e.epics).length,omittedStoryCount:0,omittedEpicCount:0,reason:"full-state",reasonCodes:m(o)}}function Ee(i,e,t,r="full-compatible",o=["full-state"]){const c=B(i,e,t,r,o);return h({...e,scope:c},e,c)}function J(i){const[e]=i.trim().split(/\s+/,1);return e?/^[A-Z]?\d+(?:\.\d+)+$/i.test(e.replace(/^@/,""))||/(?:^|\/)[A-Z]?\d+(?:\.\d+)+\.story\.md$/i.test(e.replace(/^@/,"")):!1}function x(i){const e=i.match(/(?:^|[/@\s])([A-Z]?\d+(?:\.\d+)+)\.story\.md\b/i);return e?.[1]?e[1]:i.match(/(?:^|\s|@)([A-Z]?\d+(?:\.\d+)+)(?=$|\s)/i)?.[1]??null}function W(i){const e=i.trim(),t=e.search(/\s/);return t===-1?"":e.slice(t).trim()}function O(i){return W(i).split(/\s+/).map(e=>e.replace(/^@/,"").replace(/^['"]|['"]$/g,"")).filter(e=>e.length>0&&!e.startsWith("-"))}function Oe(i){return O(i)[0]??null}function N(i,e){const r=i.replace(/^@/,"").replace(/^epic-/i,"").replace(/\.md$/i,""),o=[r,r.toUpperCase(),/^p\d+$/i.test(r)?`P${r.replace(/^p/i,"")}`:null,/^\d+$/.test(r)?`P${r}`:null].filter(c=>typeof c=="string"&&c.length>0);for(const c of o)if(e.epics[c])return c;return null}function H(i,e){const t=i.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);return t?.[1]?N(t[1],e):null}function k(i,e){const t=H(i,e);if(t)return t;for(const r of O(i)){if(/^[A-Z]?\d+(?:\.\d+)+$/i.test(r))continue;const o=N(r,e);if(o)return o}return null}function Q(i,e){const t=k(i,e);if(t)return t;const r=e.yoloop,o=r?.state?.currentSession?.currentEpicId;if(typeof o=="string"&&e.epics[o])return o;const c=r?.lock?.currentEpicId??r?.lock?.epicId;return typeof c=="string"&&e.epics[c]?c:null}function X(i){const e=i.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i)?.[1];if(e)return/^P/i.test(e)?e.toUpperCase():`P${e}`;for(const t of O(i)){if(/^P\d+$/i.test(t))return t.toUpperCase();if(/^\d+$/.test(t))return`P${t}`}return null}function b(i,e){if(typeof i.epic_id=="string"&&i.epic_id.length>0)return i.epic_id;const t=e.split(".").slice(0,-1).join(".");return t.length>0?t:null}function U(i){return typeof i=="string"&&["done","completed","merged","cancelled","canceled","abandoned"].includes(i.toLowerCase())}function v(i,e,t){if(t.has(i))return;const r=e.stories[i];if(!r)return;t.add(i);const o=r.depends_on;if(Array.isArray(o))for(const c of o)typeof c=="string"&&v(c,e,t)}function ee(i,e){const t=I(e.stories,[i]),r={};for(const o of t.orderedIds){const c=e.stories[o];c&&(r[o]=c)}return r}function M(i,e,t=[]){const r={};for(const o of t)e.epics[o]&&(r[o]=e.epics[o]);for(const[o,c]of Object.entries(i)){const s=b(c,o);s&&e.epics[s]&&(r[s]=e.epics[s])}return r}function te(i,e,t){if(t.has(i))return;const r=e.epics[i];if(!r)return;t.add(i);const o=r.depends_on;if(Array.isArray(o))for(const c of o)typeof c=="string"&&c.length>0&&te(c,e,t)}function re(i,e,t){const r=I(t.epics,[i]),o=new Set(r.orderedIds);for(const[s,d]of Object.entries(e)){const u=b(d,s);u&&t.epics[u]&&o.add(u)}const c={};for(const s of[...o].sort((d,u)=>d.localeCompare(u,"en"))){const d=t.epics[s];d&&(c[s]=s===i?d:L(s,d))}return c}function ie(i,e,t){const r=e.stories;if(!Array.isArray(r)||r.some(s=>typeof s!="string"||s.length===0))throw new f("STRUCTURAL_DEPENDENCY_MISSING",{nodes:0,edges:0,malformedStoryMemberships:1});const o=I(t.stories,r),c={};for(const s of o.orderedIds){const d=t.stories[s];d&&(c[s]=b(d,s)===i?d:D(s,d))}return c}function D(i,e){const t=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(r=>typeof r=="string"&&r.length>0))].sort((r,o)=>r.localeCompare(o,"en")):[];return{id:a(e.id)??i,...a(e.epic_id)?{epic_id:a(e.epic_id)}:{},...a(e.status,40)?{status:a(e.status,40)}:{},depends_on:t}}function L(i,e){const t=Array.isArray(e.stories)?[...new Set(e.stories.filter(o=>typeof o=="string"&&o.length>0))].sort((o,c)=>o.localeCompare(c,"en")):[],r=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(o=>typeof o=="string"&&o.length>0))].sort((o,c)=>o.localeCompare(c,"en")):[];return{id:a(e.id)??i,...a(e.status,40)?{status:a(e.status,40)}:{},...a(e.lifecycle_classification,40)?{lifecycle_classification:a(e.lifecycle_classification,40)}:{},stories:t,depends_on:r}}function oe(i,e,t){const r=I(e.stories),o=I(e.epics),c=Object.fromEntries(r.orderedIds.map(u=>[u,D(u,e.stories[u])])),s=Object.fromEntries(o.orderedIds.map(u=>[u,L(u,e.epics[u])])),d={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"yoloop-discovery",trigger:i,targetEpicId:null,targetStoryId:null,includedStoryCount:r.orderedIds.length,includedEpicCount:o.orderedIds.length,omittedStoryCount:0,omittedEpicCount:0,reason:"targeted-invocation",reasonCodes:m(["structural-required","yoloop-discovery",`structural-edges-${r.edgeCount+o.edgeCount}`,"content-fields-omitted"])};return h({...e,stories:c,epics:s,scope:d},e,d)}function ce(i,e){const t=new Set,r=i.stories;if(Array.isArray(r))for(const c of r)typeof c=="string"&&v(c,e,t);const o={};for(const c of t){const s=e.stories[c];s&&(o[c]=s)}return o}function ne(i){const e={};for(const[t,r]of Object.entries(i.epics))e[t]={id:a(r.id)??t,...a(r.status)?{status:a(r.status)}:{},..._.includes(r.lifecycle_classification)?{lifecycle_classification:r.lifecycle_classification}:{},...typeof r.total_stories=="number"&&Number.isFinite(r.total_stories)?{total_stories:r.total_stories}:{},...typeof r.completed_stories=="number"&&Number.isFinite(r.completed_stories)?{completed_stories:r.completed_stories}:{}};return e}function F(i){const e={};for(const t of Object.values(i)){const r=a(t.status,40)??"unknown";e[r]=(e[r]??0)+1}return e}function se(i){const e=Object.fromEntries(_.map(t=>[t,0]));for(const t of Object.values(i)){const r=_.includes(t.lifecycle_classification)?t.lifecycle_classification:"active";e[r]=(e[r]??0)+1}return e}function T(i,e){if(!e)return!0;const t=i.epics[e];return t?!_.includes(t.lifecycle_classification)||t.lifecycle_classification==="active":!0}function z(i){for(const e of["last_updated","updated_at","completed_at","created_at","discovered_at"]){const t=i[e];if(typeof t!="string")continue;const r=Date.parse(t);if(Number.isFinite(r))return r}return 0}function ae(i){return Object.entries(i.stories).map(([e,t])=>({id:e,story:t,timestamp:z(t)})).sort((e,t)=>t.timestamp-e.timestamp||e.id.localeCompare(t.id)).slice(0,P).map(({id:e,story:t})=>({id:e,...a(t.epic_id)?{epicId:a(t.epic_id)}:{},...a(t.status,40)?{status:a(t.status,40)}:{},...a(t.last_step??t.lastStep)?{lastStep:a(t.last_step??t.lastStep)}:{},...a(t.last_updated??t.updated_at??t.completed_at??t.created_at)?{lastUpdated:a(t.last_updated??t.updated_at??t.completed_at??t.created_at)}:{}}))}function de(i){const e=i.current_session;if(!e)return;const t={activeEpicId:a(e.active_epic_id)??null,activeStoryId:a(e.active_story_id)??null,activeStepId:a(e.active_step_id)??null,sessionId:a(e.session_id)??null,startedAt:a(e.started_at)??null};return Object.values(t).some(r=>r!=null)?t:void 0}function ue(i){const e=i.yoloop;if(!C(e))return;const t=C(e.state)?e.state:void 0,r=C(t?.currentSession)?t.currentSession:void 0,o=C(e.lock)?e.lock:void 0,c={...typeof e.active=="boolean"?{active:e.active}:{},currentEpicId:a(r?.currentEpicId??e.currentEpicId)??null,currentStoryId:a(r?.currentStoryId??e.currentStoryId)??null,sessionId:a(r?.sessionId??e.sessionId)??null,lockEpicId:a(o?.currentEpicId??o?.epicId)??null};return Object.keys(c).length>0?c:void 0}function le(i){const e=i.continuity;if(!C(e))return;const t=Array.isArray(e.reasonCodes)?e.reasonCodes.filter(r=>typeof r=="string"):void 0;return{present:!0,activeJobId:a(e.activeJobId??e.jobId)??null,activeGoalId:a(e.activeGoalId??e.goalId)??null,activeLoopId:a(e.activeLoopId??e.loopId)??null,...t&&t.length>0?{reasonCodes:m(t)}:{}}}function pe(i,e,t){const r=a(e?.activeStoryId),o=a(e?.activeEpicId),c=a(e?.activeStepId),s=r&&i.stories[r]?b(i.stories[r],r):null;if((r||o||c)&&T(i,o??s))return{epicId:o??null,storyId:r??null,stepId:c??null};const d=a(t?.currentStoryId),u=a(t?.currentEpicId??t?.lockEpicId);if((d||u)&&T(i,u))return{epicId:u??null,storyId:d??null,stepId:null};const l=Object.entries(i.stories).map(([p,y])=>({id:p,story:y,timestamp:z(y)})).filter(({id:p,story:y})=>!U(y.status)&&T(i,b(y,p))).sort((p,y)=>y.timestamp-p.timestamp||p.id.localeCompare(y.id))[0];return l?{epicId:b(l.story,l.id),storyId:l.id,stepId:a(l.story.last_step??l.story.lastStep)??null}:{epicId:null,storyId:null,stepId:null}}function ye(i,e){const t=F(i.stories),r=F(i.epics),o=se(i.epics),c=Object.values(i.epics).filter(j=>(_.includes(j.lifecycle_classification)?j.lifecycle_classification:"active")==="active"&&!U(j.status)).length,s=de(i),d=ue(i),u=le(i),l=pe(i,s,d),p=ae(i),y=m(e.reasonCodes,["state-summary-attached","state-summary-bounded",`projection-${e.projectionMode??e.kind}`,e.stateProjectionPolicy?`policy-${e.stateProjectionPolicy}`:"policy-unknown",p.length>=P?"recent-stories-capped":"recent-stories-bounded",l.storyId||l.epicId?"active-ref-derived":"active-ref-empty",d?"yoloop-session-present":"yoloop-session-absent",u?"continuity-session-present":"continuity-session-absent"]);return{schemaVersion:1,totals:{stories:Object.keys(i.stories).length,epics:Object.keys(i.epics).length,storyStatus:t,epicStatus:r,epicLifecycle:o,activeEpics:c,blockedStories:t.blocked??0},active:l,blockedCount:t.blocked??0,recentStories:p,...s?{currentSession:s}:{},...d?{currentYoloopSession:d}:{},...u?{currentContinuitySession:u}:{},projection:{commandId:e.commandId??null,stateProjectionPolicy:e.stateProjectionPolicy??null,projectionMode:e.projectionMode,scopeKind:e.kind,includedStoryCount:e.includedStoryCount,includedEpicCount:e.includedEpicCount??Object.keys(i.epics).length,omittedStoryCount:e.omittedStoryCount,omittedEpicCount:e.omittedEpicCount,reason:e.reason},reasonCodes:y,publicSafe:!0}}function h(i,e,t){return{...i,stateSummary:ye(e,t)}}function fe(i,e,t){const r={};for(const c of Object.keys(e.epics))r[c]={id:c};const o={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"summary-only",trigger:i,targetEpicId:null,targetStoryId:null,includedStoryCount:0,includedEpicCount:Object.keys(r).length,omittedStoryCount:Object.keys(e.stories).length,omittedEpicCount:0,reason:"epic-summary",reasonCodes:["epic-summary","stories-omitted","epic-stubs-only"]};return h({...e,stories:{},epics:r,scope:o},e,o)}function g(i,e,t,r=["summary-only","stories-omitted"],o="summary-only"){const c=ne(e),s={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:o,trigger:i,targetEpicId:null,targetStoryId:null,includedStoryCount:0,includedEpicCount:Object.keys(c).length,omittedStoryCount:Object.keys(e.stories).length,omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(c).length),reason:"summary-only",reasonCodes:m(r)};return h({...e,stories:{},epics:c,scope:s},e,s)}function w(i,e,t,r,o,c){const s=e.stories[r];if(!s)throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"story"});const d=b(s,r);if(!d)throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});if(!e.epics[d])throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const l=ee(r,e),p=M(l,e);if(!l[r]||!p[d])throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(l).length,epics:Object.keys(p).length,targetKind:"story"});const y={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:o,trigger:i,targetEpicId:d,targetStoryId:r,includedStoryCount:Object.keys(l).length,includedEpicCount:Object.keys(p).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(l).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(p).length),reason:"targeted-invocation",reasonCodes:m(c)};return h({...e,stories:l,epics:p,scope:y},e,y)}function G(i,e,t,r,o,c){const s=e.epics[r];if(!s)throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const d=ce(s,e),u=M(d,e,[r]);if(!u[r])throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(d).length,epics:Object.keys(u).length,targetKind:"epic"});const l={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:o,trigger:i,targetEpicId:r,targetStoryId:null,includedStoryCount:Object.keys(d).length,includedEpicCount:Object.keys(u).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(d).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(u).length),reason:"targeted-invocation",reasonCodes:m(c)};return h({...e,stories:d,epics:u,scope:l},e,l)}function me(i,e,t){const r=X(i),o=k(i,e);if(r&&!o)throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const c=Q(i,e),s=E({commandId:t.commandId,explicitYoloopEpicId:o,sessionYoloopEpicId:o?null:c});if(s==="yoloop-discovery")return oe(i,e,t);if(!c||s!=="yoloop-target"&&s!=="yoloop-session")throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const d=e.epics[c];if(!d)throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const u=ie(c,d,e),l=re(c,u,e);if(!l[c])throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(u).length,epics:Object.keys(l).length,targetKind:"epic"});const p=s,y={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:p,trigger:i,targetEpicId:c,targetStoryId:null,includedStoryCount:Object.keys(u).length,includedEpicCount:Object.keys(l).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(u).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(l).length),reason:"targeted-invocation",reasonCodes:["structural-required",p,"yoloop-targeted"]};return h({...e,stories:u,epics:l,scope:y},e,y)}function ge(i,e){const t={};for(const[r,o]of Object.entries(i.epics)){const c=Array.isArray(o.stories)?o.stories.filter(s=>typeof s=="string"&&e.has(s)):[];t[r]={id:a(o.id)??r,...a(o.status,40)?{status:a(o.status,40)}:{},...typeof o.total_stories=="number"&&Number.isFinite(o.total_stories)?{total_stories:o.total_stories}:{},...typeof o.completed_stories=="number"&&Number.isFinite(o.completed_stories)?{completed_stories:o.completed_stories}:{},...c.length>0?{stories:c}:{},...c.length>0&&Array.isArray(o.depends_on)?{depends_on:o.depends_on.filter(s=>typeof s=="string"&&s.length>0)}:{},...c.length>0&&(o.branch_mode==="epic"||o.branch_mode==="story")?{branch_mode:o.branch_mode}:{},...c.length>0&&typeof o.execution_branch=="string"?{execution_branch:o.execution_branch}:{},...c.length>0&&typeof o.origin_branch=="string"?{origin_branch:o.origin_branch}:{},...c.length>0&&(o.branch_lease===null||typeof o.branch_lease=="object")?{branch_lease:o.branch_lease}:{}}}return t}function be(i){return i.stateSummary?.totals.stories??(i.scope?.includedStoryCount??Object.keys(i.stories).length)+(i.scope?.omittedStoryCount??0)}function he(i){return i.stateSummary?.totals.epics??(i.scope?.includedEpicCount??Object.keys(i.epics).length)+(i.scope?.omittedEpicCount??0)}function je(i,e){if(i.stateSummary)return{...i.stateSummary,projection:{...i.stateSummary.projection,scopeKind:"projected",projectionMode:e.projectionMode,includedStoryCount:e.includedStoryCount,includedEpicCount:e.includedEpicCount??i.stateSummary.projection.includedEpicCount,omittedStoryCount:e.omittedStoryCount,omittedEpicCount:e.omittedEpicCount,reason:"body-size"},reasonCodes:m(i.stateSummary.reasonCodes,["payload-size-guardrail","state-summary-preserved","nonessential-state-degraded"])}}function ve(i){const e=i.scope,t=new Set,r=e?.projectionMode==="structural-required"||e?.projectionMode==="yolo-story"||e?.projectionMode==="yoloop-target"||e?.projectionMode==="yoloop-session"||e?.projectionMode==="yoloop-discovery";if(r)for(const S of Object.keys(i.stories))t.add(S);else e?.targetStoryId&&v(e.targetStoryId,i,t);const o={};for(const S of t){const R=i.stories[S];R&&(o[S]=R)}const c=ge(i,t),s=Object.keys(o).length,d=Object.keys(c).length,u=Math.max(0,be(i)-s),l=Math.max(0,he(i)-d),p=r?e?.projectionMode??"structural-required":e?.projectionMode==="yolo-story"?"yolo-story":"summary-only",y={kind:"projected",commandId:e?.commandId??null,stateProjectionPolicy:e?.stateProjectionPolicy??null,projectionMode:p,...e?.trigger?{trigger:e.trigger}:{},targetEpicId:e?.targetEpicId??null,targetStoryId:e?.targetStoryId??null,includedStoryCount:s,includedEpicCount:d,omittedStoryCount:u,omittedEpicCount:l,reason:"body-size",reasonCodes:m(e?.reasonCodes,["payload-size-guardrail",t.size>0?"structural-targets-preserved":"stories-omitted","epics-stubbed","state-summary-preserved"])},j=je(i,y);return{...i,stories:o,epics:c,scope:y,...j?{stateSummary:j}:{}}}function Se(i,e){const t=i.trim(),r=q(t);try{if(!r){if(J(t)){const c=n("story-reference","story-targeted"),s=x(t);if(s)return w(t,e,c,s,"targeted-story",["story-reference-targeted"])}return g(t,e,n("unknown","adaptive-targeted"),["unknown-command-summary-only"])}if(r.stateProjectionPolicy==="epic-summary")return fe(t,e,r);if(r.stateProjectionPolicy==="yoloop-targeted")return me(t,e,r);const o=x(t);if(r.stateProjectionPolicy==="story-targeted"){if(o){const s=E({commandId:r.commandId,targetStoryId:o})==="yolo-story";return w(t,e,r,o,s?"yolo-story":r.structuralRequired?"structural-required":"targeted-story",[s?"yolo-story":r.structuralRequired?"structural-required":"targeted-story"])}if(r.commandId==="yolo"||r.commandId==="yolo-inline"){const c=E({commandId:r.commandId});return g(t,e,r,["yolo-inline","stories-omitted","historical-content-omitted"],c??"yolo-inline")}return r.structuralRequired?(()=>{throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"story"})})():g(t,e,r,["story-target-missing-summary-only"])}if(r.stateProjectionPolicy==="adaptive-targeted"){if(o&&e.stories[o])return w(t,e,r,o,"targeted-story",["adaptive-story-targeted"]);const c=k(t,e);return c?G(t,e,r,c,"targeted-epic",["adaptive-epic-targeted"]):g(t,e,r,["adaptive-summary-only","target-unresolved-summary-only"])}if(r.stateProjectionPolicy==="epic-targeted"){const c=k(t,e);return c?G(t,e,r,c,r.structuralRequired?"structural-required":"targeted-epic",[r.structuralRequired?"structural-required":"targeted-epic"]):r.structuralRequired?(()=>{throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"})})():g(t,e,r,["epic-target-missing-summary-only"])}return r.stateProjectionPolicy==="continuity-scoped"?g(t,e,r,["continuity-scoped-summary-only"]):g(t,e,r,["policy-full-summary-only"])}catch(o){if(o instanceof f)throw o;if(r?.structuralRequired)throw new f("STRUCTURAL_DEPENDENCY_MISSING",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,projectionErrors:1});return g(t,e,r??n("unknown","adaptive-targeted"),["projection-error-summary-only"])}}const Ie=new Set(["yolo-story","yolo-inline","yoloop-target","yoloop-session","yoloop-discovery"]);function _e(i){let e=0;for(const t of[i.stories,i.epics])for(const r of Object.values(t))Array.isArray(r.depends_on)&&(e+=r.depends_on.filter(o=>typeof o=="string").length);return e}function Te(i,e){const t=q(i.trim());if(!t||!["yolo","yolo-inline","yoloop"].includes(t.commandId))return null;try{const r=Se(i,e),o=r.scope?.projectionMode;if(!o||!Ie.has(o))throw new f("STRUCTURAL_DEPENDENCY_MISSING",{stories:Object.keys(r.stories).length,epics:Object.keys(r.epics).length,projectionShapeErrors:1});return Object.freeze({ok:!0,version:2,shape:o,snapshot:r,included:{epics:r.scope?.includedEpicCount??Object.keys(r.epics).length,stories:r.scope?.includedStoryCount??Object.keys(r.stories).length,edges:_e(r)},omitted:{epics:r.scope?.omittedEpicCount??0,stories:r.scope?.omittedStoryCount??0},cycleCount:0})}catch(r){if(!(r instanceof f))throw r;return Object.freeze({ok:!1,code:r.code,publicDetails:r.publicDetails})}}export{ve as degradeStateSnapshotForPayloadLimit,Se as projectStateSnapshotForInvoke,Te as projectStateSnapshotResultV2ForInvoke};
|
|
1
|
+
import{analyzeDependencyDag as S,StructuralDagError as f}from"./structural-dag-projection.js";import{classifyInvocationShapeV2 as E}from"./invocation-shape.js";const P=12,$=16,I=["active","archived","rolled-back","synthetic","orphan"],n=(i,e,t={})=>({commandId:i,stateProjectionPolicy:e,...t}),A=Object.freeze({status:n("status","full"),"arch-plan":n("arch-plan","full"),"arch-prd":n("arch-prd","full"),"arch-architecture":n("arch-architecture","epic-targeted"),"arch-api-contracts":n("arch-api-contracts","epic-targeted"),"arch-api-integrations":n("arch-api-integrations","epic-targeted"),"arch-database":n("arch-database","epic-targeted"),"arch-security":n("arch-security","epic-targeted"),"arch-design-system":n("arch-design-system","epic-targeted"),"arch-ux-design":n("arch-ux-design","epic-targeted"),"arch-performance":n("arch-performance","epic-targeted"),"arch-testing":n("arch-testing","epic-targeted"),"arch-infrastructure":n("arch-infrastructure","epic-targeted"),"arch-review":n("arch-review","epic-targeted"),"arch-fitness-functions":n("arch-fitness-functions","epic-targeted"),"create-epic":n("create-epic","epic-summary"),"idea-diagnose":n("idea-diagnose","full"),"idea-research":n("idea-research","epic-targeted"),"generate-epic":n("generate-epic","epic-targeted"),exec:n("exec","story-targeted",{structuralRequired:!0}),yolo:n("yolo","story-targeted",{structuralRequired:!0}),"yolo-inline":n("yolo-inline","story-targeted",{structuralRequired:!0}),epic:n("epic","epic-targeted",{structuralRequired:!0}),"setup-branch":n("setup-branch","story-targeted",{structuralRequired:!0}),diagnose:n("diagnose","adaptive-targeted"),"diagnose-inline":n("diagnose-inline","full"),research:n("research","adaptive-targeted"),"research-inline":n("research-inline","full"),"write-spec":n("write-spec","story-targeted",{structuralRequired:!0}),"create-tasks":n("create-tasks","story-targeted",{structuralRequired:!0}),implement:n("implement","story-targeted",{structuralRequired:!0}),commit:n("commit","story-targeted",{structuralRequired:!0}),"commit-push":n("commit","story-targeted",{structuralRequired:!0}),sync:n("sync","story-targeted",{structuralRequired:!0}),"sync-main":n("sync","story-targeted",{structuralRequired:!0}),"create-pr":n("create-pr","story-targeted",{structuralRequired:!0}),review:n("review","story-targeted"),"review-pr":n("review","story-targeted"),merge:n("merge","story-targeted",{structuralRequired:!0}),"merge-pr":n("merge","story-targeted",{structuralRequired:!0}),"fix-blocked":n("fix-blocked","story-targeted"),"finalize-epic":n("finalize-epic","epic-targeted"),"resolve-conflicts":n("resolve-conflicts","story-targeted"),"update-memory":n("update-memory","full"),"update-project-memory":n("update-memory","story-targeted",{structuralRequired:!0}),refactor:n("refactor","adaptive-targeted"),"refactor-suggest":n("refactor","story-targeted",{structuralRequired:!0}),cleanup:n("cleanup","full"),audit:n("audit","full"),"tech-debt":n("tech-debt","full"),menu:n("menu","full"),plans:n("plans","full"),billing:n("billing","full"),subscribe:n("subscribe","full"),"qa-scan":n("qa-scan","full"),yoloop:n("yoloop","yoloop-targeted",{structuralRequired:!0}),"migrate-state":n("migrate-state","full"),"migrate-project-id":n("migrate-project-id","full"),"policy-audit":n("policy-audit","full"),"mutation-test":n("mutation-test","full"),"sync-openapi":n("sync-openapi","full"),"generate-pacts":n("generate-pacts","full"),"verify-pacts":n("verify-pacts","full"),"property-test":n("property-test","full"),"property-tests":n("property-test","story-targeted",{structuralRequired:!0}),"chaos-plan":n("chaos-plan","full"),"ui-ux-review":n("ui-ux-review","adaptive-targeted"),"solyd-system":n("solyd-system","adaptive-targeted"),goal:n("goal","continuity-scoped"),loop:n("loop","continuity-scoped"),jobs:n("jobs","continuity-scoped"),runner:n("runner","continuity-scoped"),"goal-tick":n("goal-tick","continuity-scoped"),"loop-tick":n("loop-tick","continuity-scoped"),"validate-tests":n("validate-tests","story-targeted",{structuralRequired:!0}),"qa-gate":n("qa-gate","story-targeted",{structuralRequired:!0})}),Y=Object.freeze({st:"status",arquitetura:"arch-plan",architecture:"arch-plan",arch:"arch-plan",prd:"arch-prd","product-requirements":"arch-prd","arch-doc":"arch-architecture","tech-architecture":"arch-architecture","api-contracts":"arch-api-contracts","api-contract":"arch-api-contracts","api-integrations":"arch-api-integrations","api-int":"arch-api-integrations","database-schema":"arch-database","db-schema":"arch-database",db:"arch-database","cyber-security":"arch-security",security:"arch-security",sec:"arch-security","design-system":"arch-design-system",ds:"arch-design-system","atomic-design":"arch-design-system","ux-design":"arch-ux-design",ux:"arch-ux-design",wireframes:"arch-ux-design",wireframe:"arch-ux-design","user-flows":"arch-ux-design",performance:"arch-performance",perf:"arch-performance","capacity-planning":"arch-performance",capacity:"arch-performance","arch-perf":"arch-performance","performance-strategy":"arch-performance","testing-strategy":"arch-testing","test-plan":"arch-testing","test-strategy":"arch-testing","arch-test":"arch-testing",infrastructure:"arch-infrastructure",infra:"arch-infrastructure","deploy-plan":"arch-infrastructure",deployment:"arch-infrastructure","arch-infra":"arch-infrastructure","arch-deploy":"arch-infrastructure","review-consolidation":"arch-review",consolidation:"arch-review","architecture-review":"arch-review","arch-consolidation":"arch-review",fitness:"arch-fitness-functions","fitness-functions":"arch-fitness-functions",archfit:"arch-fitness-functions","arch-fit":"arch-fitness-functions","fit-funcs":"arch-fitness-functions","criar-epic":"create-epic",planejamento:"create-epic","idea-diag":"idea-diagnose","idea-pesq":"idea-research","gerar-epic":"generate-epic",executar:"exec",pipeline:"exec","parallel-epic":"epic",setup:"setup-branch",branch:"setup-branch",diag:"diagnose",diagnostico:"diagnose",c02:"diagnose",pesquisar:"research",pesq:"research","research-fix":"research",c03:"research",spec:"write-spec",especificacao:"write-spec",c04:"write-spec",tasks:"create-tasks",tarefas:"create-tasks",c05:"create-tasks",impl:"implement",implementar:"implement",c06:"implement",push:"commit",commit_push:"commit",cp:"commit",c07:"commit",sincronizar:"sync",c08:"sync",pr:"create-pr",c09:"create-pr",revisar:"review",c11:"review",mesclar:"merge",c12:"merge",fix:"fix-blocked",corrigir:"fix-blocked",finalizar:"finalize-epic",conflitos:"resolve-conflicts",memoria:"update-memory",refactoring:"refactor",refact:"refactor",refac:"refactor",rf:"refactor","cleanup-code":"refactor","code-cleanup":"refactor","code-quality":"refactor","improve-code":"refactor",modernize:"refactor",modernization:"refactor",legacy:"refactor","legacy-code":"refactor","debt-pay":"refactor","pay-debt":"refactor","debt-reduction":"refactor","smell-fix":"refactor","fix-smells":"refactor","code-smells":"refactor",strangler:"refactor","strangler-fig":"refactor",limpar:"cleanup",limpeza:"cleanup",auditar:"audit",auditoria:"audit",debt:"tech-debt",debts:"tech-debt","debt-list":"tech-debt","tech-debts":"tech-debt",td:"tech-debt",help:"menu",ajuda:"menu","?":"menu",commands:"menu",cmds:"menu",planos:"plans",pricing:"plans",bill:"billing",subscription:"billing",sub:"billing",upgrade:"subscribe",checkout:"subscribe",qa:"qa-scan","qa-test":"qa-scan","visual-qa":"qa-scan","e2e-scan":"qa-scan",troubleshoot:"qa-scan","debug-ui":"qa-scan",scan:"qa-scan",a11y:"qa-scan",accessibility:"qa-scan",wcag:"qa-scan","auto-yolo":"yoloop","epic-runner":"yoloop","story-runner":"yoloop","loop-yolo":"yoloop","auto-epic":"yoloop",migrate:"migrate-state","state-migrate":"migrate-state","schema-migrate":"migrate-state",policy:"policy-audit","audit-policy":"policy-audit","policy-history":"policy-audit",policies:"policy-audit",mutation:"mutation-test",stryker:"mutation-test","kill-mutants":"mutation-test","openapi-sync":"sync-openapi","api-sync":"sync-openapi","spec-sync":"sync-openapi","regen-openapi":"sync-openapi",pacts:"generate-pacts","gen-pacts":"generate-pacts","regen-pacts":"generate-pacts","create-pacts":"generate-pacts","verify-pact":"verify-pacts","pact-verify":"verify-pacts","check-pacts":"verify-pacts","pact-check":"verify-pacts",property:"property-test",pbt:"property-test",proptest:"property-test","invariant-test":"property-test",chaos:"chaos-plan",gameday:"chaos-plan","resilience-test":"chaos-plan","ux-review":"ui-ux-review","design-review":"ui-ux-review","visual-review":"ui-ux-review","product-polish":"ui-ux-review","security-system":"solyd-system","authorized-security":"solyd-system","sec-system":"solyd-system",goals:"goal","durable-goal":"goal","continuity-goal":"goal",loops:"loop","durable-loop":"loop","continuity-loop":"loop",job:"jobs","continuity-jobs":"jobs","neocortex-runner":"runner","continuity-runner":"runner"}),K=Object.freeze({1:"status",3:"arch-plan",4:"arch-prd",5:"arch-architecture",6:"arch-api-contracts",7:"arch-api-integrations",8:"arch-database",9:"arch-security",10:"arch-design-system",11:"arch-ux-design",12:"arch-performance",13:"arch-testing",14:"arch-infrastructure",15:"arch-review",16:"arch-fitness-functions",17:"create-epic",18:"idea-diagnose",19:"idea-research",20:"generate-epic",21:"exec",22:"yolo",23:"epic",24:"setup-branch",25:"diagnose",26:"research",27:"write-spec",28:"create-tasks",29:"implement",30:"commit",31:"sync",32:"create-pr",33:"review",34:"merge",35:"fix-blocked",36:"finalize-epic",37:"resolve-conflicts",38:"update-memory",39:"refactor",40:"cleanup",41:"audit",42:"tech-debt",43:"menu",44:"plans",45:"billing",46:"subscribe",47:"qa-scan",48:"yoloop",49:"migrate-state",50:"policy-audit",51:"mutation-test",52:"sync-openapi",53:"generate-pacts",54:"verify-pacts",55:"property-test",56:"chaos-plan",57:"ui-ux-review",58:"solyd-system",59:"goal",60:"loop",61:"jobs",62:"runner"});function a(i,e=120){if(typeof i!="string")return;const t=i.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,e)}function C(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)}function m(...i){const e=new Set,t=[];for(const r of i)for(const o of r??[]){const c=a(o,80);if(!(!c||e.has(c))&&(e.add(c),t.push(c),t.length>=$))return t}return t}function V(i){return i.trim().replace(/^@?\*/,"").replace(/^@/,"").toLowerCase()}function Z(i){return i.trim().split(/\s+/,1)[0]??""}function q(i){const e=Z(i);if(!e)return A.menu;const t=V(e),r=K[t]??Y[t]??t;return A[r]??null}function B(i,e,t,r="full-compatible",o=["full-state"]){return{kind:"full",commandId:t?.commandId??null,stateProjectionPolicy:t?.stateProjectionPolicy??null,projectionMode:r,trigger:i,targetEpicId:null,targetStoryId:null,includedStoryCount:Object.keys(e.stories).length,includedEpicCount:Object.keys(e.epics).length,omittedStoryCount:0,omittedEpicCount:0,reason:"full-state",reasonCodes:m(o)}}function Ee(i,e,t,r="full-compatible",o=["full-state"]){const c=B(i,e,t,r,o);return h({...e,scope:c},e,c)}function J(i){const[e]=i.trim().split(/\s+/,1);return e?/^[A-Z]?\d+(?:\.\d+)+$/i.test(e.replace(/^@/,""))||/(?:^|\/)[A-Z]?\d+(?:\.\d+)+\.story\.md$/i.test(e.replace(/^@/,"")):!1}function x(i){const e=i.match(/(?:^|[/@\s])([A-Z]?\d+(?:\.\d+)+)\.story\.md\b/i);return e?.[1]?e[1]:i.match(/(?:^|\s|@)([A-Z]?\d+(?:\.\d+)+)(?=$|\s)/i)?.[1]??null}function W(i){const e=i.trim(),t=e.search(/\s/);return t===-1?"":e.slice(t).trim()}function O(i){return W(i).split(/\s+/).map(e=>e.replace(/^@/,"").replace(/^['"]|['"]$/g,"")).filter(e=>e.length>0&&!e.startsWith("-"))}function Oe(i){return O(i)[0]??null}function N(i,e){const r=i.replace(/^@/,"").replace(/^epic-/i,"").replace(/\.md$/i,""),o=[r,r.toUpperCase(),/^p\d+$/i.test(r)?`P${r.replace(/^p/i,"")}`:null,/^\d+$/.test(r)?`P${r}`:null].filter(c=>typeof c=="string"&&c.length>0);for(const c of o)if(e.epics[c])return c;return null}function H(i,e){const t=i.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);return t?.[1]?N(t[1],e):null}function k(i,e){const t=H(i,e);if(t)return t;for(const r of O(i)){if(/^[A-Z]?\d+(?:\.\d+)+$/i.test(r))continue;const o=N(r,e);if(o)return o}return null}function Q(i,e){const t=k(i,e);if(t)return t;const r=e.yoloop,o=r?.state?.currentSession?.currentEpicId;if(typeof o=="string"&&e.epics[o])return o;const c=r?.lock?.currentEpicId??r?.lock?.epicId;return typeof c=="string"&&e.epics[c]?c:null}function X(i){const e=i.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i)?.[1];if(e)return/^P/i.test(e)?e.toUpperCase():`P${e}`;for(const t of O(i)){if(/^P\d+$/i.test(t))return t.toUpperCase();if(/^\d+$/.test(t))return`P${t}`}return null}function b(i,e){if(typeof i.epic_id=="string"&&i.epic_id.length>0)return i.epic_id;const t=e.split(".").slice(0,-1).join(".");return t.length>0?t:null}function U(i){return typeof i=="string"&&["done","completed","merged","cancelled","canceled","abandoned"].includes(i.toLowerCase())}function v(i,e,t){if(t.has(i))return;const r=e.stories[i];if(!r)return;t.add(i);const o=r.depends_on;if(Array.isArray(o))for(const c of o)typeof c=="string"&&v(c,e,t)}function ee(i,e){const t=S(e.stories,[i]),r={};for(const o of t.orderedIds){const c=e.stories[o];c&&(r[o]=c)}return r}function M(i,e,t=[]){const r={};for(const o of t)e.epics[o]&&(r[o]=e.epics[o]);for(const[o,c]of Object.entries(i)){const s=b(c,o);s&&e.epics[s]&&(r[s]=e.epics[s])}return r}function te(i,e,t){if(t.has(i))return;const r=e.epics[i];if(!r)return;t.add(i);const o=r.depends_on;if(Array.isArray(o))for(const c of o)typeof c=="string"&&c.length>0&&te(c,e,t)}function re(i,e,t){const r=S(t.epics,[i]),o=new Set(r.orderedIds);for(const[s,d]of Object.entries(e)){const l=b(d,s);l&&t.epics[l]&&o.add(l)}const c={};for(const s of[...o].sort((d,l)=>d.localeCompare(l,"en"))){const d=t.epics[s];d&&(c[s]=s===i?d:L(s,d))}return c}function ie(i,e,t){const r=e.stories;if(!Array.isArray(r)||r.some(s=>typeof s!="string"||s.length===0))throw new f("STRUCTURAL_DEPENDENCY_MISSING",{nodes:0,edges:0,malformedStoryMemberships:1});const o=S(t.stories,r),c={};for(const s of o.orderedIds){const d=t.stories[s];d&&(c[s]=b(d,s)===i?d:D(s,d))}return c}function D(i,e){const t=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(r=>typeof r=="string"&&r.length>0))].sort((r,o)=>r.localeCompare(o,"en")):[];return{id:a(e.id)??i,...a(e.epic_id)?{epic_id:a(e.epic_id)}:{},...a(e.status,40)?{status:a(e.status,40)}:{},depends_on:t}}function L(i,e){const t=Array.isArray(e.stories)?[...new Set(e.stories.filter(o=>typeof o=="string"&&o.length>0))].sort((o,c)=>o.localeCompare(c,"en")):[],r=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(o=>typeof o=="string"&&o.length>0))].sort((o,c)=>o.localeCompare(c,"en")):[];return{id:a(e.id)??i,...a(e.status,40)?{status:a(e.status,40)}:{},...a(e.lifecycle_classification,40)?{lifecycle_classification:a(e.lifecycle_classification,40)}:{},stories:t,depends_on:r}}function oe(i,e,t){const r=S(e.stories),o=S(e.epics),c=Object.fromEntries(r.orderedIds.map(l=>[l,D(l,e.stories[l])])),s=Object.fromEntries(o.orderedIds.map(l=>[l,L(l,e.epics[l])])),d={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"yoloop-discovery",trigger:i,targetEpicId:null,targetStoryId:null,includedStoryCount:r.orderedIds.length,includedEpicCount:o.orderedIds.length,omittedStoryCount:0,omittedEpicCount:0,reason:"targeted-invocation",reasonCodes:m(["structural-required","yoloop-discovery",`structural-edges-${r.edgeCount+o.edgeCount}`,"content-fields-omitted"])};return h({...e,stories:c,epics:s,scope:d},e,d)}function ce(i,e){const t=new Set,r=i.stories;if(Array.isArray(r))for(const c of r)typeof c=="string"&&v(c,e,t);const o={};for(const c of t){const s=e.stories[c];s&&(o[c]=s)}return o}function ne(i){const e={};for(const[t,r]of Object.entries(i.epics))e[t]={id:a(r.id)??t,...a(r.status)?{status:a(r.status)}:{},...I.includes(r.lifecycle_classification)?{lifecycle_classification:r.lifecycle_classification}:{},...typeof r.total_stories=="number"&&Number.isFinite(r.total_stories)?{total_stories:r.total_stories}:{},...typeof r.completed_stories=="number"&&Number.isFinite(r.completed_stories)?{completed_stories:r.completed_stories}:{}};return e}function F(i){const e={};for(const t of Object.values(i)){const r=a(t.status,40)??"unknown";e[r]=(e[r]??0)+1}return e}function se(i){const e=Object.fromEntries(I.map(t=>[t,0]));for(const t of Object.values(i)){const r=I.includes(t.lifecycle_classification)?t.lifecycle_classification:"active";e[r]=(e[r]??0)+1}return e}function T(i,e){if(!e)return!0;const t=i.epics[e];return t?!I.includes(t.lifecycle_classification)||t.lifecycle_classification==="active":!0}function z(i){for(const e of["last_updated","updated_at","completed_at","created_at","discovered_at"]){const t=i[e];if(typeof t!="string")continue;const r=Date.parse(t);if(Number.isFinite(r))return r}return 0}function ae(i){return Object.entries(i.stories).map(([e,t])=>({id:e,story:t,timestamp:z(t)})).sort((e,t)=>t.timestamp-e.timestamp||e.id.localeCompare(t.id)).slice(0,P).map(({id:e,story:t})=>({id:e,...a(t.epic_id)?{epicId:a(t.epic_id)}:{},...a(t.status,40)?{status:a(t.status,40)}:{},...a(t.last_step??t.lastStep)?{lastStep:a(t.last_step??t.lastStep)}:{},...a(t.last_updated??t.updated_at??t.completed_at??t.created_at)?{lastUpdated:a(t.last_updated??t.updated_at??t.completed_at??t.created_at)}:{}}))}function de(i){const e=i.current_session;if(!e)return;const t={activeEpicId:a(e.active_epic_id)??null,activeStoryId:a(e.active_story_id)??null,activeStepId:a(e.active_step_id)??null,sessionId:a(e.session_id)??null,startedAt:a(e.started_at)??null};return Object.values(t).some(r=>r!=null)?t:void 0}function le(i){const e=i.yoloop;if(!C(e))return;const t=C(e.state)?e.state:void 0,r=C(t?.currentSession)?t.currentSession:void 0,o=C(e.lock)?e.lock:void 0,c={...typeof e.active=="boolean"?{active:e.active}:{},currentEpicId:a(r?.currentEpicId??e.currentEpicId)??null,currentStoryId:a(r?.currentStoryId??e.currentStoryId)??null,sessionId:a(r?.sessionId??e.sessionId)??null,lockEpicId:a(o?.currentEpicId??o?.epicId)??null};return Object.keys(c).length>0?c:void 0}function ue(i){const e=i.continuity;if(!C(e))return;const t=Array.isArray(e.reasonCodes)?e.reasonCodes.filter(r=>typeof r=="string"):void 0;return{present:!0,activeJobId:a(e.activeJobId??e.jobId)??null,activeGoalId:a(e.activeGoalId??e.goalId)??null,activeLoopId:a(e.activeLoopId??e.loopId)??null,...t&&t.length>0?{reasonCodes:m(t)}:{}}}function pe(i,e,t){const r=a(e?.activeStoryId),o=a(e?.activeEpicId),c=a(e?.activeStepId),s=r&&i.stories[r]?b(i.stories[r],r):null;if((r||o||c)&&T(i,o??s))return{epicId:o??null,storyId:r??null,stepId:c??null};const d=a(t?.currentStoryId),l=a(t?.currentEpicId??t?.lockEpicId);if((d||l)&&T(i,l))return{epicId:l??null,storyId:d??null,stepId:null};const u=Object.entries(i.stories).map(([p,y])=>({id:p,story:y,timestamp:z(y)})).filter(({id:p,story:y})=>!U(y.status)&&T(i,b(y,p))).sort((p,y)=>y.timestamp-p.timestamp||p.id.localeCompare(y.id))[0];return u?{epicId:b(u.story,u.id),storyId:u.id,stepId:a(u.story.last_step??u.story.lastStep)??null}:{epicId:null,storyId:null,stepId:null}}function ye(i,e){const t=F(i.stories),r=F(i.epics),o=se(i.epics),c=Object.values(i.epics).filter(j=>(I.includes(j.lifecycle_classification)?j.lifecycle_classification:"active")==="active"&&!U(j.status)).length,s=de(i),d=le(i),l=ue(i),u=pe(i,s,d),p=ae(i),y=m(e.reasonCodes,["state-summary-attached","state-summary-bounded",`projection-${e.projectionMode??e.kind}`,e.stateProjectionPolicy?`policy-${e.stateProjectionPolicy}`:"policy-unknown",p.length>=P?"recent-stories-capped":"recent-stories-bounded",u.storyId||u.epicId?"active-ref-derived":"active-ref-empty",d?"yoloop-session-present":"yoloop-session-absent",l?"continuity-session-present":"continuity-session-absent"]);return{schemaVersion:1,totals:{stories:Object.keys(i.stories).length,epics:Object.keys(i.epics).length,storyStatus:t,epicStatus:r,epicLifecycle:o,activeEpics:c,blockedStories:t.blocked??0},active:u,blockedCount:t.blocked??0,recentStories:p,...s?{currentSession:s}:{},...d?{currentYoloopSession:d}:{},...l?{currentContinuitySession:l}:{},projection:{commandId:e.commandId??null,stateProjectionPolicy:e.stateProjectionPolicy??null,projectionMode:e.projectionMode,scopeKind:e.kind,includedStoryCount:e.includedStoryCount,includedEpicCount:e.includedEpicCount??Object.keys(i.epics).length,omittedStoryCount:e.omittedStoryCount,omittedEpicCount:e.omittedEpicCount,reason:e.reason},reasonCodes:y,publicSafe:!0}}function h(i,e,t){return{...i,stateSummary:ye(e,t)}}function fe(i,e,t){const r={};for(const c of Object.keys(e.epics))r[c]={id:c};const o={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"summary-only",trigger:i,targetEpicId:null,targetStoryId:null,includedStoryCount:0,includedEpicCount:Object.keys(r).length,omittedStoryCount:Object.keys(e.stories).length,omittedEpicCount:0,reason:"epic-summary",reasonCodes:["epic-summary","stories-omitted","epic-stubs-only"]};return h({...e,stories:{},epics:r,scope:o},e,o)}function g(i,e,t,r=["summary-only","stories-omitted"],o="summary-only"){const c=ne(e),s={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:o,trigger:i,targetEpicId:null,targetStoryId:null,includedStoryCount:0,includedEpicCount:Object.keys(c).length,omittedStoryCount:Object.keys(e.stories).length,omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(c).length),reason:"summary-only",reasonCodes:m(r)};return h({...e,stories:{},epics:c,scope:s},e,s)}function w(i,e,t,r,o,c){const s=e.stories[r];if(!s)throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"story"});const d=b(s,r);if(!d)throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});if(!e.epics[d])throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const u=ee(r,e),p=M(u,e);if(!u[r]||!p[d])throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(u).length,epics:Object.keys(p).length,targetKind:"story"});const y={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:o,trigger:i,targetEpicId:d,targetStoryId:r,includedStoryCount:Object.keys(u).length,includedEpicCount:Object.keys(p).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(u).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(p).length),reason:"targeted-invocation",reasonCodes:m(c)};return h({...e,stories:u,epics:p,scope:y},e,y)}function G(i,e,t,r,o,c){const s=e.epics[r];if(!s)throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const d=ce(s,e),l=M(d,e,[r]);if(!l[r])throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(d).length,epics:Object.keys(l).length,targetKind:"epic"});const u={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:o,trigger:i,targetEpicId:r,targetStoryId:null,includedStoryCount:Object.keys(d).length,includedEpicCount:Object.keys(l).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(d).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(l).length),reason:"targeted-invocation",reasonCodes:m(c)};return h({...e,stories:d,epics:l,scope:u},e,u)}function me(i,e,t){const r=X(i),o=k(i,e);if(r&&!o)throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const c=Q(i,e),s=E({commandId:t.commandId,explicitYoloopEpicId:o,sessionYoloopEpicId:o?null:c});if(s==="yoloop-discovery")return oe(i,e,t);if(!c||s!=="yoloop-target"&&s!=="yoloop-session")throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const d=e.epics[c];if(!d)throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const l=ie(c,d,e),u=re(c,l,e);if(!u[c])throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(l).length,epics:Object.keys(u).length,targetKind:"epic"});const p=s,y={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:p,trigger:i,targetEpicId:c,targetStoryId:null,includedStoryCount:Object.keys(l).length,includedEpicCount:Object.keys(u).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(l).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(u).length),reason:"targeted-invocation",reasonCodes:["structural-required",p,"yoloop-targeted"]};return h({...e,stories:l,epics:u,scope:y},e,y)}function ge(i,e){const t={};for(const[r,o]of Object.entries(i.epics)){const c=Array.isArray(o.stories)?o.stories.filter(s=>typeof s=="string"&&e.has(s)):[];t[r]={id:a(o.id)??r,...a(o.status,40)?{status:a(o.status,40)}:{},...typeof o.total_stories=="number"&&Number.isFinite(o.total_stories)?{total_stories:o.total_stories}:{},...typeof o.completed_stories=="number"&&Number.isFinite(o.completed_stories)?{completed_stories:o.completed_stories}:{},...c.length>0?{stories:c}:{},...c.length>0&&Array.isArray(o.depends_on)?{depends_on:o.depends_on.filter(s=>typeof s=="string"&&s.length>0)}:{},...c.length>0&&(o.branch_mode==="epic"||o.branch_mode==="story")?{branch_mode:o.branch_mode}:{},...c.length>0&&typeof o.execution_branch=="string"?{execution_branch:o.execution_branch}:{},...c.length>0&&typeof o.origin_branch=="string"?{origin_branch:o.origin_branch}:{},...c.length>0&&(o.branch_lease===null||typeof o.branch_lease=="object")?{branch_lease:o.branch_lease}:{},...c.length>0&&(o.origin_binding===null||typeof o.origin_binding=="object")?{origin_binding:o.origin_binding}:{},...c.length>0&&(o.aggregate_qa_receipt===null||typeof o.aggregate_qa_receipt=="object")?{aggregate_qa_receipt:o.aggregate_qa_receipt}:{}}}return t}function be(i){return i.stateSummary?.totals.stories??(i.scope?.includedStoryCount??Object.keys(i.stories).length)+(i.scope?.omittedStoryCount??0)}function he(i){return i.stateSummary?.totals.epics??(i.scope?.includedEpicCount??Object.keys(i.epics).length)+(i.scope?.omittedEpicCount??0)}function je(i,e){if(i.stateSummary)return{...i.stateSummary,projection:{...i.stateSummary.projection,scopeKind:"projected",projectionMode:e.projectionMode,includedStoryCount:e.includedStoryCount,includedEpicCount:e.includedEpicCount??i.stateSummary.projection.includedEpicCount,omittedStoryCount:e.omittedStoryCount,omittedEpicCount:e.omittedEpicCount,reason:"body-size"},reasonCodes:m(i.stateSummary.reasonCodes,["payload-size-guardrail","state-summary-preserved","nonessential-state-degraded"])}}function ve(i){const e=i.scope,t=new Set,r=e?.projectionMode==="structural-required"||e?.projectionMode==="yolo-story"||e?.projectionMode==="yoloop-target"||e?.projectionMode==="yoloop-session"||e?.projectionMode==="yoloop-discovery";if(r)for(const _ of Object.keys(i.stories))t.add(_);else e?.targetStoryId&&v(e.targetStoryId,i,t);const o={};for(const _ of t){const R=i.stories[_];R&&(o[_]=R)}const c=ge(i,t),s=Object.keys(o).length,d=Object.keys(c).length,l=Math.max(0,be(i)-s),u=Math.max(0,he(i)-d),p=r?e?.projectionMode??"structural-required":e?.projectionMode==="yolo-story"?"yolo-story":"summary-only",y={kind:"projected",commandId:e?.commandId??null,stateProjectionPolicy:e?.stateProjectionPolicy??null,projectionMode:p,...e?.trigger?{trigger:e.trigger}:{},targetEpicId:e?.targetEpicId??null,targetStoryId:e?.targetStoryId??null,includedStoryCount:s,includedEpicCount:d,omittedStoryCount:l,omittedEpicCount:u,reason:"body-size",reasonCodes:m(e?.reasonCodes,["payload-size-guardrail",t.size>0?"structural-targets-preserved":"stories-omitted","epics-stubbed","state-summary-preserved"])},j=je(i,y);return{...i,stories:o,epics:c,scope:y,...j?{stateSummary:j}:{}}}function _e(i,e){const t=i.trim(),r=q(t);try{if(!r){if(J(t)){const c=n("story-reference","story-targeted"),s=x(t);if(s)return w(t,e,c,s,"targeted-story",["story-reference-targeted"])}return g(t,e,n("unknown","adaptive-targeted"),["unknown-command-summary-only"])}if(r.stateProjectionPolicy==="epic-summary")return fe(t,e,r);if(r.stateProjectionPolicy==="yoloop-targeted")return me(t,e,r);const o=x(t);if(r.stateProjectionPolicy==="story-targeted"){if(o){const s=E({commandId:r.commandId,targetStoryId:o})==="yolo-story";return w(t,e,r,o,s?"yolo-story":r.structuralRequired?"structural-required":"targeted-story",[s?"yolo-story":r.structuralRequired?"structural-required":"targeted-story"])}if(r.commandId==="yolo"||r.commandId==="yolo-inline"){const c=E({commandId:r.commandId});return g(t,e,r,["yolo-inline","stories-omitted","historical-content-omitted"],c??"yolo-inline")}return r.structuralRequired?(()=>{throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"story"})})():g(t,e,r,["story-target-missing-summary-only"])}if(r.stateProjectionPolicy==="adaptive-targeted"){if(o&&e.stories[o])return w(t,e,r,o,"targeted-story",["adaptive-story-targeted"]);const c=k(t,e);return c?G(t,e,r,c,"targeted-epic",["adaptive-epic-targeted"]):g(t,e,r,["adaptive-summary-only","target-unresolved-summary-only"])}if(r.stateProjectionPolicy==="epic-targeted"){const c=k(t,e);return c?G(t,e,r,c,r.structuralRequired?"structural-required":"targeted-epic",[r.structuralRequired?"structural-required":"targeted-epic"]):r.structuralRequired?(()=>{throw new f("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"})})():g(t,e,r,["epic-target-missing-summary-only"])}return r.stateProjectionPolicy==="continuity-scoped"?g(t,e,r,["continuity-scoped-summary-only"]):g(t,e,r,["policy-full-summary-only"])}catch(o){if(o instanceof f)throw o;if(r?.structuralRequired)throw new f("STRUCTURAL_DEPENDENCY_MISSING",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,projectionErrors:1});return g(t,e,r??n("unknown","adaptive-targeted"),["projection-error-summary-only"])}}const Se=new Set(["yolo-story","yolo-inline","yoloop-target","yoloop-session","yoloop-discovery"]);function Ie(i){let e=0;for(const t of[i.stories,i.epics])for(const r of Object.values(t))Array.isArray(r.depends_on)&&(e+=r.depends_on.filter(o=>typeof o=="string").length);return e}function Te(i,e){const t=q(i.trim());if(!t||!["yolo","yolo-inline","yoloop"].includes(t.commandId))return null;try{const r=_e(i,e),o=r.scope?.projectionMode;if(!o||!Se.has(o))throw new f("STRUCTURAL_DEPENDENCY_MISSING",{stories:Object.keys(r.stories).length,epics:Object.keys(r.epics).length,projectionShapeErrors:1});return Object.freeze({ok:!0,version:2,shape:o,snapshot:r,included:{epics:r.scope?.includedEpicCount??Object.keys(r.epics).length,stories:r.scope?.includedStoryCount??Object.keys(r.stories).length,edges:Ie(r)},omitted:{epics:r.scope?.omittedEpicCount??0,stories:r.scope?.omittedStoryCount??0},cycleCount:0})}catch(r){if(!(r instanceof f))throw r;return Object.freeze({ok:!1,code:r.code,publicDetails:r.publicDetails})}}export{ve as degradeStateSnapshotForPayloadLimit,_e as projectStateSnapshotForInvoke,Te as projectStateSnapshotResultV2ForInvoke};
|
|
@@ -16,7 +16,10 @@ export interface StateRepairAuditSummary {
|
|
|
16
16
|
}
|
|
17
17
|
export interface StateJsonPreInvokeRepairOptions {
|
|
18
18
|
readonly args?: string;
|
|
19
|
+
readonly canonicalCommandId?: string;
|
|
19
20
|
readonly nowIso?: string;
|
|
21
|
+
/** Internal, physically verified completion overlay; never persisted as story state. */
|
|
22
|
+
readonly effectiveDoneStoryIds?: readonly string[];
|
|
20
23
|
}
|
|
21
24
|
export declare const P189_STATE_SHAPE_GAP_CODE: "P189-GAP-STATE-SHAPE";
|
|
22
25
|
export declare const EPIC_AGGREGATE_REASON_CODES: {
|
|
@@ -62,6 +65,10 @@ export interface EpicAggregateReconciliationOptions {
|
|
|
62
65
|
readonly nowIso?: string;
|
|
63
66
|
readonly scope?: unknown;
|
|
64
67
|
readonly targetEpicId?: string;
|
|
68
|
+
/** Runtime completions accepted only after immutable Git verification. */
|
|
69
|
+
readonly effectiveDoneStoryIds?: readonly string[];
|
|
70
|
+
/** Pre-invoke validates lifecycle aggregates but leaves post-commit derivation to projections. */
|
|
71
|
+
readonly preserveGitLifecycleAggregates?: boolean;
|
|
65
72
|
}
|
|
66
73
|
export interface EpicAggregateReconciliationResult<TState extends Record<string, unknown> = Record<string, unknown>> {
|
|
67
74
|
readonly mutated: boolean;
|
|
@@ -69,6 +76,8 @@ export interface EpicAggregateReconciliationResult<TState extends Record<string,
|
|
|
69
76
|
readonly reasonCodes: readonly EpicAggregateRepairReasonCode[];
|
|
70
77
|
readonly changes: readonly EpicAggregateReconciliationChange[];
|
|
71
78
|
}
|
|
79
|
+
/** Materialization has no story/epic acceptance authority to replay or repair. */
|
|
80
|
+
export declare function isInlineYoloMaterialization(args: unknown, canonicalCommandId?: string | null): boolean;
|
|
72
81
|
export declare function isP189DoneLikeStoryStatus(value: unknown): boolean;
|
|
73
82
|
export declare function reconcileEpicAggregatesInState<TState extends Record<string, unknown>>(input: unknown, options?: EpicAggregateReconciliationOptions): EpicAggregateReconciliationResult<TState>;
|
|
74
83
|
export declare function maybeRepairStateJsonBeforeInvoke(projectRoot: string, options?: StateJsonPreInvokeRepairOptions): StateRepairAuditSummary;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync as M,mkdirSync as L,readFileSync as D,renameSync as G,writeFileSync as z,copyFileSync as F}from"node:fs";import{join as N}from"node:path";import{randomBytes as J}from"node:crypto";class v extends Error{reasonCode;constructor(o,t){super(o),this.reasonCode=t,this.name="StateRepairHardStopError"}}const q="P189-GAP-STATE-SHAPE",f={reconciled:"epic_aggregate_reconciled",totalRecounted:"epic_total_stories_recounted",completedRecounted:"epic_completed_stories_recounted",statusPromotedDone:"epic_status_promoted_done",completedAtSet:"epic_completed_at_set",stateNotObject:"epic_aggregate_state_not_object",epicsNotObject:"epic_aggregate_epics_not_object",storiesNotObject:"epic_aggregate_stories_not_object",scopeProjected:"epic_aggregate_scope_projected",epicNotObject:"epic_aggregate_epic_not_object",epicIdConflict:"epic_aggregate_epic_id_conflict",storyListNotArray:"epic_aggregate_story_list_not_array",storyRefInvalid:"epic_aggregate_story_ref_invalid",storyRefDuplicate:"epic_aggregate_story_ref_duplicate",storyMissing:"epic_aggregate_story_missing",storyNotObject:"epic_aggregate_story_not_object",storyIdConflict:"epic_aggregate_story_id_conflict",storyEpicConflict:"epic_aggregate_story_epic_conflict",terminalIncompleteConflict:"epic_aggregate_terminal_incomplete_conflict"},H=new Set(["yolo","implement","diagnose","research","write-spec","create-tasks","refactor-suggest","property-tests","validate-tests","qa-gate","update-project-memory","commit-push","sync-main","create-pr","review-pr","merge-pr","review"]),K=new Set(["yoloop","auto-yolo","epic-runner","story-runner","loop-yolo","auto-epic"]);function p(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function j(){return new Date().toISOString()}function B(){return j().replace(/[:.]/g,"-")}function I(e){return Array.isArray(e)?e.filter(o=>typeof o=="string"&&o.length>0):[]}function W(e){const[o]=e.trim().split(/\s+/,1);return o?o.replace(/^@?\*/,"").replace(/^@/,"").toLowerCase():null}function Z(e){const[o]=e.trim().split(/\s+/,1);if(!o)return!1;const t=o.replace(/^@/,"");return/^[A-Z]?\d+(?:\.\d+)+$/i.test(t)||/(?:^|\/)[A-Z]?\d+(?:\.\d+)+\.story\.md$/i.test(t)}function U(e){const o=e.match(/(?:^|[/@\s])([A-Z]?\d+(?:\.\d+)+)\.story\.md\b/i);return o?.[1]?o[1]:e.match(/(?:^|\s|@)([A-Z]?\d+(?:\.\d+)+)(?=$|\s)/i)?.[1]??null}function V(e){const o=e.trim(),t=o.search(/\s/);return t===-1?"":o.slice(t).trim()}function Y(e){const o=V(e).split(/\s+/).find(t=>t.length>0&&!t.startsWith("-"));return o?o.replace(/^@/,"").replace(/^['"]|['"]$/g,""):null}function $(e,o){const s=e.replace(/^@/,"").replace(/^epic-/i,"").replace(/\.md$/i,""),r=[s,s.toUpperCase(),/^p\d+$/i.test(s)?`P${s.replace(/^p/i,"")}`:null,/^\d+$/.test(s)?`P${s}`:null].filter(n=>typeof n=="string"&&n.length>0);for(const n of r)if(p(o[n]))return n;return null}function Q(e,o){const t=e.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);return t?.[1]?$(t[1],o):null}function X(e,o){if(typeof o!="string"||o.trim().length===0||!p(e.epics)||!p(e.stories))return;const t=o.trim(),s=W(t);if(s!==null&&H.has(s)||Z(t)){const n=U(t),l=n?e.stories[n]:void 0;if(p(l)&&typeof l.epic_id=="string"&&p(e.epics[l.epic_id]))return l.epic_id}if(s!==null&&K.has(s)){const n=Q(t,e.epics);if(n)return n;const l=Y(t);if(l){const c=$(l,e.epics);if(c)return c}}}const R="pr_merged_issue_closed_reconciled",ee="invalid_workflow_issue_removed";function S(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}const te=new Set(["done","completed","merged"]),oe=new Set(["done","completed","merged"]);function se(e){return te.has(S(e))}function k(e){return oe.has(S(e))}function y(e,o){throw new v(`${o} (${q} if this shape is intentionally new).`,e)}function re(e){return JSON.parse(JSON.stringify(e))}function ne(e,o){const t=o.scope??e.scope;if(!p(t))return;const s=typeof t.kind=="string"?t.kind:null,r=typeof t.omittedStoryCount=="number"?t.omittedStoryCount:0,n=typeof t.omittedEpicCount=="number"?t.omittedEpicCount:0;(s==="projected"||r>0||n>0)&&y(f.scopeProjected,"[Neocortex] state.json aggregate reconciliation stopped: projected or partial state coverage cannot prove epic aggregates.")}function ie(e,o){const t=[],s=new Set;for(const r of o)(typeof r!="string"||r.length===0)&&y(f.storyRefInvalid,`[Neocortex] state.json aggregate reconciliation stopped: epic "${g(e)}" has a non-string or empty story reference.`),s.has(r)&&y(f.storyRefDuplicate,`[Neocortex] state.json aggregate reconciliation stopped: epic "${g(e)}" lists story "${g(r)}" more than once.`),s.add(r),t.push(r);return t}function ae(e,o,t){const s=t[o];return s===void 0&&y(f.storyMissing,`[Neocortex] state.json aggregate reconciliation stopped: epic "${g(e)}" references missing story "${g(o)}".`),p(s)||y(f.storyNotObject,`[Neocortex] state.json aggregate reconciliation stopped: story "${g(o)}" is not an object.`),s.id!==o&&y(f.storyIdConflict,`[Neocortex] state.json aggregate reconciliation stopped: story key "${g(o)}" conflicts with its id field.`),s.epic_id!==e&&y(f.storyEpicConflict,`[Neocortex] state.json aggregate reconciliation stopped: story "${g(o)}" does not belong to epic "${g(e)}".`),s}function x(e,o){e.includes(o)||e.push(o)}function ce(e,o={}){p(e)||y(f.stateNotObject,"[Neocortex] state.json aggregate reconciliation stopped: top-level state must be an object."),p(e.epics)||y(f.epicsNotObject,"[Neocortex] state.json aggregate reconciliation stopped: `epics` must be an object before counts are authoritative."),p(e.stories)||y(f.storiesNotObject,"[Neocortex] state.json aggregate reconciliation stopped: `stories` must be an object before counts are authoritative."),ne(e,o);const t=re(e),s=t.epics,r=t.stories,n=[],l=[];for(const[c,a]of Object.entries(s)){if(o.targetEpicId&&c!==o.targetEpicId)continue;p(a)||y(f.epicNotObject,`[Neocortex] state.json aggregate reconciliation stopped: epic "${g(c)}" is not an object.`),a.id!==c&&y(f.epicIdConflict,`[Neocortex] state.json aggregate reconciliation stopped: epic key "${g(c)}" conflicts with its id field.`),Array.isArray(a.stories)||y(f.storyListNotArray,`[Neocortex] state.json aggregate reconciliation stopped: epic "${g(c)}" has non-array stories.`);const m=ie(c,a.stories),i=m.length,d=m.filter(A=>{const u=ae(c,A,r);return se(u.status)}).length,_=i>0&&d===i;k(a.status)&&!_&&i>0&&y(f.terminalIncompleteConflict,`[Neocortex] state.json aggregate reconciliation stopped: terminal epic "${g(c)}" has incomplete listed stories.`);const h=[],b={total_stories:a.total_stories,completed_stories:a.completed_stories,status:a.status,completed_at:a.completed_at};if(a.total_stories!==i&&(a.total_stories=i,x(h,f.totalRecounted)),a.completed_stories!==d&&(a.completed_stories=d,x(h,f.completedRecounted)),!k(a.status)&&_&&(a.status="done",x(h,f.statusPromotedDone),(a.completed_at===void 0||a.completed_at===null)&&(a.completed_at=o.nowIso??j(),x(h,f.completedAtSet))),h.length>0){x(h,f.reconciled);for(const A of h)x(n,A);l.push({epicId:c,reasonCodes:h,previous:b,next:{total_stories:i,completed_stories:d,status:a.status,completed_at:a.completed_at}})}}return{mutated:JSON.stringify(t)!==JSON.stringify(e),state:t,reasonCodes:n,changes:l}}function w(e,o){const t=e[o];return p(t)?t:null}function pe(e){const o=w(e,"issueCloseAudit")??w(e,"issue_close_audit");if(o){const r=S(o.event).replace(/-/g,"_"),n=o.publicSafe===!0||o.public_safe===!0,l=o.rawLogStorage==="forbidden"||o.raw_log_storage==="forbidden";if(r==="story_issue_closed"&&n&&l)return!0}const t=w(e,"completionEvidence")??w(e,"completion_evidence"),s=S(t?.issueState??t?.issue_state??t?.state);return e.issue_closed===!0||S(e.issue_state??e.issueState??e.workflow_issue_state)==="closed"||s==="closed"}function O(e){const o=w(e,"completionEvidence")??w(e,"completion_evidence"),t=w(e,"scopedCiEvidence")??w(e,"scoped_ci_evidence"),s=[e.physicalMergeStatus,e.pr_state,e.prState,e.pull_request_state,e.pullRequestState,o?.prState,o?.pr_state,o?.pullRequestState,t?.prState].map(S);return e.merged===!0||s.includes("merged")||S(t?.finalState)==="can-merge"&&e.merged===!0}function le(e){const o=w(e,"completionEvidence")??w(e,"completion_evidence"),t=[e.pr_state,e.prState,e.pull_request_state,e.pullRequestState,o?.prState,o?.pr_state,o?.pullRequestState].map(S),s=O(e),r=["denied-external-gate","denied-local-or-repo","not-attempted"].includes(S(e.physicalMergeStatus)),n=t.includes("closed")||t.includes("closed-unmerged");return s&&(e.merged===!1||r||n)||e.merged===!0&&r}function de(e,o,t){const s=`state-completion-reconciliation:${g(o)}`,r=e.filter(p).map(a=>({...a})),n={id:s,status:"open",reason:"stale_state_completion_evidence_observed",reason_codes:[R],category:"state/completion-reconciliation",story_id:g(o),public_safe:!0,raw_log_storage:"forbidden",created_at:t,last_seen_at:t,occurrences:1},l=r.findIndex(a=>a.id===s);if(l<0)return[...r,n];const c=r[l];return r[l]={...c,...n,created_at:typeof c.created_at=="string"?c.created_at:t,occurrences:Math.max(1,typeof c.occurrences=="number"?c.occurrences:1)+1},r}function ue(e,o,t){const s=p(e.stories)?e.stories:null;if(!s)return;const r=[],n=j();for(const[l,c]of Object.entries(s)){if(!p(c))continue;const a=S(c.status);if(le(c))throw new v(`[Neocortex] state.json repair stopped: story "${l}" has conflicting PR merge completion evidence. Resolve .neocortex/state.json manually before invoking Neocortex.`,"conflicting_completion_evidence");if(a!=="pr-reviewed"||!O(c)||!pe(c))continue;const m=typeof c.status=="string"?c.status:a,i=I(c.steps_completed);c.status="done",c.last_step="step-c-12-merge-pr",c.steps_completed=Array.from(new Set([...i,"step-c-12-merge-pr"])),c.merged=!0,c.physicalMergeStatus="merged",c.completion_reconciled_at=n,o.push(`reconciled completion evidence for story ${l}`),t.push(R),r.push({schemaVersion:1,publicSafe:!0,rawLogStorage:"forbidden",storyId:g(l),previousStatus:m,nextStatus:"done",reasonCodes:[R],reconciledAt:n}),e.state_repair_debt=de(Array.isArray(e.state_repair_debt)?e.state_repair_debt:[],l,n)}r.length>0&&(e.state_completion_reconciliations=[...Array.isArray(e.state_completion_reconciliations)?e.state_completion_reconciliations.filter(p):[],...r])}function _e(e,o,t){const s=p(e.stories)?e.stories:null;if(s)for(const[r,n]of Object.entries(s))!p(n)||!Object.prototype.hasOwnProperty.call(n,"workflow_issue")||typeof n.workflow_issue=="number"&&Number.isFinite(n.workflow_issue)||(delete n.workflow_issue,o.push(`removed invalid workflow_issue from story ${g(r)}`),t.push(ee))}function ge(e,o,t){const s=t[e];if(!p(s))return;const r=s.epic_id;if(typeof r=="string"&&r!==o)throw new v(`[Neocortex] state.json repair stopped: story "${e}" belongs to epic "${r}" but legacy planning maps it to "${o}". Resolve the conflicting IDs in .neocortex/state.json, then rerun the command.`,"conflicting_story_epic_id")}function fe(e,o={}){if(Array.isArray(e.stories))throw new v("[Neocortex] state.json repair stopped: `stories` is an Array. Convert it to an object keyed by story ID or run `*migrate-state --preview` for guidance.","stories_array_ambiguous");if(p(e.epics)){for(const[i,d]of Object.entries(e.epics))if(p(d)&&d.stories!==void 0&&!Array.isArray(d.stories))throw new v(`[Neocortex] state.json repair stopped: epic "${i}" has non-array \`stories\`. Repair this ambiguous shape manually before invoking Neocortex.`,"epic_stories_not_array")}if(e.schema_version!==void 0&&e.schema_version!==1)throw new v(`[Neocortex] state.json repair stopped: schema_version=${String(e.schema_version)} is not a safe automatic downgrade target. Run \`*migrate-state --preview\` or repair the schema version manually.`,"unsupported_schema_version");let t=JSON.parse(JSON.stringify(e));const s=[],r=[];let n=[];p(t.epics)||(t.epics={},s.push("initialized epics{}"),r.push("initialized_epics_object")),p(t.stories)||(t.stories={},s.push("initialized stories{}"),r.push("initialized_stories_object"));const l=t.epics,c=t.stories,a=p(t.planning)?t.planning:null;if(a&&p(a.current)){const i=a.current,d=typeof i.epic_id=="string"?i.epic_id:null;if(!d)throw new v("[Neocortex] state.json repair stopped: legacy planning.current has no epic_id. Add the missing epic_id or run `*migrate-state --preview`.","planning_current_missing_epic_id");const _=Array.isArray(i.stories)?i.stories:[],h=_.map(u=>p(u)&&typeof u.id=="string"?u.id:typeof u=="string"?u:null).filter(u=>!!u);for(const u of h)ge(u,d,c);p(l[d])||(l[d]={id:d,title:typeof i.title=="string"?i.title:`Epic ${d}`,status:i.status==="done"?"done":"in-progress",stories:h,created_at:typeof i.created_at=="string"?i.created_at:j(),completed_at:typeof i.completed_at=="string"?i.completed_at:null,completed_stories:typeof i.completed_stories=="number"?i.completed_stories:0,total_stories:typeof i.total_stories=="number"?i.total_stories:h.length,source:"client-auto-repair-P156.05"},s.push(`migrated planning.current to epics["${d}"]`),r.push("legacy_planning_current_migrated"));for(const u of _)!p(u)||typeof u.id!="string"||p(c[u.id])||(c[u.id]={...u,id:u.id,epic_id:d,title:typeof u.title=="string"?u.title:u.id,status:typeof u.status=="string"?u.status:"backlog",depends_on:I(u.depends_on),created_at:typeof u.created_at=="string"?u.created_at:j()},s.push(`migrated embedded story ${u.id}`),r.push("legacy_planning_story_migrated"));const b=typeof i.status=="string"?i.status.trim().toLowerCase().replace(/[_\s]+/g,"-"):"",C=new Set(["epic_id","title","status","created_at","updated_at","completed_at","completed_stories","total_stories","stories"]),A=Object.keys(i).filter(u=>!C.has(u));b==="generated"&&A.length===0?(delete a.current,s.push("removed safe legacy planning.current generated container"),r.push("legacy_planning_current_generated_removed")):A.length>0&&(s.push(`preserved planning.current unknown keys: ${A.sort().join(", ")}`),r.push("unknown_planning_current_keys_preserved"))}if(a&&Array.isArray(a.history)){let i=!0;const d=new Set(["epic_id","title","status","created_at","completed_at","completed_stories","total_stories","stories"]);for(const _ of a.history){if(!p(_)){i=!1;continue}Object.keys(_).filter(C=>!d.has(C)).length>0&&(i=!1);const b=typeof _.epic_id=="string"?_.epic_id:null;if(!b){i=!1;continue}p(l[b])||(l[b]={id:b,title:typeof _.title=="string"?_.title:`Epic ${b}`,status:"done",stories:I(_.stories),created_at:typeof _.created_at=="string"?_.created_at:j(),completed_at:typeof _.completed_at=="string"?_.completed_at:j(),completed_stories:typeof _.completed_stories=="number"?_.completed_stories:0,total_stories:typeof _.total_stories=="number"?_.total_stories:0,source:"client-auto-repair-P156.05"},s.push(`migrated planning.history to epics["${b}"]`),r.push("legacy_planning_history_migrated"))}i?(delete a.history,s.push("removed safe legacy planning.history container"),r.push("legacy_planning_history_removed")):(s.push("preserved planning.history because one or more entries were not safely removable"),r.push("legacy_planning_history_preserved"))}if(a&&Object.keys(a).length===0&&(delete t.planning,s.push("removed empty planning container"),r.push("empty_planning_removed")),t.schema_version!==1&&(t.schema_version=1,s.push("set schema_version=1"),r.push("schema_version_added")),_e(t,s,r),ue(t,s,r),typeof o.args=="string"){const i=X(t,o.args),d=ce(t,{nowIso:o.nowIso,targetEpicId:i});if(d.mutated){t=d.state,n=d.changes;for(const _ of d.reasonCodes)r.push(_);for(const _ of d.changes)s.push(`reconciled aggregate for epic ${g(_.epicId)}`)}}const m=JSON.stringify(t)!==JSON.stringify(e);if(m){const i=o.nowIso??j(),d=Array.from(new Set(r));n.length>0&&he(t,n,i),t.last_updated=i,t.state_migration_repairs=[...Array.isArray(t.state_migration_repairs)?t.state_migration_repairs:[],{schemaVersion:1,action:"client_auto_repair",reasonCodes:d,repairedAt:i}],t.state_repair_debt=Se(Array.isArray(t.state_repair_debt)?t.state_repair_debt:[],d,i)}return{mutated:m,state:t,reasonCodes:Array.from(new Set(r)),changes:s}}function P(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function T(e){const o=S(e);return o.length>0?E(o).slice(0,80):null}function me(e,o){return{schemaVersion:1,publicSafe:!0,epicId:g(e.epicId),reasonCodes:e.reasonCodes.map(E).filter(Boolean),previous:{total_stories:P(e.previous.total_stories),completed_stories:P(e.previous.completed_stories),status:T(e.previous.status),completed_at_present:typeof e.previous.completed_at=="string"&&e.previous.completed_at.length>0},next:{total_stories:e.next.total_stories,completed_stories:e.next.completed_stories,status:T(e.next.status),completed_at_present:typeof e.next.completed_at=="string"&&e.next.completed_at.length>0},repairedAt:o}}function ye(e,o,t){let s=e.filter(p).map(r=>({...r}));for(const r of o){const n=g(r.epicId),l=Array.from(new Set(r.reasonCodes.map(E).filter(Boolean))).sort(),c=`state-aggregate-reconciliation:${n}`,a={id:c,status:"open",reason:"epic_aggregate_reconciled",reason_codes:l,category:"state/epic-aggregate-reconciliation",epic_id:n,created_at:t,last_seen_at:t,occurrences:1},m=s.findIndex(d=>d.id===c);if(m<0){s=[...s,a];continue}const i=s[m];s[m]={...i,...a,created_at:typeof i.created_at=="string"?i.created_at:t,occurrences:Math.max(1,typeof i.occurrences=="number"?i.occurrences:1)+1}}return s}function he(e,o,t){e.state_aggregate_reconciliations=[...Array.isArray(e.state_aggregate_reconciliations)?e.state_aggregate_reconciliations.filter(p):[],...o.map(s=>me(s,t))],e.state_repair_debt=ye(Array.isArray(e.state_repair_debt)?e.state_repair_debt:[],o,t)}function Se(e,o,t){const s=Array.from(new Set(o.map(E).filter(Boolean))).sort(),r=`state-drift-repair:${s.join("+")||"unknown"}`,n=e.filter(p).map(m=>({...m})),l={id:r,status:"open",reason:"state_json_drift_repaired",reason_codes:s,category:"state/drift-repair",created_at:t,last_seen_at:t,occurrences:1},c=n.findIndex(m=>m.id===r);if(c<0)return[...n,l];const a=n[c];return n[c]={...a,...l,created_at:typeof a.created_at=="string"?a.created_at:t,occurrences:Math.max(1,typeof a.occurrences=="number"?a.occurrences:1)+1},n}function E(e){return e.replace(/\b(sk|ghp|gho|github_pat|xoxb|AKIA)[A-Za-z0-9_-]{8,}\b/g,"[redacted]").replace(/(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*[^,\s)]+/gi,"$1=[redacted]").replace(/https?:\/\/[^\s)]+/gi,"[url-redacted]").replace(/[^a-z0-9_+-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,120)}function g(e){return e.replace(/[^a-z0-9_.:-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,120)||"unknown"}function je(e,o={}){const t=N(e,".neocortex"),s=N(t,"state.json");if(!M(s))return{repaired:!1,reasonCodes:[],changes:[]};let r;try{r=JSON.parse(D(s,"utf8"))}catch(i){const d=i instanceof Error?i.message:String(i);throw new v(`[Neocortex] state.json repair stopped: invalid JSON in .neocortex/state.json (${d}). No files were overwritten. Fix the JSON or restore a backup, then rerun.`,"invalid_json")}if(!p(r))throw new v("[Neocortex] state.json repair stopped: top-level state must be a JSON object. Restore a valid .neocortex/state.json before invoking Neocortex.","state_not_object");const n=fe(r,o);if(!n.mutated)return{repaired:!1,reasonCodes:[],changes:[]};L(t,{recursive:!0});const l=B(),c=N(t,`state.json.backup-${l}`),a=N(t,`state.json.tmp.${J(6).toString("hex")}`);F(s,c),z(a,`${JSON.stringify(n.state,null,2)}
|
|
2
|
-
`,"utf8"),
|
|
3
|
-
`),{repaired:!0,reasonCodes:
|
|
1
|
+
import{existsSync as q,mkdirSync as B,readFileSync as H,renameSync as K,writeFileSync as W,copyFileSync as V}from"node:fs";import{join as E}from"node:path";import{randomBytes as Z}from"node:crypto";import{readGitLifecycleRuntimeSync as U,verifyAcceptedGitLifecycleStoryCheckpointSync as Y}from"../git/git-lifecycle-store.js";class b extends Error{reasonCode;constructor(t,o){super(t),this.reasonCode=o,this.name="StateRepairHardStopError"}}const Q="P189-GAP-STATE-SHAPE",h={reconciled:"epic_aggregate_reconciled",totalRecounted:"epic_total_stories_recounted",completedRecounted:"epic_completed_stories_recounted",statusPromotedDone:"epic_status_promoted_done",completedAtSet:"epic_completed_at_set",stateNotObject:"epic_aggregate_state_not_object",epicsNotObject:"epic_aggregate_epics_not_object",storiesNotObject:"epic_aggregate_stories_not_object",scopeProjected:"epic_aggregate_scope_projected",epicNotObject:"epic_aggregate_epic_not_object",epicIdConflict:"epic_aggregate_epic_id_conflict",storyListNotArray:"epic_aggregate_story_list_not_array",storyRefInvalid:"epic_aggregate_story_ref_invalid",storyRefDuplicate:"epic_aggregate_story_ref_duplicate",storyMissing:"epic_aggregate_story_missing",storyNotObject:"epic_aggregate_story_not_object",storyIdConflict:"epic_aggregate_story_id_conflict",storyEpicConflict:"epic_aggregate_story_epic_conflict",terminalIncompleteConflict:"epic_aggregate_terminal_incomplete_conflict"},X=new Set(["yolo","implement","diagnose","research","write-spec","create-tasks","refactor-suggest","property-tests","validate-tests","qa-gate","update-project-memory","commit-push","sync-main","create-pr","review-pr","merge-pr","review"]),ee=new Set(["yoloop","auto-yolo","epic-runner","story-runner","loop-yolo","auto-epic"]);function l(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function x(){return new Date().toISOString()}function te(){return x().replace(/[:.]/g,"-")}function k(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function $(e){const[t]=e.trim().split(/\s+/,1);return t?t.replace(/^@?\*/,"").replace(/^@/,"").toLowerCase():null}function oe(e){const[t]=e.trim().split(/\s+/,1);if(!t)return!1;const o=t.replace(/^@/,"");return/^[A-Z]?\d+(?:\.\d+)+$/i.test(o)||/(?:^|\/)[A-Z]?\d+(?:\.\d+)+\.story\.md$/i.test(o)}function O(e){const t=e.match(/(?:^|[/@\s])([A-Z]?\d+(?:\.\d+)+)\.story\.md\b/i);return t?.[1]?t[1]:e.match(/(?:^|\s|@)([A-Z]?\d+(?:\.\d+)+)(?=$|\s)/i)?.[1]??null}function P(e,t){if(typeof e!="string")return!1;const o=t??$(e);return(o==="yolo"||o==="yolo-inline")&&T(e).length>0&&O(e)===null}function T(e){const t=e.trim(),o=t.search(/\s/);return o===-1?"":t.slice(o).trim()}function re(e){const t=T(e).split(/\s+/).find(o=>o.length>0&&!o.startsWith("-"));return t?t.replace(/^@/,"").replace(/^['"]|['"]$/g,""):null}function D(e,t){const r=e.replace(/^@/,"").replace(/^epic-/i,"").replace(/\.md$/i,""),s=[r,r.toUpperCase(),/^p\d+$/i.test(r)?`P${r.replace(/^p/i,"")}`:null,/^\d+$/.test(r)?`P${r}`:null].filter(a=>typeof a=="string"&&a.length>0);for(const a of s)if(l(t[a]))return a;return null}function se(e,t){const o=e.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);return o?.[1]?D(o[1],t):null}function L(e,t,o){if(typeof t!="string"||t.trim().length===0||!l(e.epics)||!l(e.stories))return;const r=t.trim(),s=o??$(r);if(s!==null&&X.has(s)||oe(r)){const u=O(r),p=u?e.stories[u]:void 0;if(l(p)&&typeof p.epic_id=="string"&&l(e.epics[p.epic_id]))return p.epic_id;const n=u?.split(".")[0];if(n&&l(e.epics[n]))return n}if(s!==null&&ee.has(s)){const u=se(r,e.epics);if(u)return u;const p=re(r);if(p){const n=D(p,e.epics);if(n)return n}}}const R="pr_merged_issue_closed_reconciled",ne="invalid_workflow_issue_removed";function w(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}const ie=new Set(["done","completed","merged"]),ce=new Set(["done","completed","merged"]);function M(e){return ie.has(w(e))}function G(e){return ce.has(w(e))}function S(e,t){throw new b(`${t} (${Q} if this shape is intentionally new).`,e)}function ae(e){return JSON.parse(JSON.stringify(e))}function pe(e,t){const o=t.scope??e.scope;if(!l(o))return;const r=typeof o.kind=="string"?o.kind:null,s=typeof o.omittedStoryCount=="number"?o.omittedStoryCount:0,a=typeof o.omittedEpicCount=="number"?o.omittedEpicCount:0;(r==="projected"||s>0||a>0)&&S(h.scopeProjected,"[Neocortex] state.json aggregate reconciliation stopped: projected or partial state coverage cannot prove epic aggregates.")}function le(e,t){const o=[],r=new Set;for(const s of t)(typeof s!="string"||s.length===0)&&S(h.storyRefInvalid,`[Neocortex] state.json aggregate reconciliation stopped: epic "${y(e)}" has a non-string or empty story reference.`),r.has(s)&&S(h.storyRefDuplicate,`[Neocortex] state.json aggregate reconciliation stopped: epic "${y(e)}" lists story "${y(s)}" more than once.`),r.add(s),o.push(s);return o}function de(e,t,o){const r=o[t];return r===void 0&&S(h.storyMissing,`[Neocortex] state.json aggregate reconciliation stopped: epic "${y(e)}" references missing story "${y(t)}".`),l(r)||S(h.storyNotObject,`[Neocortex] state.json aggregate reconciliation stopped: story "${y(t)}" is not an object.`),r.id!==t&&S(h.storyIdConflict,`[Neocortex] state.json aggregate reconciliation stopped: story key "${y(t)}" conflicts with its id field.`),r.epic_id!==e&&S(h.storyEpicConflict,`[Neocortex] state.json aggregate reconciliation stopped: story "${y(t)}" does not belong to epic "${y(e)}".`),r}function C(e,t){e.includes(t)||e.push(t)}function ue(e,t={}){l(e)||S(h.stateNotObject,"[Neocortex] state.json aggregate reconciliation stopped: top-level state must be an object."),l(e.epics)||S(h.epicsNotObject,"[Neocortex] state.json aggregate reconciliation stopped: `epics` must be an object before counts are authoritative."),l(e.stories)||S(h.storiesNotObject,"[Neocortex] state.json aggregate reconciliation stopped: `stories` must be an object before counts are authoritative."),pe(e,t);const o=ae(e),r=o.epics,s=o.stories,a=[],u=[],p=new Set(t.effectiveDoneStoryIds??[]);for(const[n,c]of Object.entries(r)){if(t.targetEpicId&&n!==t.targetEpicId)continue;l(c)||S(h.epicNotObject,`[Neocortex] state.json aggregate reconciliation stopped: epic "${y(n)}" is not an object.`),c.id!==n&&S(h.epicIdConflict,`[Neocortex] state.json aggregate reconciliation stopped: epic key "${y(n)}" conflicts with its id field.`),Array.isArray(c.stories)||S(h.storyListNotArray,`[Neocortex] state.json aggregate reconciliation stopped: epic "${y(n)}" has non-array stories.`);const g=le(n,c.stories),i=g.length,d=g.filter(j=>{const _=de(n,j,s);return M(_.status)||p.has(j)}).length,f=i>0&&d===i;if(G(c.status)&&!f&&i>0&&S(h.terminalIncompleteConflict,`[Neocortex] state.json aggregate reconciliation stopped: terminal epic "${y(n)}" has incomplete listed stories.`),t.preserveGitLifecycleAggregates&&(c.branch_mode==="epic"||typeof c.execution_branch=="string"))continue;const m=[],v={total_stories:c.total_stories,completed_stories:c.completed_stories,status:c.status,completed_at:c.completed_at};if(c.total_stories!==i&&(c.total_stories=i,C(m,h.totalRecounted)),c.completed_stories!==d&&(c.completed_stories=d,C(m,h.completedRecounted)),!G(c.status)&&f&&(c.status="done",C(m,h.statusPromotedDone),(c.completed_at===void 0||c.completed_at===null)&&(c.completed_at=t.nowIso??x(),C(m,h.completedAtSet))),m.length>0){C(m,h.reconciled);for(const j of m)C(a,j);u.push({epicId:n,reasonCodes:m,previous:v,next:{total_stories:i,completed_stories:d,status:c.status,completed_at:c.completed_at}})}}return{mutated:JSON.stringify(o)!==JSON.stringify(e),state:o,reasonCodes:a,changes:u}}function A(e,t){const o=e[t];return l(o)?o:null}function _e(e){const t=A(e,"issueCloseAudit")??A(e,"issue_close_audit");if(t){const s=w(t.event).replace(/-/g,"_"),a=t.publicSafe===!0||t.public_safe===!0,u=t.rawLogStorage==="forbidden"||t.raw_log_storage==="forbidden";if(s==="story_issue_closed"&&a&&u)return!0}const o=A(e,"completionEvidence")??A(e,"completion_evidence"),r=w(o?.issueState??o?.issue_state??o?.state);return e.issue_closed===!0||w(e.issue_state??e.issueState??e.workflow_issue_state)==="closed"||r==="closed"}function z(e){const t=A(e,"completionEvidence")??A(e,"completion_evidence"),o=A(e,"scopedCiEvidence")??A(e,"scoped_ci_evidence"),r=[e.physicalMergeStatus,e.pr_state,e.prState,e.pull_request_state,e.pullRequestState,t?.prState,t?.pr_state,t?.pullRequestState,o?.prState].map(w);return e.merged===!0||r.includes("merged")||w(o?.finalState)==="can-merge"&&e.merged===!0}function fe(e){const t=A(e,"completionEvidence")??A(e,"completion_evidence"),o=[e.pr_state,e.prState,e.pull_request_state,e.pullRequestState,t?.prState,t?.pr_state,t?.pullRequestState].map(w),r=z(e),s=["denied-external-gate","denied-local-or-repo","not-attempted"].includes(w(e.physicalMergeStatus)),a=o.includes("closed")||o.includes("closed-unmerged");return r&&(e.merged===!1||s||a)||e.merged===!0&&s}function ge(e,t,o){const r=`state-completion-reconciliation:${y(t)}`,s=e.filter(l).map(n=>({...n})),a={id:r,status:"open",reason:"stale_state_completion_evidence_observed",reason_codes:[R],category:"state/completion-reconciliation",story_id:y(t),public_safe:!0,raw_log_storage:"forbidden",created_at:o,last_seen_at:o,occurrences:1},u=s.findIndex(n=>n.id===r);if(u<0)return[...s,a];const p=s[u];return s[u]={...p,...a,created_at:typeof p.created_at=="string"?p.created_at:o,occurrences:Math.max(1,typeof p.occurrences=="number"?p.occurrences:1)+1},s}function me(e,t,o,r){const s=l(e.stories)?e.stories:null;if(!s)return;const a=[],u=x();for(const[p,n]of Object.entries(s)){if(!l(n))continue;const c=typeof n.epic_id=="string"?n.epic_id:p.split(".")[0];if(r&&c!==r)continue;const g=w(n.status);if(fe(n))throw new b(`[Neocortex] state.json repair stopped: story "${p}" has conflicting PR merge completion evidence. Resolve .neocortex/state.json manually before invoking Neocortex.`,"conflicting_completion_evidence");if(g!=="pr-reviewed"||!z(n)||!_e(n))continue;const i=typeof n.status=="string"?n.status:g,d=k(n.steps_completed);n.status="done",n.last_step="step-c-12-merge-pr",n.steps_completed=Array.from(new Set([...d,"step-c-12-merge-pr"])),n.merged=!0,n.physicalMergeStatus="merged",n.completion_reconciled_at=u,t.push(`reconciled completion evidence for story ${p}`),o.push(R),a.push({schemaVersion:1,publicSafe:!0,rawLogStorage:"forbidden",storyId:y(p),previousStatus:i,nextStatus:"done",reasonCodes:[R],reconciledAt:u}),e.state_repair_debt=ge(Array.isArray(e.state_repair_debt)?e.state_repair_debt:[],p,u)}a.length>0&&(e.state_completion_reconciliations=[...Array.isArray(e.state_completion_reconciliations)?e.state_completion_reconciliations.filter(l):[],...a])}function ye(e,t,o){const r=l(e.stories)?e.stories:null;if(r)for(const[s,a]of Object.entries(r))!l(a)||!Object.prototype.hasOwnProperty.call(a,"workflow_issue")||typeof a.workflow_issue=="number"&&Number.isFinite(a.workflow_issue)||(delete a.workflow_issue,t.push(`removed invalid workflow_issue from story ${y(s)}`),o.push(ne))}function he(e,t,o){const r=o[e];if(!l(r))return;const s=r.epic_id;if(typeof s=="string"&&s!==t)throw new b(`[Neocortex] state.json repair stopped: story "${e}" belongs to epic "${s}" but legacy planning maps it to "${t}". Resolve the conflicting IDs in .neocortex/state.json, then rerun the command.`,"conflicting_story_epic_id")}function Se(e,t={}){if(Array.isArray(e.stories))throw new b("[Neocortex] state.json repair stopped: `stories` is an Array. Convert it to an object keyed by story ID or run `*migrate-state --preview` for guidance.","stories_array_ambiguous");if(l(e.epics)){for(const[i,d]of Object.entries(e.epics))if(l(d)&&d.stories!==void 0&&!Array.isArray(d.stories))throw new b(`[Neocortex] state.json repair stopped: epic "${i}" has non-array \`stories\`. Repair this ambiguous shape manually before invoking Neocortex.`,"epic_stories_not_array")}if(e.schema_version!==void 0&&e.schema_version!==1)throw new b(`[Neocortex] state.json repair stopped: schema_version=${String(e.schema_version)} is not a safe automatic downgrade target. Run \`*migrate-state --preview\` or repair the schema version manually.`,"unsupported_schema_version");if(P(t.args,t.canonicalCommandId)){for(const i of["epics","stories"]){const d=e[i];if(d!==void 0){if(!l(d))throw new b("[Neocortex] inline materialization stopped: invalid state collection.","inline_state_collection_invalid");for(const[f,m]of Object.entries(d)){if(!l(m))throw new b("[Neocortex] inline materialization stopped: invalid state record.","inline_state_record_invalid");if(m.id!==void 0&&m.id!==f)throw new b("[Neocortex] inline materialization stopped: conflicting state identity.","inline_state_identity_conflict")}}}return{mutated:!1,state:e,reasonCodes:[],changes:[]}}let o=JSON.parse(JSON.stringify(e));const r=[],s=[];let a=[];l(o.epics)||(o.epics={},r.push("initialized epics{}"),s.push("initialized_epics_object")),l(o.stories)||(o.stories={},r.push("initialized stories{}"),s.push("initialized_stories_object"));const u=o.epics,p=o.stories,n=L(o,t.args,t.canonicalCommandId),c=l(o.planning)?o.planning:null;if(c&&l(c.current)){const i=c.current,d=typeof i.epic_id=="string"?i.epic_id:null;if(!d)throw new b("[Neocortex] state.json repair stopped: legacy planning.current has no epic_id. Add the missing epic_id or run `*migrate-state --preview`.","planning_current_missing_epic_id");const f=Array.isArray(i.stories)?i.stories:[],m=f.map(_=>l(_)&&typeof _.id=="string"?_.id:typeof _=="string"?_:null).filter(_=>!!_);for(const _ of m)he(_,d,p);l(u[d])||(u[d]={id:d,title:typeof i.title=="string"?i.title:`Epic ${d}`,status:i.status==="done"?"done":"in-progress",stories:m,created_at:typeof i.created_at=="string"?i.created_at:x(),completed_at:typeof i.completed_at=="string"?i.completed_at:null,completed_stories:typeof i.completed_stories=="number"?i.completed_stories:0,total_stories:typeof i.total_stories=="number"?i.total_stories:m.length,source:"client-auto-repair-P156.05"},r.push(`migrated planning.current to epics["${d}"]`),s.push("legacy_planning_current_migrated"));for(const _ of f)!l(_)||typeof _.id!="string"||l(p[_.id])||(p[_.id]={..._,id:_.id,epic_id:d,title:typeof _.title=="string"?_.title:_.id,status:typeof _.status=="string"?_.status:"backlog",depends_on:k(_.depends_on),created_at:typeof _.created_at=="string"?_.created_at:x()},r.push(`migrated embedded story ${_.id}`),s.push("legacy_planning_story_migrated"));const v=typeof i.status=="string"?i.status.trim().toLowerCase().replace(/[_\s]+/g,"-"):"",I=new Set(["epic_id","title","status","created_at","updated_at","completed_at","completed_stories","total_stories","stories"]),j=Object.keys(i).filter(_=>!I.has(_));v==="generated"&&j.length===0?(delete c.current,r.push("removed safe legacy planning.current generated container"),s.push("legacy_planning_current_generated_removed")):j.length>0&&(r.push(`preserved planning.current unknown keys: ${j.sort().join(", ")}`),s.push("unknown_planning_current_keys_preserved"))}if(c&&Array.isArray(c.history)){let i=!0;const d=new Set(["epic_id","title","status","created_at","completed_at","completed_stories","total_stories","stories"]);for(const f of c.history){if(!l(f)){i=!1;continue}Object.keys(f).filter(I=>!d.has(I)).length>0&&(i=!1);const v=typeof f.epic_id=="string"?f.epic_id:null;if(!v){i=!1;continue}l(u[v])||(u[v]={id:v,title:typeof f.title=="string"?f.title:`Epic ${v}`,status:"done",stories:k(f.stories),created_at:typeof f.created_at=="string"?f.created_at:x(),completed_at:typeof f.completed_at=="string"?f.completed_at:x(),completed_stories:typeof f.completed_stories=="number"?f.completed_stories:0,total_stories:typeof f.total_stories=="number"?f.total_stories:0,source:"client-auto-repair-P156.05"},r.push(`migrated planning.history to epics["${v}"]`),s.push("legacy_planning_history_migrated"))}i?(delete c.history,r.push("removed safe legacy planning.history container"),s.push("legacy_planning_history_removed")):(r.push("preserved planning.history because one or more entries were not safely removable"),s.push("legacy_planning_history_preserved"))}if(c&&Object.keys(c).length===0&&(delete o.planning,r.push("removed empty planning container"),s.push("empty_planning_removed")),o.schema_version!==1&&(o.schema_version=1,r.push("set schema_version=1"),s.push("schema_version_added")),ye(o,r,s),me(o,r,s,n),typeof t.args=="string"){const i=ue(o,{nowIso:t.nowIso,targetEpicId:n,effectiveDoneStoryIds:t.effectiveDoneStoryIds,preserveGitLifecycleAggregates:!0});if(i.mutated){o=i.state,a=i.changes;for(const d of i.reasonCodes)s.push(d);for(const d of i.changes)r.push(`reconciled aggregate for epic ${y(d.epicId)}`)}}const g=JSON.stringify(o)!==JSON.stringify(e);if(g){const i=t.nowIso??x(),d=Array.from(new Set(s));a.length>0&&we(o,a,i),o.last_updated=i,o.state_migration_repairs=[...Array.isArray(o.state_migration_repairs)?o.state_migration_repairs:[],{schemaVersion:1,action:"client_auto_repair",reasonCodes:d,repairedAt:i}],o.state_repair_debt=Ae(Array.isArray(o.state_repair_debt)?o.state_repair_debt:[],d,i)}return{mutated:g,state:o,reasonCodes:Array.from(new Set(s)),changes:r}}function F(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function J(e){const t=w(e);return t.length>0?N(t).slice(0,80):null}function be(e,t){return{schemaVersion:1,publicSafe:!0,epicId:y(e.epicId),reasonCodes:e.reasonCodes.map(N).filter(Boolean),previous:{total_stories:F(e.previous.total_stories),completed_stories:F(e.previous.completed_stories),status:J(e.previous.status),completed_at_present:typeof e.previous.completed_at=="string"&&e.previous.completed_at.length>0},next:{total_stories:e.next.total_stories,completed_stories:e.next.completed_stories,status:J(e.next.status),completed_at_present:typeof e.next.completed_at=="string"&&e.next.completed_at.length>0},repairedAt:t}}function ve(e,t,o){let r=e.filter(l).map(s=>({...s}));for(const s of t){const a=y(s.epicId),u=Array.from(new Set(s.reasonCodes.map(N).filter(Boolean))).sort(),p=`state-aggregate-reconciliation:${a}`,n={id:p,status:"open",reason:"epic_aggregate_reconciled",reason_codes:u,category:"state/epic-aggregate-reconciliation",epic_id:a,created_at:o,last_seen_at:o,occurrences:1},c=r.findIndex(i=>i.id===p);if(c<0){r=[...r,n];continue}const g=r[c];r[c]={...g,...n,created_at:typeof g.created_at=="string"?g.created_at:o,occurrences:Math.max(1,typeof g.occurrences=="number"?g.occurrences:1)+1}}return r}function we(e,t,o){e.state_aggregate_reconciliations=[...Array.isArray(e.state_aggregate_reconciliations)?e.state_aggregate_reconciliations.filter(l):[],...t.map(r=>be(r,o))],e.state_repair_debt=ve(Array.isArray(e.state_repair_debt)?e.state_repair_debt:[],t,o)}function Ae(e,t,o){const r=Array.from(new Set(t.map(N).filter(Boolean))).sort(),s=`state-drift-repair:${r.join("+")||"unknown"}`,a=e.filter(l).map(c=>({...c})),u={id:s,status:"open",reason:"state_json_drift_repaired",reason_codes:r,category:"state/drift-repair",created_at:o,last_seen_at:o,occurrences:1},p=a.findIndex(c=>c.id===s);if(p<0)return[...a,u];const n=a[p];return a[p]={...n,...u,created_at:typeof n.created_at=="string"?n.created_at:o,occurrences:Math.max(1,typeof n.occurrences=="number"?n.occurrences:1)+1},a}function N(e){return e.replace(/\b(sk|ghp|gho|github_pat|xoxb|AKIA)[A-Za-z0-9_-]{8,}\b/g,"[redacted]").replace(/(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*[^,\s)]+/gi,"$1=[redacted]").replace(/https?:\/\/[^\s)]+/gi,"[url-redacted]").replace(/[^a-z0-9_+-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,120)}function y(e){return e.replace(/[^a-z0-9_.:-]+/gi,"_").replace(/^_+|_+$/g,"").slice(0,120)||"unknown"}function Ne(e,t={}){const o=E(e,".neocortex"),r=E(o,"state.json");if(!q(r))return{repaired:!1,reasonCodes:[],changes:[]};let s;try{s=JSON.parse(H(r,"utf8"))}catch(d){const f=d instanceof Error?d.message:String(d);throw new b(`[Neocortex] state.json repair stopped: invalid JSON in .neocortex/state.json (${f}). No files were overwritten. Fix the JSON or restore a backup, then rerun.`,"invalid_json")}if(!l(s))throw new b("[Neocortex] state.json repair stopped: top-level state must be a JSON object. Restore a valid .neocortex/state.json before invoking Neocortex.","state_not_object");const a=L(s,t.args,t.canonicalCommandId),u=P(t.args,t.canonicalCommandId)?[]:je(e,s,a),p=Se(s,{...t,effectiveDoneStoryIds:u});if(!p.mutated)return{repaired:!1,reasonCodes:[],changes:[]};B(o,{recursive:!0});const n=te(),c=E(o,`state.json.backup-${n}`),g=E(o,`state.json.tmp.${Z(6).toString("hex")}`);V(r,c),W(g,`${JSON.stringify(p.state,null,2)}
|
|
2
|
+
`,"utf8"),K(g,r);const i=`.neocortex/state.json.backup-${n}`;return process.stderr.write(`[Neocortex P156.05] state.json auto-repaired before invoke; backup=${i}; reasonCodes=${p.reasonCodes.join(",")}; changes=${p.changes.join("; ")}
|
|
3
|
+
`),{repaired:!0,reasonCodes:p.reasonCodes,backupPath:i,changes:p.changes}}function je(e,t,o){const r=U(e),s=l(t.epics)?t.epics:{},a=l(t.stories)?t.stories:{},u=[];for(const[p,n]of Object.entries(r.stories)){if(!l(n)||!M(n.status)||!n.checkpoint)continue;const c=l(a[p])?a[p]:null,g=typeof c?.epic_id=="string"?c.epic_id:p.split(".")[0];if(!g||o&&g!==o)continue;const i=l(s[g])?s[g]:null,d=l(r.epics[g])?r.epics[g]:null,f=d?.branch_mode??i?.branch_mode,m=d?.execution_branch??i?.execution_branch;if(f!=="epic"||typeof m!="string")continue;Y(e,n.checkpoint,p,g,m).verdict==="verified"&&u.push(p)}return u.sort()}export{h as EPIC_AGGREGATE_REASON_CODES,Q as P189_STATE_SHAPE_GAP_CODE,b as StateRepairHardStopError,P as isInlineYoloMaterialization,M as isP189DoneLikeStoryStatus,Ne as maybeRepairStateJsonBeforeInvoke,ue as reconcileEpicAggregatesInState};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{GENERATED_CLIENT_COMMANDS as p}from"../generated/command-registry.generated.js";const o="neocortex:tier",b="neocortex:quota:",d=300*1e3,m=3600*1e3,l=new Set(["free","pro","enterprise"]),s="free",g={status:"free",
|
|
1
|
+
import{GENERATED_CLIENT_COMMANDS as p}from"../generated/command-registry.generated.js";const o="neocortex:tier",b="neocortex:quota:",d=300*1e3,m=3600*1e3,l=new Set(["free","pro","enterprise"]),s="free",g={status:"free","create-epic":"free","idea-diagnose":"free","idea-research":"free","generate-epic":"free",exec:"pro",yolo:"pro",epic:"pro","setup-branch":"free",diagnose:"free",research:"free","write-spec":"free","create-tasks":"free",implement:"free","update-memory":"free",commit:"free",sync:"free","create-pr":"free",review:"pro",merge:"free","fix-blocked":"free","finalize-epic":"free",cleanup:"free","resolve-conflicts":"free",audit:"free",menu:"free",plans:"free",billing:"free",subscribe:"free","arch-plan":"free","arch-prd":"free","arch-architecture":"free","arch-api-contracts":"free","arch-api-integrations":"free","arch-database":"free","arch-security":"free","arch-design-system":"free","arch-ux-design":"free","arch-review":"free","arch-fitness-functions":"pro","arch-performance":"pro","arch-testing":"pro","arch-infrastructure":"pro",refactor:"pro","tech-debt":"free","tech-debt-scan":"pro","qa-scan":"pro","mutation-test":"pro",yoloop:"pro","migrate-state":"free","policy-audit":"pro","sync-openapi":"free","generate-pacts":"pro","verify-pacts":"free","property-test":"pro","chaos-plan":"pro","ui-ux-review":"pro","solyd-system":"enterprise",goal:"enterprise","goal-tick":"enterprise",loop:"enterprise","loop-tick":"enterprise",jobs:"enterprise",runner:"enterprise"},y=Object.freeze(Object.fromEntries(p.map(r=>[r.id,r.policy.minimumTier]))),T=[{id:"status",number:1,aliases:["st"]},{id:"arch-plan",number:3,aliases:["arquitetura","architecture","arch"]},{id:"arch-prd",number:4,aliases:["prd","product-requirements"]},{id:"arch-architecture",number:5,aliases:["arch-doc","tech-architecture"]},{id:"arch-api-contracts",number:6,aliases:["api-contracts","api-contract"]},{id:"arch-api-integrations",number:7,aliases:["api-integrations","api-int"]},{id:"arch-database",number:8,aliases:["database-schema","db-schema","db"]},{id:"arch-security",number:9,aliases:["cyber-security","security","sec"]},{id:"arch-design-system",number:10,aliases:["design-system","ds","atomic-design"]},{id:"arch-ux-design",number:11,aliases:["ux-design","ux","wireframes","wireframe","user-flows"]},{id:"arch-performance",number:12,aliases:["performance","perf","capacity-planning","capacity","arch-perf","performance-strategy"]},{id:"arch-testing",number:13,aliases:["testing-strategy","test-plan","test-strategy","arch-test"]},{id:"arch-infrastructure",number:14,aliases:["infrastructure","infra","deploy-plan","deployment","arch-infra","arch-deploy"]},{id:"arch-review",number:15,aliases:["review-consolidation","consolidation","architecture-review","arch-consolidation"]},{id:"arch-fitness-functions",number:16,aliases:["fitness","fitness-functions","archfit","arch-fit","fit-funcs"]},{id:"create-epic",number:17,aliases:["criar-epic","planejamento"]},{id:"idea-diagnose",number:18,aliases:["idea-diag"]},{id:"idea-research",number:19,aliases:["idea-pesq"]},{id:"generate-epic",number:20,aliases:["gerar-epic"]},{id:"exec",number:21,aliases:["executar","pipeline"]},{id:"yolo",number:22,aliases:[]},{id:"epic",number:23,aliases:["parallel-epic"]},{id:"setup-branch",number:24,aliases:["setup","branch"]},{id:"diagnose",number:25,aliases:["diag","diagnostico","c02"]},{id:"research",number:26,aliases:["pesquisar","pesq","research-fix","c03"]},{id:"write-spec",number:27,aliases:["spec","especificacao","c04"]},{id:"create-tasks",number:28,aliases:["tasks","tarefas","c05"]},{id:"implement",number:29,aliases:["impl","implementar","c06"]},{id:"commit",number:30,aliases:["push","commit-push","commit_push","cp","c07"]},{id:"sync",number:31,aliases:["sincronizar","c08"]},{id:"create-pr",number:32,aliases:["pr","c09"]},{id:"review",number:33,aliases:["revisar","c11"]},{id:"merge",number:34,aliases:["mesclar","c12"]},{id:"fix-blocked",number:35,aliases:["fix","corrigir"]},{id:"finalize-epic",number:36,aliases:["finalizar"]},{id:"resolve-conflicts",number:37,aliases:["conflitos"]},{id:"update-memory",number:38,aliases:["memoria"]},{id:"refactor",number:39,aliases:["refactoring","refact","refac","rf","cleanup-code","code-cleanup","code-quality","improve-code","modernize","modernization","legacy","legacy-code","debt-pay","pay-debt","debt-reduction","smell-fix","fix-smells","code-smells","strangler","strangler-fig"]},{id:"cleanup",number:40,aliases:["limpar","limpeza"]},{id:"audit",number:41,aliases:["auditar","auditoria"]},{id:"tech-debt",number:42,aliases:["debt","debts","debt-list","tech-debts","td"]},{id:"menu",number:43,aliases:["help","ajuda","?","commands","cmds"]},{id:"plans",number:44,aliases:["planos","pricing"]},{id:"billing",number:45,aliases:["bill","subscription","sub"]},{id:"subscribe",number:46,aliases:["upgrade","checkout"]},{id:"qa-scan",number:47,aliases:["qa","qa-test","visual-qa","e2e-scan","troubleshoot","debug-ui","scan","a11y","accessibility","wcag"]},{id:"yoloop",number:48,aliases:["auto-yolo","epic-runner","story-runner","loop-yolo","auto-epic"]},{id:"migrate-state",number:49,aliases:["migrate","state-migrate","schema-migrate"]},{id:"policy-audit",number:50,aliases:["policy","audit-policy","policy-history","policies"]},{id:"mutation-test",number:51,aliases:["mutation","stryker","kill-mutants"]},{id:"sync-openapi",number:52,aliases:["openapi-sync","api-sync","spec-sync","regen-openapi"]},{id:"generate-pacts",number:53,aliases:["pacts","gen-pacts","regen-pacts","create-pacts"]},{id:"verify-pacts",number:54,aliases:["verify-pact","pact-verify","check-pacts","pact-check"]},{id:"property-test",number:55,aliases:["property","pbt","proptest","property-tests","invariant-test"]},{id:"chaos-plan",number:56,aliases:["chaos","gameday","resilience-test"]},{id:"ui-ux-review",number:57,aliases:["ux-review","design-review","visual-review","product-polish"]},{id:"solyd-system",number:58,aliases:["security-system","authorized-security","sec-system"]},{id:"goal",number:59,aliases:["goals","durable-goal","continuity-goal"]},{id:"loop",number:60,aliases:["loops","durable-loop","continuity-loop"]},{id:"jobs",number:61,aliases:["job","continuity-jobs"]},{id:"runner",number:62,aliases:["neocortex-runner","continuity-runner"]}],u=Object.freeze(p.map(r=>Object.freeze({id:r.id,number:r.number,aliases:r.aliases}))),w=new Map(u.map(r=>[r.id,r])),C=new Map(u.map(r=>[r.number,r])),v=new Map(u.flatMap(r=>r.aliases.map(a=>[h(a),r.id])));function h(r){if(/[^\x20-\x7e]/.test(r))return"";const a=r.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g,"");if(!a||a.startsWith("**"))return"";const e=(a.startsWith("*")?a.slice(1):a).replace(/[A-Z]/g,i=>i.toLowerCase());return/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(e)||e==="?"?e:""}function _(r){const a=r.trim();if(/^@?epic-[a-z0-9][a-z0-9._-]*$/i.test(a))return"epic";const e=a.split(/\s+/,1)[0]??"",i=e.trim().replace(/^\*/,"");if(/^\d+$/.test(i))return C.get(Number.parseInt(i,10))?.id??null;const t=h(e);return t?t==="goal-tick"?"goal":t==="loop-tick"?"loop":w.has(t)?t:v.get(t)??null:null}const f={free:0,pro:1,enterprise:2};class R{cache;licenseClient;cachedTier=null;constructor(a){this.cache=a.cacheProvider,this.licenseClient=a.licenseClient}async getCachedTier(){try{if(this.cachedTier)return this.cachedTier;const a=await this.cache.get(o);if(a&&l.has(a))return this.cachedTier=a,this.cachedTier;const e=await this.licenseClient.getToken();if(e){const i=this.extractTierFromJwt(e);return this.cachedTier=i,await this.cache.set(o,i,m).catch(()=>{}),i}return s}catch{return s}}async updateTier(a){try{if(!l.has(a))return;this.cachedTier=a,await this.cache.set(o,a,m).catch(()=>{})}catch{}}async invalidateTierCache(){try{this.cachedTier=null,await this.cache.clear().catch(()=>{})}catch{}}async preFlightCheck(a,e){try{const i=e??await this.getCachedTier(),t=_(a)??a,n=y[t]??"free";return f[i]>=f[n]?{allowed:!0}:{allowed:!1,message:this.buildUpgradeMessage(t,i,n)}}catch{return{allowed:!0}}}async updateQuotaFromResponse(a){try{const e=a.quotaRemaining;if(!e)return;const i={stepsRemaining:e.stepsRemaining??0,invocationsRemaining:e.invocationsRemaining??0,stepsLimit:e.stepsLimit??0,invocationsLimit:e.invocationsLimit??0,cachedAt:Date.now()},t=this.getQuotaCacheKey();await this.cache.set(t,JSON.stringify(i),d).catch(()=>{})}catch{}}async getCachedQuota(){try{const a=this.getQuotaCacheKey(),e=await this.cache.get(a);if(!e)return null;const i=JSON.parse(e);return Date.now()-i.cachedAt>d?null:i}catch{return null}}async offlineQuotaCheck(a=!1){try{if(!a)return{allowed:!0};const e=await this.getCachedQuota();return e?e.stepsRemaining<=0&&e.stepsLimit>0?{allowed:!1,message:`Daily step limit reached (${e.stepsLimit}/${e.stepsLimit}). Resets at 00:00 UTC.`}:e.invocationsRemaining<=0&&e.invocationsLimit>0?{allowed:!1,message:`Daily invocation limit reached (${e.invocationsLimit}/${e.invocationsLimit}). Resets at 00:00 UTC.`}:{allowed:!0}:{allowed:!0}}catch{return{allowed:!0}}}extractTierFromJwt(a){try{const e=a.split(".");if(e.length!==3)return s;const i=e[1],t=Buffer.from(i,"base64url").toString("utf8"),c=JSON.parse(t).tier;return c&&l.has(c)?c:s}catch{return s}}buildUpgradeMessage(a,e,i){return`The *${a} command requires ${i.toUpperCase()} plan. Your current plan: ${e.toUpperCase()}. Upgrade: https://neocortex.sh/portal/dashboard/plans`}getQuotaCacheKey(){const e=new Date().toISOString().slice(0,10);return`${b}${e}`}}export{u as CLIENT_PREFLIGHT_COMMAND_REGISTRY,R as TierAwareClient,h as normalizeCommandToken,_ as resolveClientPreFlightTrigger};
|
|
@@ -79,12 +79,10 @@ export declare function persistYoloopFromResponse(metadata: Record<string, unkno
|
|
|
79
79
|
* Epic P125.03 -- Post-response hook: persist server-migrated state back
|
|
80
80
|
* to `.neocortex/state.json` via atomic temp+rename.
|
|
81
81
|
*
|
|
82
|
-
* Triggered when `metadata.stateMutated === true
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
* v1 payload back via metadata. This hook writes that payload verbatim to
|
|
87
|
-
* the client filesystem.
|
|
82
|
+
* Triggered when `metadata.stateMutated === true`. Complete canonical
|
|
83
|
+
* migrations use full replacement. Inline-yolo materialization uses a bounded
|
|
84
|
+
* merge over a freshly-read full local state because its request snapshot is
|
|
85
|
+
* normally projected and can never be a safe replacement payload.
|
|
88
86
|
*
|
|
89
87
|
* P101 ADR preserved: the server NEVER touches client filesystem -- the
|
|
90
88
|
* mutation is computed server-side and persisted client-side. The hook is
|
|
@@ -95,11 +93,16 @@ export declare function persistYoloopFromResponse(metadata: Record<string, unkno
|
|
|
95
93
|
* on crash mid-write. Mirrors `YoloopClientStateStore.writeState()`
|
|
96
94
|
* pattern.
|
|
97
95
|
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
96
|
+
* Migration filesystem failures remain fail-soft. Unsafe/partial replacement
|
|
97
|
+
* payloads and inline materialization failures return `blocking: true` so the
|
|
98
|
+
* invoke boundary can fail closed.
|
|
101
99
|
*/
|
|
102
|
-
export
|
|
100
|
+
export interface StateWritebackResult {
|
|
101
|
+
readonly applied: boolean;
|
|
102
|
+
readonly blocking: boolean;
|
|
103
|
+
readonly reasonCode: string;
|
|
104
|
+
}
|
|
105
|
+
export declare function persistMigratedStateFromResponse(metadata: Record<string, unknown> | undefined, projectRoot: string): Promise<StateWritebackResult>;
|
|
103
106
|
/**
|
|
104
107
|
* P120.04: lazy-loaded discovery hook wrapper.
|
|
105
108
|
*
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
import{YoloopClientStateStore as
|
|
2
|
-
`);return}}async function
|
|
3
|
-
`)}}
|
|
4
|
-
`)}catch(
|
|
5
|
-
`)}}async function
|
|
1
|
+
import{YoloopClientStateStore as A}from"./yoloop-client-state-store.js";import{isYoloopInvocation as N}from"./target-normalization.js";function I(e){return N(e)}const D=/^\s*\*?(yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i;function G(e){if(typeof e.args!="string"||e.args.length===0)return;const t=e.args.match(D);if(!t)return;const r=t[0];if(e.args.slice(r.length).trim()!=="")return;let i=!1;try{const l=require("node:fs"),a=require("node:path").join(e.projectRoot,"docs","epics");i=l.statSync(a).isDirectory()}catch(l){const p=l instanceof Error?l.message:String(l);e.logger?.warn?.(`[Neocortex] Zero-config *yoloop hook (P121.05): could not stat docs/epics/: ${p}. Proceeding with raw args.`);return}i&&(e.args=`${r} @docs/epics/`,e.logger?.info?.("[Neocortex] Zero-config *yoloop (P121.05): auto-resolved empty args to @docs/epics/"))}async function H(e,t,r){if(I(e))try{return await new A(t).readAll(r)}catch(o){process.stderr.write(`[yoloop] Failed to read local state: ${o.message}. Continuing without state.
|
|
2
|
+
`);return}}async function K(e,t,r){if(!e)return;const o=e.yoloopStateUpdate;if(!(!o||!Array.isArray(o.operations)||o.operations.length===0))try{await new A(t).applyUpdate(o,r)}catch(i){const l=i.message??String(i);process.stderr.write(`[yoloop] Failed to persist state: ${l}. Your next *yoloop may repeat or skip an operation. Run *yoloop again to retry.
|
|
3
|
+
`)}}function s(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function E(e){return s(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 O(e){const t={...e};return delete t.scope,delete t.stateSummary,delete t.graphRetrieval,delete t.runnerBootstrap,delete t.projectEvidence,delete t.continuity,delete t.implementCheckpoint,t}function T(e){return typeof e=="string"&&["done","completed","merged"].includes(e.trim().toLowerCase())}async function M(e,t){const r=e.syntheticStory;if(!s(r))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-missing"};const o=r.storyId,i=r.storyPath,l=r.deterministicKey,p=r.storyContent;if(typeof o!="string"||!/^P\d+(?:\.\d+){2}$/.test(o)||typeof i!="string"||i!==`docs/stories/${o}.story.md`||typeof l!="string"||!/^[a-f0-9]{16}$/.test(l)||typeof p!="string"||p.length===0||p.length>131072||r.publicSafe!==!0||r.sanitized!==!0)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-invalid"};const a=await import("node:fs/promises"),u=await import("node:path"),k=await import("node:crypto"),w=u.join(t,".neocortex"),b=u.join(w,"state.json"),f=u.join(t,...i.split("/"));let S;try{S=await a.readFile(b,"utf8")}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-missing"}}let d;try{d=JSON.parse(S)}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-corrupt"}}if(!s(d)||!s(d.stories)||!s(d.epics)||E(d))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-not-full"};const n=d.stories[o];if(n!==void 0&&(!s(n)||n.epic_id!=="P174"||n.story_file!==i||!s(n.inlineYolo)||n.inlineYolo.deterministicKey!==l))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-conflict"};const y=d.epics.P174;if(y!==void 0&&(!s(y)||y.id!==void 0&&y.id!=="P174"||!Array.isArray(y.stories)))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-conflict"};const C=s(y)?y:{},g=Array.isArray(C.stories)?C.stories:[];if(g.some(c=>typeof c!="string")||new Set(g).size!==g.length)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-story-list-invalid"};for(const c of g){const h=d.stories[c];if(!s(h)||h.id!==c||h.epic_id!=="P174")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-ownership-conflict"}}try{const c=await a.readFile(f,"utf8"),h=c.includes(`id: ${o}`)&&c.includes(`synthetic_key: ${l}`);if(c!==p&&!h)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-conflict"}}catch(c){if(c.code!=="ENOENT")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-unreadable"}}const m=g.includes(o)?[...g]:[...g,o],P={...d.stories,[o]:{...s(n)?n:{},id:o,epic_id:"P174",title:"Synthetic inline USER STORY for yolo",status:s(n)&&typeof n.status=="string"?n.status:"backlog",steps_completed:s(n)&&Array.isArray(n.steps_completed)?n.steps_completed:[],last_step:s(n)?n.last_step??null:null,branch_name:s(n)?n.branch_name??null:null,story_file:i,source:"inline-yolo-materialization",inlineYolo:{...s(n)&&s(n.inlineYolo)?n.inlineYolo:{},schemaVersion:1,deterministicKey:l,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0}}},j=m.filter(c=>s(P[c])&&T(P[c].status)).length,$=s(d.inlineYolo)?d.inlineYolo:{},F=s($.materializations)?$.materializations:{},R=O({...d,stories:P,epics:{...d.epics,P174:{...C,id:"P174",status:j===m.length&&m.length>0?"done":"in-progress",stories:m,total_stories:m.length,completed_stories:j,...j===m.length&&m.length>0?{}:{completed_at:null}}},inlineYolo:{...$,schemaVersion:1,materializations:{...F,[o]:{schemaVersion:1,storyId:o,storyPath:i,deterministicKey:l,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0,pipelineTrigger:`*yolo @${i}`,reasonCodes:Array.isArray(r.reasonCodes)?r.reasonCodes:[]}}},last_updated:new Date().toISOString()}),_=`${Date.now()}-${k.randomBytes(6).toString("hex")}`,z=u.join(w,`state.json.tmp.${_}`),x=`${f}.tmp.${_}`,v=u.join(w,`state.json.backup-${new Date().toISOString().replace(/[:.]/g,"-")}`);let Y=!1;try{await a.mkdir(w,{recursive:!0}),await a.mkdir(u.dirname(f),{recursive:!0});try{await a.access(f)}catch{await a.writeFile(x,p,{encoding:"utf8",flag:"wx"}),await a.rename(x,f),Y=!0}return await a.copyFile(b,v),await a.writeFile(z,JSON.stringify(R,null,2),{encoding:"utf8",flag:"wx"}),await a.rename(z,b),process.stderr.write(`[Neocortex] inline yolo story materialized with bounded full-state merge; story=${o}; backup=${u.basename(v)}.
|
|
4
|
+
`),{applied:!0,blocking:!1,reasonCode:"inline-yolo-materialized"}}catch(c){await Promise.allSettled([a.unlink(z),a.unlink(x)]),Y&&await a.unlink(f).catch(()=>{});const h=c.message??String(c);return process.stderr.write(`[Neocortex] inline yolo materialization failed: ${h}.
|
|
5
|
+
`),{applied:!1,blocking:!0,reasonCode:"inline-yolo-persistence-failed"}}}async function L(e,t){if(!e||e.stateMutated!==!0)return{applied:!1,blocking:!1,reasonCode:"state-writeback-not-requested"};if(e.stateMutationStrategy==="merge-inline-yolo-v1"||e.stateMutationReason==="inline-yolo-materialized-synthetic-story")return M(e,t);const r=e.migratedState;if(!r||typeof r!="object"||Array.isArray(r))return{applied:!1,blocking:!1,reasonCode:"state-writeback-payload-missing"};if(E(r))return process.stderr.write(`[Neocortex] Refused projected/partial state replacement; canonical state was not modified.
|
|
6
|
+
`),{applied:!1,blocking:!0,reasonCode:"state-writeback-partial-rejected"};try{const o=await import("node:fs/promises"),i=await import("node:path"),l=await import("node:crypto"),p=i.join(t,".neocortex"),a=i.join(p,"state.json"),u=i.join(p,`state.json.backup-${new Date().toISOString().replace(/[:.]/g,"-")}`),k=i.join(p,`state.json.tmp.${l.randomBytes(6).toString("hex")}`);await o.mkdir(p,{recursive:!0});try{await o.copyFile(a,u)}catch(f){if(f?.code!=="ENOENT")throw f}const w=O(r),b=JSON.stringify(w,null,2);return await o.writeFile(k,b,"utf8"),await o.rename(k,a),process.stderr.write(`[Neocortex P125.03] state.json auto-migrated to canonical v1 schema by server. Legacy planning.* fields converted to epics{} + stories{}; backup=${i.basename(u)}.
|
|
7
|
+
`),{applied:!0,blocking:!1,reasonCode:"state-writeback-applied"}}catch(o){const i=o.message??String(o);return process.stderr.write(`[Neocortex P125.03] Failed to persist auto-migrated state: ${i}. Your next invoke will retry (server runs migrate idempotently). If the warning persists, run \`neocortex invoke "*migrate-state --apply"\` manually.
|
|
8
|
+
`),{applied:!1,blocking:!1,reasonCode:"state-writeback-failed-soft"}}}async function J(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(t){const r=t instanceof Error?t.message:String(t);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 U(e){if(!e.featureFlag)return{applied:!1,reason:"flag_off"};try{return await(await import("../graph-retrieval/pre-command-hook.js")).runGraphRetrievalHook(e)}catch(t){const r=t instanceof Error?t.message:String(t);return e.logger?.warn?.(`[neocortex] graph retrieval hook (lazy load) failed: ${r}. Proceeding without enrichment.`),{applied:!1,reason:"hook_error",warning:r}}}export{I as isYoloopTrigger,G as maybeAutoResolveYoloopArgs,J as maybeRunDiscoveryHook,U as maybeRunGraphRetrievalHook,L as persistMigratedStateFromResponse,K as persistYoloopFromResponse,H as readYoloopForRequest};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const me=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"])})}),E=Object.freeze([/^epic-(P?\d+(?:\.\d+)?)\.md$/i,/^EPIC-(\d+)(?:[-_].*)?\.md$/,/^epic-([a-z0-9][a-z0-9_-]*)\.md$/i]),j=Object.freeze([/^(P?\d+\.\d+(?:\.\d+)?)\.story\.md$/i,/^story-(P?\d+\.\d+)\.md$/i,/^EPIC-(\d+)\.STORY-(\d+)\.md$/]),x=Object.freeze([".archive","_archive","_archives","_drafts","archive","archives","archived","drafts"]),A=/^---\s*\n([\s\S]*?)\n---/;function w(t,e){const i=new RegExp(`^${e}:\\s*(.+?)\\s*$`,"mi"),n=t.match(i);if(!n)return;let a=n[1].trim();return(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),a||void 0}function M(t){if(typeof t!="string"||t.length===0)return{};const e=t.match(A);if(!e)return{};const i=e[1];return{id:w(i,"id"),title:w(i,"title"),status:w(i,"status"),epic_id:w(i,"epic_id"),depends_on:Q(i),files_to_modify:R(i,"files_to_modify"),total_stories:D(w(i,"total_stories"))}}const C=32,Y=4096,G=/^\s*\*\*([^*\r\n]+?):\*\*\s*(.*?)\s*$/,B=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 W(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 D(t){if(t===void 0||!/^\d{1,5}$/.test(t.trim()))return;const e=Number(t);return Number.isSafeInteger(e)?e:void 0}function H(t){const e=W(t).toLowerCase().replace(/[_\s]+/g,"-"),n={planned:"planning",complete:"completed",closed:"done",finished:"done"}[e]??e;return B.has(n)?n:void 0}function U(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 Z(t){const e=t.find(a=>/^#\s+\S/.test(a));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 v(t,e,i,n){const a=[...new Set(t.map(W).filter(Boolean))];if(a.length>1){n.push(`legacy metadata ambiguous for '${e}' in '${i}': conflicting values ignored`);return}return a[0]}function X(t,e){const i=[],n=[],a=t.slice(0,Y).split(/\r?\n/,C);for(const d of a){if(n.length>0&&(/^\s*---\s*$/.test(d)||/^##\s+/.test(d)))break;n.push(d)}const o=new Map;for(const d of n){const u=d.match(G);if(!u)continue;const m=U(u[1]);if(!m)continue;const h=o.get(m)??[];h.push(u[2]),o.set(m,h)}const f=v(o.get("id")??[],"id",e,i),l=v(o.get("title")??[],"title",e,i),g=v(o.get("status")??[],"status",e,i),_=v(o.get("total_stories")??[],"total_stories",e,i),p=g===void 0?void 0:H(g);g!==void 0&&p===void 0&&i.push(`legacy metadata status unrecognized in '${e}': value ignored`);const y=D(_);_!==void 0&&y===void 0&&i.push(`legacy metadata total_stories invalid in '${e}': value ignored`);const b=f&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(f)?f:void 0;f!==void 0&&b===void 0&&i.push(`legacy metadata id invalid in '${e}': value ignored`);const r=Z(n),s=l??r;return{metadata:{...b?{id:b}:{},...s?{title:s.slice(0,200)}:{},...p?{status:p}:{},...y!==void 0?{total_stories:y}:{}},source:"legacy-metadata",warnings:Object.freeze(i)}}function q(t){return/^[A-Za-z0-9._-]{1,160}$/.test(t)?t:"markdown-target.md"}function K(t){return new TextEncoder().encode(t).length}function V(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 a=i.match(/^[A-Za-z0-9_-]+:\s*(.*?)\s*$/);if(!a)return!0;const o=a[1].trim();if(e=o.length===0,o.startsWith('"')&&!o.endsWith('"')||o.startsWith("'")&&!o.endsWith("'"))return!0}return!1}function J(t,e,i){const n=q(e),a=t.match(A);if(!a)return Object.freeze([`metadata-frontmatter reason=frontmatter-malformed file='${n}': repair the bounded leading YAML envelope; source content omitted`]);const o=a[1];return K(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`]):V(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 F(t,e){if(/^---(?:\s*\r?\n|\s*$)/.test(t)){const i=M(t);return{metadata:i,source:"frontmatter",warnings:J(t,e,i)}}return typeof t!="string"||t.length===0?{metadata:{},source:"none",warnings:Object.freeze([])}:X(t,e)}function L(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 Q(t){return R(t,"depends_on")}function R(t,e){const i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=t.match(new RegExp(`^${i}:[ \\t]*(.+?)[ \\t]*$`,"mi"))?.[1]?.trim();if(a!==void 0){const _=(a.startsWith("[")&&a.endsWith("]")?a.slice(1,-1).split(","):[a]).map(L).filter(p=>typeof p=="string"&&p.length>0);return _.length>0?Object.freeze(_):void 0}const o=t.split(/\r?\n/),f=[];let l=!1;for(const g of o){if(!l){new RegExp(`^${i}:\\s*$`,"i").test(g.trim())&&(l=!0);continue}if(/^[A-Za-z0-9_-]+:\s*/.test(g))break;const _=g.match(/^\s*-\s*(.+?)\s*$/);if(!_)continue;const p=L(_[1]);p&&f.push(p)}return f.length>0?Object.freeze(f):void 0}function N(t){return t.startsWith("_")||t.startsWith(".")}function ee(t){return x.includes(t)}async function ge(){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 te(t,e){let i=!1,n=null,a=null;for(let o=0;o<E.length;o++){const f=E[o],l=t.match(f);if(l){i=!0,n=l[1],a=o===2?"filename-slug":"filename-canonical";break}}return i?e.id&&e.id.length>0?{id:e.id,source:"frontmatter"}:{id:n,source:a}:null}function ie(t){for(const e of E){const i=t.match(e);if(i)return i[1]}return null}function O(t){const e=t.trim();return/^\d+(?:\.\d+)*$/i.test(e)?`P${e}`.toUpperCase():e.toUpperCase()}function ne(t){const e=O(t);return/^P\d+(?:\.\d+)?$/i.test(e)?`epic-${e}.md`:`epic-${t}.md`}function se(t){const e=O(t);return/^P\d+\.\d+(?:\.\d+)?$/i.test(e)?`${e}.story.md`:`${t}.story.md`}function P(t,e){return!t||!e?!1:O(t)!==O(e)}function re(t,e,i){return`frontmatter/filename mismatch: epic '${t}' has frontmatter id '${e}' but filename implies '${i}'. Repair by using generated canonical '${ne(e)}' or changing frontmatter id to '${i}'.`}function oe(t,e,i){return`frontmatter/filename mismatch: story '${t}' has frontmatter id '${e}' but filename implies '${i}'. Repair by using generated canonical '${se(e)}' or changing frontmatter id to '${i}'.`}function ae(t){let e=t.match(j[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(j[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(j[2]),e){const i=e[1],n=e[2];return{id:`${i}.${n}`,epic_id_hint:i}}return null}function ce(t,e){return e.join(t,"..","stories")}function he(t,e){const i=[],n=[],a=[],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 r of f){const s=e.join(t,r);if(N(r)){n.push(`${r}: ignored (draft or hidden prefix)`);continue}if(e.isDirectory(s)){if(ee(r)){n.push(`${r}: ignored subdirectory`);continue}n.push(`${r}: subdirectory not recursed`);continue}if(!r.endsWith(".md"))continue;if(!E.some(S=>S.test(r))){n.push(`${r}: did not match any EPIC_FILE_PATTERNS`);continue}const d=e.readFile(s),u=F(d,r);i.push(...u.warnings);const m=u.metadata,h=ie(r);m.id&&P(m.id,h)&&i.push(u.source==="frontmatter"?re(r,m.id,h):`legacy metadata/filename mismatch: epic '${r}' id does not match its filename`),l.push({filename:r,fullPath:s,metadata:m,metadataSource:u.source})}const g=new Map,_=[];for(const r of l){const s=te(r.filename,r.metadata);if(s===null){n.push(`${r.filename}: id resolution returned null`);continue}let c=s.id;const d=c,u=g.get(d)??0;u>0&&(c=`${d}-${u+1}`,i.push(`epic ID collision: '${d}' resolved to '${c}' for ${r.filename}`)),g.set(d,u+1),_.push({candidate:r,finalId:c,idSource:r.metadataSource==="legacy-metadata"&&r.metadata.id?"legacy-metadata":s.source})}const p=new Map,y=ce(t,e);if(e.isDirectory(y)){const r=[...e.readdir(y)].sort();for(const s of r){if(N(s)||!s.endsWith(".md"))continue;const c=e.join(y,s);if(e.isDirectory(c))continue;const d=ae(s);if(!d)continue;const u=e.readFile(c),m=F(u,s);i.push(...m.warnings);const h=m.metadata;h.id&&P(h.id,d.id)&&i.push(m.source==="frontmatter"?oe(s,h.id,d.id):`legacy metadata/filename mismatch: story '${s}' id does not match its filename`);const S=h.epic_id??d.epic_id_hint;if(!S){i.push(`story '${s}' has no epic_id (frontmatter or filename pattern)`);continue}const k=Object.freeze({id:d.id,epic_id:S,filename:s,path:c,...h.title?{title:h.title}:{},...h.status?{status:h.status}:{},...h.depends_on?{depends_on:h.depends_on}:{},...h.files_to_modify?{files_to_modify:h.files_to_modify}:{}});p.has(S)||p.set(S,[]),p.get(S).push(k)}}for(const r of _){const s=p.get(r.finalId)??[],c=Object.freeze({id:r.finalId,filename:r.candidate.filename,path:r.candidate.fullPath,...r.candidate.metadata.title?{title:r.candidate.metadata.title}:{},...r.candidate.metadata.status?{status:r.candidate.metadata.status}:{},...r.candidate.metadata.total_stories!==void 0?{total_stories:r.candidate.metadata.total_stories}:{},...r.candidate.metadata.depends_on?{depends_on:r.candidate.metadata.depends_on}:{},source:"discovered",discovered_at:o,stories:Object.freeze([...s]),t:r.idSource,e:r.candidate.metadataSource});a.push(c)}const b=new Set(a.map(r=>r.id));for(const[r,s]of p.entries())if(!b.has(r))for(const c of s)i.push(`orphan story '${c.filename}' references unknown epic '${r}'`);return Object.freeze({epics:Object.freeze(a),warnings:Object.freeze(i),skipped:Object.freeze(n)})}function de(t){return I(t)}function I(t){const e=ue(t);return e==="done"||e==="completed"||e==="merged"}function z(t){return I(t)}function ue(t){return typeof t=="string"?t.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}function T(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function $(t){throw new Error(`epic-aggregate-writer:${t}`)}function fe(t){const e=[],i=new Set;for(const n of t)(typeof n!="string"||n.length===0)&&$("epic_aggregate_story_ref_invalid"),i.has(n)&&$("epic_aggregate_story_ref_duplicate"),i.add(n),e.push(n);return e}function le(t,e,i){const n=i[e];return n===void 0&&$("epic_aggregate_story_missing"),T(n)||$("epic_aggregate_story_not_object"),n.id!==e&&$("epic_aggregate_story_id_conflict"),n.epic_id!==t&&$("epic_aggregate_story_epic_conflict"),n}function pe(t,e,i,n,a){const o=e[t];T(o)||$("epic_aggregate_epic_not_object"),o.id!==t&&$("epic_aggregate_epic_id_conflict"),Array.isArray(o.stories)||$("epic_aggregate_story_list_not_array");const f=fe(o.stories),l=f.length,g=f.filter(s=>I(le(t,s,i).status)).length,_=a?.total_stories,p=a?.e==="legacy-metadata"&&z(o.status),y=p?_??l:l>0?l:_??0,b=p||l===0&&y>0&&z(o.status)?y:g,r=l>0&&g===l;z(o.status)&&!p&&!r&&l>0&&$("epic_aggregate_terminal_incomplete_conflict"),o.total_stories=y,o.completed_stories=b,!z(o.status)&&r&&(o.status="done",(o.completed_at===void 0||o.completed_at===null)&&(o.completed_at=n))}function _e(t,e,i){const n=t??{};(!n.epics||typeof n.epics!="object")&&(n.epics={}),(!n.stories||typeof n.stories!="object")&&(n.stories={});const a=n.epics,o=n.stories,f=[],l=[],g=new Set,_=new Map;let p=0;const y=i?.forceOverwrite===!0,b=i?.nowIso??new Date().toISOString(),r=new Set;for(const s of e.epics)r.add(s.id),_.set(s.id,s);for(const s of e.epics){const c=a[s.id];if(c&&c.source==="create-epic"&&!y){l.push({id:s.id,reason:"create-epic source preserved (defense)"});continue}if(c&&c.source==="discovered"&&!y){const u=c;u.depends_on=s.depends_on??[],u.stories=s.stories.map(m=>m.id),s.title!==void 0&&(u.title=s.title),s.status!==void 0&&!z(u.status)&&(u.status=s.status),g.add(s.id);continue}const d={id:s.id,title:s.title??"",status:s.status??"planning",source:"discovered",discovered_at:b,merged_at:b,stories:s.stories.map(u=>u.id),depends_on:s.depends_on??[]};a[s.id]=d,g.add(s.id),f.push(s.id)}for(const s of e.epics)for(const c of s.stories){const d=o[c.id];if(d&&d.source==="create-epic"&&!y){l.push({id:c.id,reason:"create-epic source preserved (defense, story)"});continue}if(d&&de(d.status)&&!y){const m=d;m.depends_on=c.depends_on??[],m.files_to_modify=c.files_to_modify??[];continue}if(d&&d.source==="discovered"&&!y){const m=d;m.depends_on=c.depends_on??[],m.files_to_modify=c.files_to_modify??[];continue}const u={id:c.id,epic_id:c.epic_id,title:c.title??"",status:c.status??"backlog",source:"discovered",discovered_at:b,depends_on:c.depends_on??[],files_to_modify:c.files_to_modify??[]};o[c.id]=u,p++}for(const s of g)pe(s,a,o,b,_.get(s));return{state:n,added:Object.freeze([...f]),skipped:Object.freeze([...l]),storiesAdded:p}}export{E as EPIC_FILE_PATTERNS,me as GENERATED_NAMING_CONTRACT,j as STORY_FILE_PATTERNS,ge as buildDefaultDiscoveryFs,he as discoverEpicsFromDir,te as getEpicIdFromDescriptor,_e as mergeDiscoveredIntoState};
|
|
1
|
+
const me=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"])})}),E=Object.freeze([/^epic-(P?\d+(?:\.\d+)?)\.md$/i,/^EPIC-(\d+)(?:[-_].*)?\.md$/,/^epic-([a-z0-9][a-z0-9_-]*)\.md$/i]),j=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"]),A=/^---\s*\n([\s\S]*?)\n---/;function w(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 M(t){if(typeof t!="string"||t.length===0)return{};const e=t.match(A);if(!e)return{};const i=e[1];return{id:w(i,"id"),title:w(i,"title"),status:w(i,"status"),epic_id:w(i,"epic_id"),depends_on:Q(i),files_to_modify:R(i,"files_to_modify"),total_stories:D(w(i,"total_stories"))}}const C=32,G=4096,Y=/^\s*\*\*([^*\r\n]+?):\*\*\s*(.*?)\s*$/,B=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 W(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 D(t){if(t===void 0||!/^\d{1,5}$/.test(t.trim()))return;const e=Number(t);return Number.isSafeInteger(e)?e:void 0}function H(t){const e=W(t).toLowerCase().replace(/[_\s]+/g,"-"),n={planned:"planning",complete:"completed",closed:"done",finished:"done"}[e]??e;return B.has(n)?n:void 0}function U(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 Z(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 v(t,e,i,n){const c=[...new Set(t.map(W).filter(Boolean))];if(c.length>1){n.push(`legacy metadata ambiguous for '${e}' in '${i}': conflicting values ignored`);return}return c[0]}function X(t,e){const i=[],n=[],c=t.slice(0,G).split(/\r?\n/,C);for(const d of c){if(n.length>0&&(/^\s*---\s*$/.test(d)||/^##\s+/.test(d)))break;n.push(d)}const o=new Map;for(const d of n){const g=d.match(Y);if(!g)continue;const m=U(g[1]);if(!m)continue;const u=o.get(m)??[];u.push(g[2]),o.set(m,u)}const l=v(o.get("id")??[],"id",e,i),f=v(o.get("title")??[],"title",e,i),h=v(o.get("status")??[],"status",e,i),_=v(o.get("total_stories")??[],"total_stories",e,i),p=h===void 0?void 0:H(h);h!==void 0&&p===void 0&&i.push(`legacy metadata status unrecognized in '${e}': value ignored`);const y=D(_);_!==void 0&&y===void 0&&i.push(`legacy metadata total_stories invalid in '${e}': value ignored`);const b=l&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(l)?l:void 0;l!==void 0&&b===void 0&&i.push(`legacy metadata id invalid in '${e}': value ignored`);const r=Z(n),s=f??r;return{metadata:{...b?{id:b}:{},...s?{title:s.slice(0,200)}:{},...p?{status:p}:{},...y!==void 0?{total_stories:y}:{}},source:"legacy-metadata",warnings:Object.freeze(i)}}function q(t){return/^[A-Za-z0-9._-]{1,160}$/.test(t)?t:"markdown-target.md"}function K(t){return new TextEncoder().encode(t).length}function V(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 l=n[1].trim();if(l.startsWith('"')&&!l.endsWith('"')||l.startsWith("'")&&!l.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 J(t,e,i){const n=q(e),c=t.match(A);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 K(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`]):V(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 F(t,e){if(/^---(?:\s*\r?\n|\s*$)/.test(t)){const i=M(t);return{metadata:i,source:"frontmatter",warnings:J(t,e,i)}}return typeof t!="string"||t.length===0?{metadata:{},source:"none",warnings:Object.freeze([])}:X(t,e)}function L(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 Q(t){return R(t,"depends_on")}function R(t,e){const i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=t.match(new RegExp(`^${i}:[ \\t]*(.+?)[ \\t]*$`,"mi"))?.[1]?.trim();if(c!==void 0){const _=(c.startsWith("[")&&c.endsWith("]")?c.slice(1,-1).split(","):[c]).map(L).filter(p=>typeof p=="string"&&p.length>0);return _.length>0?Object.freeze(_):void 0}const o=t.split(/\r?\n/),l=[];let f=!1;for(const h of o){if(!f){new RegExp(`^${i}:\\s*$`,"i").test(h.trim())&&(f=!0);continue}if(/^[A-Za-z0-9_-]+:\s*/.test(h))break;const _=h.match(/^\s*-\s*(.+?)\s*$/);if(!_)continue;const p=L(_[1]);p&&l.push(p)}return l.length>0?Object.freeze(l):void 0}function N(t){return t.startsWith("_")||t.startsWith(".")}function ee(t){return k.includes(t)}async function ge(){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 te(t,e){let i=!1,n=null,c=null;for(let o=0;o<E.length;o++){const l=E[o],f=t.match(l);if(f){i=!0,n=f[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 ie(t){for(const e of E){const i=t.match(e);if(i)return i[1]}return null}function O(t){const e=t.trim();return/^\d+(?:\.\d+)*$/i.test(e)?`P${e}`.toUpperCase():e.toUpperCase()}function ne(t){const e=O(t);return/^P\d+(?:\.\d+)?$/i.test(e)?`epic-${e}.md`:`epic-${t}.md`}function se(t){const e=O(t);return/^P\d+\.\d+(?:\.\d+)?$/i.test(e)?`${e}.story.md`:`${t}.story.md`}function P(t,e){return!t||!e?!1:O(t)!==O(e)}function re(t,e,i){return`frontmatter/filename mismatch: epic '${t}' has frontmatter id '${e}' but filename implies '${i}'. Repair by using generated canonical '${ne(e)}' or changing frontmatter id to '${i}'.`}function oe(t,e,i){return`frontmatter/filename mismatch: story '${t}' has frontmatter id '${e}' but filename implies '${i}'. Repair by using generated canonical '${se(e)}' or changing frontmatter id to '${i}'.`}function ce(t){let e=t.match(j[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(j[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(j[2]),e){const i=e[1],n=e[2];return{id:`${i}.${n}`,epic_id_hint:i}}return null}function ae(t,e){return e.join(t,"..","stories")}function he(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 l=[...e.readdir(t)].sort(),f=[];for(const r of l){const s=e.join(t,r);if(N(r)){n.push(`${r}: ignored (draft or hidden prefix)`);continue}if(e.isDirectory(s)){if(ee(r)){n.push(`${r}: ignored subdirectory`);continue}n.push(`${r}: subdirectory not recursed`);continue}if(!r.endsWith(".md"))continue;if(!E.some(S=>S.test(r))){n.push(`${r}: did not match any EPIC_FILE_PATTERNS`);continue}const d=e.readFile(s),g=F(d,r);i.push(...g.warnings);const m=g.metadata,u=ie(r);m.id&&P(m.id,u)&&i.push(g.source==="frontmatter"?re(r,m.id,u):`legacy metadata/filename mismatch: epic '${r}' id does not match its filename`),f.push({filename:r,fullPath:s,metadata:m,metadataSource:g.source})}const h=new Map,_=[];for(const r of f){const s=te(r.filename,r.metadata);if(s===null){n.push(`${r.filename}: id resolution returned null`);continue}let a=s.id;const d=a,g=h.get(d)??0;g>0&&(a=`${d}-${g+1}`,i.push(`epic ID collision: '${d}' resolved to '${a}' for ${r.filename}`)),h.set(d,g+1),_.push({candidate:r,finalId:a,idSource:r.metadataSource==="legacy-metadata"&&r.metadata.id?"legacy-metadata":s.source})}const p=new Map,y=ae(t,e);if(e.isDirectory(y)){const r=[...e.readdir(y)].sort();for(const s of r){if(N(s)||!s.endsWith(".md"))continue;const a=e.join(y,s);if(e.isDirectory(a))continue;const d=ce(s);if(!d)continue;const g=e.readFile(a),m=F(g,s);i.push(...m.warnings);const u=m.metadata;u.id&&P(u.id,d.id)&&i.push(m.source==="frontmatter"?oe(s,u.id,d.id):`legacy metadata/filename mismatch: story '${s}' id does not match its filename`);const S=u.epic_id??d.epic_id_hint;if(!S){i.push(`story '${s}' has no epic_id (frontmatter or filename pattern)`);continue}const x=Object.freeze({id:d.id,epic_id:S,filename:s,path:a,...u.title?{title:u.title}:{},...u.status?{status:u.status}:{},...u.depends_on?{depends_on:u.depends_on}:{},...u.files_to_modify?{files_to_modify:u.files_to_modify}:{}});p.has(S)||p.set(S,[]),p.get(S).push(x)}}for(const r of _){const s=p.get(r.finalId)??[],a=Object.freeze({id:r.finalId,filename:r.candidate.filename,path:r.candidate.fullPath,...r.candidate.metadata.title?{title:r.candidate.metadata.title}:{},...r.candidate.metadata.status?{status:r.candidate.metadata.status}:{},...r.candidate.metadata.total_stories!==void 0?{total_stories:r.candidate.metadata.total_stories}:{},...r.candidate.metadata.depends_on?{depends_on:r.candidate.metadata.depends_on}:{},source:"discovered",discovered_at:o,stories:Object.freeze([...s]),t:r.idSource,e:r.candidate.metadataSource});c.push(a)}const b=new Set(c.map(r=>r.id));for(const[r,s]of p.entries())if(!b.has(r))for(const a of s)i.push(`orphan story '${a.filename}' references unknown epic '${r}'`);return Object.freeze({epics:Object.freeze(c),warnings:Object.freeze(i),skipped:Object.freeze(n)})}function de(t){return I(t)}function I(t){const e=ue(t);return e==="done"||e==="completed"||e==="merged"}function z(t){return I(t)}function ue(t){return typeof t=="string"?t.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}function T(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function $(t){throw new Error(`epic-aggregate-writer:${t}`)}function fe(t){const e=[],i=new Set;for(const n of t)(typeof n!="string"||n.length===0)&&$("epic_aggregate_story_ref_invalid"),i.has(n)&&$("epic_aggregate_story_ref_duplicate"),i.add(n),e.push(n);return e}function le(t,e,i){const n=i[e];return n===void 0&&$("epic_aggregate_story_missing"),T(n)||$("epic_aggregate_story_not_object"),n.id!==e&&$("epic_aggregate_story_id_conflict"),n.epic_id!==t&&$("epic_aggregate_story_epic_conflict"),n}function pe(t,e,i,n,c){const o=e[t];T(o)||$("epic_aggregate_epic_not_object"),o.id!==t&&$("epic_aggregate_epic_id_conflict"),Array.isArray(o.stories)||$("epic_aggregate_story_list_not_array");const l=fe(o.stories),f=l.length,h=l.filter(s=>I(le(t,s,i).status)).length,_=c?.total_stories,p=c?.e==="legacy-metadata"&&z(o.status),y=p?_??f:f>0?f:_??0,b=p||f===0&&y>0&&z(o.status)?y:h,r=f>0&&h===f;z(o.status)&&!p&&!r&&f>0&&$("epic_aggregate_terminal_incomplete_conflict"),o.total_stories=y,o.completed_stories=b,!z(o.status)&&r&&(o.status="done",(o.completed_at===void 0||o.completed_at===null)&&(o.completed_at=n))}function _e(t,e,i){const n=t??{};(!n.epics||typeof n.epics!="object")&&(n.epics={}),(!n.stories||typeof n.stories!="object")&&(n.stories={});const c=n.epics,o=n.stories,l=[],f=[],h=new Set,_=new Map;let p=0;const y=i?.forceOverwrite===!0,b=i?.nowIso??new Date().toISOString(),r=new Set;for(const s of e.epics)r.add(s.id),_.set(s.id,s);for(const s of e.epics){const a=c[s.id],d=a;if(d&&(d.branch_mode==="epic"||typeof d.execution_branch=="string")){f.push({id:s.id,reason:"epic Git lifecycle preserved"});continue}if(a&&a.source==="create-epic"&&!y){f.push({id:s.id,reason:"create-epic source preserved (defense)"});continue}if(a&&a.source==="discovered"&&!y){const m=a;m.depends_on=s.depends_on??[],m.stories=s.stories.map(u=>u.id),s.title!==void 0&&(m.title=s.title),s.status!==void 0&&!z(m.status)&&(m.status=s.status),h.add(s.id);continue}const g={id:s.id,title:s.title??"",status:s.status??"planning",source:"discovered",discovered_at:b,merged_at:b,stories:s.stories.map(m=>m.id),depends_on:s.depends_on??[]};c[s.id]=g,h.add(s.id),l.push(s.id)}for(const s of e.epics)for(const a of s.stories){const d=o[a.id],g=c[s.id];if(d&&g&&(g.branch_mode==="epic"||typeof g.execution_branch=="string")){f.push({id:a.id,reason:"story Git lifecycle preserved"});continue}if(d&&d.source==="create-epic"&&!y){f.push({id:a.id,reason:"create-epic source preserved (defense, story)"});continue}if(d&&de(d.status)&&!y){const u=d;u.depends_on=a.depends_on??[],u.files_to_modify=a.files_to_modify??[];continue}if(d&&d.source==="discovered"&&!y){const u=d;u.depends_on=a.depends_on??[],u.files_to_modify=a.files_to_modify??[];continue}const m={id:a.id,epic_id:a.epic_id,title:a.title??"",status:a.status??"backlog",source:"discovered",discovered_at:b,depends_on:a.depends_on??[],files_to_modify:a.files_to_modify??[]};o[a.id]=m,p++}for(const s of h)pe(s,c,o,b,_.get(s));return{state:n,added:Object.freeze([...l]),skipped:Object.freeze([...f]),storiesAdded:p}}export{E as EPIC_FILE_PATTERNS,me as GENERATED_NAMING_CONTRACT,j as STORY_FILE_PATTERNS,ge as buildDefaultDiscoveryFs,he as discoverEpicsFromDir,te as getEpicIdFromDescriptor,_e as mergeDiscoveredIntoState};
|