@ornexus/neocortex 4.60.22 → 4.60.24
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 +24 -24
- package/install.js +67 -10
- package/install.ps1 +39 -8
- package/install.sh +18 -6
- package/package.json +9 -3
- 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 +39 -26
- package/packages/client/dist/commands/invoke.js +56 -50
- 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/continuity/invoke-hooks.js +1 -1
- package/packages/client/dist/fs/atomic-state-replace.d.ts +16 -0
- package/packages/client/dist/fs/atomic-state-replace.js +1 -0
- package/packages/client/dist/generated/command-registry.generated.d.ts +51 -51
- 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-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/pre-command-hook.d.ts +11 -0
- package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -1
- 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/invocation/invoke-input.d.ts +9 -0
- package/packages/client/dist/invocation/invoke-input.js +1 -0
- 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/migrations/project-identity-capability.d.ts +13 -0
- package/packages/client/dist/migrations/project-identity-capability.js +1 -0
- package/packages/client/dist/migrations/project-identity.d.ts +41 -0
- package/packages/client/dist/migrations/project-identity.js +7 -0
- 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/state/invocation-shape.d.ts +9 -0
- package/packages/client/dist/state/invocation-shape.js +1 -0
- package/packages/client/dist/state/project-state-snapshot.d.ts +9 -3
- 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/state/structural-dag-projection.d.ts +24 -0
- package/packages/client/dist/state/structural-dag-projection.js +1 -0
- 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 +64 -65
- package/packages/shared/dist/generated/invocation-schema.generated.js +16 -24
- package/packages/shared/dist/invocation/index.d.ts +6 -2
- package/packages/shared/dist/invocation/index.js +5 -0
- package/packages/shared/dist/invocation/input-envelope.d.ts +37 -0
- package/packages/shared/dist/invocation/input-envelope.js +98 -0
- package/packages/shared/dist/invocation/project-identity-migration.d.ts +28 -0
- package/packages/shared/dist/invocation/project-identity-migration.js +83 -0
- package/packages/shared/dist/invocation/public-diagnostics.d.ts +87 -0
- package/packages/shared/dist/invocation/public-diagnostics.js +181 -0
- package/packages/shared/dist/invocation/state-projection.d.ts +21 -0
- package/packages/shared/dist/invocation/state-projection.js +1 -0
- package/packages/shared/dist/invocation/strict-effect-receipt.d.ts +12 -0
- package/packages/shared/dist/invocation/strict-effect-receipt.js +43 -0
- 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
|
-
const le=12,pe=16,h=["active","archived","rolled-back","synthetic","orphan"],n=(r,e,t={})=>({commandId:r,stateProjectionPolicy:e,...t}),P=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"),"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})}),L=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"}),N=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(r,e=120){if(typeof r!="string")return;const t=r.trim();if(t)return t.replace(/[^a-z0-9_.:-]+/gi,"_").slice(0,e)}function j(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function g(...r){const e=new Set,t=[];for(const i of r)for(const c of i??[]){const o=a(c,80);if(!(!o||e.has(o))&&(e.add(o),t.push(o),t.length>=16))return t}return t}function F(r){return r.trim().replace(/^@?\*/,"").replace(/^@/,"").toLowerCase()}function $(r){return r.trim().split(/\s+/,1)[0]??""}function D(r){const e=$(r);if(!e)return P.menu;const t=F(e),i=N[t]??L[t]??t;return P[i]??null}function Y(r,e,t,i="full-compatible",c=["full-state"]){return{kind:"full",commandId:t?.commandId??null,stateProjectionPolicy:t?.stateProjectionPolicy??null,projectionMode:i,trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:Object.keys(e.stories).length,includedEpicCount:Object.keys(e.epics).length,omittedStoryCount:0,omittedEpicCount:0,reason:"full-state",reasonCodes:g(c)}}function y(r,e,t,i="full-compatible",c=["full-state"]){const o=Y(r,e,t,i,c);return b({...e,scope:o},e,o)}function Z(r){const[e]=r.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(r){const e=r.match(/(?:^|[/@\s])([A-Z]?\d+(?:\.\d+)+)\.story\.md\b/i);return e?.[1]?e[1]:r.match(/(?:^|\s|@)([A-Z]?\d+(?:\.\d+)+)(?=$|\s)/i)?.[1]??null}function G(r){const e=r.trim(),t=e.search(/\s/);return t===-1?"":e.slice(t).trim()}function w(r){return G(r).split(/\s+/).map(e=>e.replace(/^@/,"").replace(/^['"]|['"]$/g,"")).filter(e=>e.length>0&&!e.startsWith("-"))}function fe(r){return w(r)[0]??null}function R(r,e){const i=r.replace(/^@/,"").replace(/^epic-/i,"").replace(/\.md$/i,""),c=[i,i.toUpperCase(),/^p\d+$/i.test(i)?`P${i.replace(/^p/i,"")}`:null,/^\d+$/.test(i)?`P${i}`:null].filter(o=>typeof o=="string"&&o.length>0);for(const o of c)if(e.epics[o])return o;return null}function U(r,e){const t=r.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);return t?.[1]?R(t[1],e):null}function k(r,e){const t=U(r,e);if(t)return t;for(const i of w(r)){if(/^[A-Z]?\d+(?:\.\d+)+$/i.test(i))continue;const c=R(i,e);if(c)return c}return null}function B(r,e){const t=k(r,e);if(t)return t;const i=e.yoloop,c=i?.state?.currentSession?.currentEpicId;if(typeof c=="string"&&e.epics[c])return c;const o=i?.lock?.currentEpicId??i?.lock?.epicId;return typeof o=="string"&&e.epics[o]?o:null}function I(r,e){if(typeof r.epic_id=="string"&&r.epic_id.length>0)return r.epic_id;const t=e.split(".").slice(0,-1).join(".");return t.length>0?t:null}function E(r){return typeof r=="string"&&["done","completed","merged","cancelled","canceled","abandoned"].includes(r.toLowerCase())}function S(r,e,t){if(t.has(r))return;const i=e.stories[r];if(!i)return;t.add(r);const c=i.depends_on;if(Array.isArray(c))for(const o of c)typeof o=="string"&&S(o,e,t)}function J(r,e,t){const i=new Set;S(r,t,i);const c=e.stories;if(Array.isArray(c))for(const s of c)typeof s=="string"&&t.stories[s]&&i.add(s);const o={};for(const s of i){const u=t.stories[s];u&&(o[s]=u)}return o}function C(r,e,t=[]){const i={};for(const c of t)e.epics[c]&&(i[c]=e.epics[c]);for(const[c,o]of Object.entries(r)){const s=I(o,c);s&&e.epics[s]&&(i[s]=e.epics[s])}return i}function A(r,e,t){if(t.has(r))return;const i=e.epics[r];if(!i)return;t.add(r);const c=i.depends_on;if(Array.isArray(c))for(const o of c)typeof o=="string"&&o.length>0&&A(o,e,t)}function K(r,e,t){const i=new Set;return A(r,t,i),C(e,t,[...i])}function W(r,e){const t=new Set,i=r.stories;if(Array.isArray(i))for(const o of i){if(typeof o!="string")continue;const s=e.stories[o];if(s){if(E(s.status)){t.add(o);continue}S(o,e,t)}}const c={};for(const o of t){const s=e.stories[o];s&&(c[o]=s)}return c}function V(r,e){const t=new Set,i=r.stories;if(Array.isArray(i))for(const o of i)typeof o=="string"&&S(o,e,t);const c={};for(const o of t){const s=e.stories[o];s&&(c[o]=s)}return c}function H(r){const e={};for(const[t,i]of Object.entries(r.epics))e[t]={id:a(i.id)??t,...a(i.status)?{status:a(i.status)}:{},...h.includes(i.lifecycle_classification)?{lifecycle_classification:i.lifecycle_classification}:{},...typeof i.total_stories=="number"&&Number.isFinite(i.total_stories)?{total_stories:i.total_stories}:{},...typeof i.completed_stories=="number"&&Number.isFinite(i.completed_stories)?{completed_stories:i.completed_stories}:{}};return e}function T(r){const e={};for(const t of Object.values(r)){const i=a(t.status,40)??"unknown";e[i]=(e[i]??0)+1}return e}function Q(r){const e=Object.fromEntries(h.map(t=>[t,0]));for(const t of Object.values(r)){const i=h.includes(t.lifecycle_classification)?t.lifecycle_classification:"active";e[i]=(e[i]??0)+1}return e}function q(r,e){if(!e)return!0;const t=r.epics[e];return t?!h.includes(t.lifecycle_classification)||t.lifecycle_classification==="active":!0}function M(r){for(const e of["last_updated","updated_at","completed_at","created_at","discovered_at"]){const t=r[e];if(typeof t!="string")continue;const i=Date.parse(t);if(Number.isFinite(i))return i}return 0}function X(r){return Object.entries(r.stories).map(([e,t])=>({id:e,story:t,timestamp:M(t)})).sort((e,t)=>t.timestamp-e.timestamp||e.id.localeCompare(t.id)).slice(0,12).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 ee(r){const e=r.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(i=>i!=null)?t:void 0}function te(r){const e=r.yoloop;if(!j(e))return;const t=j(e.state)?e.state:void 0,i=j(t?.currentSession)?t.currentSession:void 0,c=j(e.lock)?e.lock:void 0,o={...typeof e.active=="boolean"?{active:e.active}:{},currentEpicId:a(i?.currentEpicId??e.currentEpicId)??null,currentStoryId:a(i?.currentStoryId??e.currentStoryId)??null,sessionId:a(i?.sessionId??e.sessionId)??null,lockEpicId:a(c?.currentEpicId??c?.epicId)??null};return Object.keys(o).length>0?o:void 0}function re(r){const e=r.continuity;if(!j(e))return;const t=Array.isArray(e.reasonCodes)?e.reasonCodes.filter(i=>typeof i=="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:g(t)}:{}}}function ie(r,e,t){const i=a(e?.activeStoryId),c=a(e?.activeEpicId),o=a(e?.activeStepId),s=i&&r.stories[i]?I(r.stories[i],i):null;if((i||c||o)&&q(r,c??s))return{epicId:c??null,storyId:i??null,stepId:o??null};const u=a(t?.currentStoryId),l=a(t?.currentEpicId??t?.lockEpicId);if((u||l)&&q(r,l))return{epicId:l??null,storyId:u??null,stepId:null};const d=Object.entries(r.stories).map(([p,f])=>({id:p,story:f,timestamp:M(f)})).filter(({id:p,story:f})=>!E(f.status)&&q(r,I(f,p))).sort((p,f)=>f.timestamp-p.timestamp||p.id.localeCompare(f.id))[0];return d?{epicId:I(d.story,d.id),storyId:d.id,stepId:a(d.story.last_step??d.story.lastStep)??null}:{epicId:null,storyId:null,stepId:null}}function ce(r,e){const t=T(r.stories),i=T(r.epics),c=Q(r.epics),o=Object.values(r.epics).filter(m=>(h.includes(m.lifecycle_classification)?m.lifecycle_classification:"active")==="active"&&!E(m.status)).length,s=ee(r),u=te(r),l=re(r),d=ie(r,s,u),p=X(r),f=g(e.reasonCodes,["state-summary-attached","state-summary-bounded",`projection-${e.projectionMode??e.kind}`,e.stateProjectionPolicy?`policy-${e.stateProjectionPolicy}`:"policy-unknown",p.length>=12?"recent-stories-capped":"recent-stories-bounded",d.storyId||d.epicId?"active-ref-derived":"active-ref-empty",u?"yoloop-session-present":"yoloop-session-absent",l?"continuity-session-present":"continuity-session-absent"]);return{schemaVersion:1,totals:{stories:Object.keys(r.stories).length,epics:Object.keys(r.epics).length,storyStatus:t,epicStatus:i,epicLifecycle:c,activeEpics:o,blockedStories:t.blocked??0},active:d,blockedCount:t.blocked??0,recentStories:p,...s?{currentSession:s}:{},...u?{currentYoloopSession:u}:{},...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(r.epics).length,omittedStoryCount:e.omittedStoryCount,omittedEpicCount:e.omittedEpicCount,reason:e.reason},reasonCodes:f,publicSafe:!0}}function b(r,e,t){return{...r,stateSummary:ce(e,t)}}function oe(r,e,t){const i={};for(const o of Object.keys(e.epics))i[o]={id:o};const c={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"summary-only",trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:0,includedEpicCount:Object.keys(i).length,omittedStoryCount:Object.keys(e.stories).length,omittedEpicCount:0,reason:"epic-summary",reasonCodes:["epic-summary","stories-omitted","epic-stubs-only"]};return b({...e,stories:{},epics:i,scope:c},e,c)}function v(r,e,t,i=["summary-only","stories-omitted"]){const c=H(e),o={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"summary-only",trigger:r,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:g(i)};return b({...e,stories:{},epics:c,scope:o},e,o)}function O(r,e,t,i,c,o){const s=e.stories[i];if(!s)return y(r,e,t,c,[...o,"target-story-missing-full-state"]);const u=I(s,i);if(!u)return y(r,e,t,c,[...o,"target-epic-unresolved-full-state"]);const l=e.epics[u];if(!l)return y(r,e,t,c,[...o,"target-epic-missing-full-state"]);const d=J(i,l,e),p=C(d,e);if(!d[i]||!p[u])return y(r,e,t,c,[...o,"target-projection-incomplete-full-state"]);const f={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:u,targetStoryId:i,includedStoryCount:Object.keys(d).length,includedEpicCount:Object.keys(p).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(p).length),reason:"targeted-invocation",reasonCodes:g(o)};return b({...e,stories:d,epics:p,scope:f},e,f)}function z(r,e,t,i,c,o){const s=e.epics[i];if(!s)return y(r,e,t,c,[...o,"target-epic-missing-full-state"]);const u=V(s,e),l=C(u,e,[i]);if(!l[i])return y(r,e,t,c,[...o,"target-epic-projection-incomplete-full-state"]);const d={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:i,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:g(o)};return b({...e,stories:u,epics:l,scope:d},e,d)}function ne(r,e,t){const i=B(r,e);if(!i)return y(r,e,t,"structural-required",["yoloop-target-missing-full-state"]);const c=e.epics[i];if(!c)return y(r,e,t,"structural-required",["yoloop-target-epic-missing-full-state"]);const o=W(c,e),s=K(i,o,e);if(!s[i])return y(r,e,t,"structural-required",["yoloop-projection-incomplete-full-state"]);const u={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"structural-required",trigger:r,targetEpicId:i,targetStoryId:null,includedStoryCount:Object.keys(o).length,includedEpicCount:Object.keys(s).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(o).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(s).length),reason:"targeted-invocation",reasonCodes:["structural-required","yoloop-targeted"]};return b({...e,stories:o,epics:s,scope:u},e,u)}function se(r,e){const t={};for(const[i,c]of Object.entries(r.epics)){const o=Array.isArray(c.stories)?c.stories.filter(s=>typeof s=="string"&&e.has(s)):[];t[i]={id:a(c.id)??i,...a(c.status,40)?{status:a(c.status,40)}:{},...typeof c.total_stories=="number"&&Number.isFinite(c.total_stories)?{total_stories:c.total_stories}:{},...typeof c.completed_stories=="number"&&Number.isFinite(c.completed_stories)?{completed_stories:c.completed_stories}:{},...o.length>0?{stories:o}:{},...o.length>0&&Array.isArray(c.depends_on)?{depends_on:c.depends_on.filter(s=>typeof s=="string"&&s.length>0)}:{},...o.length>0&&(c.branch_mode==="epic"||c.branch_mode==="story")?{branch_mode:c.branch_mode}:{},...o.length>0&&typeof c.execution_branch=="string"?{execution_branch:c.execution_branch}:{},...o.length>0&&typeof c.origin_branch=="string"?{origin_branch:c.origin_branch}:{},...o.length>0&&(c.branch_lease===null||typeof c.branch_lease=="object")?{branch_lease:c.branch_lease}:{}}}return t}function ae(r){return r.stateSummary?.totals.stories??(r.scope?.includedStoryCount??Object.keys(r.stories).length)+(r.scope?.omittedStoryCount??0)}function ue(r){return r.stateSummary?.totals.epics??(r.scope?.includedEpicCount??Object.keys(r.epics).length)+(r.scope?.omittedEpicCount??0)}function de(r,e){if(r.stateSummary)return{...r.stateSummary,projection:{...r.stateSummary.projection,scopeKind:"projected",projectionMode:e.projectionMode,includedStoryCount:e.includedStoryCount,includedEpicCount:e.includedEpicCount??r.stateSummary.projection.includedEpicCount,omittedStoryCount:e.omittedStoryCount,omittedEpicCount:e.omittedEpicCount,reason:"body-size"},reasonCodes:g(r.stateSummary.reasonCodes,["payload-size-guardrail","state-summary-preserved","nonessential-state-degraded"])}}function ye(r){const e=r.scope,t=new Set;if(e?.projectionMode==="structural-required")for(const m of Object.keys(r.stories))t.add(m);else e?.targetStoryId&&S(e.targetStoryId,r,t);const i={};for(const m of t){const _=r.stories[m];_&&(i[m]=_)}const c=se(r,t),o=Object.keys(i).length,s=Object.keys(c).length,u=Math.max(0,ae(r)-o),l=Math.max(0,ue(r)-s),d=e?.projectionMode==="structural-required"?"structural-required":"summary-only",p={kind:"projected",commandId:e?.commandId??null,stateProjectionPolicy:e?.stateProjectionPolicy??null,projectionMode:d,...e?.trigger?{trigger:e.trigger}:{},targetEpicId:e?.targetEpicId??null,targetStoryId:e?.targetStoryId??null,includedStoryCount:o,includedEpicCount:s,omittedStoryCount:u,omittedEpicCount:l,reason:"body-size",reasonCodes:g(e?.reasonCodes,["payload-size-guardrail",t.size>0?"structural-targets-preserved":"stories-omitted","epics-stubbed","state-summary-preserved"])},f=de(r,p);return{...r,stories:i,epics:c,scope:p,...f?{stateSummary:f}:{}}}function me(r,e){const t=r.trim();try{const i=D(t);if(!i){if(Z(t)){const o=n("story-reference","story-targeted"),s=x(t);if(s)return O(t,e,o,s,"targeted-story",["story-reference-targeted"])}return y(t,e,null,"full-compatible",["unknown-command-full-state"])}if(i.stateProjectionPolicy==="epic-summary")return oe(t,e,i);if(i.stateProjectionPolicy==="yoloop-targeted")return ne(t,e,i);const c=x(t);if(i.stateProjectionPolicy==="story-targeted")return c?O(t,e,i,c,i.structuralRequired?"structural-required":"targeted-story",[i.structuralRequired?"structural-required":"targeted-story"]):i.structuralRequired?y(t,e,i,"structural-required",["structural-target-missing-full-state"]):v(t,e,i,["story-target-missing-summary-only"]);if(i.stateProjectionPolicy==="adaptive-targeted"){if(c&&e.stories[c])return O(t,e,i,c,"targeted-story",["adaptive-story-targeted"]);const o=k(t,e);return o?z(t,e,i,o,"targeted-epic",["adaptive-epic-targeted"]):v(t,e,i,["adaptive-summary-only","target-unresolved-summary-only"])}if(i.stateProjectionPolicy==="epic-targeted"){const o=k(t,e);return o?z(t,e,i,o,i.structuralRequired?"structural-required":"targeted-epic",[i.structuralRequired?"structural-required":"targeted-epic"]):i.structuralRequired?y(t,e,i,"structural-required",["structural-epic-target-missing-full-state"]):v(t,e,i,["epic-target-missing-summary-only"])}return i.stateProjectionPolicy==="continuity-scoped"?v(t,e,i,["continuity-scoped-summary-only"]):v(t,e,i,["policy-full-summary-only"])}catch{return y(t,e,null,"full-compatible",["projection-error-full-state"])}}export{ye as degradeStateSnapshotForPayloadLimit,me as projectStateSnapshotForInvoke};
|
|
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};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export type StructuralDagErrorCode = 'STRUCTURAL_TARGET_NOT_FOUND' | 'STRUCTURAL_DEPENDENCY_MISSING' | 'STRUCTURAL_DEPENDENCY_CYCLE' | 'STRUCTURAL_CONTEXT_TOO_LARGE';
|
|
2
|
+
export declare class StructuralDagError extends Error {
|
|
3
|
+
readonly code: StructuralDagErrorCode;
|
|
4
|
+
readonly publicDetails: Readonly<Record<string, number | string>>;
|
|
5
|
+
constructor(code: StructuralDagErrorCode, publicDetails: Readonly<Record<string, number | string>>);
|
|
6
|
+
}
|
|
7
|
+
export interface DependencyDagAnalysis {
|
|
8
|
+
readonly orderedIds: readonly string[];
|
|
9
|
+
readonly edgeCount: number;
|
|
10
|
+
readonly structuralBytes: number;
|
|
11
|
+
readonly maxDepth: number;
|
|
12
|
+
}
|
|
13
|
+
export interface DependencyDagBudgets {
|
|
14
|
+
readonly maxNodes?: number;
|
|
15
|
+
readonly maxEdges?: number;
|
|
16
|
+
readonly maxDepth?: number;
|
|
17
|
+
readonly maxBytes?: number;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Deterministic three-colour traversal used by YOLO and yoloop projections.
|
|
21
|
+
* Public diagnostics expose counts only; node names can contain customer data
|
|
22
|
+
* and must not escape through errors or telemetry.
|
|
23
|
+
*/
|
|
24
|
+
export declare function analyzeDependencyDag(nodes: Readonly<Record<string, Record<string, unknown>>>, roots?: readonly string[], budgets?: DependencyDagBudgets): DependencyDagAnalysis;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class c extends Error{code;publicDetails;constructor(t,o){super(t),this.code=t,this.publicDetails=o,this.name="StructuralDagError"}}const g=1e4,m=5e4,U=1024,h=192*1024;function w(s){if(s.depends_on===void 0)return[];if(!Array.isArray(s.depends_on)||s.depends_on.some(t=>typeof t!="string"||t.length===0))throw new c("STRUCTURAL_DEPENDENCY_MISSING",{nodes:0,edges:0,malformedDependencies:1});return[...new Set(s.depends_on)].sort((t,o)=>t.localeCompare(o,"en"))}function L(s,t,o={}){const a=o.maxNodes??g,E=o.maxEdges??m,D=o.maxDepth??U,f=o.maxBytes??h,T=new Map,p=[];let n=0,r=0,_=0,i=0;const l=(e,d)=>{const u=T.get(e)??0;if(u===2)return;if(u===1)throw new c("STRUCTURAL_DEPENDENCY_CYCLE",{nodes:r,edges:n,cycles:1});const A=s[e];if(!A)throw new c("STRUCTURAL_DEPENDENCY_MISSING",{nodes:r,edges:n,missingDependencies:1});if(d>D)throw new c("STRUCTURAL_CONTEXT_TOO_LARGE",{nodes:r,edges:n,maxDepth:D,observedDepth:d});T.set(e,1),r+=1,i=Math.max(i,d);const C=w(A);if(_+=Buffer.byteLength(JSON.stringify({id:e,depends_on:C}),"utf8"),r>a)throw new c("STRUCTURAL_CONTEXT_TOO_LARGE",{nodes:r,edges:n,maxNodes:a,maxEdges:E});if(_>f)throw new c("STRUCTURAL_CONTEXT_TOO_LARGE",{nodes:r,edges:n,structuralBytes:_,maxBytes:f});for(const S of C){if(n+=1,n>E)throw new c("STRUCTURAL_CONTEXT_TOO_LARGE",{nodes:r,edges:n,maxNodes:a,maxEdges:E});l(S,d+1)}T.set(e,2),p.push(e)},R=t===void 0?Object.keys(s).sort((e,d)=>e.localeCompare(d,"en")):[...new Set(t)].sort((e,d)=>e.localeCompare(d,"en"));for(const e of R)l(e,1);return Object.freeze({orderedIds:Object.freeze(p),edgeCount:n,structuralBytes:_,maxDepth:i})}export{c as StructuralDagError,L as analyzeDependencyDag};
|
|
@@ -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};
|