@ornexus/neocortex 4.60.59 → 4.60.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/sbom.cdx.json +241 -82
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +6 -2
- package/packages/client/dist/cli.js +37 -4
- package/packages/client/dist/commands/architecture-answers.d.ts +26 -0
- package/packages/client/dist/commands/architecture-answers.js +7 -0
- package/packages/client/dist/commands/architecture-memory-terminal.d.ts +21 -0
- package/packages/client/dist/commands/architecture-memory-terminal.js +2 -0
- package/packages/client/dist/commands/architecture-root-binding.d.ts +2 -0
- package/packages/client/dist/commands/architecture-root-binding.js +1 -0
- package/packages/client/dist/commands/invoke.d.ts +43 -2
- package/packages/client/dist/commands/invoke.js +98 -70
- package/packages/client/dist/commands/legacy-story-branch.d.ts +10 -0
- package/packages/client/dist/commands/legacy-story-branch.js +1 -0
- package/packages/client/dist/commands/legacy-story-pr.d.ts +18 -0
- package/packages/client/dist/commands/legacy-story-pr.js +1 -0
- package/packages/client/dist/commands/planning-diagnosis.d.ts +4 -0
- package/packages/client/dist/commands/planning-diagnosis.js +1 -0
- package/packages/client/dist/commands/planning-generation.d.ts +2 -0
- package/packages/client/dist/commands/planning-generation.js +1 -0
- package/packages/client/dist/commands/planning-research.d.ts +3 -0
- package/packages/client/dist/commands/planning-research.js +1 -0
- package/packages/client/dist/commands/refresh-memory.d.ts +10 -0
- package/packages/client/dist/commands/refresh-memory.js +3 -1
- package/packages/client/dist/commands/story-checkpoint.d.ts +1 -1
- package/packages/client/dist/commands/story-checkpoint.js +1 -1
- package/packages/client/dist/config/profile-directory.d.ts +2 -0
- package/packages/client/dist/config/profile-directory.js +1 -0
- package/packages/client/dist/config/secure-config.js +5 -5
- package/packages/client/dist/continuity/runner-bootstrap-policy.d.ts +1 -1
- package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -1
- package/packages/client/dist/generated/command-registry.generated.d.ts +11 -11
- package/packages/client/dist/generated/command-registry.generated.js +1 -1
- package/packages/client/dist/generated/public-projections.generated.d.ts +20 -20
- package/packages/client/dist/generated/public-projections.generated.js +1 -1
- package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +9 -0
- package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
- package/packages/client/dist/git/git-lifecycle-step-ids.d.ts +5 -0
- package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -1
- package/packages/client/dist/git/git-lifecycle-store.d.ts +16 -0
- package/packages/client/dist/git/git-lifecycle-store.js +9 -4
- package/packages/client/dist/git/legacy-story-branch-checkpoint.d.ts +38 -0
- package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -0
- package/packages/client/dist/git/legacy-story-branch-setup.d.ts +56 -0
- package/packages/client/dist/git/legacy-story-branch-setup.js +4 -0
- package/packages/client/dist/git/legacy-story-pr.d.ts +514 -0
- package/packages/client/dist/git/legacy-story-pr.js +62 -0
- package/packages/client/dist/git/secure-filesystem-boundary.d.ts +2 -0
- package/packages/client/dist/git/secure-filesystem-boundary.js +34 -7
- package/packages/client/dist/machine/fingerprint.js +2 -2
- package/packages/client/dist/memory/project-memory-writer.js +17 -17
- package/packages/client/dist/memory/shared-project-memory-types.d.ts +23 -13
- package/packages/client/dist/memory/shared-project-memory-types.js +2 -2
- package/packages/client/dist/migrations/state-json.d.ts +23 -1
- package/packages/client/dist/migrations/state-json.js +4 -4
- package/packages/client/dist/private-execution/delivery.d.ts +131 -3
- package/packages/client/dist/private-execution/delivery.js +2 -2
- package/packages/client/dist/private-execution/isolated-admission.d.ts +28 -1
- package/packages/client/dist/private-execution/isolated-admission.js +11 -2
- package/packages/client/dist/private-execution/isolated-session.js +2 -2
- package/packages/client/dist/private-execution/isolated-workspace.d.ts +8 -0
- package/packages/client/dist/private-execution/isolated-workspace.js +1 -1
- package/packages/client/dist/private-execution/pact-consumer-runtime.d.ts +19 -0
- package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -0
- package/packages/client/dist/private-execution/pact-test-source.d.ts +9 -0
- package/packages/client/dist/private-execution/pact-test-source.js +1 -0
- package/packages/client/dist/private-execution/pact-toolchain.d.ts +37 -0
- package/packages/client/dist/private-execution/pact-toolchain.js +3 -0
- package/packages/client/dist/private-execution/pact-write-set.d.ts +24 -0
- package/packages/client/dist/private-execution/pact-write-set.js +1 -0
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +38 -0
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -0
- package/packages/client/dist/private-execution/planning-generation-checkpoint.d.ts +34 -0
- package/packages/client/dist/private-execution/planning-generation-checkpoint.js +4 -0
- package/packages/client/dist/private-execution/planning-research-checkpoint.d.ts +38 -0
- package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -0
- package/packages/client/dist/private-execution/ux-source-validation.d.ts +2 -0
- package/packages/client/dist/private-execution/ux-source-validation.js +1 -0
- package/packages/client/dist/private-execution/ux-write-set.d.ts +30 -0
- package/packages/client/dist/private-execution/ux-write-set.js +2 -0
- package/packages/client/dist/resolvers/remote-resolver.d.ts +5 -22
- package/packages/client/dist/resolvers/remote-resolver.js +1 -1
- package/packages/client/dist/runner/project-identity.js +1 -1
- package/packages/client/dist/runner/scheduler.d.ts +20 -0
- package/packages/client/dist/runner/scheduler.js +7 -7
- package/packages/client/dist/state/project-state-snapshot.js +1 -1
- package/packages/client/dist/yolo/change-evidence-collector.d.ts +8 -0
- package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
- package/packages/client/dist/yolo/spec-envelope-collector.d.ts +2 -0
- package/packages/client/dist/yolo/spec-envelope-collector.js +3 -3
- package/packages/client/dist/yoloop/invoke-hooks.js +7 -7
- package/packages/shared/dist/generated/command-registry.generated.js +12 -10
- package/packages/shared/dist/generated/invocation-schema.generated.js +14 -6
- package/packages/shared/dist/generated/public-projections.generated.js +18 -18
- package/packages/shared/dist/invocation/index.d.ts +1 -1
- package/packages/shared/dist/merge-readiness/c12-remote-observation.js +80 -0
- package/packages/shared/dist/planning/diagnosis-state.js +143 -0
- package/packages/shared/dist/yoloop/branch-unit.js +23 -1
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/opencode/neocortex-root.md +1 -1
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
import{existsSync as
|
|
2
|
-
`).length>e.budget.maxLines||Buffer.byteLength(t,"utf8")>e.budget.maxBytes)throw new Error("Canonical project memory update exceeds its context budget; refusing to truncate existing content.")}function
|
|
1
|
+
import{randomUUID as B}from"node:crypto";import{constants as ee,existsSync as g,lstatSync as $,mkdirSync as j,copyFileSync as M,readdirSync as te,readFileSync as R,readlinkSync as q,realpathSync as Ce,renameSync as re,rmSync as A,statSync as $e,symlinkSync as W,unlinkSync as ne,writeFileSync as F}from"node:fs";import{platform as I}from"node:os";import{dirname as T,isAbsolute as oe,join as p,relative as se,resolve as ae,sep as Pe,win32 as Te}from"node:path";import{CANONICAL_PROJECT_MEMORY_SOURCE as y,getProjectMemoryTarget as X,renderArchitectureReferenceTable as ve}from"./shared-project-memory-types.js";function ie(e){return(e.memoryNotes?.length??0)>0||(e.architectureReferences?.length??0)>0||e.bootstrapArchitecture!==void 0}const z="<!-- NEOCORTEX-REFRESH-UPDATES-START -->",G="<!-- NEOCORTEX-REFRESH-UPDATES-END -->";function L(e,t){return e.split(t).length-1}function Oe(e){me(e.memoryNotes??[],e.architectureReferences??[],e.bootstrapArchitecture);const t=H(e.memoryNotes??[]).map(s=>`- [${s.reasonCode}] ${s.summary} (layer: ${s.layer})`),r=(e.architectureReferences??[]).map(s=>`- [architecture-reference] \`${s.path}\`: ${s.title}; ${s.purpose}; use: ${s.suggestedUsage}`),o=e.bootstrapArchitecture,n=o===void 0?[]:[...(o.universalLaws??[]).map(s=>`- [bootstrap-law] ${s}`),...(o.businessContext??[]).map(s=>`- [bootstrap-business] ${s}`),...(o.activeContext??[]).map(s=>`- [bootstrap-context] ${s}`),...(o.repositoryMap??[]).map(s=>`- [bootstrap-repository] ${s}`),...(o.environmentPractices??[]).map(s=>`- [bootstrap-environment] ${s}`),...(o.platformMemoryContract??[]).map(s=>`- [bootstrap-platform] ${s}`),...(o.maintenanceRules??[]).map(s=>`- [bootstrap-maintenance] ${s}`),...(o.heuristics??[]).map(s=>`- [bootstrap-heuristic] ${s}`)];return w([...t,...r,...n])}function xe(e,t){if(t.split(`
|
|
2
|
+
`).length>e.budget.maxLines||Buffer.byteLength(t,"utf8")>e.budget.maxBytes)throw new Error("Canonical project memory update exceeds its context budget; refusing to truncate existing content.")}function ce(e,t,r){const o=Oe(r);if(o.length===0)return t;const n=t.includes(`\r
|
|
3
3
|
`)?`\r
|
|
4
4
|
`:`
|
|
5
|
-
`,s=
|
|
5
|
+
`,s=v(e),a=_(e),u=L(t,s),c=L(t,a);if(u!==1||c!==1||t.indexOf(a)<t.indexOf(s))throw new Error("Canonical project memory has ambiguous managed-block markers; refusing refresh.");const l=L(t,z),i=L(t,G);if(l!==i||l>1)throw new Error("Canonical project memory has ambiguous refresh-update markers; refusing refresh.");let d;if(l===0){const m=t.indexOf(a),b=t.slice(0,m),k=[z,"## Durable Refresh Updates",...o,G,""].join(n);d=`${b}${b.endsWith(n)?"":n}${k}${t.slice(m)}`}else{const m=t.indexOf(z),b=t.indexOf(G),k=t.indexOf(s),S=t.indexOf(a);if(m<k||b>S||b<m)throw new Error("Canonical refresh-update block is outside the managed block; refusing refresh.");const D=t.slice(m,b),U=new Set(D.split(/\r?\n/).map(C=>C.trim().toLowerCase())),f=o.filter(C=>!U.has(C.trim().toLowerCase()));if(f.length===0)return t;const N=t.slice(0,b);d=`${N}${N.endsWith(n)?"":n}${f.join(n)}${n}${t.slice(b)}`}return xe(e,d),d}function Ne(){return{readFile(e){try{return R(e,"utf8")}catch{return}},writeFileAtomic(e,t){j(T(e),{recursive:!0});const r=B(),o=`${e}.tmp-${r}`,n=g(e)?`${e}.bak-${r}`:void 0;try{return F(o,t,{encoding:"utf8",flag:"wx",mode:384}),n!==void 0&&M(e,n,ee.COPYFILE_EXCL),re(o,e),{backupPath:n}}catch(s){if(A(o,{force:!0}),n!==void 0&&g(n))try{M(n,e)}catch{}throw s}},join(...e){return p(...e)}}}function v(e){return`<!-- ${e.ownedBlockName}-START -->`}function _(e){return`<!-- ${e.ownedBlockName}-END -->`}function w(e){const t=new Set,r=[];for(const o of e){const n=o.trim().replace(/\s+/g," ");n.length===0||t.has(n.toLowerCase())||(t.add(n.toLowerCase()),r.push(n))}return r}function je(e){const t=new Set,r=[];for(const o of e)t.has(o.path)||(t.add(o.path),r.push(o));return r}function Me(e){switch(e.templateKind){case"neocortex-md":return"# NEOCORTEX.md Project Memory";case"claude-md":return"# CLAUDE.md Project Memory";case"agents-md":return"# AGENTS.md Project Instructions";case"gemini-md":return"# GEMINI.md Project Memory";case"copilot-instructions":return"# GitHub Copilot Repository Instructions";case"cursor-rule":return`---
|
|
6
6
|
description: Neocortex project memory
|
|
7
7
|
alwaysApply: true
|
|
8
8
|
---
|
|
9
9
|
|
|
10
|
-
# Cursor Project Memory`}}const
|
|
11
|
-
`),
|
|
12
|
-
`),
|
|
13
|
-
`);return
|
|
14
|
-
`)}function
|
|
15
|
-
`)}const
|
|
16
|
-
${t.slice(0,2e3)}`),
|
|
10
|
+
# Cursor Project Memory`}}const Ae=["Keep always-loaded memory compact: laws, active context, and references only.","Preserve human-authored instructions outside this owned block.","Prefer repository SSoT docs over duplicating architecture details here."],Ie=["Consult `docs/architecture/` before changes that affect architecture, contracts, data, security, performance, UX, or infrastructure.","Reference architecture documents by repository path, such as `docs/architecture/architecture.md`, before changing related implementation.","Summarize decisions and trade-offs in NEOCORTEX.md; do not paste complete architecture documents into memory.","Update memory for durable cross-layer changes across skills/agents, frontend, backend, API, DB, schemas, envs, DevOps, cyber security, testing/QA, observability, product, docs, and platform contracts.","Prioritize compact summaries of durable decisions, public contracts, operational risks, debts, command behavior, and repository paths; skip transient logs, raw payloads, secrets, private prompts, long documents, and duplicated canonical sources.","Keep platform memory files symlink-backed or include-backed to NEOCORTEX.md when supported."],it=["skills-agents","frontend","backend","api","db","schemas","envs","devops","cyber-security","testing-qa","observability","product-business","docs-architecture","platform-memory","command-behavior","generic"],Le=360,ue={feature:"Features",rule:"Rules/Policies",flag:"Flags",route:"Routes",api:"APIs/Contracts","db-schema":"DB/Schema",architecture:"Architecture",debt:"Debts",decision:"Decisions",generic:"General Updates"},_e=/\b(private|proprietary|server[- ]only|system)\s+prompt\b|\b(api[-_ ]?key|license[-_ ]?key|password|authorization|bearer|token|secret)\s*[:=]|\b(ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|xox[baprs]-[A-Za-z0-9-]+)\b|\b(customer|cliente)\s+(payload|record|email|phone)\b|\b(customer|cliente)\s+(data|dados)\s+(payload|record|email|phone)\b|\b(customer|cliente)\s+(data|dados)\s*[:=]|\braw\s+payload\b/i;function De(e){const t=e.toLowerCase();return/\b(project memory|canonical memory|memory heuristic|neocortex\.md|\*update-memory)\b/.test(t)?"decision":/\b(feature|capability|funcionalidade|release)\b/.test(t)?"feature":/\b(rule|policy|guardrail|regra|lei|must|never)\b/.test(t)?"rule":/\b(flag|feature[- ]?flag|toggle|env var|environment variable)\b/.test(t)?"flag":/\b(api|contract|schema contract|graphql|rest|rpc|webhook)\b/.test(t)?"api":/\b(db|database|schema|migration|table|column|prisma|sql)\b/.test(t)?"db-schema":/\b(decision|decisão|decisao|accepted|rejected|trade[- ]?off)\b/.test(t)?"decision":/\b(route|endpoint route|url path|pathname)\b|\/(api|admin|portal|v\d+)\//.test(t)?"route":/\b(architecture|arquitetura|adr|topology|infra|boundary)\b/.test(t)?"architecture":/\b(debt|follow[- ]?up|todo|tech[- ]?debt|dívida|divida)\b/.test(t)?"debt":"generic"}function Ue(e){const t=e.toLowerCase();return/\b(neocortex\.md|project memory|canonical memory|memory wrapper|symlink|owned block|memory heuristic)\b/.test(t)?"platform-memory":/\b(command|cli|\*update-memory|\*create-epic|\*arch-plan|workflow behavior)\b/.test(t)?"command-behavior":/\b(skill|agent|subagent|orchestrator|opencode|codex|claude|gemini|cursor)\b/.test(t)?"skills-agents":/\b(frontend|ui|ux|react|component|design[- ]?system|css|accessibility|a11y)\b/.test(t)?"frontend":/\b(backend|server|service|worker|job|queue)\b/.test(t)?"backend":/\b(api|endpoint|rest|graphql|rpc|webhook|contract)\b/.test(t)?"api":/\b(db|database|table|column|migration|sql|prisma)\b/.test(t)?"db":/\b(schema|schemas|zod|json schema|protobuf|openapi)\b/.test(t)?"schemas":/\b(env|environment|\.env\.example|config|configuration|feature[- ]?flag)\b/.test(t)?"envs":/\b(devops|deploy|deployment|ci|cd|docker|container|kubernetes|infra|terraform|rollback)\b/.test(t)?"devops":/\b(security|cyber|auth|authorization|permission|compliance|vulnerability|secret|token redaction)\b/.test(t)?"cyber-security":/\b(test|testing|qa|e2e|unit|integration|snapshot|property[- ]?based|flaky)\b/.test(t)?"testing-qa":/\b(observability|metric|metrics|log|logging|trace|tracing|alert|monitoring|slo)\b/.test(t)?"observability":/\b(product|business|user journey|onboarding|pricing|tenant|customer-facing)\b/.test(t)?"product-business":/\b(docs|documentation|architecture|arquitetura|adr|runbook|decision record)\b/.test(t)?"docs-architecture":"generic"}function de(e){const t=e.trim().replace(/\s+/g," ");if(Buffer.byteLength(t,"utf8")<=Le)return t;const r=t.match(/(?:^|\s)([\w.-]+(?:\/[\w.@-]+)+(?:\.[A-Za-z0-9]+)?)/)?.[1],o=t.slice(0,220).replace(/\s+\S*$/,"").trim();return r?`${o}\u2026 See ${r} for details.`:`${o}\u2026 Details omitted from always-loaded memory; keep source content in repository docs.`}function Be(e){h(e);const t=De(e),r=Ue(e);return{kind:t,layer:r,sectionTitle:ue[t],summary:de(e),reasonCode:`memory_update_${t.replace("-","_")}`}}function H(e){const t=new Set,r=[];for(const o of e){const n=Be(o),s=`${n.kind}:${n.summary.toLowerCase()}`;t.has(s)||(t.add(s),r.push(n))}return r}function h(e){if(_e.test(e))throw new Error("Project memory input violates IP boundary guardrails.")}function le(e,t){const r=(e??"").split(`
|
|
11
|
+
`),o=t.split(`
|
|
12
|
+
`),n=[],s=Math.max(r.length,o.length);for(let u=0;u<s;u++){const c=r[u],l=o[u];if(c!==l&&(c!==void 0&&n.push(`- ${c}`),l!==void 0&&n.push(`+ ${l}`),n.length>=80)){n.push("\u2026 diff truncated; inspect repository diff for full context.");break}}const a=n.join(`
|
|
13
|
+
`);return h(a),a}function Y(e){h(e.path),h(e.title),h(e.purpose),h(e.suggestedUsage)}function me(e,t,r){e.forEach(h),t.forEach(Y),r?.universalLaws?.forEach(h),r?.businessContext?.forEach(h),r?.activeContext?.forEach(h),r?.repositoryMap?.forEach(h),r?.environmentPractices?.forEach(h),r?.platformMemoryContract?.forEach(h),r?.maintenanceRules?.forEach(h),r?.heuristics?.forEach(h),r?.importantReferences?.forEach(Y),r?.architectureReferences?.forEach(Y)}function fe(e){return[Me(e),"","This file contains compact, always-loaded project memory. Keep detailed architecture in referenced docs.",""].join(`
|
|
14
|
+
`)}function pe(e,t,r,o){me(t,r,o);const n=w([...Ae,...o?.universalLaws??[]]),s=w([...o?.activeContext??[],...t.map(de)]),a=H(t),u=w(o?.businessContext??["Product/business context was not explicitly documented during bootstrap; treat conclusions as repository-inferred until a human updates this section."]),c=w(o?.repositoryMap??["Source, tests, package/build files, docs, CI, and runtime manifests are the permitted bootstrap sources for repository orientation."]),l=w(o?.environmentPractices??["Use `.env.example` for configuration shape only; do not read real environment files or credential-bearing files into always-loaded memory."]),i=w(o?.platformMemoryContract??["Semantic platform memory file must resolve to NEOCORTEX.md through a symlink; do not replace it with an unrelated wrapper or copied frontmatter.","Platform wrapper/frontmatter must be preserved via split/include/managed block while the semantic memory payload remains symlink-backed by NEOCORTEX.md."]),d=w(o?.maintenanceRules??["Keep NEOCORTEX.md deterministic, compact, objective, and direct; store only summaries, indexes, and links to detailed docs.","Do not copy protected prompt bodies, proprietary wrappers, server-side internals, customer data, license keys, or long document bodies into always-loaded memory."]),m=je([...o?.importantReferences??[],...o?.architectureReferences??[],...r]),b=w([...Ie,...o?.heuristics??[]]),k=n.map(f=>`- ${f}`),S=s.length>0?s.map(f=>`- ${f}`):["- No active project notes recorded."],D=m.length>0?ve(m):"No architecture references discovered.",U=a.length>0?Object.entries(ue).flatMap(([f,N])=>{const C=a.filter(P=>P.kind===f);return C.length>0?[`### ${N}`,...C.map(P=>`- [${P.reasonCode}] ${P.summary} (layer: ${P.layer})`)]:[]}):["- No durable change feedback recorded."];return[v(e),"## Universal Project Laws",...k,"","## Business/Product Context",...u.map(f=>`- ${f}`),"","## Active Context",...S,"","## Durable Change Feedback",...U,"","## Architecture References",D,"","## Repository Map",...c.map(f=>`- ${f}`),"","## Environment/Container/Production/Security/Dev Practices",...l.map(f=>`- ${f}`),"","## Platform Memory Contract",...i.map(f=>`- ${f}`),`- NEOCORTEX.md is the canonical project memory source for every platform target; run \`${e.bidirectionalReference.feedbackTrigger}\` when durable context discovered in a platform wrapper should be fed back into canonical memory.`,"","## Maintenance Rules",...d.map(f=>`- ${f}`),"","## Architecture Heuristics",...b.map(f=>`- ${f}`),_(e)].join(`
|
|
15
|
+
`)}const ye=["docs/architecture","docs/arquitetura-software"],qe=["README.md","readme.md","architecture.md","docs/architecture.md"],We=["package.json","pnpm-lock.yaml","package-lock.json","yarn.lock","tsconfig.json","vite.config.ts","turbo.json"],Fe=["Dockerfile","docker-compose.yml","compose.yml",".env.example","fly.toml"],Xe=["AGENTS.md","CLAUDE.md","GEMINI.md",".opencode/AGENTS.md",".cursor/rules/neocortex.mdc"];function he(e,t,r=24e3){const o=p(e,t);try{if(!g(o)||$(o).isDirectory())return;const n=R(o,"utf8");return n.length<=r?n:n.slice(0,r)}catch{return}}function K(e,t){j(T(e),{recursive:!0});const r=B(),o=`${e}.tmp-${r}`,n=g(e)?`${e}.bak-${r}`:void 0;try{return F(o,t,{encoding:"utf8",flag:"wx",mode:384}),n!==void 0&&M(e,n,ee.COPYFILE_EXCL),re(o,e),n}catch(s){if(A(o,{force:!0}),n!==void 0&&g(n))try{M(n,e)}catch{}throw s}}function E(e){throw new Error(`project-memory-path-${e}`)}function be(e){return typeof e=="string"&&e.length>0&&!e.startsWith("~")&&!e.includes("\\")&&!e.includes("\0")&&!oe(e)&&!Te.isAbsolute(e)&&!/^[a-zA-Z]:/.test(e)&&!e.split("/").some(t=>t===""||t==="."||t==="..")}function Z(e,t){let r;try{r=Ce(e)}catch{E("out-of-scope")}const o=p(r,y);for(const n of t){be(n)||E("invalid");const s=ae(r,n),a=se(r,s);(a===""||a===".."||a.startsWith(`..${Pe}`)||oe(a))&&E("out-of-scope");const u=n.split("/");for(let c=0;c<u.length;c++){const l=p(r,...u.slice(0,c+1));let i;try{i=$(l)}catch(m){if(m.code==="ENOENT")continue;E("out-of-scope")}if(!i.isSymbolicLink())continue;(c!==u.length-1||n===y)&&E("out-of-scope");let d;try{d=q(l)}catch{E("out-of-scope")}ae(T(l),d)!==o&&E("out-of-scope")}}}function J(e){return Array.from(new Set(H(e).map(t=>t.reasonCode)))}function O(e,t){try{return g(p(e,t))}catch{return!1}}function ze(e,t){try{return te(p(e,t),{withFileTypes:!0}).filter(r=>!r.name.startsWith(".")&&!r.name.toLowerCase().includes("secret")).sort((r,o)=>r.name.localeCompare(o.name)).slice(0,8).map(r=>`${t}/${r.name}${r.isDirectory()?"/":""}`)}catch{return[]}}function ge(e,t,r=16){try{const o=te(p(e,t),{withFileTypes:!0}).filter(s=>!s.name.startsWith(".")&&!s.name.startsWith("_")).sort((s,a)=>s.name.localeCompare(a.name)),n=[];for(const s of o){const a=`${t}/${s.name}`;if(s.isDirectory()?n.push(...ge(e,a,r-n.length)):/\.(md|markdown)$/i.test(s.name)&&n.push(a),n.length>=r)break}return n}catch{return[]}}function Ge(e,t){const r=t.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim();return r?r.replace(/[`*_#]/g,""):e.split("/").pop()?.replace(/\.(md|markdown)$/i,"").replace(/[-_]+/g," ")??e}function He(e,t){const r=/\b(stale|deprecated|outdated|incerto|uncertain)\b/i.test(`${e}
|
|
16
|
+
${t.slice(0,2e3)}`),o=t.replace(/^---[\s\S]*?---\s*/,"").split(/\n{2,}/).map(s=>s.replace(/^#+\s+.+$/gm,"").replace(/[`*_>#]/g,"").replace(/\s+/g," ").trim()).find(s=>s.length>0&&!s.startsWith("|"));return`${r?"[stale/uncertain evidence] ":""}${(o??"Architecture reference for this project.").slice(0,180)}`}function Ye(e){const t=e.toLowerCase();return/deploy|infra|docker|production|runbook/.test(t)?"Use before changing deployment, runtime, containers, or production operations.":/security|auth|compliance/.test(t)?"Use before changing auth, compliance, or security-sensitive behavior.":/api|contract|state|schema/.test(t)?"Use before changing contracts, APIs, schemas, or persisted state.":"Use before implementation in this area; verify freshness when marked stale or uncertain."}function ke(e){const t=We.filter(i=>O(e,i)),r=Fe.filter(i=>O(e,i)),o=Xe.filter(i=>O(e,i)),n=["packages","src","apps","tests","__tests__"].filter(i=>O(e,i)),a=[...ye.flatMap(i=>ge(e,i)),...qe.filter(i=>O(e,i))].slice(0,24).flatMap(i=>{const d=he(e,i,48e3);return d?[{path:i,title:Ge(i,d),purpose:He(i,d),suggestedUsage:Ye(i),source:ye.some(m=>i.startsWith(`${m}/`))?"architecture-root":"fallback-file"}]:[]}),u=he(e,"package.json"),c=u?.match(/"name"\s*:\s*"([^"]+)"/)?.[1],l=[...u?.matchAll(/"(test|build|lint|typecheck|dev)"\s*:/g)??[]].map(i=>i[1]);return{universalLaws:["Bootstrap canonical memory before creating or repairing platform memory wrappers when NEOCORTEX.md is absent.","Use only permitted repository sources for bootstrap: package/build files, architecture docs, README/deploy docs, .env.example, runtime manifests, CI, source/test layout, and platform memory wrappers."],businessContext:[c?`Repository package name: ${c}.`:"Repository product name was not declared in package metadata.","Business/product conclusions are bootstrap-inferred and must be refined from canonical docs or human input."],activeContext:[`Bootstrap scanned ${t.length} package/build files, ${a.length} architecture/readme docs, ${r.length} runtime/config templates, and ${o.length} platform memory wrappers.`,l.length>0?`Detected quality scripts: ${l.sort().join(", ")}.`:"No standard quality scripts were detected in package metadata."],repositoryMap:[t.length>0?`Package/build files: ${t.join(", ")}.`:"No package/build files detected in permitted bootstrap set.",n.length>0?`Source/test roots: ${n.flatMap(i=>ze(e,i)).slice(0,16).join(", ")}.`:"Source/test roots were not detected in standard locations.",o.length>0?`Platform memory/wrappers: ${o.join(", ")}.`:"No platform memory wrappers detected before bootstrap."],environmentPractices:[r.length>0?`Runtime/config templates: ${r.join(", ")}.`:"No Docker/compose/.env.example/runtime manifest detected in permitted bootstrap set.","Read `.env.example` only for configuration shape; never ingest real .env files, credentials, customer data, or license keys into memory.","Run repository quality scripts before commit and keep CI/deploy evidence referenced by path or URL rather than copied verbatim."],platformMemoryContract:["Semantic platform memory file must resolve to NEOCORTEX.md through a symlink; do not replace it with an unrelated wrapper or copied frontmatter.","Preserve wrappers/frontmatter via split/include/managed block while the semantic memory payload remains symlink-backed by NEOCORTEX.md."],maintenanceRules:["Generated memory must be deterministic, objective, direct, compact, and inside the target always-loaded context budget.","Cite long architecture docs by path with usage guidance; mark stale or uncertain docs when repository evidence indicates that status.","Do not copy protected prompt bodies, proprietary wrappers, server internals, secrets, customer data, license keys, or complete long documents."],architectureReferences:a,heuristics:["Before processing a story, consult the cited Architecture References whose path or suggested usage intersects the change.","When a referenced doc is marked stale/uncertain, validate against current package/runtime/source evidence before relying on it."]}}function V(e,t,r){const o=v(t),n=_(t),s=e.indexOf(o),a=e.indexOf(n);if(s>=0&&a>=s){const c=a+n.length;return`${e.slice(0,s)}${r}${e.slice(c)}`}const u=e.endsWith(`
|
|
17
17
|
`)?`
|
|
18
18
|
`:`
|
|
19
19
|
|
|
20
|
-
`;return`${e}${u}${
|
|
21
|
-
`}function
|
|
20
|
+
`;return`${e}${u}${r}
|
|
21
|
+
`}function Ke(e){return e.endsWith(".mdc")?`---
|
|
22
22
|
description: Neocortex project memory
|
|
23
23
|
alwaysApply: true
|
|
24
24
|
---
|
|
@@ -32,9 +32,9 @@ name: neocortex
|
|
|
32
32
|
description: Neocortex project memory wrapper
|
|
33
33
|
---
|
|
34
34
|
|
|
35
|
-
`:""}function
|
|
35
|
+
`:""}function we(e,t){const r=T(p(e,t)),o=p(e,y),n=se(r,o);return n.length>0?n:y}function x(e,t){return!!(e.targetId==="canonical"||e.requiresWrapperPreservation||e.linkRequirement.requiresWrapperPreservation||e.linkRequirement.wrapperAllowed||t==="AGENTS.md"||t.includes("/agents/")||t.includes("/skills/")||t.endsWith(".toml")||t.endsWith(".mdc")||t.endsWith(".agent.md")||t.endsWith(".instructions.md"))}function Ze(e){return e.linkRequirement.symlinkBacked&&e.linkRequirement.semanticFileRequired}function Q(e){return/EPERM|EACCES|operation not permitted|permission/i.test(e)?"EPERM: symlink permission denied":/ENOSYS|ENOTSUP|EOPNOTSUPP|not supported/i.test(e)?"symlink filesystem unsupported":"symlink capability unavailable"}function Ee(e,t,r,o,n=!1){if(o!==void 0)return o;const s=Ze(t);if(!s)return{os:I(),supported:!1,permission:"unknown",filesystem:"unknown",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:s,requiresWrapperPreservation:x(t,r),reason:`target policy ${t.linkRequirement.policy} does not allow semantic symlink orchestration`};if(n)return{os:I(),supported:!0,permission:"unknown",filesystem:"unknown",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:s,requiresWrapperPreservation:x(t,r),reason:"dry-run does not probe filesystem symlink support"};const a=p(e,".neocortex","tmp"),u=B(),c=p(a,`symlink-capability-source-${u}`),l=p(a,`symlink-capability-link-${u}`);try{j(a,{recursive:!0}),F(c,"probe",{encoding:"utf8",flag:"wx",mode:384}),W(c,l);const i=$(l).isSymbolicLink()&&$e(l).isFile();return{os:I(),supported:i,permission:i?"ok":"unknown",filesystem:i?"supports-symlink":"no-symlink-support",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:s,requiresWrapperPreservation:x(t,r),reason:i?void 0:"filesystem probe did not create a resolvable symbolic link"}}catch(i){const d=i instanceof Error?i.message:String(i),m=/EPERM|EACCES|operation not permitted|permission/i.test(d);return{os:I(),supported:!1,permission:m?"denied":"unknown",filesystem:"no-symlink-support",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:s,requiresWrapperPreservation:x(t,r),reason:Q(d)}}finally{A(l,{force:!0}),A(c,{force:!0})}}function Je(e,t,r,o){const n=we(o,t),s=r??`${Ke(t)}# ${e.platformName} Neocortex Memory Wrapper
|
|
36
36
|
|
|
37
|
-
`,a=[
|
|
38
|
-
`);return
|
|
39
|
-
`)}${
|
|
40
|
-
`).length<=e.budget.maxLines&&Buffer.byteLength(
|
|
37
|
+
`,a=[v(e),"## Canonical Project Memory Source","",`This platform wrapper preserves host-specific frontmatter/instructions while resolving project memory to \`${n}\`.`,"",`- Canonical source: \`${y}\``,`- Symlink-backed/source-of-truth file: \`${n}\``,`- Feedback loop: read \`${n}\` for shared context and run \`${e.bidirectionalReference.feedbackTrigger}\` when durable platform findings should update \`${y}\`.`,"- Human-authored content outside this managed block is preserved byte-for-byte.",_(e)].join(`
|
|
38
|
+
`);return V(s,e,a)}function Re(e,t,r,o,n,s=!1){const a=p(e,t),u=Q(n),l=`${["[NEOCORTEX COMPATIBILITY REMEDIATION]","Materialized project memory fallback because semantic symlink orchestration failed.","This is not product mode; repair host permissions/filesystem support and restore the symlink to NEOCORTEX.md.","WARNING: materialized fallback is remediation debt, not a silent mode; run *update-memory for durable context and repair this file back to canonical NEOCORTEX.md resolution.",`Fallback reason: ${u}`,""].join(`
|
|
39
|
+
`)}${r}`,d=(g(a)?R(a,"utf8"):void 0)!==l;return d&&!s&&(g(a)&&$(a).isSymbolicLink()&&ne(a),K(a,l)),{filePath:a,relativeFile:t,changed:d,content:l,mode:"compatibility-materialized-fallback",canonicalSource:y,symlinkCapability:o,fallbackReason:u,remediationDebt:`Repair ${t} so it is a symlink to ${y}; fallback is compatibility remediation only.`}}function Ve(e,t,r,o,n,s=!1){const a=p(e,t),u=we(e,t);s||j(T(a),{recursive:!0});const c=Ee(e,r,t,n,s);if(!c.supported)return Re(e,t,o,c,c.reason??"symlink capability detection reported unsupported host",s);if(s){let i=!0;try{i=!(g(a)&&$(a).isSymbolicLink()&&q(a)===u)}catch{i=!0}return{filePath:a,relativeFile:t,changed:i,content:o,mode:"semantic-symlink",canonicalSource:y,symlinkCapability:c}}let l=!1;try{return g(a)?$(a).isSymbolicLink()&&q(a)===u?l=!1:(ne(a),W(u,a),l=!0):(W(u,a),l=!0),{filePath:a,relativeFile:t,changed:l,content:R(a,"utf8"),mode:"semantic-symlink",canonicalSource:y,symlinkCapability:c}}catch(i){const d=i instanceof Error?i.message:String(i),m=Q(d);return Re(e,t,o,{...c,supported:!1,permission:/EPERM|EACCES|operation not permitted|permission/i.test(d)?"denied":c.permission,filesystem:"no-symlink-support",reason:m},m,s)}}function Qe(e,t,r,o,n){const s=c=>c.split(`
|
|
40
|
+
`).length<=e.budget.maxLines&&Buffer.byteLength(c,"utf8")<=e.budget.maxBytes;if(s(t))return t;const a=pe(e,r.slice(0,8),o.slice(0,12),n),u=V(t.includes(v(e))?t:fe(e),e,a);return s(u)?u:u.slice(0,e.budget.maxBytes)}function Se(e,t,r=[],o=[],n){const s=t??fe(e),a=pe(e,r,o,n),u=V(s,e,a);return Qe(e,u,r,o,n)}function et(e){const t=X(e.targetId),r=e.fs??Ne(),o=r.join(e.projectRoot,t.primaryFile);if(e.fs===void 0&&t.targetId==="canonical"&&Z(e.projectRoot,[y]),t.targetId!=="canonical"&&e.fs===void 0){const c=tt(e).files.find(l=>l.relativeFile===t.primaryFile);if(c===void 0)throw new Error(`Primary project memory file was not written for ${t.targetId}.`);return{filePath:c.filePath,changed:c.changed,content:c.content}}const n=r.readFile(o),s=e.bootstrapArchitecture??(e.fs===void 0&&t.targetId==="canonical"&&n===void 0?ke(e.projectRoot):void 0),a=t.targetId==="canonical"&&n!==void 0?ie(e)?ce(t,n,e):n:Se(t,n,e.memoryNotes,e.architectureReferences,s);if(n===a)return{filePath:o,changed:!1,content:a};const u=e.dryRun?void 0:r.writeFileAtomic(o,a);return{filePath:o,changed:!0,content:a,safeDiff:le(n,a),backupPath:u?.backupPath,reasonCodes:J(e.memoryNotes??[])}}function ct(e){return et({...e,targetId:"canonical"})}function tt(e){if(e.fs!==void 0)throw new Error("writeProjectMemoryTargetFiles requires the node filesystem to manage symlinks safely.");const t=X(e.targetId),r=X("canonical");t.secondaryFiles.some(d=>d===null||d.scope!=="project"&&d.scope!=="user"||!be(d.path))&&E("invalid");const o=Array.from(new Set([t.primaryFile,...t.targetId==="canonical"?[]:t.secondaryFiles.filter(d=>d.scope==="project").map(d=>d.path)]));Z(e.projectRoot,[y,...o,".neocortex/tmp"]);const n=p(e.projectRoot,y),s=g(n)?R(n,"utf8"):void 0,a=e.bootstrapArchitecture??(s===void 0?ke(e.projectRoot):void 0),u=s!==void 0?ie(e)?ce(r,s,e):s:Se(r,s,e.memoryNotes,e.architectureReferences,a),c=!g(n)||R(n,"utf8")!==u;let l;if(c&&!e.dryRun&&(l=K(n,u)),t.targetId==="canonical")return{targetId:t.targetId,canonicalFilePath:n,changed:c,files:[{filePath:n,relativeFile:y,changed:c,content:u,mode:"canonical",canonicalSource:y,safeDiff:le(s,u),backupPath:l,reasonCodes:J(e.memoryNotes??[])}]};const i=o.map(d=>{if(Z(e.projectRoot,[d,".neocortex/tmp"]),!x(t,d))return Ve(e.projectRoot,d,t,u,e.symlinkCapability,e.dryRun);const m=p(e.projectRoot,d),b=g(m)?R(m,"utf8"):void 0,k=Je(t,d,b,e.projectRoot),S=b!==k;return S&&!e.dryRun&&K(m,k),{filePath:m,relativeFile:d,changed:S,content:k,mode:"managed-wrapper",canonicalSource:y,symlinkCapability:Ee(e.projectRoot,t,d,e.symlinkCapability,e.dryRun),reasonCodes:J(e.memoryNotes??[])}});return{targetId:t.targetId,canonicalFilePath:n,files:i,changed:c||i.some(d=>d.changed)}}export{it as PROJECT_MEMORY_LAYER_CATEGORIES,ke as bootstrapArchitectureMemory,Se as buildProjectMemoryContent,Be as classifyProjectMemoryUpdate,Ne as createNodeProjectMemoryFs,le as createSafeProjectMemoryDiff,ct as writeCanonicalProjectMemory,et as writeProjectMemory,tt as writeProjectMemoryTargetFiles};
|
|
@@ -28,7 +28,7 @@ export interface ProjectMemoryTarget {
|
|
|
28
28
|
readonly platformName: string;
|
|
29
29
|
readonly canonicalSource: typeof CANONICAL_PROJECT_MEMORY_SOURCE;
|
|
30
30
|
readonly primaryFile: string;
|
|
31
|
-
readonly secondaryFiles: readonly
|
|
31
|
+
readonly secondaryFiles: readonly ProjectMemoryFileRef[];
|
|
32
32
|
readonly ownedBlockName: string;
|
|
33
33
|
readonly templateKind: ProjectMemoryTemplateKind;
|
|
34
34
|
readonly budget: ProjectMemoryBudget;
|
|
@@ -37,6 +37,13 @@ export interface ProjectMemoryTarget {
|
|
|
37
37
|
readonly requiresWrapperPreservation: boolean;
|
|
38
38
|
readonly notes: string;
|
|
39
39
|
}
|
|
40
|
+
export type ProjectMemoryFileRef = {
|
|
41
|
+
readonly scope: 'project';
|
|
42
|
+
readonly path: string;
|
|
43
|
+
} | {
|
|
44
|
+
readonly scope: 'user';
|
|
45
|
+
readonly path: string;
|
|
46
|
+
};
|
|
40
47
|
export interface ProjectMemoryBidirectionalReference {
|
|
41
48
|
readonly canonicalSource: typeof CANONICAL_PROJECT_MEMORY_SOURCE;
|
|
42
49
|
readonly resolvesVia: ProjectMemoryLinkPolicy;
|
|
@@ -71,7 +78,7 @@ export declare const PROJECT_MEMORY_TARGETS: {
|
|
|
71
78
|
readonly platformName: "Neocortex Canonical Memory";
|
|
72
79
|
readonly canonicalSource: "NEOCORTEX.md";
|
|
73
80
|
readonly primaryFile: "NEOCORTEX.md";
|
|
74
|
-
readonly secondaryFiles: readonly [
|
|
81
|
+
readonly secondaryFiles: readonly ProjectMemoryFileRef[];
|
|
75
82
|
readonly ownedBlockName: "NEOCORTEX-MEMORY";
|
|
76
83
|
readonly templateKind: "neocortex-md";
|
|
77
84
|
readonly budget: {
|
|
@@ -98,7 +105,7 @@ export declare const PROJECT_MEMORY_TARGETS: {
|
|
|
98
105
|
readonly platformName: "Claude Code";
|
|
99
106
|
readonly canonicalSource: "NEOCORTEX.md";
|
|
100
107
|
readonly primaryFile: "CLAUDE.md";
|
|
101
|
-
readonly secondaryFiles: readonly [
|
|
108
|
+
readonly secondaryFiles: readonly ProjectMemoryFileRef[];
|
|
102
109
|
readonly ownedBlockName: "NEOCORTEX-MEMORY";
|
|
103
110
|
readonly templateKind: "claude-md";
|
|
104
111
|
readonly budget: {
|
|
@@ -125,7 +132,7 @@ export declare const PROJECT_MEMORY_TARGETS: {
|
|
|
125
132
|
readonly platformName: "Codex CLI";
|
|
126
133
|
readonly canonicalSource: "NEOCORTEX.md";
|
|
127
134
|
readonly primaryFile: "AGENTS.md";
|
|
128
|
-
readonly secondaryFiles: readonly [
|
|
135
|
+
readonly secondaryFiles: readonly ProjectMemoryFileRef[];
|
|
129
136
|
readonly ownedBlockName: "NEOCORTEX-MEMORY";
|
|
130
137
|
readonly templateKind: "agents-md";
|
|
131
138
|
readonly budget: {
|
|
@@ -152,7 +159,7 @@ export declare const PROJECT_MEMORY_TARGETS: {
|
|
|
152
159
|
readonly platformName: "Grok Build";
|
|
153
160
|
readonly canonicalSource: "NEOCORTEX.md";
|
|
154
161
|
readonly primaryFile: "AGENTS.md";
|
|
155
|
-
readonly secondaryFiles: readonly [
|
|
162
|
+
readonly secondaryFiles: readonly ProjectMemoryFileRef[];
|
|
156
163
|
readonly ownedBlockName: "NEOCORTEX-MEMORY";
|
|
157
164
|
readonly templateKind: "agents-md";
|
|
158
165
|
readonly budget: {
|
|
@@ -179,7 +186,7 @@ export declare const PROJECT_MEMORY_TARGETS: {
|
|
|
179
186
|
readonly platformName: "Gemini CLI";
|
|
180
187
|
readonly canonicalSource: "NEOCORTEX.md";
|
|
181
188
|
readonly primaryFile: "GEMINI.md";
|
|
182
|
-
readonly secondaryFiles: readonly [
|
|
189
|
+
readonly secondaryFiles: readonly ProjectMemoryFileRef[];
|
|
183
190
|
readonly ownedBlockName: "NEOCORTEX-MEMORY";
|
|
184
191
|
readonly templateKind: "gemini-md";
|
|
185
192
|
readonly budget: {
|
|
@@ -206,7 +213,7 @@ export declare const PROJECT_MEMORY_TARGETS: {
|
|
|
206
213
|
readonly platformName: "Antigravity";
|
|
207
214
|
readonly canonicalSource: "NEOCORTEX.md";
|
|
208
215
|
readonly primaryFile: "GEMINI.md";
|
|
209
|
-
readonly secondaryFiles: readonly [
|
|
216
|
+
readonly secondaryFiles: readonly ProjectMemoryFileRef[];
|
|
210
217
|
readonly ownedBlockName: "NEOCORTEX-MEMORY";
|
|
211
218
|
readonly templateKind: "gemini-md";
|
|
212
219
|
readonly budget: {
|
|
@@ -233,7 +240,7 @@ export declare const PROJECT_MEMORY_TARGETS: {
|
|
|
233
240
|
readonly platformName: "VS Code / GitHub Copilot";
|
|
234
241
|
readonly canonicalSource: "NEOCORTEX.md";
|
|
235
242
|
readonly primaryFile: ".github/copilot-instructions.md";
|
|
236
|
-
readonly secondaryFiles: readonly [
|
|
243
|
+
readonly secondaryFiles: readonly ProjectMemoryFileRef[];
|
|
237
244
|
readonly ownedBlockName: "NEOCORTEX-MEMORY";
|
|
238
245
|
readonly templateKind: "copilot-instructions";
|
|
239
246
|
readonly budget: {
|
|
@@ -260,7 +267,7 @@ export declare const PROJECT_MEMORY_TARGETS: {
|
|
|
260
267
|
readonly platformName: "Cursor";
|
|
261
268
|
readonly canonicalSource: "NEOCORTEX.md";
|
|
262
269
|
readonly primaryFile: ".cursor/rules/neocortex.mdc";
|
|
263
|
-
readonly secondaryFiles: readonly [
|
|
270
|
+
readonly secondaryFiles: readonly ProjectMemoryFileRef[];
|
|
264
271
|
readonly ownedBlockName: "NEOCORTEX-MEMORY";
|
|
265
272
|
readonly templateKind: "cursor-rule";
|
|
266
273
|
readonly budget: {
|
|
@@ -287,7 +294,7 @@ export declare const PROJECT_MEMORY_TARGETS: {
|
|
|
287
294
|
readonly platformName: "OpenCode";
|
|
288
295
|
readonly canonicalSource: "NEOCORTEX.md";
|
|
289
296
|
readonly primaryFile: "AGENTS.md";
|
|
290
|
-
readonly secondaryFiles: readonly [
|
|
297
|
+
readonly secondaryFiles: readonly ProjectMemoryFileRef[];
|
|
291
298
|
readonly ownedBlockName: "NEOCORTEX-MEMORY";
|
|
292
299
|
readonly templateKind: "agents-md";
|
|
293
300
|
readonly budget: {
|
|
@@ -314,7 +321,10 @@ export declare const PROJECT_MEMORY_TARGETS: {
|
|
|
314
321
|
readonly platformName: "OpenClaw";
|
|
315
322
|
readonly canonicalSource: "NEOCORTEX.md";
|
|
316
323
|
readonly primaryFile: ".openclaw/skills/neocortex/SKILL.md";
|
|
317
|
-
readonly secondaryFiles: readonly [
|
|
324
|
+
readonly secondaryFiles: readonly [{
|
|
325
|
+
readonly scope: "user";
|
|
326
|
+
readonly path: ".openclaw/skills/neocortex/SKILL.md";
|
|
327
|
+
}];
|
|
318
328
|
readonly ownedBlockName: "NEOCORTEX-MEMORY";
|
|
319
329
|
readonly templateKind: "agents-md";
|
|
320
330
|
readonly budget: {
|
|
@@ -341,7 +351,7 @@ export declare const PROJECT_MEMORY_TARGETS: {
|
|
|
341
351
|
readonly platformName: "Kimi";
|
|
342
352
|
readonly canonicalSource: "NEOCORTEX.md";
|
|
343
353
|
readonly primaryFile: "KIMI.md";
|
|
344
|
-
readonly secondaryFiles: readonly [
|
|
354
|
+
readonly secondaryFiles: readonly ProjectMemoryFileRef[];
|
|
345
355
|
readonly ownedBlockName: "NEOCORTEX-MEMORY";
|
|
346
356
|
readonly templateKind: "agents-md";
|
|
347
357
|
readonly budget: {
|
|
@@ -368,7 +378,7 @@ export declare const PROJECT_MEMORY_TARGETS: {
|
|
|
368
378
|
readonly platformName: "GitHub Copilot CLI / gh alias";
|
|
369
379
|
readonly canonicalSource: "NEOCORTEX.md";
|
|
370
380
|
readonly primaryFile: ".github/copilot-instructions.md";
|
|
371
|
-
readonly secondaryFiles: readonly [
|
|
381
|
+
readonly secondaryFiles: readonly ProjectMemoryFileRef[];
|
|
372
382
|
readonly ownedBlockName: "NEOCORTEX-MEMORY";
|
|
373
383
|
readonly templateKind: "copilot-instructions";
|
|
374
384
|
readonly budget: {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e="NEOCORTEX.md",r={canonicalSource:e,semanticFileRequired:!0,symlinkBacked:!0,wrapperAllowed:!1,includeFallbackAllowed:!1,requiresWrapperPreservation:!1,fallbackIsCompatibilityRemediation:!0,policy:"mandatory-semantic-symlink",notes:"Semantic platform memory file must resolve to NEOCORTEX.md through a symlink; do not replace it with an unrelated wrapper or copied frontmatter."},
|
|
2
|
-
`)}export{e as CANONICAL_PROJECT_MEMORY_SOURCE,
|
|
1
|
+
function i(...t){return t.map(a=>({scope:"project",path:a}))}const e="NEOCORTEX.md",r={canonicalSource:e,semanticFileRequired:!0,symlinkBacked:!0,wrapperAllowed:!1,includeFallbackAllowed:!1,requiresWrapperPreservation:!1,fallbackIsCompatibilityRemediation:!0,policy:"mandatory-semantic-symlink",notes:"Semantic platform memory file must resolve to NEOCORTEX.md through a symlink; do not replace it with an unrelated wrapper or copied frontmatter."},l={canonicalSource:e,semanticFileRequired:!0,symlinkBacked:!0,wrapperAllowed:!0,includeFallbackAllowed:!1,requiresWrapperPreservation:!0,fallbackIsCompatibilityRemediation:!0,policy:"symlink-backed-wrapper",notes:"Platform wrapper/frontmatter is allowed only when the semantic memory payload remains symlink-backed by NEOCORTEX.md."},c={canonicalSource:e,semanticFileRequired:!0,symlinkBacked:!0,wrapperAllowed:!0,includeFallbackAllowed:!0,requiresWrapperPreservation:!0,fallbackIsCompatibilityRemediation:!0,policy:"safe-include-fallback",notes:"Use a safe include/import only for platforms that cannot consume symlinks directly; the include must resolve back to NEOCORTEX.md."};function o(t){return{canonicalSource:e,resolvesVia:t.policy,feedbackTrigger:"*update-memory",guidance:"Treat NEOCORTEX.md as canonical project memory; consult it before platform-specific memory, and run *update-memory when durable project context changes should flow back to the canonical source."}}const s=["claude-code","codex","grok","gemini-cli","antigravity","vscode","cursor","opencode","openclaw","kimi","github-copilot-cli"],m={canonical:{targetId:"canonical",platformName:"Neocortex Canonical Memory",canonicalSource:e,primaryFile:e,secondaryFiles:i("AGENTS.md","CLAUDE.md","GEMINI.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"neocortex-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:r,bidirectionalReference:o(r),requiresWrapperPreservation:!1,notes:"Canonical compact project memory source for platform symlinks and wrappers. Store only summaries, indexes, and links to architecture docs here."},"claude-code":{targetId:"claude-code",platformName:"Claude Code",canonicalSource:e,primaryFile:"CLAUDE.md",secondaryFiles:i(".claude/agents/neocortex.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"claude-md",budget:{maxLines:320,maxBytes:28e3},linkRequirement:r,bidirectionalReference:o(r),requiresWrapperPreservation:!1,notes:"Claude Code project memory. Resolve to NEOCORTEX.md; keep root content concise and link deeper docs with @path references."},codex:{targetId:"codex",platformName:"Codex CLI",canonicalSource:e,primaryFile:"AGENTS.md",secondaryFiles:i(".codex/agents/neocortex.toml"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:r,bidirectionalReference:o(r),requiresWrapperPreservation:!0,notes:"Codex root instructions. Uppercase AGENTS.md is required on case-sensitive filesystems."},grok:{targetId:"grok",platformName:"Grok Build",canonicalSource:e,primaryFile:"AGENTS.md",secondaryFiles:i(".grok/skills/neocortex/SKILL.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:r,bidirectionalReference:o(r),requiresWrapperPreservation:!0,notes:"Grok Build reads AGENTS.md and the project-local Neocortex Skill; both resolve to canonical NEOCORTEX.md context."},"gemini-cli":{targetId:"gemini-cli",platformName:"Gemini CLI",canonicalSource:e,primaryFile:"GEMINI.md",secondaryFiles:i(".gemini/agents/neocortex.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"gemini-md",budget:{maxLines:260,maxBytes:22e3},linkRequirement:r,bidirectionalReference:o(r),requiresWrapperPreservation:!1,notes:"Gemini CLI context file. Prefer shallow @file.md imports for detailed architecture docs."},antigravity:{targetId:"antigravity",platformName:"Antigravity",canonicalSource:e,primaryFile:"GEMINI.md",secondaryFiles:i(".gemini/agents/neocortex.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"gemini-md",budget:{maxLines:260,maxBytes:22e3},linkRequirement:r,bidirectionalReference:o(r),requiresWrapperPreservation:!1,notes:"Antigravity currently shares GEMINI.md behavior with the Gemini target stubs."},vscode:{targetId:"vscode",platformName:"VS Code / GitHub Copilot",canonicalSource:e,primaryFile:".github/copilot-instructions.md",secondaryFiles:i(".github/instructions/neocortex.instructions.md",".github/agents/neocortex.agent.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"copilot-instructions",budget:{maxLines:180,maxBytes:14e3},linkRequirement:l,bidirectionalReference:o(l),requiresWrapperPreservation:!0,notes:"VS Code and GitHub Copilot always-on repository instructions."},cursor:{targetId:"cursor",platformName:"Cursor",canonicalSource:e,primaryFile:".cursor/rules/neocortex.mdc",secondaryFiles:i("AGENTS.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"cursor-rule",budget:{maxLines:180,maxBytes:14e3},linkRequirement:l,bidirectionalReference:o(l),requiresWrapperPreservation:!0,notes:"Cursor rule memory. Use AGENTS.md as compatibility fallback when Cursor rules are absent."},opencode:{targetId:"opencode",platformName:"OpenCode",canonicalSource:e,primaryFile:"AGENTS.md",secondaryFiles:i(".opencode/AGENTS.md",".opencode/agents/neocortex-root.md",".opencode/agents/neocortex.md",".agent/skills/neocortex/SKILL.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:r,bidirectionalReference:o(r),requiresWrapperPreservation:!0,notes:"OpenCode agent memory. It consumes AGENTS.md-compatible instructions and must resolve to canonical NEOCORTEX.md."},openclaw:{targetId:"openclaw",platformName:"OpenClaw",canonicalSource:e,primaryFile:".openclaw/skills/neocortex/SKILL.md",secondaryFiles:[{scope:"user",path:".openclaw/skills/neocortex/SKILL.md"}],ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:c,bidirectionalReference:o(c),requiresWrapperPreservation:!0,notes:"OpenClaw Skill thin-client memory entrypoint. Use the project Skill path when --create-project is requested; do not mutate ~/.openclaw/openclaw.json, and keep memory content public-safe."},kimi:{targetId:"kimi",platformName:"Kimi",canonicalSource:e,primaryFile:"KIMI.md",secondaryFiles:i("AGENTS.md",".kimi/skills/neocortex/SKILL.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"agents-md",budget:{maxLines:220,maxBytes:18e3},linkRequirement:c,bidirectionalReference:o(c),requiresWrapperPreservation:!0,notes:"Kimi memory entrypoint. Prefer a symlink to NEOCORTEX.md; use a compact include only if the host cannot follow symlinks."},"github-copilot-cli":{targetId:"github-copilot-cli",platformName:"GitHub Copilot CLI / gh alias",canonicalSource:e,primaryFile:".github/copilot-instructions.md",secondaryFiles:i("AGENTS.md"),ownedBlockName:"NEOCORTEX-MEMORY",templateKind:"copilot-instructions",budget:{maxLines:180,maxBytes:14e3},linkRequirement:c,bidirectionalReference:o(c),requiresWrapperPreservation:!0,notes:"GitHub Copilot CLI or gh alias instructions. Resolve compact memory back to NEOCORTEX.md without copying private prompt bodies."}};function p(t){return m[t]}function u(t){return t==="canonical"||s.includes(t)}function y(){return s.map(t=>m[t])}function E(t){const a=n=>n.replace(/\|/g,"\\|").replace(/\n/g," ");return["| Path | Title | Purpose | Suggested Usage |","| --- | --- | --- | --- |",...t.map(n=>`| ${a(n.path)} | ${a(n.title)} | ${a(n.purpose)} | ${a(n.suggestedUsage)} |`)].join(`
|
|
2
|
+
`)}export{e as CANONICAL_PROJECT_MEMORY_SOURCE,m as PROJECT_MEMORY_TARGETS,s as PROJECT_MEMORY_TARGET_IDS,p as getProjectMemoryTarget,u as isProjectMemoryTargetId,y as listProjectMemoryTargets,E as renderArchitectureReferenceTable};
|
|
@@ -1,4 +1,23 @@
|
|
|
1
1
|
import { type StateMigrationPlanV1, type StateMigrationReceiptV1 } from '../../../shared/dist/state/index.js';
|
|
2
|
+
export declare const STATE_MIGRATION_INPUT_LIMIT_BYTES: number;
|
|
3
|
+
/** Request-only evidence. The canonical state and unknown values stay local. */
|
|
4
|
+
export interface StateMigrationAuthorityV1 {
|
|
5
|
+
readonly schemaVersion: 'StateMigrationAuthority/1.0';
|
|
6
|
+
readonly sourceByteDigest: string;
|
|
7
|
+
readonly sourceCanonicalHash: string;
|
|
8
|
+
readonly sourceByteLength: number;
|
|
9
|
+
readonly before: {
|
|
10
|
+
readonly epics: number;
|
|
11
|
+
readonly stories: number;
|
|
12
|
+
};
|
|
13
|
+
readonly after: {
|
|
14
|
+
readonly epics: number;
|
|
15
|
+
readonly stories: number;
|
|
16
|
+
};
|
|
17
|
+
readonly outcome: 'unchanged' | 'migrate';
|
|
18
|
+
readonly plan: Omit<StateMigrationPlanV1, 'targetState'> | null;
|
|
19
|
+
readonly publicSafe: true;
|
|
20
|
+
}
|
|
2
21
|
export declare class StateMigrationApplyError extends Error {
|
|
3
22
|
readonly reasonCode: string;
|
|
4
23
|
readonly receipt?: StateMigrationReceiptV1 | undefined;
|
|
@@ -9,6 +28,9 @@ export interface StateMigrationApplyHooks {
|
|
|
9
28
|
readonly afterPrepared?: (statePath: string) => void;
|
|
10
29
|
readonly afterReplace?: (statePath: string) => void;
|
|
11
30
|
}
|
|
31
|
+
export declare function collectStateMigrationAuthority(projectRoot: string): StateMigrationAuthorityV1;
|
|
12
32
|
export declare function previewStateMigration(projectRoot: string): StateMigrationPlanV1 | null;
|
|
13
33
|
/** Apply one shared plan under a client-owned lock, byte CAS and durable backup. */
|
|
14
|
-
export declare function applyStateMigration(projectRoot: string, expectedPlan?: Pick<StateMigrationPlanV1, 'operationId' | 'sourceCanonicalHash' | 'targetCanonicalHash'
|
|
34
|
+
export declare function applyStateMigration(projectRoot: string, expectedPlan?: Pick<StateMigrationPlanV1, 'operationId' | 'sourceCanonicalHash' | 'targetCanonicalHash'> & {
|
|
35
|
+
readonly sourceByteDigest?: string;
|
|
36
|
+
}, hooks?: StateMigrationApplyHooks): StateMigrationReceiptV1;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createHash as
|
|
2
|
-
`;function
|
|
3
|
-
`,
|
|
4
|
-
`)}function k(i,e,
|
|
1
|
+
import{createHash as q,randomUUID as N}from"node:crypto";import{existsSync as S,linkSync as J,lstatSync as E,mkdirSync as z,readFileSync as h,realpathSync as G,statSync as j,unlinkSync as v}from"node:fs";import{dirname as A,join as d,resolve as K}from"node:path";import{assertStateMigrationPlanV1 as X,assertStateMigrationReceiptV1 as Y,planStateMigration as T,stateMigrationDigest as Q,STATE_MIGRATION_RECEIPT_SCHEMA as W,StateMigrationHardStopError as B}from"../../../shared/dist/state/index.js";import{atomicReplaceUtf8 as M,durableCreateUtf8 as L,fsyncDirectoryBestEffort as O,recoverAtomicReplaceUtf8 as V}from"../fs/atomic-state-replace.js";const D=d(".neocortex","state.json"),R=d(".neocortex","state-migration.json"),Z=d(".neocortex","state-migration.lock"),P=4*1024*1024;class o extends Error{reasonCode;receipt;constructor(e,a=e,t){super(a),this.reasonCode=e,this.receipt=t,this.name="StateMigrationApplyError"}}const _=i=>q("sha256").update(i).digest("hex"),tt=i=>`${JSON.stringify(i,null,2)}
|
|
2
|
+
`;function $(i){let e;try{e=G(K(i))}catch{throw new o("state_migration_root_invalid")}if(!j(e).isDirectory())throw new o("state_migration_root_invalid");for(const a of[".neocortex",D,R]){const t=d(e,a);if(!S(t))continue;const s=E(t);if(s.isSymbolicLink()||a!==".neocortex"&&!s.isFile()||a===".neocortex"&&!s.isDirectory())throw new o("state_migration_symlink_or_type_rejected")}return e}function U(i){try{const e=JSON.parse(i);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}throw new o("state_migration_state_corrupt")}function F(i){const e=d(i,D);if(!S(e))throw new o("state_migration_state_missing");const a=j(e).size;if(a>P)throw new o("state_migration_input_too_large");const t=h(e,"utf8"),s=Buffer.byteLength(t,"utf8");if(s!==a||s>P)throw new o("state_migration_source_changed");return{state:U(t),raw:t,digest:_(t),bytes:s}}function ct(i){const e=F($(i));let a;try{a=T(e.state)}catch(l){throw l instanceof B?new o(l.reasonCode,l.message):l}const t=a.kind==="migrate"?a.plan.targetState:e.state,s=(l,p)=>{const n=l[p];return n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n).length:0},c=a.kind==="migrate"?(({targetState:l,...p})=>p)(a.plan):null;return Object.freeze({schemaVersion:"StateMigrationAuthority/1.0",sourceByteDigest:e.digest,sourceCanonicalHash:a.kind==="migrate"?a.plan.sourceCanonicalHash:a.sourceCanonicalHash,sourceByteLength:e.bytes,before:{epics:s(e.state,"epics"),stories:s(e.state,"stories")},after:{epics:s(t,"epics"),stories:s(t,"stories")},outcome:a.kind,plan:c,publicSafe:!0})}function et(i){const e=d(i,Z);z(A(e),{recursive:!0,mode:448});const a=N(),t=`${process.pid}:${a}
|
|
3
|
+
`,s=()=>{const c=`${e}.${process.pid}.${N()}.owner`;L(c,t);try{J(c,e)}finally{try{v(c)}catch{}O(A(e))}};try{s()}catch(c){if(c.code!=="EEXIST")throw new o("state_migration_lock_failed");const l=E(e);if(l.isSymbolicLink()||!l.isFile())throw new o("state_migration_lock_corrupt");const p=h(e,"utf8"),n=p.match(/^([1-9][0-9]*):([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\n$/i);if(!n||p.length>64)throw new o("state_migration_lock_corrupt");let f=!0;try{process.kill(Number(n[1]),0)}catch(r){f=r.code!=="ESRCH"}if(f)throw new o("state_migration_locked");try{v(e),s()}catch{throw new o("state_migration_locked")}}return()=>{try{if(h(e,"utf8")!==t)return;v(e),O(A(e))}catch{}}}function rt(i){const e=d(i,R);if(V(e),!S(e))return null;let a;try{a=JSON.parse(h(e,"utf8"))}catch{throw new o("state_migration_manifest_corrupt")}if(!a||typeof a!="object"||Array.isArray(a))throw new o("state_migration_manifest_corrupt");const t=a;if(t.schemaVersion!==1||typeof t.operationId!="string"||!/^smig_[a-f0-9]{32}$/.test(t.operationId)||!["prepared","applied","rolled-back"].includes(String(t.phase))||typeof t.sourceCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(t.sourceCanonicalHash)||typeof t.sourceByteDigest!="string"||!/^[a-f0-9]{64}$/.test(t.sourceByteDigest)||typeof t.targetCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(t.targetCanonicalHash)||typeof t.targetByteDigest!="string"||!/^[a-f0-9]{64}$/.test(t.targetByteDigest)||!Number.isSafeInteger(t.migratedEpicCount)||(t.migratedEpicCount??-1)<0||!Number.isSafeInteger(t.migratedStoryCount)||(t.migratedStoryCount??-1)<0||!Number.isSafeInteger(t.preservedUnknownFieldCount)||(t.preservedUnknownFieldCount??-1)<0||typeof t.backupPath!="string"||t.backupPath!==d(".neocortex",`state.json.migration-backup-${t.operationId}`))throw new o("state_migration_manifest_corrupt");return t}function b(i,e){M(d(i,R),`${JSON.stringify(e,null,2)}
|
|
4
|
+
`)}function k(i,e,a,t,s,c,l,p,n,f,r,g){const m={schemaVersion:W,operationId:e,outcome:i,sourceBytesHash:a,targetBytesHash:t,sourceCanonicalHash:s,targetCanonicalHash:c,backupHash:l,rollbackStatus:p,migratedEpicCount:n,migratedStoryCount:f,preservedUnknownFieldCount:r,reasonCodes:g,publicSafe:!0};return Y(m),m}function lt(i){const e=$(i);let a;try{a=T(F(e).state)}catch(t){throw t instanceof B?new o(t.reasonCode,t.message):t}return a.kind==="migrate"?a.plan:null}function pt(i,e,a={}){const t=$(i),s=et(t);try{const c=d(t,D);try{V(c)}catch{throw new o("state_migration_atomic_recovery_failed")}if(!S(c))throw new o("state_migration_state_missing");const l=F(t).raw;if(e?.sourceByteDigest&&_(l)!==e.sourceByteDigest)throw new o("state_migration_expected_bytes_conflict");let p;try{p=T(U(l))}catch(u){throw u instanceof B?new o(u.reasonCode,u.message):u}const n=rt(t),f=_(l);if(p.kind==="unchanged"){if(e&&p.sourceCanonicalHash!==e.targetCanonicalHash)throw new o("state_migration_expected_plan_conflict");if(n&&n.targetCanonicalHash===p.sourceCanonicalHash){if(n.targetByteDigest!==f)throw new o("state_migration_state_drift");if(n.phase==="prepared"&&b(t,{...n,phase:"applied"}),n.phase==="rolled-back")throw new o("state_migration_state_drift");return k("already-applied",n.operationId,n.sourceByteDigest,n.targetByteDigest,n.sourceCanonicalHash,n.targetCanonicalHash,n.sourceByteDigest,"not-required",n.migratedEpicCount,n.migratedStoryCount,n.preservedUnknownFieldCount,["migration_replay_verified"])}if(n)throw new o("state_migration_state_drift");return k("already-applied",e?.operationId??"smig_00000000000000000000000000000000",f,f,p.sourceCanonicalHash,p.sourceCanonicalHash,null,"not-required",0,0,0,["canonical_state_unchanged"])}const r=p.plan;if(X(r),e&&(e.operationId!==r.operationId||e.sourceCanonicalHash!==r.sourceCanonicalHash||e.targetCanonicalHash!==r.targetCanonicalHash))throw new o("state_migration_expected_plan_conflict");if(n&&n.operationId!==r.operationId)throw new o("state_migration_operation_conflict");const g=f,m=tt(r.targetState),w=_(m),x=d(".neocortex",`state.json.migration-backup-${r.operationId}`),y=d(t,x);if(S(y)){const u=E(y);if(u.isSymbolicLink()||!u.isFile()||_(h(y))!==g)throw new o("state_migration_backup_conflict")}else L(y,l);const I={schemaVersion:1,operationId:r.operationId,phase:"prepared",sourceCanonicalHash:r.sourceCanonicalHash,sourceByteDigest:g,targetCanonicalHash:r.targetCanonicalHash,targetByteDigest:w,migratedEpicCount:r.migratedEpicIds.length,migratedStoryCount:r.migratedStoryIds.length,preservedUnknownFieldCount:r.preservedUnknownFieldCount,backupPath:x};if(b(t,I),a.afterPrepared?.(c),_(h(c))!==g)throw new o("state_migration_source_cas_conflict");try{M(c,m),a.afterReplace?.(c);const u=h(c,"utf8"),H=U(u);if(_(u)!==w||Q(H)!==r.targetCanonicalHash)throw new Error("readback-digest-mismatch");b(t,{...I,phase:"applied"})}catch(u){try{const C=h(y,"utf8");if(_(C)!==g)throw new Error("rollback-backup-digest-mismatch");if(M(c,C),_(h(c))!==g)throw new Error("rollback-digest-mismatch");b(t,{...I,phase:"rolled-back"})}catch{const C=k("blocked",r.operationId,g,w,r.sourceCanonicalHash,r.targetCanonicalHash,g,"unverified",r.migratedEpicIds.length,r.migratedStoryIds.length,r.preservedUnknownFieldCount,["apply_failed","rollback_unverified"]);throw new o("state_migration_rollback_failed",String(u),C)}const H=k("blocked",r.operationId,g,w,r.sourceCanonicalHash,r.targetCanonicalHash,g,"restored",r.migratedEpicIds.length,r.migratedStoryIds.length,r.preservedUnknownFieldCount,["apply_failed","rollback_verified"]);throw new o("state_migration_apply_rolled_back",String(u),H)}return k("applied",r.operationId,g,w,r.sourceCanonicalHash,r.targetCanonicalHash,g,"not-required",r.migratedEpicIds.length,r.migratedStoryIds.length,r.preservedUnknownFieldCount,["lock_acquired","source_cas_verified","backup_verified","atomic_replace_verified"])}finally{s()}}export{P as STATE_MIGRATION_INPUT_LIMIT_BYTES,o as StateMigrationApplyError,pt as applyStateMigration,ct as collectStateMigrationAuthority,lt as previewStateMigration};
|