@ornexus/neocortex 4.60.45 → 4.60.47

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.
@@ -1 +1 @@
1
- import{analyzeDependencyDag as k,StructuralDagError as m}from"./structural-dag-projection.js";import{classifyInvocationShapeV2 as O}from"./invocation-shape.js";const x=12,B=16,v=["active","archived","rolled-back","synthetic","orphan"],H=new Set(["in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","partial"]),n=(r,e,t={})=>({commandId:r,stateProjectionPolicy:e,...t}),N=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})}),J=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"}),Q=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 d(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 R(r,e=120){if(typeof r!="string")return;const t=r.trim(),i=d(r,e);return i===t?i:void 0}function D(r){if(typeof r!="string")return;const e=r.trim();if(!(!e||e.length>240||!/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(e)||e.includes("..")||e.includes("//")||e.includes("@{")||e.endsWith("/")||e.endsWith(".")||e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))))return e}function X(r){if(typeof r!="string")return;const e=r.replace(/\\/g,"/");if(!(!e||e.length>240||e.startsWith("/")||/^[A-Za-z]:/.test(e)||e.includes("..")||e.includes("//")||e.split("/").includes(".")||!/^[A-Za-z0-9._/:@#-]+$/.test(e)))return e}function b(r){if(r===void 0||!Array.isArray(r)||r.length>128)return;const e=r.map(X);if(!e.some(t=>t===void 0))return[...new Set(e)].sort((t,i)=>t.localeCompare(i,"en"))}function ee(r){return typeof r=="string"&&H.has(r.trim().toLowerCase().replace(/_/g,"-"))}function C(r,e){const t={};for(const i of e){const c=r[i];typeof c=="string"||typeof c=="boolean"||typeof c=="number"&&Number.isFinite(c)?t[i]=c:Array.isArray(c)&&c.every(o=>typeof o=="string")&&(t[i]=[...c])}return t}function te(r,e){const t=e.checkpoint;if(!g(t)||t.schemaVersion!==1||t.storyId!==r||t.epicId!==e.epic_id||!D(t.branch)||typeof t.baseSha!="string"||!/^[0-9a-f]{7,64}$/i.test(t.baseSha)||typeof t.headSha!="string"||!/^[0-9a-f]{7,64}$/i.test(t.headSha)||t.baseSha===t.headSha||!R(t.idempotencyKey)||typeof t.recordedAt!="string"||!Number.isFinite(Date.parse(t.recordedAt))||!Array.isArray(t.commits)||t.commits.length===0||t.commits.length>256||t.commits.some(c=>typeof c!="string"||!/^[0-9a-f]{7,64}$/i.test(c))||!Array.isArray(t.receiptRefs)||t.receiptRefs.length===0||t.receiptRefs.length>256||t.receiptRefs.some(c=>typeof c!="string"||c.length>240||c.includes("..")||!/^[A-Za-z0-9._:/#\-[\]]+$/.test(c))||!g(t.qaReceipt)||t.qaReceipt.kind!=="story_qa_evidence"||t.qaReceipt.producer!=="local-yolo-tdd"||!["passed","blocked"].includes(String(t.qaVerdict))||!["approved","changes-requested","pending"].includes(String(t.reviewVerdict))||(t.reviewVerdict==="pending"?t.reviewReceipt!==void 0:!g(t.reviewReceipt)))return;const i=C(t,["schemaVersion","storyId","epicId","branch","baseSha","headSha","idempotencyKey","dispatchId","bundleId","bundleDigest","graphRevision","claimRevision","qaVerdict","reviewVerdict","recordedAt","commits","receiptRefs"]);return i.qaReceipt=C(t.qaReceipt,["schemaVersion","kind","producer","evidenceVersion","storyId","epicId","contract","command","manifestDigest","gateIds","resultDigest","baseSha","headSha","bundleDigest","graphRevision","sourceEvidenceDigest","verdict","checkedAt","receiptRef"]),g(t.reviewReceipt)&&(i.reviewReceipt=C(t.reviewReceipt,["schemaVersion","kind","producer","storyId","epicId","baseSha","headSha","bundleDigest","graphRevision","sourceEvidenceDigest","qaReceiptRef","verdict","reviewedAt","receiptRef"])),i}function re(r,e){const t=e.checkpoint_verification;if(!(!g(t)||t.schemaVersion!==1||t.kind!=="story_checkpoint_physical_verification"||t.producer!=="client-p205-transient-v1"||t.publicSafe!==!0||t.storyId!==r||t.epicId!==e.epic_id||!["verified","rejected"].includes(String(t.verdict))))return C(t,["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","aggregateHeadSha","commitBodyDigest","changedPathsDigest","claimVerification","effectiveClaimRevision","command","manifestDigest","gateIds","resultDigest","graphRevision","executionEvidenceDigest","sourceEvidenceDigest","verifiedAt","verdict","reasonCodes","publicSafe"])}function g(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function h(...r){const e=new Set,t=[];for(const i of r)for(const c of i??[]){const o=d(c,80);if(!(!o||e.has(o))&&(e.add(o),t.push(o),t.length>=B))return t}return t}function ie(r){return r.trim().replace(/^@?\*/,"").replace(/^@/,"").toLowerCase()}function ce(r){return r.trim().split(/\s+/,1)[0]??""}function U(r){const e=ce(r);if(!e)return N.menu;const t=ie(e),i=Q[t]??J[t]??t;return N[i]??null}function oe(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:h(c)}}function xe(r,e,t,i="full-compatible",c=["full-state"]){const o=oe(r,e,t,i,c);return I({...e,scope:o},e,o)}function ne(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 M(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 se(r){const e=r.trim(),t=e.search(/\s/);return t===-1?"":e.slice(t).trim()}function w(r){return se(r).split(/\s+/).map(e=>e.replace(/^@/,"").replace(/^['"]|['"]$/g,"")).filter(e=>e.length>0&&!e.startsWith("-"))}function Ne(r){return w(r)[0]??null}function z(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 ae(r,e){const t=r.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);return t?.[1]?z(t[1],e):null}function E(r,e){const t=ae(r,e);if(t)return t;for(const i of w(r)){if(/^[A-Z]?\d+(?:\.\d+)+$/i.test(i))continue;const c=z(i,e);if(c)return c}return null}function de(r,e){const t=E(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 ue(r){const e=r.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i)?.[1];if(e)return/^P/i.test(e)?e.toUpperCase():`P${e}`;for(const t of w(r)){if(/^P\d+$/i.test(t))return t.toUpperCase();if(/^\d+$/.test(t))return`P${t}`}return null}function S(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 F(r){return typeof r=="string"&&["done","completed","merged","cancelled","canceled","abandoned"].includes(r.toLowerCase())}function A(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"&&A(o,e,t)}function le(r,e){const t=k(e.stories,[r]),i={};for(const c of t.orderedIds){const o=e.stories[c];o&&(i[c]=o)}return i}function L(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=S(o,c);s&&e.epics[s]&&(i[s]=e.epics[s])}return i}function pe(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&&pe(o,e,t)}function $(r,e,t){const i=k(t.epics,[r]),c=new Set(i.orderedIds);for(const[s,a]of Object.entries(e)){const u=S(a,s);u&&t.epics[u]&&c.add(u)}const o={};for(const s of[...c].sort((a,u)=>a.localeCompare(u,"en"))){const a=t.epics[s];a&&(o[s]=s===r?a:Y(s,a))}return o}function G(r,e,t){const i=e.stories;if(!Array.isArray(i)||i.some(s=>typeof s!="string"||s.length===0))throw new m("STRUCTURAL_DEPENDENCY_MISSING",{nodes:0,edges:0,malformedStoryMemberships:1});const c=k(t.stories,i),o={};for(const s of c.orderedIds){const a=t.stories[s];a&&(o[s]=S(a,s)===r?a:V(s,a))}return o}function V(r,e){const t=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(y=>typeof y=="string"&&y.length>0))].sort((y,j)=>y.localeCompare(j,"en")):[],i={id:d(e.id)??r,...d(e.epic_id)?{epic_id:d(e.epic_id)}:{},...d(e.status,40)?{status:d(e.status,40)}:{},depends_on:t};if(!ee(e.status))return i;const c=e.source==="create-epic"||e.source==="discovered"?e.source:void 0,o=D(e.branch_name),s=R(e.last_step,120),a=Array.isArray(e.steps_completed)&&e.steps_completed.length<=64?e.steps_completed.map(y=>R(y,120)):[],u=a.length>0&&a.every(y=>y!==void 0)?a:void 0,l=typeof e.pr_number=="number"&&Number.isSafeInteger(e.pr_number)&&e.pr_number>0?e.pr_number:void 0,p=te(r,e),f=p?re(r,e):void 0;return{...i,...c?{source:c}:{},...o?{branch_name:o}:{},...s?{last_step:s}:{},...u?{steps_completed:u}:{},...l?{pr_number:l}:{},...p?{checkpoint:p}:{},...f?{checkpoint_verification:f}:{},...b(e.files_to_modify)!==void 0?{files_to_modify:b(e.files_to_modify)}:{},...b(e.contracts)!==void 0?{contracts:b(e.contracts)}:{},...b(e.contract_refs)!==void 0?{contract_refs:b(e.contract_refs)}:{},...b(e.shared_surfaces)!==void 0?{shared_surfaces:b(e.shared_surfaces)}:{}}}function Y(r,e){const t=Array.isArray(e.stories)?[...new Set(e.stories.filter(c=>typeof c=="string"&&c.length>0))].sort((c,o)=>c.localeCompare(o,"en")):[],i=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(c=>typeof c=="string"&&c.length>0))].sort((c,o)=>c.localeCompare(o,"en")):[];return{id:d(e.id)??r,...d(e.status,40)?{status:d(e.status,40)}:{},...d(e.lifecycle_classification,40)?{lifecycle_classification:d(e.lifecycle_classification,40)}:{},stories:t,depends_on:i}}function fe(r,e,t){const i=k(e.stories),c=k(e.epics),o=Object.fromEntries(i.orderedIds.map(u=>[u,V(u,e.stories[u])])),s=Object.fromEntries(c.orderedIds.map(u=>[u,Y(u,e.epics[u])])),a={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"yoloop-discovery",trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:i.orderedIds.length,includedEpicCount:c.orderedIds.length,omittedStoryCount:0,omittedEpicCount:0,reason:"targeted-invocation",reasonCodes:h(["structural-required","yoloop-discovery",`structural-edges-${i.edgeCount+c.edgeCount}`,"content-fields-omitted"])};return I({...e,stories:o,epics:s,scope:a},e,a)}function ye(r,e){const t=new Set,i=r.stories;if(Array.isArray(i))for(const o of i)typeof o=="string"&&A(o,e,t);const c={};for(const o of t){const s=e.stories[o];s&&(c[o]=s)}return c}function me(r){const e={};for(const[t,i]of Object.entries(r.epics))e[t]={id:d(i.id)??t,...d(i.status)?{status:d(i.status)}:{},...v.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 K(r){const e={};for(const t of Object.values(r)){const i=d(t.status,40)??"unknown";e[i]=(e[i]??0)+1}return e}function ge(r){const e=Object.fromEntries(v.map(t=>[t,0]));for(const t of Object.values(r)){const i=v.includes(t.lifecycle_classification)?t.lifecycle_classification:"active";e[i]=(e[i]??0)+1}return e}function T(r,e){if(!e)return!0;const t=r.epics[e];return t?!v.includes(t.lifecycle_classification)||t.lifecycle_classification==="active":!0}function Z(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 he(r){return Object.entries(r.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,x).map(({id:e,story:t})=>({id:e,...d(t.epic_id)?{epicId:d(t.epic_id)}:{},...d(t.status,40)?{status:d(t.status,40)}:{},...d(t.last_step??t.lastStep)?{lastStep:d(t.last_step??t.lastStep)}:{},...d(t.last_updated??t.updated_at??t.completed_at??t.created_at)?{lastUpdated:d(t.last_updated??t.updated_at??t.completed_at??t.created_at)}:{}}))}function be(r){const e=r.current_session;if(!e)return;const t={activeEpicId:d(e.active_epic_id)??null,activeStoryId:d(e.active_story_id)??null,activeStepId:d(e.active_step_id)??null,sessionId:d(e.session_id)??null,startedAt:d(e.started_at)??null};return Object.values(t).some(i=>i!=null)?t:void 0}function _e(r){const e=r.yoloop;if(!g(e))return;const t=g(e.state)?e.state:void 0,i=g(t?.currentSession)?t.currentSession:void 0,c=g(e.lock)?e.lock:void 0,o={...typeof e.active=="boolean"?{active:e.active}:{},currentEpicId:d(i?.currentEpicId??e.currentEpicId)??null,currentStoryId:d(i?.currentStoryId??e.currentStoryId)??null,sessionId:d(i?.sessionId??e.sessionId)??null,lockEpicId:d(c?.currentEpicId??c?.epicId)??null};return Object.keys(o).length>0?o:void 0}function je(r){const e=r.continuity;if(!g(e))return;const t=Array.isArray(e.reasonCodes)?e.reasonCodes.filter(i=>typeof i=="string"):void 0;return{present:!0,activeJobId:d(e.activeJobId??e.jobId)??null,activeGoalId:d(e.activeGoalId??e.goalId)??null,activeLoopId:d(e.activeLoopId??e.loopId)??null,...t&&t.length>0?{reasonCodes:h(t)}:{}}}function Se(r,e,t){const i=d(e?.activeStoryId),c=d(e?.activeEpicId),o=d(e?.activeStepId),s=i&&r.stories[i]?S(r.stories[i],i):null;if((i||c||o)&&T(r,c??s))return{epicId:c??null,storyId:i??null,stepId:o??null};const a=d(t?.currentStoryId),u=d(t?.currentEpicId??t?.lockEpicId);if((a||u)&&T(r,u))return{epicId:u??null,storyId:a??null,stepId:null};const l=Object.entries(r.stories).map(([p,f])=>({id:p,story:f,timestamp:Z(f)})).filter(({id:p,story:f})=>!F(f.status)&&T(r,S(f,p))).sort((p,f)=>f.timestamp-p.timestamp||p.id.localeCompare(f.id))[0];return l?{epicId:S(l.story,l.id),storyId:l.id,stepId:d(l.story.last_step??l.story.lastStep)??null}:{epicId:null,storyId:null,stepId:null}}function Ie(r,e){const t=K(r.stories),i=K(r.epics),c=ge(r.epics),o=Object.values(r.epics).filter(y=>(v.includes(y.lifecycle_classification)?y.lifecycle_classification:"active")==="active"&&!F(y.status)).length,s=be(r),a=_e(r),u=je(r),l=Se(r,s,a),p=he(r),f=h(e.reasonCodes,["state-summary-attached","state-summary-bounded",`projection-${e.projectionMode??e.kind}`,e.stateProjectionPolicy?`policy-${e.stateProjectionPolicy}`:"policy-unknown",p.length>=x?"recent-stories-capped":"recent-stories-bounded",l.storyId||l.epicId?"active-ref-derived":"active-ref-empty",a?"yoloop-session-present":"yoloop-session-absent",u?"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:l,blockedCount:t.blocked??0,recentStories:p,...s?{currentSession:s}:{},...a?{currentYoloopSession:a}:{},...u?{currentContinuitySession:u}:{},projection:{commandId:e.commandId??null,stateProjectionPolicy:e.stateProjectionPolicy??null,projectionMode:e.projectionMode,scopeKind:e.kind,includedStoryCount:e.includedStoryCount,includedEpicCount:e.includedEpicCount??Object.keys(r.epics).length,omittedStoryCount:e.omittedStoryCount,omittedEpicCount:e.omittedEpicCount,reason:e.reason},reasonCodes:f,publicSafe:!0}}function I(r,e,t){return{...r,stateSummary:Ie(e,t)}}function ke(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 I({...e,stories:{},epics:i,scope:c},e,c)}function _(r,e,t,i=["summary-only","stories-omitted"],c="summary-only"){const o=me(e),s={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:0,includedEpicCount:Object.keys(o).length,omittedStoryCount:Object.keys(e.stories).length,omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(o).length),reason:"summary-only",reasonCodes:h(i)};return I({...e,stories:{},epics:o,scope:s},e,s)}function P(r,e,t,i,c,o){const s=e.stories[i];if(!s)throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"story"});const a=S(s,i);if(!a)throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const u=e.epics[a];if(!u)throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const l=c==="yolo-story",p=l?G(a,u,e):le(i,e),f=l?$(a,p,e):L(p,e);if(!p[i]||!f[a])throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(p).length,epics:Object.keys(f).length,targetKind:"story"});const y={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:a,targetStoryId:i,includedStoryCount:Object.keys(p).length,includedEpicCount:Object.keys(f).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(p).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(f).length),reason:"targeted-invocation",reasonCodes:h(o,l?["epic-graph-authority-complete"]:[])};return I({...e,stories:p,epics:f,scope:y},e,y)}function W(r,e,t,i,c,o){const s=e.epics[i];if(!s)throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const a=ye(s,e),u=L(a,e,[i]);if(!u[i])throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(a).length,epics:Object.keys(u).length,targetKind:"epic"});const l={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:i,targetStoryId:null,includedStoryCount:Object.keys(a).length,includedEpicCount:Object.keys(u).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(a).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(u).length),reason:"targeted-invocation",reasonCodes:h(o)};return I({...e,stories:a,epics:u,scope:l},e,l)}function ve(r,e,t){const i=ue(r),c=E(r,e);if(i&&!c)throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const o=de(r,e),s=O({commandId:t.commandId,explicitYoloopEpicId:c,sessionYoloopEpicId:c?null:o});if(s==="yoloop-discovery")return fe(r,e,t);if(!o||s!=="yoloop-target"&&s!=="yoloop-session")throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const a=e.epics[o];if(!a)throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const u=G(o,a,e),l=$(o,u,e);if(!l[o])throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(u).length,epics:Object.keys(l).length,targetKind:"epic"});const p=s,f={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:p,trigger:r,targetEpicId:o,targetStoryId:null,includedStoryCount:Object.keys(u).length,includedEpicCount:Object.keys(l).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(u).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(l).length),reason:"targeted-invocation",reasonCodes:["structural-required",p,"yoloop-targeted"]};return I({...e,stories:u,epics:l,scope:f},e,f)}function Ce(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:d(c.id)??i,...d(c.status,40)?{status:d(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}:{},...o.length>0&&(c.origin_binding===null||typeof c.origin_binding=="object")?{origin_binding:c.origin_binding}:{},...o.length>0&&(c.aggregate_qa_receipt===null||typeof c.aggregate_qa_receipt=="object")?{aggregate_qa_receipt:c.aggregate_qa_receipt}:{}}}return t}function Ee(r){return r.stateSummary?.totals.stories??(r.scope?.includedStoryCount??Object.keys(r.stories).length)+(r.scope?.omittedStoryCount??0)}function Oe(r){return r.stateSummary?.totals.epics??(r.scope?.includedEpicCount??Object.keys(r.epics).length)+(r.scope?.omittedEpicCount??0)}function Re(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:h(r.stateSummary.reasonCodes,["payload-size-guardrail","state-summary-preserved","nonessential-state-degraded"])}}function De(r){const e=r.scope,t=new Set,i=e?.projectionMode==="structural-required"||e?.projectionMode==="yolo-story"||e?.projectionMode==="yoloop-target"||e?.projectionMode==="yoloop-session"||e?.projectionMode==="yoloop-discovery";if(i)for(const j of Object.keys(r.stories))t.add(j);else e?.targetStoryId&&A(e.targetStoryId,r,t);const c={};for(const j of t){const q=r.stories[j];q&&(c[j]=q)}const o=Ce(r,t),s=Object.keys(c).length,a=Object.keys(o).length,u=Math.max(0,Ee(r)-s),l=Math.max(0,Oe(r)-a),p=i?e?.projectionMode??"structural-required":e?.projectionMode==="yolo-story"?"yolo-story":"summary-only",f={kind:"projected",commandId:e?.commandId??null,stateProjectionPolicy:e?.stateProjectionPolicy??null,projectionMode:p,targetEpicId:e?.targetEpicId??null,targetStoryId:e?.targetStoryId??null,includedStoryCount:s,includedEpicCount:a,omittedStoryCount:u,omittedEpicCount:l,reason:"body-size",reasonCodes:h(e?.reasonCodes,["payload-size-guardrail",t.size>0?"structural-targets-preserved":"stories-omitted","epics-stubbed","state-summary-preserved","redundant-trigger-omitted"])},y=Re(r,f);return{...r,stories:c,epics:o,scope:f,...y?{stateSummary:y}:{}}}function we(r,e){const t=r.trim(),i=U(t);try{if(!i){if(ne(t)){const o=n("story-reference","story-targeted"),s=M(t);if(s)return P(t,e,o,s,"targeted-story",["story-reference-targeted"])}return _(t,e,n("unknown","adaptive-targeted"),["unknown-command-summary-only"])}if(i.stateProjectionPolicy==="epic-summary")return ke(t,e,i);if(i.stateProjectionPolicy==="yoloop-targeted")return ve(t,e,i);const c=M(t);if(i.stateProjectionPolicy==="story-targeted"){if(c){const s=O({commandId:i.commandId,targetStoryId:c})==="yolo-story";return P(t,e,i,c,s?"yolo-story":i.structuralRequired?"structural-required":"targeted-story",[s?"yolo-story":i.structuralRequired?"structural-required":"targeted-story"])}if(i.commandId==="yolo"||i.commandId==="yolo-inline"){const o=O({commandId:i.commandId});return _(t,e,i,["yolo-inline","stories-omitted","historical-content-omitted"],o??"yolo-inline")}return i.structuralRequired?(()=>{throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"story"})})():_(t,e,i,["story-target-missing-summary-only"])}if(i.stateProjectionPolicy==="adaptive-targeted"){if(c&&e.stories[c])return P(t,e,i,c,"targeted-story",["adaptive-story-targeted"]);const o=E(t,e);return o?W(t,e,i,o,"targeted-epic",["adaptive-epic-targeted"]):_(t,e,i,["adaptive-summary-only","target-unresolved-summary-only"])}if(i.stateProjectionPolicy==="epic-targeted"){const o=E(t,e);return o?W(t,e,i,o,i.structuralRequired?"structural-required":"targeted-epic",[i.structuralRequired?"structural-required":"targeted-epic"]):i.structuralRequired?(()=>{throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"})})():_(t,e,i,["epic-target-missing-summary-only"])}return i.stateProjectionPolicy==="continuity-scoped"?_(t,e,i,["continuity-scoped-summary-only"]):_(t,e,i,["policy-full-summary-only"])}catch(c){if(c instanceof m)throw c;if(i?.structuralRequired)throw new m("STRUCTURAL_DEPENDENCY_MISSING",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,projectionErrors:1});return _(t,e,i??n("unknown","adaptive-targeted"),["projection-error-summary-only"])}}const Ae=new Set(["yolo-story","yolo-inline","yoloop-target","yoloop-session","yoloop-discovery"]);function Te(r){let e=0;for(const t of[r.stories,r.epics])for(const i of Object.values(t))Array.isArray(i.depends_on)&&(e+=i.depends_on.filter(c=>typeof c=="string").length);return e}function Ue(r,e){const t=U(r.trim());if(!t||!["yolo","yolo-inline","yoloop"].includes(t.commandId))return null;try{const i=we(r,e),c=i.scope?.projectionMode;if(!c||!Ae.has(c))throw new m("STRUCTURAL_DEPENDENCY_MISSING",{stories:Object.keys(i.stories).length,epics:Object.keys(i.epics).length,projectionShapeErrors:1});return Object.freeze({ok:!0,version:2,shape:c,snapshot:i,included:{epics:i.scope?.includedEpicCount??Object.keys(i.epics).length,stories:i.scope?.includedStoryCount??Object.keys(i.stories).length,edges:Te(i)},omitted:{epics:i.scope?.omittedEpicCount??0,stories:i.scope?.omittedStoryCount??0},cycleCount:0})}catch(i){if(!(i instanceof m))throw i;return Object.freeze({ok:!1,code:i.code,publicDetails:i.publicDetails})}}export{De as degradeStateSnapshotForPayloadLimit,we as projectStateSnapshotForInvoke,Ue as projectStateSnapshotResultV2ForInvoke};
1
+ import{createHash as B}from"node:crypto";import{analyzeDependencyDag as v,StructuralDagError as m}from"./structural-dag-projection.js";import{classifyInvocationShapeV2 as O}from"./invocation-shape.js";const x=12,H=16,k=["active","archived","rolled-back","synthetic","orphan"],J=new Set(["in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","partial"]),n=(r,e,t={})=>({commandId:r,stateProjectionPolicy:e,...t}),N=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})}),Q=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"}),X=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 d(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 R(r,e=120){if(typeof r!="string")return;const t=r.trim(),i=d(r,e);return i===t?i:void 0}function D(r){if(typeof r!="string")return;const e=r.trim();if(!(!e||e.length>240||!/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(e)||e.includes("..")||e.includes("//")||e.includes("@{")||e.endsWith("/")||e.endsWith(".")||e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))))return e}function ee(r){if(typeof r!="string")return;const e=r.replace(/\\/g,"/");if(!(!e||e.length>240||e.startsWith("/")||/^[A-Za-z]:/.test(e)||e.includes("..")||e.includes("//")||e.split("/").includes(".")||!/^[A-Za-z0-9._/:@#-]+$/.test(e)))return e}function b(r){if(r===void 0||!Array.isArray(r)||r.length>128)return;const e=r.map(ee);if(!e.some(t=>t===void 0))return[...new Set(e)].sort((t,i)=>t.localeCompare(i,"en"))}function te(r){return typeof r=="string"&&J.has(r.trim().toLowerCase().replace(/_/g,"-"))}function C(r,e){const t={};for(const i of e){const c=r[i];typeof c=="string"||typeof c=="boolean"||typeof c=="number"&&Number.isFinite(c)?t[i]=c:Array.isArray(c)&&c.every(o=>typeof o=="string")&&(t[i]=[...c])}return t}function re(r,e){const t=e.checkpoint;if(!g(t)||t.schemaVersion!==1||t.storyId!==r||t.epicId!==e.epic_id||!D(t.branch)||typeof t.baseSha!="string"||!/^[0-9a-f]{7,64}$/i.test(t.baseSha)||typeof t.headSha!="string"||!/^[0-9a-f]{7,64}$/i.test(t.headSha)||t.baseSha===t.headSha||!R(t.idempotencyKey)||typeof t.recordedAt!="string"||!Number.isFinite(Date.parse(t.recordedAt))||!Array.isArray(t.commits)||t.commits.length===0||t.commits.length>256||t.commits.some(c=>typeof c!="string"||!/^[0-9a-f]{7,64}$/i.test(c))||!Array.isArray(t.receiptRefs)||t.receiptRefs.length===0||t.receiptRefs.length>256||t.receiptRefs.some(c=>typeof c!="string"||c.length>240||c.includes("..")||!/^[A-Za-z0-9._:/#\-[\]]+$/.test(c))||!g(t.qaReceipt)||t.qaReceipt.kind!=="story_qa_evidence"||t.qaReceipt.producer!=="local-yolo-tdd"||!["passed","blocked"].includes(String(t.qaVerdict))||!["approved","changes-requested","pending"].includes(String(t.reviewVerdict))||(t.reviewVerdict==="pending"?t.reviewReceipt!==void 0:!g(t.reviewReceipt)))return;const i=C(t,["schemaVersion","storyId","epicId","branch","baseSha","headSha","idempotencyKey","dispatchId","bundleId","bundleDigest","graphRevision","claimRevision","qaVerdict","reviewVerdict","recordedAt","commits","receiptRefs"]);return i.qaReceipt=C(t.qaReceipt,["schemaVersion","kind","producer","evidenceVersion","storyId","epicId","contract","command","manifestDigest","gateIds","resultDigest","baseSha","headSha","bundleDigest","graphRevision","sourceEvidenceDigest","verdict","checkedAt","receiptRef"]),g(t.reviewReceipt)&&(i.reviewReceipt=C(t.reviewReceipt,["schemaVersion","kind","producer","storyId","epicId","baseSha","headSha","bundleDigest","graphRevision","sourceEvidenceDigest","qaReceiptRef","verdict","reviewedAt","receiptRef"])),i}function ie(r,e){const t=e.checkpoint_verification;if(!(!g(t)||t.schemaVersion!==1||t.kind!=="story_checkpoint_physical_verification"||t.producer!=="client-p205-transient-v1"||t.publicSafe!==!0||t.storyId!==r||t.epicId!==e.epic_id||!["verified","rejected"].includes(String(t.verdict))))return C(t,["schemaVersion","kind","producer","storyId","epicId","branch","baseSha","headSha","aggregateHeadSha","commitBodyDigest","changedPathsDigest","claimVerification","effectiveClaimRevision","command","manifestDigest","gateIds","resultDigest","graphRevision","executionEvidenceDigest","sourceEvidenceDigest","verifiedAt","verdict","reasonCodes","publicSafe"])}function g(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function h(...r){const e=new Set,t=[];for(const i of r)for(const c of i??[]){const o=d(c,80);if(!(!o||e.has(o))&&(e.add(o),t.push(o),t.length>=H))return t}return t}function ce(r){return r.trim().replace(/^@?\*/,"").replace(/^@/,"").toLowerCase()}function oe(r){return r.trim().split(/\s+/,1)[0]??""}function U(r){const e=oe(r);if(!e)return N.menu;const t=ce(e),i=X[t]??Q[t]??t;return N[i]??null}function ne(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:h(c)}}function Ue(r,e,t,i="full-compatible",c=["full-state"]){const o=ne(r,e,t,i,c);return I({...e,scope:o},e,o)}function se(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 M(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 ae(r){const e=r.trim(),t=e.search(/\s/);return t===-1?"":e.slice(t).trim()}function T(r){return ae(r).split(/\s+/).map(e=>e.replace(/^@/,"").replace(/^['"]|['"]$/g,"")).filter(e=>e.length>0&&!e.startsWith("-"))}function Me(r){return T(r)[0]??null}function z(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 de(r,e){const t=r.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i);return t?.[1]?z(t[1],e):null}function E(r,e){const t=de(r,e);if(t)return t;for(const i of T(r)){if(/^[A-Z]?\d+(?:\.\d+)+$/i.test(i))continue;const c=z(i,e);if(c)return c}return null}function ue(r,e){const t=E(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 le(r){const e=r.match(/(?:^|[/@\s])epic-(P?\d+)\.md\b/i)?.[1];if(e)return/^P/i.test(e)?e.toUpperCase():`P${e}`;for(const t of T(r)){if(/^P\d+$/i.test(t))return t.toUpperCase();if(/^\d+$/.test(t))return`P${t}`}return null}function _(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 F(r){return typeof r=="string"&&["done","completed","merged","cancelled","canceled","abandoned"].includes(r.toLowerCase())}function w(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"&&w(o,e,t)}function pe(r,e){const t=v(e.stories,[r]),i={};for(const c of t.orderedIds){const o=e.stories[c];o&&(i[c]=o)}return i}function L(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=_(o,c);s&&e.epics[s]&&(i[s]=e.epics[s])}return i}function fe(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&&fe(o,e,t)}function $(r,e,t){const i=v(t.epics,[r]),c=new Set(i.orderedIds);for(const[s,a]of Object.entries(e)){const u=_(a,s);u&&t.epics[u]&&c.add(u)}const o={};for(const s of[...c].sort((a,u)=>a.localeCompare(u,"en"))){const a=t.epics[s];a&&(o[s]=s===r?a:Y(s,a))}return o}function V(r,e,t){const i=e.stories;if(!Array.isArray(i)||i.some(s=>typeof s!="string"||s.length===0))throw new m("STRUCTURAL_DEPENDENCY_MISSING",{nodes:0,edges:0,malformedStoryMemberships:1});const c=v(t.stories,i),o={};for(const s of c.orderedIds){const a=t.stories[s];a&&(o[s]=_(a,s)===r?a:G(s,a))}return o}function ye(r,e,t){const i=[...e.stories].sort((s,a)=>s.localeCompare(a,"en")),c=Object.entries(t).filter(([s,a])=>_(a,s)===r).map(([s])=>s).sort((s,a)=>s.localeCompare(a,"en")),o=B("sha256").update(`target-epic-coverage-v1\0${JSON.stringify({targetEpicId:r,declaredStoryIds:i,includedStoryIds:c})}`).digest("hex");return{schemaVersion:"TargetEpicCoverage/1.0",targetEpicId:r,declaredStoryIds:i,includedStoryIds:c,membershipSha256:o,publicSafe:!0}}function G(r,e){const t=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(y=>typeof y=="string"&&y.length>0))].sort((y,S)=>y.localeCompare(S,"en")):[],i={id:d(e.id)??r,...d(e.epic_id)?{epic_id:d(e.epic_id)}:{},...d(e.status,40)?{status:d(e.status,40)}:{},depends_on:t};if(!te(e.status))return i;const c=e.source==="create-epic"||e.source==="discovered"?e.source:void 0,o=D(e.branch_name),s=R(e.last_step,120),a=Array.isArray(e.steps_completed)&&e.steps_completed.length<=64?e.steps_completed.map(y=>R(y,120)):[],u=a.length>0&&a.every(y=>y!==void 0)?a:void 0,l=typeof e.pr_number=="number"&&Number.isSafeInteger(e.pr_number)&&e.pr_number>0?e.pr_number:void 0,p=re(r,e),f=p?ie(r,e):void 0;return{...i,...c?{source:c}:{},...o?{branch_name:o}:{},...s?{last_step:s}:{},...u?{steps_completed:u}:{},...l?{pr_number:l}:{},...p?{checkpoint:p}:{},...f?{checkpoint_verification:f}:{},...b(e.files_to_modify)!==void 0?{files_to_modify:b(e.files_to_modify)}:{},...b(e.contracts)!==void 0?{contracts:b(e.contracts)}:{},...b(e.contract_refs)!==void 0?{contract_refs:b(e.contract_refs)}:{},...b(e.shared_surfaces)!==void 0?{shared_surfaces:b(e.shared_surfaces)}:{}}}function Y(r,e){const t=Array.isArray(e.stories)?[...new Set(e.stories.filter(c=>typeof c=="string"&&c.length>0))].sort((c,o)=>c.localeCompare(o,"en")):[],i=Array.isArray(e.depends_on)?[...new Set(e.depends_on.filter(c=>typeof c=="string"&&c.length>0))].sort((c,o)=>c.localeCompare(o,"en")):[];return{id:d(e.id)??r,...d(e.status,40)?{status:d(e.status,40)}:{},...d(e.lifecycle_classification,40)?{lifecycle_classification:d(e.lifecycle_classification,40)}:{},stories:t,depends_on:i}}function me(r,e,t){const i=v(e.stories),c=v(e.epics),o=Object.fromEntries(i.orderedIds.map(u=>[u,G(u,e.stories[u])])),s=Object.fromEntries(c.orderedIds.map(u=>[u,Y(u,e.epics[u])])),a={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:"yoloop-discovery",trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:i.orderedIds.length,includedEpicCount:c.orderedIds.length,omittedStoryCount:0,omittedEpicCount:0,reason:"targeted-invocation",reasonCodes:h(["structural-required","yoloop-discovery",`structural-edges-${i.edgeCount+c.edgeCount}`,"content-fields-omitted"])};return I({...e,stories:o,epics:s,scope:a},e,a)}function ge(r,e){const t=new Set,i=r.stories;if(Array.isArray(i))for(const o of i)typeof o=="string"&&w(o,e,t);const c={};for(const o of t){const s=e.stories[o];s&&(c[o]=s)}return c}function he(r){const e={};for(const[t,i]of Object.entries(r.epics))e[t]={id:d(i.id)??t,...d(i.status)?{status:d(i.status)}:{},...k.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 K(r){const e={};for(const t of Object.values(r)){const i=d(t.status,40)??"unknown";e[i]=(e[i]??0)+1}return e}function be(r){const e=Object.fromEntries(k.map(t=>[t,0]));for(const t of Object.values(r)){const i=k.includes(t.lifecycle_classification)?t.lifecycle_classification:"active";e[i]=(e[i]??0)+1}return e}function A(r,e){if(!e)return!0;const t=r.epics[e];return t?!k.includes(t.lifecycle_classification)||t.lifecycle_classification==="active":!0}function Z(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 _e(r){return Object.entries(r.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,x).map(({id:e,story:t})=>({id:e,...d(t.epic_id)?{epicId:d(t.epic_id)}:{},...d(t.status,40)?{status:d(t.status,40)}:{},...d(t.last_step??t.lastStep)?{lastStep:d(t.last_step??t.lastStep)}:{},...d(t.last_updated??t.updated_at??t.completed_at??t.created_at)?{lastUpdated:d(t.last_updated??t.updated_at??t.completed_at??t.created_at)}:{}}))}function je(r){const e=r.current_session;if(!e)return;const t={activeEpicId:d(e.active_epic_id)??null,activeStoryId:d(e.active_story_id)??null,activeStepId:d(e.active_step_id)??null,sessionId:d(e.session_id)??null,startedAt:d(e.started_at)??null};return Object.values(t).some(i=>i!=null)?t:void 0}function Se(r){const e=r.yoloop;if(!g(e))return;const t=g(e.state)?e.state:void 0,i=g(t?.currentSession)?t.currentSession:void 0,c=g(e.lock)?e.lock:void 0,o={...typeof e.active=="boolean"?{active:e.active}:{},currentEpicId:d(i?.currentEpicId??e.currentEpicId)??null,currentStoryId:d(i?.currentStoryId??e.currentStoryId)??null,sessionId:d(i?.sessionId??e.sessionId)??null,lockEpicId:d(c?.currentEpicId??c?.epicId)??null};return Object.keys(o).length>0?o:void 0}function Ie(r){const e=r.continuity;if(!g(e))return;const t=Array.isArray(e.reasonCodes)?e.reasonCodes.filter(i=>typeof i=="string"):void 0;return{present:!0,activeJobId:d(e.activeJobId??e.jobId)??null,activeGoalId:d(e.activeGoalId??e.goalId)??null,activeLoopId:d(e.activeLoopId??e.loopId)??null,...t&&t.length>0?{reasonCodes:h(t)}:{}}}function ve(r,e,t){const i=d(e?.activeStoryId),c=d(e?.activeEpicId),o=d(e?.activeStepId),s=i&&r.stories[i]?_(r.stories[i],i):null;if((i||c||o)&&A(r,c??s))return{epicId:c??null,storyId:i??null,stepId:o??null};const a=d(t?.currentStoryId),u=d(t?.currentEpicId??t?.lockEpicId);if((a||u)&&A(r,u))return{epicId:u??null,storyId:a??null,stepId:null};const l=Object.entries(r.stories).map(([p,f])=>({id:p,story:f,timestamp:Z(f)})).filter(({id:p,story:f})=>!F(f.status)&&A(r,_(f,p))).sort((p,f)=>f.timestamp-p.timestamp||p.id.localeCompare(f.id))[0];return l?{epicId:_(l.story,l.id),storyId:l.id,stepId:d(l.story.last_step??l.story.lastStep)??null}:{epicId:null,storyId:null,stepId:null}}function ke(r,e){const t=K(r.stories),i=K(r.epics),c=be(r.epics),o=Object.values(r.epics).filter(y=>(k.includes(y.lifecycle_classification)?y.lifecycle_classification:"active")==="active"&&!F(y.status)).length,s=je(r),a=Se(r),u=Ie(r),l=ve(r,s,a),p=_e(r),f=h(e.reasonCodes,["state-summary-attached","state-summary-bounded",`projection-${e.projectionMode??e.kind}`,e.stateProjectionPolicy?`policy-${e.stateProjectionPolicy}`:"policy-unknown",p.length>=x?"recent-stories-capped":"recent-stories-bounded",l.storyId||l.epicId?"active-ref-derived":"active-ref-empty",a?"yoloop-session-present":"yoloop-session-absent",u?"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:l,blockedCount:t.blocked??0,recentStories:p,...s?{currentSession:s}:{},...a?{currentYoloopSession:a}:{},...u?{currentContinuitySession:u}:{},projection:{commandId:e.commandId??null,stateProjectionPolicy:e.stateProjectionPolicy??null,projectionMode:e.projectionMode,scopeKind:e.kind,includedStoryCount:e.includedStoryCount,includedEpicCount:e.includedEpicCount??Object.keys(r.epics).length,omittedStoryCount:e.omittedStoryCount,omittedEpicCount:e.omittedEpicCount,reason:e.reason},reasonCodes:f,publicSafe:!0}}function I(r,e,t){return{...r,stateSummary:ke(e,t)}}function Ce(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 I({...e,stories:{},epics:i,scope:c},e,c)}function j(r,e,t,i=["summary-only","stories-omitted"],c="summary-only"){const o=he(e),s={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:null,targetStoryId:null,includedStoryCount:0,includedEpicCount:Object.keys(o).length,omittedStoryCount:Object.keys(e.stories).length,omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(o).length),reason:"summary-only",reasonCodes:h(i)};return I({...e,stories:{},epics:o,scope:s},e,s)}function P(r,e,t,i,c,o){const s=e.stories[i];if(!s)throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"story"});const a=_(s,i);if(!a)throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const u=e.epics[a];if(!u)throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const l=c==="yolo-story",p=l?V(a,u,e):pe(i,e),f=l?$(a,p,e):L(p,e);if(!p[i]||!f[a])throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(p).length,epics:Object.keys(f).length,targetKind:"story"});const y={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:a,targetStoryId:i,includedStoryCount:Object.keys(p).length,includedEpicCount:Object.keys(f).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(p).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(f).length),reason:"targeted-invocation",reasonCodes:h(o,l?["epic-graph-authority-complete"]:[])};return I({...e,stories:p,epics:f,scope:y},e,y)}function W(r,e,t,i,c,o){const s=e.epics[i];if(!s)throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const a=ge(s,e),u=L(a,e,[i]);if(!u[i])throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(a).length,epics:Object.keys(u).length,targetKind:"epic"});const l={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:c,trigger:r,targetEpicId:i,targetStoryId:null,includedStoryCount:Object.keys(a).length,includedEpicCount:Object.keys(u).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(a).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(u).length),reason:"targeted-invocation",reasonCodes:h(o)};return I({...e,stories:a,epics:u,scope:l},e,l)}function Ee(r,e,t){const i=le(r),c=E(r,e);if(i&&!c)throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const o=ue(r,e),s=O({commandId:t.commandId,explicitYoloopEpicId:c,sessionYoloopEpicId:c?null:o});if(s==="yoloop-discovery")return me(r,e,t);if(!o||s!=="yoloop-target"&&s!=="yoloop-session")throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const a=e.epics[o];if(!a)throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"});const u=V(o,a,e),l=$(o,u,e);if(!l[o])throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(u).length,epics:Object.keys(l).length,targetKind:"epic"});const p=s,f={kind:"projected",commandId:t.commandId,stateProjectionPolicy:t.stateProjectionPolicy,projectionMode:p,trigger:r,targetEpicId:o,targetStoryId:null,targetEpicCoverage:ye(o,a,u),includedStoryCount:Object.keys(u).length,includedEpicCount:Object.keys(l).length,omittedStoryCount:Math.max(0,Object.keys(e.stories).length-Object.keys(u).length),omittedEpicCount:Math.max(0,Object.keys(e.epics).length-Object.keys(l).length),reason:"targeted-invocation",reasonCodes:["structural-required",p,"yoloop-targeted"]};return I({...e,stories:u,epics:l,scope:f},e,f)}function Oe(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:d(c.id)??i,...d(c.status,40)?{status:d(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}:{},...o.length>0&&(c.origin_binding===null||typeof c.origin_binding=="object")?{origin_binding:c.origin_binding}:{},...o.length>0&&(c.aggregate_qa_receipt===null||typeof c.aggregate_qa_receipt=="object")?{aggregate_qa_receipt:c.aggregate_qa_receipt}:{}}}return t}function Re(r){return r.stateSummary?.totals.stories??(r.scope?.includedStoryCount??Object.keys(r.stories).length)+(r.scope?.omittedStoryCount??0)}function Te(r){return r.stateSummary?.totals.epics??(r.scope?.includedEpicCount??Object.keys(r.epics).length)+(r.scope?.omittedEpicCount??0)}function we(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:h(r.stateSummary.reasonCodes,["payload-size-guardrail","state-summary-preserved","nonessential-state-degraded"])}}function ze(r){const e=r.scope,t=new Set,i=e?.projectionMode==="structural-required"||e?.projectionMode==="yolo-story"||e?.projectionMode==="yoloop-target"||e?.projectionMode==="yoloop-session"||e?.projectionMode==="yoloop-discovery";if(i)for(const S of Object.keys(r.stories))t.add(S);else e?.targetStoryId&&w(e.targetStoryId,r,t);const c={};for(const S of t){const q=r.stories[S];q&&(c[S]=q)}const o=Oe(r,t),s=Object.keys(c).length,a=Object.keys(o).length,u=Math.max(0,Re(r)-s),l=Math.max(0,Te(r)-a),p=i?e?.projectionMode??"structural-required":e?.projectionMode==="yolo-story"?"yolo-story":"summary-only",f={kind:"projected",commandId:e?.commandId??null,stateProjectionPolicy:e?.stateProjectionPolicy??null,projectionMode:p,targetEpicId:e?.targetEpicId??null,targetStoryId:e?.targetStoryId??null,...e?.targetEpicCoverage?{targetEpicCoverage:e.targetEpicCoverage}:{},includedStoryCount:s,includedEpicCount:a,omittedStoryCount:u,omittedEpicCount:l,reason:"body-size",reasonCodes:h(e?.reasonCodes,["payload-size-guardrail",t.size>0?"structural-targets-preserved":"stories-omitted","epics-stubbed","state-summary-preserved","redundant-trigger-omitted"])},y=we(r,f);return{...r,stories:c,epics:o,scope:f,...y?{stateSummary:y}:{}}}function Ae(r,e){const t=r.trim(),i=U(t);try{if(!i){if(se(t)){const o=n("story-reference","story-targeted"),s=M(t);if(s)return P(t,e,o,s,"targeted-story",["story-reference-targeted"])}return j(t,e,n("unknown","adaptive-targeted"),["unknown-command-summary-only"])}if(i.stateProjectionPolicy==="epic-summary")return Ce(t,e,i);if(i.stateProjectionPolicy==="yoloop-targeted")return Ee(t,e,i);const c=M(t);if(i.stateProjectionPolicy==="story-targeted"){if(c){const s=O({commandId:i.commandId,targetStoryId:c})==="yolo-story";return P(t,e,i,c,s?"yolo-story":i.structuralRequired?"structural-required":"targeted-story",[s?"yolo-story":i.structuralRequired?"structural-required":"targeted-story"])}if(i.commandId==="yolo"||i.commandId==="yolo-inline"){const o=O({commandId:i.commandId});return j(t,e,i,["yolo-inline","stories-omitted","historical-content-omitted"],o??"yolo-inline")}return i.structuralRequired?(()=>{throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"story"})})():j(t,e,i,["story-target-missing-summary-only"])}if(i.stateProjectionPolicy==="adaptive-targeted"){if(c&&e.stories[c])return P(t,e,i,c,"targeted-story",["adaptive-story-targeted"]);const o=E(t,e);return o?W(t,e,i,o,"targeted-epic",["adaptive-epic-targeted"]):j(t,e,i,["adaptive-summary-only","target-unresolved-summary-only"])}if(i.stateProjectionPolicy==="epic-targeted"){const o=E(t,e);return o?W(t,e,i,o,i.structuralRequired?"structural-required":"targeted-epic",[i.structuralRequired?"structural-required":"targeted-epic"]):i.structuralRequired?(()=>{throw new m("STRUCTURAL_TARGET_NOT_FOUND",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,targetKind:"epic"})})():j(t,e,i,["epic-target-missing-summary-only"])}return i.stateProjectionPolicy==="continuity-scoped"?j(t,e,i,["continuity-scoped-summary-only"]):j(t,e,i,["policy-full-summary-only"])}catch(c){if(c instanceof m)throw c;if(i?.structuralRequired)throw new m("STRUCTURAL_DEPENDENCY_MISSING",{stories:Object.keys(e.stories).length,epics:Object.keys(e.epics).length,projectionErrors:1});return j(t,e,i??n("unknown","adaptive-targeted"),["projection-error-summary-only"])}}const Pe=new Set(["yolo-story","yolo-inline","yoloop-target","yoloop-session","yoloop-discovery"]);function qe(r){let e=0;for(const t of[r.stories,r.epics])for(const i of Object.values(t))Array.isArray(i.depends_on)&&(e+=i.depends_on.filter(c=>typeof c=="string").length);return e}function Fe(r,e){const t=U(r.trim());if(!t||!["yolo","yolo-inline","yoloop"].includes(t.commandId))return null;try{const i=Ae(r,e),c=i.scope?.projectionMode;if(!c||!Pe.has(c))throw new m("STRUCTURAL_DEPENDENCY_MISSING",{stories:Object.keys(i.stories).length,epics:Object.keys(i.epics).length,projectionShapeErrors:1});return Object.freeze({ok:!0,version:2,shape:c,snapshot:i,included:{epics:i.scope?.includedEpicCount??Object.keys(i.epics).length,stories:i.scope?.includedStoryCount??Object.keys(i.stories).length,edges:qe(i)},omitted:{epics:i.scope?.omittedEpicCount??0,stories:i.scope?.omittedStoryCount??0},cycleCount:0})}catch(i){if(!(i instanceof m))throw i;return Object.freeze({ok:!1,code:i.code,publicDetails:i.publicDetails})}}export{ze as degradeStateSnapshotForPayloadLimit,Ae as projectStateSnapshotForInvoke,Fe as projectStateSnapshotResultV2ForInvoke};
@@ -7,7 +7,8 @@
7
7
  * Returns undefined (no-op) for non-yoloop invocations to avoid I/O.
8
8
  * - `persistYoloopFromResponse(metadata, projectRoot)` — post-response;
9
9
  * if the server returned `yoloopStateUpdate`, apply operations locally.
10
- * Fail-soft: warns to stderr on error but never throws.
10
+ * Authoritative rollover failures are returned to the invoke boundary;
11
+ * auxiliary legacy updates retain bounded fail-soft compatibility.
11
12
  *
12
13
  * Trigger detection is regex-based over the first token of `args`, aligned
13
14
  * with the P96.01 TRIGGER_ALIASES set for yoloop. Cheap enough to run on
@@ -23,6 +24,20 @@ import type { GraphRetrievalHookContext, GraphRetrievalHookResult } from '../gra
23
24
  * and optional `*` prefix).
24
25
  */
25
26
  export declare function isYoloopTrigger(args: string): boolean;
27
+ export declare const YOLOOP_PERSISTENCE_REASON_CODES: Readonly<{
28
+ readonly stateReadFailed: "YOLOOP_STATE_READ_FAILED";
29
+ readonly authoritativeWritebackFailed: "YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED";
30
+ readonly auxiliaryWritebackFailed: "YOLOOP_AUXILIARY_WRITEBACK_FAILED";
31
+ }>;
32
+ export declare class YoloopStateReadError extends Error {
33
+ readonly reasonCode: string;
34
+ constructor(reasonCode: string);
35
+ }
36
+ export interface YoloopPersistenceResult {
37
+ readonly ok: boolean;
38
+ readonly authoritative: boolean;
39
+ readonly reasonCodes: readonly string[];
40
+ }
26
41
  /**
27
42
  * Input context for `maybeAutoResolveYoloopArgs`.
28
43
  *
@@ -64,17 +79,19 @@ export interface AutoResolveYoloopContext {
64
79
  export declare function maybeAutoResolveYoloopArgs(ctx: AutoResolveYoloopContext): void;
65
80
  /**
66
81
  * Pre-request hook: read client-side yoloop state for the given project.
67
- * Returns undefined for non-yoloop invocations (no I/O). Returns undefined
68
- * on read error (fail-soft -- server treats as fresh start).
82
+ * Returns undefined for non-yoloop invocations (no I/O). A yoloop read or
83
+ * recovery failure is authoritative and fails closed so the server can never
84
+ * reinterpret corrupt/unavailable persisted state as a fresh session.
69
85
  */
70
86
  export declare function readYoloopForRequest(args: string, projectRoot: string, nowIso?: string): Promise<YoloopPersistedState | undefined>;
71
87
  /**
72
88
  * Post-response hook: apply server-provided operations to local state.
73
89
  * Safe to call for any response — no-op if no yoloopStateUpdate present.
74
- * Fail-soft: warns to stderr on error, never throws (the agent already
75
- * received instructions; next invoke self-heals via stateSnapshot.yoloop).
90
+ * A `rollover_session` update is authoritative: failure is returned to the
91
+ * caller so instructions cannot be released before durable state exists.
92
+ * Non-rollover legacy operations retain fail-soft compatibility.
76
93
  */
77
- export declare function persistYoloopFromResponse(metadata: Record<string, unknown> | undefined, projectRoot: string, nowIso?: string): Promise<void>;
94
+ export declare function persistYoloopFromResponse(metadata: Record<string, unknown> | undefined, projectRoot: string, nowIso?: string): Promise<YoloopPersistenceResult>;
78
95
  /**
79
96
  * Epic P125.03 -- Post-response hook: persist server-migrated state back
80
97
  * to `.neocortex/state.json` via atomic temp+rename.
@@ -1,11 +1,12 @@
1
- import{statSync as Z}from"node:fs";import{join as K}from"node:path";import{YoloopClientStateStore as D}from"./yoloop-client-state-store.js";import{isYoloopInvocation as W}from"./target-normalization.js";import{applyStateMigration as q,StateMigrationApplyError as J}from"../migrations/state-json.js";function X(e){return W(e)}const Q=/^\s*\*?(yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i;function le(e){if(typeof e.args!="string"||e.args.length===0)return;const i=e.args.match(Q);if(!i)return;const o=i[0];if(e.args.slice(o.length).trim()!=="")return;let s=!1;try{const t=K(e.projectRoot,"docs","epics");s=Z(t).isDirectory()}catch(t){const d=t instanceof Error?t.message:String(t);e.logger?.warn?.(`[Neocortex] Zero-config *yoloop hook (P121.05): could not stat docs/epics/: ${d}. Proceeding with raw args.`);return}s&&(e.args=`${o} @docs/epics/`,e.logger?.info?.("[Neocortex] Zero-config *yoloop (P121.05): auto-resolved empty args to @docs/epics/"))}async function de(e,i,o){if(X(e))try{return await new D(i).readAll(o)}catch(r){process.stderr.write(`[yoloop] Failed to read local state: ${r.message}. Continuing without state.
2
- `);return}}async function pe(e,i,o){if(!e)return;const r=e.yoloopStateUpdate;if(!(!r||!Array.isArray(r.operations)||r.operations.length===0))try{await new D(i).applyUpdate(r,o)}catch(s){const t=s.message??String(s);process.stderr.write(`[yoloop] Failed to persist state: ${t}. Your next *yoloop may repeat or skip an operation. Run *yoloop again to retry.
3
- `)}}function n(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function T(e,i){return Array.isArray(e)&&e.length<=i&&e.every(o=>typeof o=="string"&&o.length>0&&o.length<=160&&/^[A-Za-z0-9_.:+-]+$/.test(o))}function L(e){return n(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 ee(e){const i={...e};return delete i.scope,delete i.stateSummary,delete i.graphRetrieval,delete i.runnerBootstrap,delete i.projectEvidence,delete i.continuity,delete i.implementCheckpoint,i}function te(e){return typeof e=="string"&&["done","completed","merged"].includes(e.trim().toLowerCase())}function oe(e){return/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(e)&&!e.includes("..")&&!e.includes("//")&&!e.includes("@{")&&!e.endsWith("/")&&!e.endsWith(".")&&!e.endsWith(".lock")}async function ie(e,i){const o=e.syntheticStory;if(!n(o))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-missing"};const r=o.schemaVersion,s=o.epicId,t=o.storyId,d=o.storyPath,m=o.deterministicKey,b=o.storyContent,_=o.storyContentSha256,p=o.lifecycle;if(r!==2||typeof s!="string"||!/^P9\d{18}$/.test(s)||typeof t!="string"||t!==`${s}.01.000001`||typeof d!="string"||d!==`docs/stories/${t}.story.md`||typeof m!="string"||!/^[a-f0-9]{16}$/.test(m)||typeof _!="string"||!/^[a-f0-9]{64}$/.test(_)||typeof b!="string"||b.length===0||b.length>131072||!n(p)||p.branchMode!=="epic"||p.executionBranch!==`epic/${s}`||typeof p.originBranch!="string"||!oe(p.originBranch)||typeof p.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(p.graphRevision)||p.isolatedSyntheticEpic!==!0||o.publicSafe!==!0||o.sanitized!==!0)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-invalid"};const l=await import("node:fs/promises"),h=await import("node:path"),A=await import("node:crypto");if(A.createHash("sha256").update(b).digest("hex")!==_)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-content-integrity-invalid"};const C=h.join(i,".neocortex"),I=h.join(C,"state.json"),w=h.join(i,...d.split("/"));let P;try{P=await l.readFile(I,"utf8")}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-missing"}}const R=A.createHash("sha256").update(P).digest("hex");let u;try{u=JSON.parse(P)}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-corrupt"}}if(!n(u)||!n(u.stories)||!n(u.epics)||L(u))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-not-full"};if(!n(u.config)||u.config.default_branch!==p.originBranch)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-origin-branch-conflict"};const c=u.stories[t];if(c!==void 0&&(!n(c)||c.epic_id!==s||c.story_file!==d||!n(c.inlineYolo)||c.inlineYolo.deterministicKey!==m))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-conflict"};const y=u.epics[s];if(y!==void 0&&(!n(y)||y.id!==s||y.source!=="inline-yolo-materialization"||y.branch_mode!=="epic"||y.execution_branch!==p.executionBranch||y.origin_branch!==p.originBranch||y.graph_revision!==p.graphRevision||!n(y.inlineYoloLifecycle)||y.inlineYoloLifecycle.deterministicKey!==m||y.inlineYoloLifecycle.isolatedSyntheticEpic!==!0||!Array.isArray(y.stories)))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-conflict"};const $=n(y)?y:{},S=Array.isArray($.stories)?$.stories:[];if(S.some(a=>typeof a!="string")||new Set(S).size!==S.length)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-story-list-invalid"};for(const a of S){const f=u.stories[a];if(!n(f)||f.id!==a||f.epic_id!==s)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-ownership-conflict"}}try{const a=await l.readFile(w,"utf8"),f=a.includes(`id: ${t}`)&&a.includes(`synthetic_key: ${m}`);if(a!==b&&!f)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-conflict"}}catch(a){if(a.code!=="ENOENT")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-unreadable"}}const k=S.includes(t)?[...S]:[...S,t],v={...u.stories,[t]:{...n(c)?c:{},id:t,epic_id:s,title:"Synthetic inline USER STORY for yolo",status:n(c)&&typeof c.status=="string"?c.status:"backlog",steps_completed:n(c)&&Array.isArray(c.steps_completed)?c.steps_completed:[],last_step:n(c)?c.last_step??null:null,branch_name:n(c)?c.branch_name??null:null,story_file:d,source:"inline-yolo-materialization",inlineYolo:{...n(c)&&n(c.inlineYolo)?c.inlineYolo:{},schemaVersion:2,deterministicKey:m,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0}}},x=k.filter(a=>n(v[a])&&te(v[a].status)).length,j=n(u.inlineYolo)?u.inlineYolo:{},G=n(j.materializations)?j.materializations:{},U=ee({...u,stories:v,epics:{...u.epics,[s]:{...$,id:s,title:typeof $.title=="string"?$.title:"Isolated synthetic inline yolo lifecycle",status:x===k.length&&k.length>0?"done":"in-progress",source:"inline-yolo-materialization",branch_mode:"epic",execution_branch:p.executionBranch,origin_branch:p.originBranch,graph_revision:p.graphRevision,stories:k,total_stories:k.length,completed_stories:x,...x===k.length&&k.length>0?{}:{completed_at:null},inlineYoloLifecycle:{schemaVersion:2,deterministicKey:m,isolatedSyntheticEpic:!0}}},inlineYolo:{...j,schemaVersion:2,materializations:{...G,[t]:{schemaVersion:2,epicId:s,storyId:t,storyPath:d,deterministicKey:m,storyContentSha256:_,sourceStateSha256:R,lifecycle:p,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0,pipelineTrigger:`*yolo @${d}`,reasonCodes:Array.isArray(o.reasonCodes)?o.reasonCodes:[]}}},last_updated:new Date().toISOString()}),M=`${Date.now()}-${A.randomBytes(6).toString("hex")}`,Y=h.join(C,`state.json.tmp.${M}`),O=`${w}.tmp.${M}`,F=h.join(C,`state.json.backup-${new Date().toISOString().replace(/[:.]/g,"-")}`),H=h.join(C,"state.json.inline-yolo.lock");let N=!1,E;const V=async a=>{let f;try{f=await l.open(a,"r"),await f.sync()}catch(g){const z=g.code;if(!["EINVAL","ENOTSUP","EPERM","EISDIR"].includes(z??""))throw g}finally{await f?.close().catch(()=>{})}},B=async(a,f)=>{const g=await l.open(a,"wx",384);try{await g.writeFile(f,"utf8"),await g.sync()}finally{await g.close()}};try{await l.mkdir(C,{recursive:!0}),await l.mkdir(h.dirname(w),{recursive:!0});try{E=await l.open(H,"wx",384),await E.writeFile(`${process.pid}
4
- ${R}
5
- `,"utf8"),await E.sync()}catch(z){if(z.code==="EEXIST")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-writeback-locked"};throw z}const a=await l.readFile(I,"utf8");if(A.createHash("sha256").update(a).digest("hex")!==R)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-cas-conflict"};try{await l.access(w)}catch{await B(O,b),await l.rename(O,w),await V(h.dirname(w)),N=!0}await l.copyFile(I,F);const g=await l.open(F,"r");try{await g.sync()}finally{await g.close()}return await B(Y,JSON.stringify(U,null,2)),await l.rename(Y,I),await V(C),process.stderr.write(`[Neocortex] inline yolo story materialized with bounded full-state merge; story=${t}; backup=${h.basename(F)}.
6
- `),{applied:!0,blocking:!1,reasonCode:"inline-yolo-materialized"}}catch(a){await Promise.allSettled([l.unlink(Y),l.unlink(O)]),N&&await l.readFile(w,"utf8").catch(()=>{})===b&&await l.unlink(w).catch(()=>{});const f=a.message??String(a);return process.stderr.write(`[Neocortex] inline yolo materialization failed: ${f}.
7
- `),{applied:!1,blocking:!0,reasonCode:"inline-yolo-persistence-failed"}}finally{await E?.close().catch(()=>{}),E&&await l.unlink(H).catch(()=>{})}}async function ue(e,i){if(!e||e.stateMutated!==!0)return{applied:!1,blocking:!1,reasonCode:"state-writeback-not-requested"};if(e.stateMutationStrategy==="merge-inline-yolo-v2"||e.stateMutationReason==="inline-yolo-materialized-synthetic-story")return ie(e,i);if(e.stateMutationStrategy==="state-migration-v1"||e.stateMigrationPlan!==void 0){const r=e.stateMigrationPlan,s=new Set(["schemaVersion","operationId","sourceSchemaVersion","targetSchemaVersion","sourceCanonicalHash","targetCanonicalHash","steps","migratedEpicIds","migratedStoryIds","preservedUnknownFieldCount","reasonCodes"]);if(!n(r)||Object.keys(r).some(t=>!s.has(t))||r.schemaVersion!=="StateMigrationPlan/1.0"||typeof r.operationId!="string"||!/^smig_[a-f0-9]{32}$/.test(r.operationId)||typeof r.sourceCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(r.sourceCanonicalHash)||typeof r.targetCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(r.targetCanonicalHash)||![0,1,"absent"].includes(r.sourceSchemaVersion)||r.targetSchemaVersion!==1||!Array.isArray(r.steps)||r.steps.length>8192||r.steps.some(t=>!n(t)||Object.keys(t).some(d=>!["kind","source","target"].includes(d))||!["initialize-collection","merge-epic","merge-story","preserve-legacy","remove-legacy","set-schema-version"].includes(String(t.kind))||typeof t.target!="string"||t.target.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(t.target)||t.source!==void 0&&(typeof t.source!="string"||t.source.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(t.source)))||!T(r.migratedEpicIds,4096)||!T(r.migratedStoryIds,4096)||!T(r.reasonCodes,32)||!Number.isSafeInteger(r.preservedUnknownFieldCount)||r.preservedUnknownFieldCount<0)return{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"};try{const t=q(i,r),d=`.neocortex/state.json.migration-backup-${t.operationId}`;return process.stderr.write(`[P220-EV-STATE-MIGRATION] outcome=${t.outcome}; operation=${t.operationId}; backup=${t.backupHash?d:"none"}.
8
- `),{applied:t.outcome==="applied",blocking:!1,reasonCode:t.outcome==="applied"?"state-migration-applied":"state-migration-replay-verified"}}catch(t){const d=t instanceof J?t.reasonCode:"state-migration-apply-failed";return process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=${d}.
9
- `),{applied:!1,blocking:!0,reasonCode:d}}}const o=e.migratedState;return!o||typeof o!="object"||Array.isArray(o)?{applied:!1,blocking:!0,reasonCode:"state-writeback-payload-missing"}:L(o)?(process.stderr.write(`[Neocortex] Refused projected/partial state replacement; canonical state was not modified.
1
+ import{statSync as G}from"node:fs";import{join as q}from"node:path";import{YoloopClientStateStore as D}from"./yoloop-client-state-store.js";import{isYoloopInvocation as J}from"./target-normalization.js";import{applyStateMigration as X,StateMigrationApplyError as Q}from"../migrations/state-json.js";function ee(e){return J(e)}const j=Object.freeze({stateReadFailed:"YOLOOP_STATE_READ_FAILED",authoritativeWritebackFailed:"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED",auxiliaryWritebackFailed:"YOLOOP_AUXILIARY_WRITEBACK_FAILED"});class te extends Error{reasonCode;constructor(o){super(o),this.reasonCode=o,this.name="YoloopStateReadError"}}function W(e,o){return(e instanceof Error?e.message:String(e)).match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??o}const oe=/^\s*\*?(yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i;function ue(e){if(typeof e.args!="string"||e.args.length===0)return;const o=e.args.match(oe);if(!o)return;const i=o[0];if(e.args.slice(i.length).trim()!=="")return;let a=!1;try{const t=q(e.projectRoot,"docs","epics");a=G(t).isDirectory()}catch(t){const s=t instanceof Error?t.message:String(t);e.logger?.warn?.(`[Neocortex] Zero-config *yoloop hook (P121.05): could not stat docs/epics/: ${s}. Proceeding with raw args.`);return}a&&(e.args=`${i} @docs/epics/`,e.logger?.info?.("[Neocortex] Zero-config *yoloop (P121.05): auto-resolved empty args to @docs/epics/"))}async function ye(e,o,i){if(ee(e))try{return await new D(o).readAll(i)}catch(r){const a=W(r,j.stateReadFailed);throw process.stderr.write(`[yoloop] ${a}. Local yoloop authority was not read; no request was sent.
2
+ `),new te(a)}}async function fe(e,o,i){if(!e)return{ok:!0,authoritative:!1,reasonCodes:[]};const r=e.yoloopStateUpdate;if(!r||!Array.isArray(r.operations)||r.operations.length===0)return{ok:!0,authoritative:!1,reasonCodes:[]};const a=r.operations.some(t=>t.type==="rollover_session");try{return await new D(o).applyUpdate(r,i),{ok:!0,authoritative:a,reasonCodes:[]}}catch(t){const s=W(t,a?j.authoritativeWritebackFailed:j.auxiliaryWritebackFailed);return a?(process.stderr.write(`[yoloop] ${s}. Authoritative rollover was not persisted; no continuation instructions were released.
3
+ `),{ok:!1,authoritative:!0,reasonCodes:[s]}):(process.stderr.write(`[yoloop] ${s}. Auxiliary state update was not persisted; retry the same command.
4
+ `),{ok:!0,authoritative:!1,reasonCodes:[s]})}}function n(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function L(e,o){return Array.isArray(e)&&e.length<=o&&e.every(i=>typeof i=="string"&&i.length>0&&i.length<=160&&/^[A-Za-z0-9_.:+-]+$/.test(i))}function U(e){return n(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 ie(e){const o={...e};return delete o.scope,delete o.stateSummary,delete o.graphRetrieval,delete o.runnerBootstrap,delete o.projectEvidence,delete o.continuity,delete o.implementCheckpoint,o}function re(e){return typeof e=="string"&&["done","completed","merged"].includes(e.trim().toLowerCase())}function ne(e){return/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(e)&&!e.includes("..")&&!e.includes("//")&&!e.includes("@{")&&!e.endsWith("/")&&!e.endsWith(".")&&!e.endsWith(".lock")}async function ae(e,o){const i=e.syntheticStory;if(!n(i))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-missing"};const r=i.schemaVersion,a=i.epicId,t=i.storyId,s=i.storyPath,m=i.deterministicKey,b=i.storyContent,A=i.storyContentSha256,p=i.lifecycle;if(r!==2||typeof a!="string"||!/^P9\d{18}$/.test(a)||typeof t!="string"||t!==`${a}.01.000001`||typeof s!="string"||s!==`docs/stories/${t}.story.md`||typeof m!="string"||!/^[a-f0-9]{16}$/.test(m)||typeof A!="string"||!/^[a-f0-9]{64}$/.test(A)||typeof b!="string"||b.length===0||b.length>131072||!n(p)||p.branchMode!=="epic"||p.executionBranch!==`epic/${a}`||typeof p.originBranch!="string"||!ne(p.originBranch)||typeof p.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(p.graphRevision)||p.isolatedSyntheticEpic!==!0||i.publicSafe!==!0||i.sanitized!==!0)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-invalid"};const d=await import("node:fs/promises"),h=await import("node:path"),I=await import("node:crypto");if(I.createHash("sha256").update(b).digest("hex")!==A)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-content-integrity-invalid"};const C=h.join(o,".neocortex"),O=h.join(C,"state.json"),w=h.join(o,...s.split("/"));let R;try{R=await d.readFile(O,"utf8")}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-missing"}}const v=I.createHash("sha256").update(R).digest("hex");let u;try{u=JSON.parse(R)}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-corrupt"}}if(!n(u)||!n(u.stories)||!n(u.epics)||U(u))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-not-full"};if(!n(u.config)||u.config.default_branch!==p.originBranch)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-origin-branch-conflict"};const l=u.stories[t];if(l!==void 0&&(!n(l)||l.epic_id!==a||l.story_file!==s||!n(l.inlineYolo)||l.inlineYolo.deterministicKey!==m))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-conflict"};const y=u.epics[a];if(y!==void 0&&(!n(y)||y.id!==a||y.source!=="inline-yolo-materialization"||y.branch_mode!=="epic"||y.execution_branch!==p.executionBranch||y.origin_branch!==p.originBranch||y.graph_revision!==p.graphRevision||!n(y.inlineYoloLifecycle)||y.inlineYoloLifecycle.deterministicKey!==m||y.inlineYoloLifecycle.isolatedSyntheticEpic!==!0||!Array.isArray(y.stories)))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-conflict"};const E=n(y)?y:{},S=Array.isArray(E.stories)?E.stories:[];if(S.some(c=>typeof c!="string")||new Set(S).size!==S.length)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-story-list-invalid"};for(const c of S){const f=u.stories[c];if(!n(f)||f.id!==c||f.epic_id!==a)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-ownership-conflict"}}try{const c=await d.readFile(w,"utf8"),f=c.includes(`id: ${t}`)&&c.includes(`synthetic_key: ${m}`);if(c!==b&&!f)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 k=S.includes(t)?[...S]:[...S,t],P={...u.stories,[t]:{...n(l)?l:{},id:t,epic_id:a,title:"Synthetic inline USER STORY for yolo",status:n(l)&&typeof l.status=="string"?l.status:"backlog",steps_completed:n(l)&&Array.isArray(l.steps_completed)?l.steps_completed:[],last_step:n(l)?l.last_step??null:null,branch_name:n(l)?l.branch_name??null:null,story_file:s,source:"inline-yolo-materialization",inlineYolo:{...n(l)&&n(l.inlineYolo)?l.inlineYolo:{},schemaVersion:2,deterministicKey:m,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0}}},z=k.filter(c=>n(P[c])&&re(P[c].status)).length,x=n(u.inlineYolo)?u.inlineYolo:{},K=n(x.materializations)?x.materializations:{},Z=ie({...u,stories:P,epics:{...u.epics,[a]:{...E,id:a,title:typeof E.title=="string"?E.title:"Isolated synthetic inline yolo lifecycle",status:z===k.length&&k.length>0?"done":"in-progress",source:"inline-yolo-materialization",branch_mode:"epic",execution_branch:p.executionBranch,origin_branch:p.originBranch,graph_revision:p.graphRevision,stories:k,total_stories:k.length,completed_stories:z,...z===k.length&&k.length>0?{}:{completed_at:null},inlineYoloLifecycle:{schemaVersion:2,deterministicKey:m,isolatedSyntheticEpic:!0}}},inlineYolo:{...x,schemaVersion:2,materializations:{...K,[t]:{schemaVersion:2,epicId:a,storyId:t,storyPath:s,deterministicKey:m,storyContentSha256:A,sourceStateSha256:v,lifecycle:p,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0,pipelineTrigger:`*yolo @${s}`,reasonCodes:Array.isArray(i.reasonCodes)?i.reasonCodes:[]}}},last_updated:new Date().toISOString()}),N=`${Date.now()}-${I.randomBytes(6).toString("hex")}`,Y=h.join(C,`state.json.tmp.${N}`),T=`${w}.tmp.${N}`,F=h.join(C,`state.json.backup-${new Date().toISOString().replace(/[:.]/g,"-")}`),H=h.join(C,"state.json.inline-yolo.lock");let M=!1,_;const V=async c=>{let f;try{f=await d.open(c,"r"),await f.sync()}catch(g){const $=g.code;if(!["EINVAL","ENOTSUP","EPERM","EISDIR"].includes($??""))throw g}finally{await f?.close().catch(()=>{})}},B=async(c,f)=>{const g=await d.open(c,"wx",384);try{await g.writeFile(f,"utf8"),await g.sync()}finally{await g.close()}};try{await d.mkdir(C,{recursive:!0}),await d.mkdir(h.dirname(w),{recursive:!0});try{_=await d.open(H,"wx",384),await _.writeFile(`${process.pid}
5
+ ${v}
6
+ `,"utf8"),await _.sync()}catch($){if($.code==="EEXIST")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-writeback-locked"};throw $}const c=await d.readFile(O,"utf8");if(I.createHash("sha256").update(c).digest("hex")!==v)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-cas-conflict"};try{await d.access(w)}catch{await B(T,b),await d.rename(T,w),await V(h.dirname(w)),M=!0}await d.copyFile(O,F);const g=await d.open(F,"r");try{await g.sync()}finally{await g.close()}return await B(Y,JSON.stringify(Z,null,2)),await d.rename(Y,O),await V(C),process.stderr.write(`[Neocortex] inline yolo story materialized with bounded full-state merge; story=${t}; backup=${h.basename(F)}.
7
+ `),{applied:!0,blocking:!1,reasonCode:"inline-yolo-materialized"}}catch(c){await Promise.allSettled([d.unlink(Y),d.unlink(T)]),M&&await d.readFile(w,"utf8").catch(()=>{})===b&&await d.unlink(w).catch(()=>{});const f=c.message??String(c);return process.stderr.write(`[Neocortex] inline yolo materialization failed: ${f}.
8
+ `),{applied:!1,blocking:!0,reasonCode:"inline-yolo-persistence-failed"}}finally{await _?.close().catch(()=>{}),_&&await d.unlink(H).catch(()=>{})}}async function ge(e,o){if(!e||e.stateMutated!==!0)return{applied:!1,blocking:!1,reasonCode:"state-writeback-not-requested"};if(e.stateMutationStrategy==="merge-inline-yolo-v2"||e.stateMutationReason==="inline-yolo-materialized-synthetic-story")return ae(e,o);if(e.stateMutationStrategy==="state-migration-v1"||e.stateMigrationPlan!==void 0){const r=e.stateMigrationPlan,a=new Set(["schemaVersion","operationId","sourceSchemaVersion","targetSchemaVersion","sourceCanonicalHash","targetCanonicalHash","steps","migratedEpicIds","migratedStoryIds","preservedUnknownFieldCount","reasonCodes"]);if(!n(r)||Object.keys(r).some(t=>!a.has(t))||r.schemaVersion!=="StateMigrationPlan/1.0"||typeof r.operationId!="string"||!/^smig_[a-f0-9]{32}$/.test(r.operationId)||typeof r.sourceCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(r.sourceCanonicalHash)||typeof r.targetCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(r.targetCanonicalHash)||![0,1,"absent"].includes(r.sourceSchemaVersion)||r.targetSchemaVersion!==1||!Array.isArray(r.steps)||r.steps.length>8192||r.steps.some(t=>!n(t)||Object.keys(t).some(s=>!["kind","source","target"].includes(s))||!["initialize-collection","merge-epic","merge-story","preserve-legacy","remove-legacy","set-schema-version"].includes(String(t.kind))||typeof t.target!="string"||t.target.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(t.target)||t.source!==void 0&&(typeof t.source!="string"||t.source.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(t.source)))||!L(r.migratedEpicIds,4096)||!L(r.migratedStoryIds,4096)||!L(r.reasonCodes,32)||!Number.isSafeInteger(r.preservedUnknownFieldCount)||r.preservedUnknownFieldCount<0)return{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"};try{const t=X(o,r),s=`.neocortex/state.json.migration-backup-${t.operationId}`;return process.stderr.write(`[P220-EV-STATE-MIGRATION] outcome=${t.outcome}; operation=${t.operationId}; backup=${t.backupHash?s:"none"}.
9
+ `),{applied:t.outcome==="applied",blocking:!1,reasonCode:t.outcome==="applied"?"state-migration-applied":"state-migration-replay-verified"}}catch(t){const s=t instanceof Q?t.reasonCode:"state-migration-apply-failed";return process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=${s}.
10
+ `),{applied:!1,blocking:!0,reasonCode:s}}}const i=e.migratedState;return!i||typeof i!="object"||Array.isArray(i)?{applied:!1,blocking:!0,reasonCode:"state-writeback-payload-missing"}:U(i)?(process.stderr.write(`[Neocortex] Refused projected/partial state replacement; canonical state was not modified.
10
11
  `),{applied:!1,blocking:!0,reasonCode:"state-writeback-partial-rejected"}):(process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=state-migration-plan-missing-or-invalid; canonical state was not modified.
11
- `),{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"})}async function ye(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(i){const o=i instanceof Error?i.message:String(i);return e.logger?.warn?.(`[neocortex] discovery hook (lazy load) failed: ${o}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`lazy load error: ${o}`}}}async function fe(e){if(!e.featureFlag)return{applied:!1,reason:"flag_off"};try{return await(await import("../graph-retrieval/pre-command-hook.js")).runGraphRetrievalHook(e)}catch(i){const o=i instanceof Error?i.message:String(i);return e.logger?.warn?.(`[neocortex] graph retrieval hook (lazy load) failed: ${o}. Proceeding without enrichment.`),{applied:!1,reason:"hook_error",warning:o}}}export{X as isYoloopTrigger,le as maybeAutoResolveYoloopArgs,ye as maybeRunDiscoveryHook,fe as maybeRunGraphRetrievalHook,ue as persistMigratedStateFromResponse,pe as persistYoloopFromResponse,de as readYoloopForRequest};
12
+ `),{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"})}async function he(e){if(!e.featureFlag)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"flag off"};try{return await(await import("./discovery-hook.js")).runDiscoveryHook(e)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger?.warn?.(`[neocortex] discovery hook (lazy load) failed: ${i}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`lazy load error: ${i}`}}}async function me(e){if(!e.featureFlag)return{applied:!1,reason:"flag_off"};try{return await(await import("../graph-retrieval/pre-command-hook.js")).runGraphRetrievalHook(e)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger?.warn?.(`[neocortex] graph retrieval hook (lazy load) failed: ${i}. Proceeding without enrichment.`),{applied:!1,reason:"hook_error",warning:i}}}export{j as YOLOOP_PERSISTENCE_REASON_CODES,te as YoloopStateReadError,ee as isYoloopTrigger,ue as maybeAutoResolveYoloopArgs,he as maybeRunDiscoveryHook,me as maybeRunGraphRetrievalHook,ge as persistMigratedStateFromResponse,fe as persistYoloopFromResponse,ye as readYoloopForRequest};
@@ -1 +1 @@
1
- import{promises as u}from"node:fs";import{createHash as Y}from"node:crypto";import{join as _,dirname as U}from"node:path";import{hostname as I}from"node:os";import{setSecureFilePermissions as F,setSecureDirPermissions as K}from"../config/secure-config.js";import{RECOVERY_HISTORY_CAP as g}from"./shared-yoloop-types.js";const b=".neocortex",m="yoloop-state.json",V="yoloop.lock",M="yoloop-state.mutation.lock",T="yoloop-session-rollover.json",q=360*60*1e3,$=3e4,B=200,C=Object.freeze(["rollover-session-v1"]),J={warn:()=>{},info:()=>{},error:()=>{}};function S(t){const e=t.slice(0,10);return{version:"1.1",lastResetAt:t,storiesRunToday:0,iterationsToday:0,iterationsTodayDate:e,tokensUsedToday:0,lastRunAt:null,coolDownUntil:null,totalRunsAllTime:0,totalStoriesAllTime:0,currentSession:null,continuationPolicy:"p205-finite-resume-v2",pendingContinuationAuthorities:[],continuationReceipts:[],continuationRecoveryReceipts:[]}}function ue(t){return{lock:null,state:S(t),capabilities:C}}class he{stateDir;statePath;lockPath;mutationLockPath;rolloverManifestPath;logger;constructor(e,n=J){this.stateDir=_(e,b),this.statePath=_(this.stateDir,m),this.lockPath=_(this.stateDir,V),this.mutationLockPath=_(this.stateDir,M),this.rolloverManifestPath=_(this.stateDir,T),this.logger=n}async readAll(e){const n=e??new Date().toISOString();await this.cleanupOrphanTempFiles(),await this.recoverSessionRolloverIfPresent(n);const[s,o]=await Promise.all([this.readLock(),this.readState(n)]);return{lock:await this.prepareLockForSnapshot(s,n),state:o,capabilities:C}}async applyUpdate(e,n){const s=n??new Date().toISOString();await this.ensureDir(),await this.recoverSessionRolloverIfPresent(s);for(const o of e.operations)await this.applyOperation(o,s)}async requestRunTransition(e,n){const s=n??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(()=>this.transitionRun(e,s))}async requestLifecycleAction(e,n={},s){const o=s??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(async()=>{const i=(await this.readState(o)).runControl;if(!i)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const a=Date.parse(o).toString(36),c=n.operationId??`op-${e}-${a}`,l=n.idempotencyKey??`idem-${e}-${a}`,h=i.receipts.find(y=>y.operationId===c||y.idempotencyKey===l);if(h){if(h.operationId===c&&h.idempotencyKey===l)return h;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}const O=Z(i.status,e);if(!O)throw new Error(R.has(i.status)?"YOLOOP_RUN_TERMINAL":"YOLOOP_RUN_TRANSITION_INVALID");return this.transitionRun(ee({current:i,action:e,target:O,operationId:c,idempotencyKey:l,occurredAt:o}),o)})}async applyOperation(e,n){switch(e.type){case"acquire_lock":await this.acquireLock(e.lock,n);return;case"release_lock":await this.releaseLock(e);return;case"write_state":await this.withMutationLock(async()=>{const s=await this.readState(n),{runControl:o,...r}=e.state;await this.writeState({...r,...s.runControl?{version:"1.2",runControl:s.runControl}:{}})});return;case"advance_epic":await this.advanceEpic(e.nextEpicIndex,e.nextEpicId,n);return;case"no_op":this.logger.info({event:"yoloop_noop"},"yoloop server sent no-op");return;case"reserve_continuation_authority":await this.reserveContinuationAuthority(e.authority,n);return;case"acknowledge_continuation_authority":await this.acknowledgeContinuationAuthority(e.idempotencyKey,e.receipt,n);return;case"repair_continuation_authority":await this.repairContinuationAuthority(e.beforeHash,e.authority,e.receipt,n);return;case"switch_continuation_policy":await this.switchContinuationPolicy(e.policy,e.session,n);return;case"transition_run":await this.requestRunTransition(e,n);return;case"start_successor_run":await this.withMutationLock(()=>this.startSuccessorRun(e,n));return;case"rollover_session":await this.withMutationLock(()=>this.rolloverSession(e,n));return;case"recovery_attempted":await this.appendRecoveryAttempt(e.attempt,n);return;case"recovery_resolved":await this.resolveRecoveryAttempt(e.attempt_id,e.outcome,n);return;default:{const s=e;throw this.logger.error({event:"yoloop_unknown_op",op:s},"unknown yoloop operation rejected"),new Error("YOLOOP_STATE_OPERATION_UNSUPPORTED")}}}async reserveContinuationAuthority(e,n){const s=await this.readState(n),o=s.pendingContinuationAuthorities??[],r=typeof e.idempotencyKey=="string"?e.idempotencyKey:"";if(!r)throw new Error("YOLOOP_CONTINUATION_AUTHORITY_INVALID");const i=o.find(a=>a.idempotencyKey===r);if(i){if(d(i)===d(e))return;throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}if(o.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");await this.writeState({...s,pendingContinuationAuthorities:[...o,e]})}async acknowledgeContinuationAuthority(e,n,s){const o=await this.readState(s),r=o.pendingContinuationAuthorities??[],i=r.findIndex(h=>h.idempotencyKey===e);if(i<0)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const a=r[i];if(n.idempotencyKey!==e||n.sessionId!==a.sessionId||JSON.stringify(n.storyIds)!==JSON.stringify(a.storyIds))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const c=r.filter((h,O)=>O!==i),l=o.continuationReceipts??[];await this.writeState({...o,pendingContinuationAuthorities:c,continuationReceipts:[...l.slice(-63),n]})}async repairContinuationAuthority(e,n,s,o){const r=await this.readState(o),i=r.pendingContinuationAuthorities??[],a=r.continuationRecoveryReceipts??[],c=typeof s.idempotencyKey=="string"?s.idempotencyKey:"",l=a.find(y=>y.idempotencyKey===c);if(l){if(d(l)===d(s))return;throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_CONFLICT")}if(i.length!==1||p("p208-legacy-authority-before-v1",i[0])!==e)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const h=p("p208-legacy-authority-after-v1",n);if(s.beforeHash!==e||s.afterHash!==h)throw new Error("YOLOOP_CONTINUATION_RECOVERY_HASH_MISMATCH");const O={...s};if(delete O.idempotencyKey,!c||p("p208-legacy-authority-recovery-receipt-v1",O)!==c)throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_INVALID");await this.writeState({...r,pendingContinuationAuthorities:[n],continuationRecoveryReceipts:[...a.slice(-63),s]})}async switchContinuationPolicy(e,n,s){const o=await this.readState(s);if(o.currentSession||(o.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");try{await u.copyFile(this.statePath,`${this.statePath}.policy-backup`)}catch(r){if(r.code!=="ENOENT")throw r}await this.writeState({...o,continuationPolicy:e,continuationSession:n})}async appendRecoveryAttempt(e,n){const s=await this.readState(n),o=s.recovery_history??[];if(o.some(c=>c.attempted_at===e.attempted_at&&c.story_id===e.story_id)){this.logger.warn({event:"recovery_attempted_duplicate",story_id:e.story_id},"duplicate recovery_attempted op; skipping");return}const i=H([...o,e]),a={...s,recovery_history:i};await this.writeState(a),this.logger.info({event:"recovery_attempted_persisted",story_id:e.story_id,history_size:i.length},"recovery attempt persisted")}async resolveRecoveryAttempt(e,n,s){const o=await this.readState(s),r=o.recovery_history??[],i=r.findIndex(h=>h.recovery_step_id_tokenized===e);if(i===-1){this.logger.warn({event:"recovery_resolve_orphan",attempt_id:e},"recovery_resolved op had no matching attempt; skipping");return}const a=r[i];if(a.outcome===n&&a.finished_at){this.logger.info({event:"recovery_resolved_duplicate",attempt_id:e,outcome:n},"duplicate recovery_resolved op; skipping");return}const c=r.slice();c[i]={...a,outcome:n,finished_at:s};const l={...o,recovery_history:c};await this.writeState(l),this.logger.info({event:"recovery_resolved_persisted",attempt_id:e,outcome:n},"recovery attempt resolved")}async acquireLock(e,n){const s={...e,pid:process.pid,hostname:I(),ownerKind:"client",startedAt:e.startedAt||n,leaseId:e.leaseId??ne(e.sessionId,n),leaseState:"active",leaseAcquiredAt:e.leaseAcquiredAt??n,leaseDurationMs:e.leaseDurationMs??q,leaseExpiresAt:e.leaseExpiresAt??e.ttlExpiresAt},o=JSON.stringify(s,null,2);try{const r=await u.open(this.lockPath,"wx");try{await r.writeFile(o,"utf8")}finally{await r.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired",pid:s.pid,sessionId:s.sessionId},"yoloop lock acquired");return}catch(r){const i=r;if(i.code!=="EEXIST")throw this.logger.error({event:"yoloop_lock_acquire_error",err:i.message},"failed to acquire yoloop lock"),r;const a=await this.readLock();if(a&&this.isSameClientSessionLock(a,s)){this.logger.info({event:"yoloop_lock_acquire_duplicate",sessionId:s.sessionId},"duplicate acquire_lock for current yoloop session; treating as no-op");return}if(!await this.maybeRecoverOrphanLock(n))throw this.logger.warn({event:"yoloop_lock_held"},"yoloop lock held by another live process"),r;const l=await u.open(this.lockPath,"wx");try{await l.writeFile(o,"utf8")}finally{await l.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired_after_recovery",pid:s.pid},"yoloop lock acquired after orphan recovery")}}async releaseLock(e){const n=await this.readState(new Date().toISOString()),s=await this.readLock();if(n.runControl){if(!e.expectedRunId||!e.expectedSessionId||!e.expectedLeaseId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(e.expectedRunId!==n.runControl.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(!s||e.expectedSessionId!==s.sessionId||e.expectedLeaseId!==s.leaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}try{await u.unlink(this.lockPath),this.logger.info({event:"yoloop_lock_released"},"yoloop lock released")}catch(o){const r=o;if(r.code==="ENOENT"){this.logger.info({event:"yoloop_lock_release_noop"},"yoloop lock release noop (file absent)");return}this.logger.warn({event:"yoloop_lock_release_error",err:r.message},"unexpected error releasing yoloop lock")}}async readLock(){try{const e=await u.readFile(this.lockPath,"utf8"),n=JSON.parse(e),s=n.currentEpicId??n.epicId??"";return{pid:n.pid??0,hostname:n.hostname??"",...n.ownerKind?{ownerKind:n.ownerKind}:{},...n.ownerPidState?{ownerPidState:n.ownerPidState}:{},...typeof n.leaseId=="string"?{leaseId:n.leaseId}:{},...n.leaseState?{leaseState:n.leaseState}:{},...typeof n.leaseAcquiredAt=="string"?{leaseAcquiredAt:n.leaseAcquiredAt}:{},...typeof n.leaseDurationMs=="number"?{leaseDurationMs:n.leaseDurationMs}:{},...typeof n.leaseExpiresAt=="string"?{leaseExpiresAt:n.leaseExpiresAt}:{},startedAt:n.startedAt??"",sessionId:n.sessionId??"",mode:n.mode??"epic-id",inputPath:n.inputPath??"",epicQueue:n.epicQueue??(s?[s]:[]),currentEpicIndex:n.currentEpicIndex??0,currentEpicId:s,ttlExpiresAt:n.ttlExpiresAt??"",epicId:n.epicId??s}}catch{return null}}async readState(e){try{const n=await u.readFile(this.statePath,"utf8"),s=JSON.parse(n);return se(s,e)}catch(n){const s=n;return s.code!=="ENOENT"&&this.logger.warn({event:"yoloop_state_read_error",err:s.message},"yoloop state file unreadable; using defaults"),S(e)}}async writeState(e){const n=`${this.statePath}.tmp.${process.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{const o=await u.open(n,"w",384);try{await o.writeFile(s,"utf8"),await o.sync()}finally{await o.close()}this.trySetFilePerms(n),await u.rename(n,this.statePath),await this.syncStateDirectory()}catch(o){const r=o;this.logger.error({event:"yoloop_state_write_error",err:r.message},"failed to write yoloop state");try{await u.unlink(n)}catch{}throw o}}async rolloverSession(e,n){f(e);const s=await this.readRolloverManifest();if(s){if(G(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSessionRollover(s.operation,n);return}else if(s.phase==="prepared")throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT")}const o=await this.readState(n),r=await this.readLock();P(e,o,r),await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSessionRollover(e,n)}async completePreparedSessionRollover(e,n){const s=await this.readState(n);let o=d(s)===d(e.next);if(!o){const i=await this.readLock();P(e,s,i),await this.writeState(e.next),o=!0}const r=await this.readLock();if(e.expectedSessionId===null||e.expectedLeaseId===null){if(e.expectedSessionId!==null||e.expectedLeaseId!==null||r)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(r){if(r.sessionId!==e.expectedSessionId||r.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await u.unlink(this.lockPath),await this.syncStateDirectory()}else if(!o)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_session_rollover_applied",runId:e.runId,operationId:e.operationId,coolDownUntil:e.coolDownUntil},"yoloop per-run-cap session rollover applied")}async recoverSessionRolloverIfPresent(e){try{await u.access(this.rolloverManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readRolloverManifest();n?.phase==="prepared"&&await this.completePreparedSessionRollover(n.operation,e)})}async readRolloverManifest(){try{const e=JSON.parse(await u.readFile(this.rolloverManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSessionRolloverManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="rollover_session")throw new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT");return f(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT")}}async writeRolloverManifest(e){const n=`${this.rolloverManifestPath}.tmp.${process.pid}.${Date.now()}`,s=await u.open(n,"w",384);try{await s.writeFile(JSON.stringify(e,null,2),"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await u.rename(n,this.rolloverManifestPath),await this.syncStateDirectory()}async advanceEpic(e,n,s){const o=await this.readState(s);if(!o.currentSession){this.logger.warn({event:"yoloop_advance_no_session",nextEpicId:n},"advance_epic with no active session; skipping");return}const r={...o,currentSession:{...o.currentSession,currentEpicIndex:e}};await this.writeState(r),this.logger.info({event:"yoloop_epic_advance",nextEpicId:n,nextIndex:e},"yoloop advanced to next epic")}async ensureDir(){try{await u.mkdir(this.stateDir,{recursive:!0}),this.trySetDirPerms(this.stateDir)}catch(e){const n=e;throw this.logger.error({event:"yoloop_mkdir_error",err:n.message,path:this.stateDir},"failed to ensure .neocortex/ directory"),e}}async syncStateDirectory(){try{const e=await u.open(this.stateDir,"r");try{await e.sync()}finally{await e.close()}}catch(e){const n=e.code;if(n!=="EINVAL"&&n!=="EISDIR"&&n!=="ENOTSUP"&&n!=="EPERM")throw e}}async withMutationLock(e){let n=null;for(let s=0;s<B;s+=1)try{n=await u.open(this.mutationLockPath,"wx",384),await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await n.sync();break}catch(o){if(o.code!=="EEXIST")throw o;try{const r=await u.stat(this.mutationLockPath);if(Date.now()-r.mtimeMs>$){await u.unlink(this.mutationLockPath);continue}}catch{continue}await new Promise(r=>setTimeout(r,5))}if(!n)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");try{return await e()}finally{await n.close().catch(()=>{}),await u.unlink(this.mutationLockPath).catch(()=>{})}}async transitionRun(e,n){v(e);const s=await this.readState(n),o=s.runControl,r=o?.receipts.find(l=>l.operationId===e.operationId||l.idempotencyKey===e.idempotencyKey);if(r){if(r.operationId===e.operationId&&r.idempotencyKey===e.idempotencyKey&&r.payloadHash===e.payloadHash)return r;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(o&&o.runId!==e.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((o?.revision??0)!==e.expectedRevision)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((o?.latestSnapshotHash??null)!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT");E(o,e);const c=e.next.receipts.at(-1);if(!c)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");return await this.writeState({...s,version:"1.2",runControl:e.next}),this.logger.info({event:"yoloop_run_transition_committed",runId:e.runId,operationId:e.operationId,revision:c.revision,status:c.status},"yoloop run transition committed"),c}async startSuccessorRun(e,n){X(e);const s=await this.readState(n),o=s.runControl,r={schemaVersion:"YoloopRunPredecessor/1.0",runId:e.previousRunId,revision:e.expectedRevision,snapshotHash:e.expectedSnapshotHash,successorOperationId:e.operationId,publicSafe:!0},i=o?.receipts.find(l=>l.operationId===e.operationId||l.idempotencyKey===e.idempotencyKey);if(i){if(i.operationId===e.operationId&&i.idempotencyKey===e.idempotencyKey&&e.next.receipts.at(-1)?.payloadHash===i.payloadHash&&d(o?.predecessor)===d(r))return i;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(!o||o.runId!==e.previousRunId||o.status!=="exhausted"||o.revision!==e.expectedRevision||o.latestSnapshotHash!==e.expectedSnapshotHash||s.currentSession!==null||!s.coolDownUntil||Date.parse(s.coolDownUntil)>Date.parse(n))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const a=e.next.receipts.at(-1);if(!a||d(e.next.predecessor)!==d(r))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const c={type:"transition_run",runId:e.runId,operationId:e.operationId,idempotencyKey:e.idempotencyKey,expectedRevision:0,expectedSnapshotHash:null,payloadHash:a.payloadHash,next:e.next};return v(c),E(void 0,c),await this.writeState({...s,version:"1.2",runControl:e.next}),a}trySetFilePerms(e){try{F(e)}catch{}}trySetDirPerms(e){try{K(e)}catch{}}async prepareLockForSnapshot(e,n){if(!e)return null;if(e.ownerKind!=="client")return e;const s=k(e,n),o={...e,leaseState:s};if(s==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"lease_expired"},"expired client-owned yoloop lock lease recovered before snapshot echo"),null;if(!o.pid||o.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"invalid_pid"},"invalid PID in client-owned yoloop lock; recovered"),null;if(o.hostname&&o.hostname!==I())return{...o,ownerPidState:"unknown"};try{return process.kill(o.pid,0),{...o,ownerPidState:"live"}}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"dead_pid"},"stale client-owned yoloop lock recovered before snapshot echo"),null}}async maybeRecoverOrphanLock(e){const n=await this.readLock();if(!n)return!0;if(k(n,e)==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"lease_expired"},"expired yoloop lock lease recovered"),!0;if(!n.pid||n.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"invalid_pid"},"invalid PID in lock file; recovered"),!0;if(n.hostname&&n.hostname!==I())return this.logger.warn({event:"yoloop_lock_remote_host",ownerKind:n.ownerKind??"server",ownerPidState:"unknown"},"lock held by a remote host; honoring"),!1;try{return process.kill(n.pid,0),!1}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"dead_pid"},"orphan yoloop lock recovered"),!0}}async deleteLockBestEffort(){try{await u.unlink(this.lockPath)}catch{}}isSameClientSessionLock(e,n){return e.ownerKind==="client"&&e.sessionId===n.sessionId&&e.pid===process.pid&&e.hostname===I()}async cleanupOrphanTempFiles(){try{const e=U(this.statePath),n=await u.readdir(e),s=[`${m}.tmp.`,`${T}.tmp.`],o=n.filter(r=>s.some(i=>r.startsWith(i)));for(const r of o)try{await u.unlink(_(e,r))}catch{}}catch{}}}function d(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(d).join(",")}]`:`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${d(n)}`).join(",")}}`}function p(t,e){return Y("sha256").update(`${t}\0${d(e)}`).digest("hex")}function j(t){return p("p9390812898200217364-yoloop-session-v1",t)}function z(t){return p("p9390812898200217364-yoloop-rollover-v1",t)}function W(t){return p("p9390812898200217364-yoloop-successor-run-v1",t)}function G(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function f(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,expectedSessionId:t.expectedSessionId,expectedSessionFingerprint:t.expectedSessionFingerprint,expectedLeaseId:t.expectedLeaseId,coolDownUntil:t.coolDownUntil,reason:t.reason,exhaustedRun:t.exhaustedRun,next:t.next};if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.expectedSessionFingerprint)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0||!Number.isFinite(Date.parse(t.coolDownUntil))||!["YOLOOP_PER_RUN_CAP_REACHED","YOLOOP_SESSION_TIMEOUT"].includes(t.reason)||t.payloadHash!==z(n)||t.receipt.schemaVersion!=="YoloopSessionRolloverReceipt/1.0"||t.receipt.runId!==t.runId||t.receipt.operationId!==t.operationId||t.receipt.idempotencyKey!==t.idempotencyKey||t.receipt.payloadHash!==t.payloadHash||t.receipt.coolDownUntil!==t.coolDownUntil||t.receipt.revision!==(t.exhaustedRun?.revision??0)||t.receipt.snapshotHash!==(t.exhaustedRun?.latestSnapshotHash??null)||t.receipt.status!=="exhausted"||t.receipt.publicSafe!==!0)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(t.expectedSessionId===null!=(t.expectedLeaseId===null)||t.expectedSessionId!==null&&!e.test(t.expectedSessionId)||t.expectedLeaseId!==null&&!e.test(t.expectedLeaseId))throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}function X(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,previousRunId:t.previousRunId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:t.next};if(!e.test(t.runId)||!e.test(t.previousRunId)||t.runId===t.previousRunId||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<1||t.payloadHash!==W(n))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT")}function P(t,e,n){f(t);const s=e.currentSession;if(!s||j(s)!==t.expectedSessionFingerprint)throw new Error("YOLOOP_SESSION_ROLLOVER_SESSION_CONFLICT");const o=e.runControl;if((o?.revision??0)!==t.expectedRevision||(o?.latestSnapshotHash??null)!==t.expectedSnapshotHash||o&&o.runId!==t.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(t.expectedSessionId===null||t.expectedLeaseId===null){if(n)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(!n||n.sessionId!==t.expectedSessionId||n.leaseId!==t.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");const r=t.exhaustedRun;if(o)if(o.status==="exhausted"){if(d(r)!==d(o))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}else{if(!r||r.status!=="exhausted")throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const a=r.receipts.at(-1);if(!a)throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const c={type:"transition_run",runId:o.runId,operationId:a.operationId,idempotencyKey:a.idempotencyKey,expectedRevision:o.revision,expectedSnapshotHash:o.latestSnapshotHash,payloadHash:a.payloadHash,next:r};v(c),E(o,c)}else if(r)throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const i={...e,version:"1.2",coolDownUntil:t.coolDownUntil,currentSession:null,...r?{runControl:r}:{}};if(d(i)!==d(t.next))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}function A(t){const{receipts:e,...n}=t.next;return p("p220-yoloop-run-transition-payload-v1",{runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:n})}const R=new Set(["success","partial","blocked","failure","exhausted","cancelled"]),Q={created:["running","cancelling","exhausted"],running:["pausing","cancelling","success","partial","blocked","failure","exhausted"],pausing:["paused","cancelling","failure","exhausted"],paused:["resuming","cancelling","exhausted"],resuming:["running","cancelling","failure","exhausted"],cancelling:["cancelled","failure","exhausted"]};function Z(t,e){return e==="pause"?t==="running"?"pausing":null:e==="resume"?t==="paused"?"resuming":null:R.has(t)||t==="cancelling"?null:"cancelling"}function ee(t){const e=t.current.revision+1,n=t.action==="cancel"?["YOLOOP_RUN_CANCEL_REQUESTED"]:[],s={schemaVersion:"YoloopOperationalBudgetSummary/1.0",limits:t.current.operationalBudget.limits,usage:t.current.usage,exhaustedDimension:null},o={schemaVersion:"ProgressSnapshot/1.0",runId:t.current.runId,sequence:t.current.progressSnapshots.length+1,revision:e,operationId:t.operationId,boundary:t.action,phase:"before",status:t.current.status,occurredAt:t.occurredAt,parentSnapshotHash:t.current.latestSnapshotHash,budget:s,reasonCodes:n,publicSafe:!0},r=p("p220-yoloop-progress-snapshot-id-v1",{runId:o.runId,operationId:o.operationId,sequence:o.sequence,phase:o.phase}),i={...o,snapshotId:r,snapshotHash:p("p220-yoloop-progress-snapshot-v1",{...o,snapshotId:r})},a={...o,sequence:i.sequence+1,phase:"after",status:t.target,parentSnapshotHash:i.snapshotHash},c=p("p220-yoloop-progress-snapshot-id-v1",{runId:a.runId,operationId:a.operationId,sequence:a.sequence,phase:a.phase}),l={...a,snapshotId:c,snapshotHash:p("p220-yoloop-progress-snapshot-v1",{...a,snapshotId:c})},h={schemaVersion:"YoloopRunEvent/1.0",runId:t.current.runId,operationId:t.operationId,kind:"intent",sequence:t.current.events.length+1,revision:e,occurredAt:t.occurredAt,fromStatus:t.current.status,toStatus:t.target,reasonCodes:n,budgetDimension:null,parentEventHash:t.current.events.at(-1)?.eventHash??null,publicSafe:!0},O=p("p220-yoloop-run-event-id-v1",{runId:h.runId,operationId:h.operationId,sequence:h.sequence}),y={...h,eventId:O,eventHash:p("p220-yoloop-run-event-v1",{...h,eventId:O})},w={...t.current,revision:e,status:t.target,events:[...t.current.events,y],progressSnapshots:[...t.current.progressSnapshots,i,l],latestSnapshotHash:l.snapshotHash,receipts:[...t.current.receipts]},L={runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.current.revision,expectedSnapshotHash:t.current.latestSnapshotHash,next:w},N=A(L),D={schemaVersion:"YoloopRunTransitionReceipt/1.0",runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,payloadHash:N,revision:e,snapshotHash:l.snapshotHash,status:t.target};return{type:"transition_run",...L,payloadHash:N,next:{...w,receipts:[...w.receipts,D]}}}function v(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(t.payloadHash!==A(t))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}function E(t,e){const n=e.next,s=t?.events??[],o=t?.progressSnapshots??[],r=t?.receipts??[];if(n.schemaVersion!=="YoloopRunControl/1.0"||n.runId!==e.runId||n.revision!==e.expectedRevision+1||n.events.length!==s.length+1||n.progressSnapshots.length!==o.length+2||n.receipts.length!==r.length+1||d(n.events.slice(0,s.length))!==d(s)||d(n.progressSnapshots.slice(0,o.length))!==d(o)||d(n.receipts.slice(0,r.length))!==d(r))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t){if(R.has(t.status))throw new Error("YOLOOP_RUN_TERMINAL");const h=n.progressSnapshots.at(-2)?.boundary,O=t.status===n.status&&(h==="budget"||h==="retry");if(!(Q[t.status]??[]).includes(n.status)&&!O)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t.startedAt!==n.startedAt||t.deadlineAt!==n.deadlineAt)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(d(t.predecessor)!==d(n.predecessor))throw new Error("YOLOOP_RUN_TRANSITION_INVALID")}else if(n.status!=="created")throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const i=n.progressSnapshots.at(-2),a=n.progressSnapshots.at(-1),c=n.events.at(-1),l=n.receipts.at(-1);if(!i||!a||!c||!l||i.phase!=="before"||a.phase!=="after"||i.operationId!==e.operationId||a.operationId!==e.operationId||c.operationId!==e.operationId||i.runId!==e.runId||a.runId!==e.runId||c.runId!==e.runId||i.revision!==n.revision||a.revision!==n.revision||c.revision!==n.revision||i.parentSnapshotHash!==(t?.latestSnapshotHash??null)||a.parentSnapshotHash!==i.snapshotHash||n.latestSnapshotHash!==a.snapshotHash||l.schemaVersion!=="YoloopRunTransitionReceipt/1.0"||l.runId!==e.runId||l.operationId!==e.operationId||l.idempotencyKey!==e.idempotencyKey||l.payloadHash!==e.payloadHash||l.revision!==n.revision||l.snapshotHash!==n.latestSnapshotHash||l.status!==n.status||Date.parse(n.deadlineAt)<=Date.parse(n.startedAt))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");x(i),x(a),te(c,s.at(-1)?.eventHash??null)}function x(t){const{snapshotHash:e,...n}=t;if(e!==p("p220-yoloop-progress-snapshot-v1",n))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function te(t,e){const{eventHash:n,...s}=t;if(t.parentEventHash!==e||n!==p("p220-yoloop-run-event-v1",s))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function ne(t,e){return`lease-${oe(`${t}:${e}`)}`}function oe(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(36).padStart(7,"0")}function k(t,e){const n=t.leaseExpiresAt??t.ttlExpiresAt,s=Date.parse(n),o=Date.parse(e);return!Number.isFinite(s)||!Number.isFinite(o)?"unknown":s<=o?"expired":"active"}function se(t,e){const n=S(e);return{...t,version:t.version==="1.2"?"1.2":"1.1",lastResetAt:t.lastResetAt??n.lastResetAt,storiesRunToday:t.storiesRunToday??0,iterationsToday:t.iterationsToday??0,iterationsTodayDate:t.iterationsTodayDate??n.iterationsTodayDate,tokensUsedToday:t.tokensUsedToday??0,lastRunAt:t.lastRunAt??null,coolDownUntil:t.coolDownUntil??null,totalRunsAllTime:t.totalRunsAllTime??0,totalStoriesAllTime:t.totalStoriesAllTime??0,currentSession:t.currentSession??null,...t.runControl!==void 0?{runControl:t.runControl}:{},...t.continuationPolicy!==void 0?{continuationPolicy:t.continuationPolicy}:{},...t.continuationSession!==void 0?{continuationSession:t.continuationSession}:{},...t.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:t.pendingContinuationAuthorities}:{},...t.continuationReceipts!==void 0?{continuationReceipts:t.continuationReceipts}:{},...t.continuationRecoveryReceipts!==void 0?{continuationRecoveryReceipts:t.continuationRecoveryReceipts}:{},recovery_history:Array.isArray(t.recovery_history)?H(t.recovery_history):[]}}function H(t){return t.length<=g?t:t.slice(t.length-g)}export{C as YOLOOP_PERSISTENCE_CAPABILITIES,he as YoloopClientStateStore,A as buildYoloopRunTransitionPayloadHash,z as buildYoloopSessionRolloverPayloadHash,W as buildYoloopSuccessorRunPayloadHash,H as capRecoveryHistory,S as createDefaultCounters,ue as createDefaultState,j as fingerprintYoloopSession};
1
+ import{promises as u}from"node:fs";import{createHash as D}from"node:crypto";import{join as _,dirname as U}from"node:path";import{hostname as I}from"node:os";import{setSecureFilePermissions as F,setSecureDirPermissions as K}from"../config/secure-config.js";import{RECOVERY_HISTORY_CAP as g}from"./shared-yoloop-types.js";const b=".neocortex",m="yoloop-state.json",V="yoloop.lock",M="yoloop-state.mutation.lock",T="yoloop-session-rollover.json",q=360*60*1e3,$=3e4,B=200,C=Object.freeze(["rollover-session-v1"]),J={warn:()=>{},info:()=>{},error:()=>{}};function S(t){const e=t.slice(0,10);return{version:"1.1",lastResetAt:t,storiesRunToday:0,iterationsToday:0,iterationsTodayDate:e,tokensUsedToday:0,lastRunAt:null,coolDownUntil:null,totalRunsAllTime:0,totalStoriesAllTime:0,currentSession:null,continuationPolicy:"p205-finite-resume-v2",pendingContinuationAuthorities:[],continuationReceipts:[],continuationRecoveryReceipts:[]}}function ue(t){return{lock:null,state:S(t),capabilities:C}}class he{stateDir;statePath;lockPath;mutationLockPath;rolloverManifestPath;logger;constructor(e,n=J){this.stateDir=_(e,b),this.statePath=_(this.stateDir,m),this.lockPath=_(this.stateDir,V),this.mutationLockPath=_(this.stateDir,M),this.rolloverManifestPath=_(this.stateDir,T),this.logger=n}async readAll(e){const n=e??new Date().toISOString();await this.cleanupOrphanTempFiles(),await this.recoverSessionRolloverIfPresent(n);const[r,s]=await Promise.all([this.readLock(),this.readState(n)]);return{lock:await this.prepareLockForSnapshot(r,n),state:s,capabilities:C}}async applyUpdate(e,n){const r=n??new Date().toISOString();await this.ensureDir(),await this.recoverSessionRolloverIfPresent(r);for(const s of e.operations)await this.applyOperation(s,r)}async requestRunTransition(e,n){const r=n??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(()=>this.transitionRun(e,r))}async requestLifecycleAction(e,n={},r){const s=r??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(async()=>{const i=(await this.readState(s)).runControl;if(!i)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const a=Date.parse(s).toString(36),c=n.operationId??`op-${e}-${a}`,l=n.idempotencyKey??`idem-${e}-${a}`,h=i.receipts.find(O=>O.operationId===c||O.idempotencyKey===l);if(h){if(h.operationId===c&&h.idempotencyKey===l)return h;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}const y=Z(i.status,e);if(!y)throw new Error(R.has(i.status)?"YOLOOP_RUN_TERMINAL":"YOLOOP_RUN_TRANSITION_INVALID");return this.transitionRun(ee({current:i,action:e,target:y,operationId:c,idempotencyKey:l,occurredAt:s}),s)})}async applyOperation(e,n){switch(e.type){case"acquire_lock":await this.acquireLock(e.lock,n);return;case"release_lock":await this.releaseLock(e);return;case"write_state":await this.withMutationLock(async()=>{const r=await this.readState(n),{runControl:s,...o}=e.state;await this.writeState({...o,...r.runControl?{version:"1.2",runControl:r.runControl}:{}})});return;case"advance_epic":await this.advanceEpic(e.nextEpicIndex,e.nextEpicId,n);return;case"no_op":this.logger.info({event:"yoloop_noop"},"yoloop server sent no-op");return;case"reserve_continuation_authority":await this.reserveContinuationAuthority(e.authority,n);return;case"acknowledge_continuation_authority":await this.acknowledgeContinuationAuthority(e.idempotencyKey,e.receipt,n);return;case"repair_continuation_authority":await this.repairContinuationAuthority(e.beforeHash,e.authority,e.receipt,n);return;case"switch_continuation_policy":await this.switchContinuationPolicy(e.policy,e.session,n);return;case"transition_run":await this.requestRunTransition(e,n);return;case"start_successor_run":await this.withMutationLock(()=>this.startSuccessorRun(e,n));return;case"rollover_session":await this.withMutationLock(()=>this.rolloverSession(e,n));return;case"recovery_attempted":await this.appendRecoveryAttempt(e.attempt,n);return;case"recovery_resolved":await this.resolveRecoveryAttempt(e.attempt_id,e.outcome,n);return;default:{const r=e;throw this.logger.error({event:"yoloop_unknown_op",op:r},"unknown yoloop operation rejected"),new Error("YOLOOP_STATE_OPERATION_UNSUPPORTED")}}}async reserveContinuationAuthority(e,n){const r=await this.readState(n),s=r.pendingContinuationAuthorities??[],o=typeof e.idempotencyKey=="string"?e.idempotencyKey:"";if(!o)throw new Error("YOLOOP_CONTINUATION_AUTHORITY_INVALID");const i=s.find(a=>a.idempotencyKey===o);if(i){if(d(i)===d(e))return;throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}if(s.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");await this.writeState({...r,pendingContinuationAuthorities:[...s,e]})}async acknowledgeContinuationAuthority(e,n,r){const s=await this.readState(r),o=s.pendingContinuationAuthorities??[],i=o.findIndex(h=>h.idempotencyKey===e);if(i<0)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const a=o[i];if(n.idempotencyKey!==e||n.sessionId!==a.sessionId||JSON.stringify(n.storyIds)!==JSON.stringify(a.storyIds))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const c=o.filter((h,y)=>y!==i),l=s.continuationReceipts??[];await this.writeState({...s,pendingContinuationAuthorities:c,continuationReceipts:[...l.slice(-63),n]})}async repairContinuationAuthority(e,n,r,s){const o=await this.readState(s),i=o.pendingContinuationAuthorities??[],a=o.continuationRecoveryReceipts??[],c=typeof r.idempotencyKey=="string"?r.idempotencyKey:"",l=a.find(O=>O.idempotencyKey===c);if(l){if(d(l)===d(r))return;throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_CONFLICT")}if(i.length!==1||p("p208-legacy-authority-before-v1",i[0])!==e)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const h=p("p208-legacy-authority-after-v1",n);if(r.beforeHash!==e||r.afterHash!==h)throw new Error("YOLOOP_CONTINUATION_RECOVERY_HASH_MISMATCH");const y={...r};if(delete y.idempotencyKey,!c||p("p208-legacy-authority-recovery-receipt-v1",y)!==c)throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_INVALID");await this.writeState({...o,pendingContinuationAuthorities:[n],continuationRecoveryReceipts:[...a.slice(-63),r]})}async switchContinuationPolicy(e,n,r){const s=await this.readState(r);if(s.currentSession||(s.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");try{await u.copyFile(this.statePath,`${this.statePath}.policy-backup`)}catch(o){if(o.code!=="ENOENT")throw o}await this.writeState({...s,continuationPolicy:e,continuationSession:n})}async appendRecoveryAttempt(e,n){const r=await this.readState(n),s=r.recovery_history??[];if(s.some(c=>c.attempted_at===e.attempted_at&&c.story_id===e.story_id)){this.logger.warn({event:"recovery_attempted_duplicate",story_id:e.story_id},"duplicate recovery_attempted op; skipping");return}const i=H([...s,e]),a={...r,recovery_history:i};await this.writeState(a),this.logger.info({event:"recovery_attempted_persisted",story_id:e.story_id,history_size:i.length},"recovery attempt persisted")}async resolveRecoveryAttempt(e,n,r){const s=await this.readState(r),o=s.recovery_history??[],i=o.findIndex(h=>h.recovery_step_id_tokenized===e);if(i===-1){this.logger.warn({event:"recovery_resolve_orphan",attempt_id:e},"recovery_resolved op had no matching attempt; skipping");return}const a=o[i];if(a.outcome===n&&a.finished_at){this.logger.info({event:"recovery_resolved_duplicate",attempt_id:e,outcome:n},"duplicate recovery_resolved op; skipping");return}const c=o.slice();c[i]={...a,outcome:n,finished_at:r};const l={...s,recovery_history:c};await this.writeState(l),this.logger.info({event:"recovery_resolved_persisted",attempt_id:e,outcome:n},"recovery attempt resolved")}async acquireLock(e,n){const r={...e,pid:process.pid,hostname:I(),ownerKind:"client",startedAt:e.startedAt||n,leaseId:e.leaseId??ne(e.sessionId,n),leaseState:"active",leaseAcquiredAt:e.leaseAcquiredAt??n,leaseDurationMs:e.leaseDurationMs??q,leaseExpiresAt:e.leaseExpiresAt??e.ttlExpiresAt},s=JSON.stringify(r,null,2);try{const o=await u.open(this.lockPath,"wx");try{await o.writeFile(s,"utf8")}finally{await o.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired",pid:r.pid,sessionId:r.sessionId},"yoloop lock acquired");return}catch(o){const i=o;if(i.code!=="EEXIST")throw this.logger.error({event:"yoloop_lock_acquire_error",err:i.message},"failed to acquire yoloop lock"),o;const a=await this.readLock();if(a&&this.isSameClientSessionLock(a,r)){this.logger.info({event:"yoloop_lock_acquire_duplicate",sessionId:r.sessionId},"duplicate acquire_lock for current yoloop session; treating as no-op");return}if(!await this.maybeRecoverOrphanLock(n))throw this.logger.warn({event:"yoloop_lock_held"},"yoloop lock held by another live process"),o;const l=await u.open(this.lockPath,"wx");try{await l.writeFile(s,"utf8")}finally{await l.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired_after_recovery",pid:r.pid},"yoloop lock acquired after orphan recovery")}}async releaseLock(e){const n=await this.readState(new Date().toISOString()),r=await this.readLock();if(n.runControl){if(!e.expectedRunId||!e.expectedSessionId||!e.expectedLeaseId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(e.expectedRunId!==n.runControl.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(!r||e.expectedSessionId!==r.sessionId||e.expectedLeaseId!==r.leaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}try{await u.unlink(this.lockPath),this.logger.info({event:"yoloop_lock_released"},"yoloop lock released")}catch(s){const o=s;if(o.code==="ENOENT"){this.logger.info({event:"yoloop_lock_release_noop"},"yoloop lock release noop (file absent)");return}this.logger.warn({event:"yoloop_lock_release_error",err:o.message},"unexpected error releasing yoloop lock")}}async readLock(){try{const e=await u.readFile(this.lockPath,"utf8"),n=JSON.parse(e),r=n.currentEpicId??n.epicId??"";return{pid:n.pid??0,hostname:n.hostname??"",...n.ownerKind?{ownerKind:n.ownerKind}:{},...n.ownerPidState?{ownerPidState:n.ownerPidState}:{},...typeof n.leaseId=="string"?{leaseId:n.leaseId}:{},...n.leaseState?{leaseState:n.leaseState}:{},...typeof n.leaseAcquiredAt=="string"?{leaseAcquiredAt:n.leaseAcquiredAt}:{},...typeof n.leaseDurationMs=="number"?{leaseDurationMs:n.leaseDurationMs}:{},...typeof n.leaseExpiresAt=="string"?{leaseExpiresAt:n.leaseExpiresAt}:{},startedAt:n.startedAt??"",sessionId:n.sessionId??"",mode:n.mode??"epic-id",inputPath:n.inputPath??"",epicQueue:n.epicQueue??(r?[r]:[]),currentEpicIndex:n.currentEpicIndex??0,currentEpicId:r,ttlExpiresAt:n.ttlExpiresAt??"",epicId:n.epicId??r}}catch{return null}}async readState(e){try{const n=await u.readFile(this.statePath,"utf8"),r=JSON.parse(n);return re(r,e)}catch(n){const r=n;return r.code!=="ENOENT"&&this.logger.warn({event:"yoloop_state_read_error",err:r.message},"yoloop state file unreadable; using defaults"),S(e)}}async writeState(e){const n=`${this.statePath}.tmp.${process.pid}.${Date.now()}`,r=JSON.stringify(e,null,2);try{const s=await u.open(n,"w",384);try{await s.writeFile(r,"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await u.rename(n,this.statePath),await this.syncStateDirectory()}catch(s){const o=s;this.logger.error({event:"yoloop_state_write_error",err:o.message},"failed to write yoloop state");try{await u.unlink(n)}catch{}throw s}}async rolloverSession(e,n){f(e);const r=await this.readRolloverManifest();if(r){if(G(r.operation,e)){if(r.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(r.phase==="applied")return;await this.completePreparedSessionRollover(r.operation,n);return}else if(r.phase==="prepared")throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT")}const s=await this.readState(n),o=await this.readLock();P(e,s,o),await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSessionRollover(e,n)}async completePreparedSessionRollover(e,n){const r=await this.readState(n);let s=d(r)===d(e.next);if(!s){const i=await this.readLock();P(e,r,i),await this.writeState(e.next),s=!0}const o=await this.readLock();if(e.expectedSessionId===null||e.expectedLeaseId===null){if(e.expectedSessionId!==null||e.expectedLeaseId!==null||o)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(o){if(o.sessionId!==e.expectedSessionId||o.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await u.unlink(this.lockPath),await this.syncStateDirectory()}else if(!s)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_session_rollover_applied",runId:e.runId,operationId:e.operationId,coolDownUntil:e.coolDownUntil},"yoloop per-run-cap session rollover applied")}async recoverSessionRolloverIfPresent(e){try{await u.access(this.rolloverManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readRolloverManifest();n?.phase==="prepared"&&await this.completePreparedSessionRollover(n.operation,e)})}async readRolloverManifest(){try{const e=JSON.parse(await u.readFile(this.rolloverManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSessionRolloverManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="rollover_session")throw new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT");return f(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT")}}async writeRolloverManifest(e){const n=`${this.rolloverManifestPath}.tmp.${process.pid}.${Date.now()}`,r=await u.open(n,"w",384);try{await r.writeFile(JSON.stringify(e,null,2),"utf8"),await r.sync()}finally{await r.close()}this.trySetFilePerms(n),await u.rename(n,this.rolloverManifestPath),await this.syncStateDirectory()}async advanceEpic(e,n,r){const s=await this.readState(r);if(!s.currentSession){this.logger.warn({event:"yoloop_advance_no_session",nextEpicId:n},"advance_epic with no active session; skipping");return}const o={...s,currentSession:{...s.currentSession,currentEpicIndex:e}};await this.writeState(o),this.logger.info({event:"yoloop_epic_advance",nextEpicId:n,nextIndex:e},"yoloop advanced to next epic")}async ensureDir(){try{await u.mkdir(this.stateDir,{recursive:!0}),this.trySetDirPerms(this.stateDir)}catch(e){const n=e;throw this.logger.error({event:"yoloop_mkdir_error",err:n.message,path:this.stateDir},"failed to ensure .neocortex/ directory"),e}}async syncStateDirectory(){try{const e=await u.open(this.stateDir,"r");try{await e.sync()}finally{await e.close()}}catch(e){const n=e.code;if(n!=="EINVAL"&&n!=="EISDIR"&&n!=="ENOTSUP"&&n!=="EPERM")throw e}}async withMutationLock(e){let n=null;for(let r=0;r<B;r+=1)try{n=await u.open(this.mutationLockPath,"wx",384),await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await n.sync();break}catch(s){if(s.code!=="EEXIST")throw s;try{const o=await u.stat(this.mutationLockPath);if(Date.now()-o.mtimeMs>$){await u.unlink(this.mutationLockPath);continue}}catch{continue}await new Promise(o=>setTimeout(o,5))}if(!n)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");try{return await e()}finally{await n.close().catch(()=>{}),await u.unlink(this.mutationLockPath).catch(()=>{})}}async transitionRun(e,n){v(e);const r=await this.readState(n),s=r.runControl,o=s?.receipts.find(l=>l.operationId===e.operationId||l.idempotencyKey===e.idempotencyKey);if(o){if(o.operationId===e.operationId&&o.idempotencyKey===e.idempotencyKey&&o.payloadHash===e.payloadHash)return o;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(s&&s.runId!==e.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((s?.revision??0)!==e.expectedRevision)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((s?.latestSnapshotHash??null)!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT");E(s,e);const c=e.next.receipts.at(-1);if(!c)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");return await this.writeState({...r,version:"1.2",runControl:e.next}),this.logger.info({event:"yoloop_run_transition_committed",runId:e.runId,operationId:e.operationId,revision:c.revision,status:c.status},"yoloop run transition committed"),c}async startSuccessorRun(e,n){X(e);const r=await this.readState(n),s=r.runControl,o={schemaVersion:"YoloopRunPredecessor/1.0",runId:e.previousRunId,revision:e.expectedRevision,snapshotHash:e.expectedSnapshotHash,successorOperationId:e.operationId,publicSafe:!0},i=s?.receipts.find(l=>l.operationId===e.operationId||l.idempotencyKey===e.idempotencyKey);if(i){if(i.operationId===e.operationId&&i.idempotencyKey===e.idempotencyKey&&e.next.receipts.at(-1)?.payloadHash===i.payloadHash&&d(s?.predecessor)===d(o))return i;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(!s||s.runId!==e.previousRunId||s.status!=="exhausted"||s.revision!==e.expectedRevision||s.latestSnapshotHash!==e.expectedSnapshotHash||r.currentSession!==null)throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const a=e.next.receipts.at(-1);if(!a||d(e.next.predecessor)!==d(o))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const c={type:"transition_run",runId:e.runId,operationId:e.operationId,idempotencyKey:e.idempotencyKey,expectedRevision:0,expectedSnapshotHash:null,payloadHash:a.payloadHash,next:e.next};return v(c),E(void 0,c),await this.writeState({...r,version:"1.2",runControl:e.next}),a}trySetFilePerms(e){try{F(e)}catch{}}trySetDirPerms(e){try{K(e)}catch{}}async prepareLockForSnapshot(e,n){if(!e)return null;if(e.ownerKind!=="client")return e;const r=k(e,n),s={...e,leaseState:r};if(r==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"lease_expired"},"expired client-owned yoloop lock lease recovered before snapshot echo"),null;if(!s.pid||s.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"invalid_pid"},"invalid PID in client-owned yoloop lock; recovered"),null;if(s.hostname&&s.hostname!==I())return{...s,ownerPidState:"unknown"};try{return process.kill(s.pid,0),{...s,ownerPidState:"live"}}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"dead_pid"},"stale client-owned yoloop lock recovered before snapshot echo"),null}}async maybeRecoverOrphanLock(e){const n=await this.readLock();if(!n)return!0;if(k(n,e)==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"lease_expired"},"expired yoloop lock lease recovered"),!0;if(!n.pid||n.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"invalid_pid"},"invalid PID in lock file; recovered"),!0;if(n.hostname&&n.hostname!==I())return this.logger.warn({event:"yoloop_lock_remote_host",ownerKind:n.ownerKind??"server",ownerPidState:"unknown"},"lock held by a remote host; honoring"),!1;try{return process.kill(n.pid,0),!1}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"dead_pid"},"orphan yoloop lock recovered"),!0}}async deleteLockBestEffort(){try{await u.unlink(this.lockPath)}catch{}}isSameClientSessionLock(e,n){return e.ownerKind==="client"&&e.sessionId===n.sessionId&&e.pid===process.pid&&e.hostname===I()}async cleanupOrphanTempFiles(){try{const e=U(this.statePath),n=await u.readdir(e),r=[`${m}.tmp.`,`${T}.tmp.`],s=n.filter(o=>r.some(i=>o.startsWith(i)));for(const o of s)try{await u.unlink(_(e,o))}catch{}}catch{}}}function d(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(d).join(",")}]`:`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${d(n)}`).join(",")}}`}function p(t,e){return D("sha256").update(`${t}\0${d(e)}`).digest("hex")}function j(t){return p("p9390812898200217364-yoloop-session-v1",t)}function z(t){return p("p9390812898200217364-yoloop-rollover-v1",t)}function W(t){return p("p9390812898200217364-yoloop-successor-run-v1",t)}function G(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function f(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,expectedSessionId:t.expectedSessionId,expectedSessionFingerprint:t.expectedSessionFingerprint,expectedLeaseId:t.expectedLeaseId,coolDownUntil:t.coolDownUntil,reason:t.reason,exhaustedRun:t.exhaustedRun,next:t.next};if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.expectedSessionFingerprint)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0||!Number.isFinite(Date.parse(t.coolDownUntil))||!["YOLOOP_PER_RUN_CAP_REACHED","YOLOOP_SESSION_TIMEOUT"].includes(t.reason)||t.payloadHash!==z(n)||t.receipt.schemaVersion!=="YoloopSessionRolloverReceipt/1.0"||t.receipt.runId!==t.runId||t.receipt.operationId!==t.operationId||t.receipt.idempotencyKey!==t.idempotencyKey||t.receipt.payloadHash!==t.payloadHash||t.receipt.coolDownUntil!==t.coolDownUntil||t.receipt.revision!==(t.exhaustedRun?.revision??0)||t.receipt.snapshotHash!==(t.exhaustedRun?.latestSnapshotHash??null)||t.receipt.status!=="exhausted"||t.receipt.publicSafe!==!0)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(t.expectedSessionId===null!=(t.expectedLeaseId===null)||t.expectedSessionId!==null&&!e.test(t.expectedSessionId)||t.expectedLeaseId!==null&&!e.test(t.expectedLeaseId))throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}function X(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,previousRunId:t.previousRunId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:t.next};if(!e.test(t.runId)||!e.test(t.previousRunId)||t.runId===t.previousRunId||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<1||t.payloadHash!==W(n))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT")}function P(t,e,n){f(t);const r=e.currentSession;if(!r||j(r)!==t.expectedSessionFingerprint)throw new Error("YOLOOP_SESSION_ROLLOVER_SESSION_CONFLICT");const s=e.runControl;if((s?.revision??0)!==t.expectedRevision||(s?.latestSnapshotHash??null)!==t.expectedSnapshotHash||s&&s.runId!==t.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(t.expectedSessionId===null||t.expectedLeaseId===null){if(n)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(!n||n.sessionId!==t.expectedSessionId||n.leaseId!==t.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");const o=t.exhaustedRun;if(s)if(s.status==="exhausted"){if(d(o)!==d(s))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}else{if(!o||o.status!=="exhausted")throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const a=o.receipts.at(-1);if(!a)throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const c={type:"transition_run",runId:s.runId,operationId:a.operationId,idempotencyKey:a.idempotencyKey,expectedRevision:s.revision,expectedSnapshotHash:s.latestSnapshotHash,payloadHash:a.payloadHash,next:o};v(c),E(s,c)}else{const a=o?.receipts[0],c=o?.receipts[1];if(o&&(o.runId!==t.runId||o.status!=="exhausted"||o.revision!==2||o.events.length!==2||o.progressSnapshots.length!==4||o.receipts.length!==2||a?.runId!==t.runId||a.revision!==1||a.status!=="created"||c?.runId!==t.runId||c.revision!==2||c.status!=="exhausted"||c.operationId!==`${t.operationId}:run`||c.idempotencyKey!==`${t.idempotencyKey}:run`||o.latestSnapshotHash!==c.snapshotHash||o.predecessor!==void 0))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}const i={...e,version:"1.2",coolDownUntil:t.coolDownUntil,currentSession:null,...o?{runControl:o}:{}};if(d(i)!==d(t.next))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}function x(t){const{receipts:e,...n}=t.next;return p("p220-yoloop-run-transition-payload-v1",{runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:n})}const R=new Set(["success","partial","blocked","failure","exhausted","cancelled"]),Q={created:["running","cancelling","exhausted"],running:["pausing","cancelling","success","partial","blocked","failure","exhausted"],pausing:["paused","cancelling","failure","exhausted"],paused:["resuming","cancelling","exhausted"],resuming:["running","cancelling","failure","exhausted"],cancelling:["cancelled","failure","exhausted"]};function Z(t,e){return e==="pause"?t==="running"?"pausing":null:e==="resume"?t==="paused"?"resuming":null:R.has(t)||t==="cancelling"?null:"cancelling"}function ee(t){const e=t.current.revision+1,n=t.action==="cancel"?["YOLOOP_RUN_CANCEL_REQUESTED"]:[],r={schemaVersion:"YoloopOperationalBudgetSummary/1.0",limits:t.current.operationalBudget.limits,usage:t.current.usage,exhaustedDimension:null},s={schemaVersion:"ProgressSnapshot/1.0",runId:t.current.runId,sequence:t.current.progressSnapshots.length+1,revision:e,operationId:t.operationId,boundary:t.action,phase:"before",status:t.current.status,occurredAt:t.occurredAt,parentSnapshotHash:t.current.latestSnapshotHash,budget:r,reasonCodes:n,publicSafe:!0},o=p("p220-yoloop-progress-snapshot-id-v1",{runId:s.runId,operationId:s.operationId,sequence:s.sequence,phase:s.phase}),i={...s,snapshotId:o,snapshotHash:p("p220-yoloop-progress-snapshot-v1",{...s,snapshotId:o})},a={...s,sequence:i.sequence+1,phase:"after",status:t.target,parentSnapshotHash:i.snapshotHash},c=p("p220-yoloop-progress-snapshot-id-v1",{runId:a.runId,operationId:a.operationId,sequence:a.sequence,phase:a.phase}),l={...a,snapshotId:c,snapshotHash:p("p220-yoloop-progress-snapshot-v1",{...a,snapshotId:c})},h={schemaVersion:"YoloopRunEvent/1.0",runId:t.current.runId,operationId:t.operationId,kind:"intent",sequence:t.current.events.length+1,revision:e,occurredAt:t.occurredAt,fromStatus:t.current.status,toStatus:t.target,reasonCodes:n,budgetDimension:null,parentEventHash:t.current.events.at(-1)?.eventHash??null,publicSafe:!0},y=p("p220-yoloop-run-event-id-v1",{runId:h.runId,operationId:h.operationId,sequence:h.sequence}),O={...h,eventId:y,eventHash:p("p220-yoloop-run-event-v1",{...h,eventId:y})},w={...t.current,revision:e,status:t.target,events:[...t.current.events,O],progressSnapshots:[...t.current.progressSnapshots,i,l],latestSnapshotHash:l.snapshotHash,receipts:[...t.current.receipts]},L={runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.current.revision,expectedSnapshotHash:t.current.latestSnapshotHash,next:w},N=x(L),Y={schemaVersion:"YoloopRunTransitionReceipt/1.0",runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,payloadHash:N,revision:e,snapshotHash:l.snapshotHash,status:t.target};return{type:"transition_run",...L,payloadHash:N,next:{...w,receipts:[...w.receipts,Y]}}}function v(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(t.payloadHash!==x(t))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}function E(t,e){const n=e.next,r=t?.events??[],s=t?.progressSnapshots??[],o=t?.receipts??[];if(n.schemaVersion!=="YoloopRunControl/1.0"||n.runId!==e.runId||n.revision!==e.expectedRevision+1||n.events.length!==r.length+1||n.progressSnapshots.length!==s.length+2||n.receipts.length!==o.length+1||d(n.events.slice(0,r.length))!==d(r)||d(n.progressSnapshots.slice(0,s.length))!==d(s)||d(n.receipts.slice(0,o.length))!==d(o))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t){if(R.has(t.status))throw new Error("YOLOOP_RUN_TERMINAL");const h=n.progressSnapshots.at(-2)?.boundary,y=t.status===n.status&&(h==="budget"||h==="retry");if(!(Q[t.status]??[]).includes(n.status)&&!y)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t.startedAt!==n.startedAt||t.deadlineAt!==n.deadlineAt)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(d(t.predecessor)!==d(n.predecessor))throw new Error("YOLOOP_RUN_TRANSITION_INVALID")}else if(n.status!=="created")throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const i=n.progressSnapshots.at(-2),a=n.progressSnapshots.at(-1),c=n.events.at(-1),l=n.receipts.at(-1);if(!i||!a||!c||!l||i.phase!=="before"||a.phase!=="after"||i.operationId!==e.operationId||a.operationId!==e.operationId||c.operationId!==e.operationId||i.runId!==e.runId||a.runId!==e.runId||c.runId!==e.runId||i.revision!==n.revision||a.revision!==n.revision||c.revision!==n.revision||i.parentSnapshotHash!==(t?.latestSnapshotHash??null)||a.parentSnapshotHash!==i.snapshotHash||n.latestSnapshotHash!==a.snapshotHash||l.schemaVersion!=="YoloopRunTransitionReceipt/1.0"||l.runId!==e.runId||l.operationId!==e.operationId||l.idempotencyKey!==e.idempotencyKey||l.payloadHash!==e.payloadHash||l.revision!==n.revision||l.snapshotHash!==n.latestSnapshotHash||l.status!==n.status||Date.parse(n.deadlineAt)<=Date.parse(n.startedAt))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");A(i),A(a),te(c,r.at(-1)?.eventHash??null)}function A(t){const{snapshotHash:e,...n}=t;if(e!==p("p220-yoloop-progress-snapshot-v1",n))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function te(t,e){const{eventHash:n,...r}=t;if(t.parentEventHash!==e||n!==p("p220-yoloop-run-event-v1",r))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function ne(t,e){return`lease-${se(`${t}:${e}`)}`}function se(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(36).padStart(7,"0")}function k(t,e){const n=t.leaseExpiresAt??t.ttlExpiresAt,r=Date.parse(n),s=Date.parse(e);return!Number.isFinite(r)||!Number.isFinite(s)?"unknown":r<=s?"expired":"active"}function re(t,e){const n=S(e);return{...t,version:t.version==="1.2"?"1.2":"1.1",lastResetAt:t.lastResetAt??n.lastResetAt,storiesRunToday:t.storiesRunToday??0,iterationsToday:t.iterationsToday??0,iterationsTodayDate:t.iterationsTodayDate??n.iterationsTodayDate,tokensUsedToday:t.tokensUsedToday??0,lastRunAt:t.lastRunAt??null,coolDownUntil:t.coolDownUntil??null,totalRunsAllTime:t.totalRunsAllTime??0,totalStoriesAllTime:t.totalStoriesAllTime??0,currentSession:t.currentSession??null,...t.runControl!==void 0?{runControl:t.runControl}:{},...t.continuationPolicy!==void 0?{continuationPolicy:t.continuationPolicy}:{},...t.continuationSession!==void 0?{continuationSession:t.continuationSession}:{},...t.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:t.pendingContinuationAuthorities}:{},...t.continuationReceipts!==void 0?{continuationReceipts:t.continuationReceipts}:{},...t.continuationRecoveryReceipts!==void 0?{continuationRecoveryReceipts:t.continuationRecoveryReceipts}:{},recovery_history:Array.isArray(t.recovery_history)?H(t.recovery_history):[]}}function H(t){return t.length<=g?t:t.slice(t.length-g)}export{C as YOLOOP_PERSISTENCE_CAPABILITIES,he as YoloopClientStateStore,x as buildYoloopRunTransitionPayloadHash,z as buildYoloopSessionRolloverPayloadHash,W as buildYoloopSuccessorRunPayloadHash,H as capRecoveryHistory,S as createDefaultCounters,ue as createDefaultState,j as fingerprintYoloopSession};
@@ -1,4 +1,4 @@
1
- # 🧠 Neocortex v4.60.45 | OrNexus Team
1
+ # 🧠 Neocortex v4.60.47 | OrNexus Team
2
2
 
3
3
  This project uses Neocortex, a Development Orchestrator.
4
4
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.60.45 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.60.47 | OrNexus Team"
4
4
  ---
5
5
 
6
6
  <!--
@@ -4,7 +4,7 @@ agent:
4
4
  name: 'Neocortex Root Agent'
5
5
  title: 'Development Orchestrator (Root)'
6
6
  icon: '>'
7
- version: '4.60.45'
7
+ version: '4.60.47'
8
8
  architecture: 'thin-client'
9
9
  module: stand-alone
10
10
  hasSidecar: false
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex-root
3
- description: "🧠 Neocortex Root Agent v4.60.45 | OrNexus Team"
3
+ description: "🧠 Neocortex Root Agent v4.60.47 | OrNexus Team"
4
4
  model: opus
5
5
  color: blue
6
6
  tools:
@@ -108,7 +108,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
108
108
  ┌────────────────────────────────────────────────────────────┐
109
109
  │ │
110
110
  │ ####### N E O C O R T E X │
111
- │ ### ######## v4.60.45 │
111
+ │ ### ######## v4.60.47 │
112
112
  │ ######### ##### │
113
113
  │ ## ############## Development Orchestrator │
114
114
  │ ## ### ###### ## OrNexus Team │
@@ -4,7 +4,7 @@ agent:
4
4
  name: 'Neocortex'
5
5
  title: 'Development Orchestrator'
6
6
  icon: '>'
7
- version: '4.60.45'
7
+ version: '4.60.47'
8
8
  architecture: 'thin-client'
9
9
  module: stand-alone
10
10
  hasSidecar: false