@ornexus/neocortex 4.66.3 → 4.66.5

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.
Files changed (62) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1194 -1194
  3. package/install.js +2 -0
  4. package/install.ps1 +89 -35
  5. package/install.sh +63 -99
  6. package/package.json +2 -2
  7. package/packages/client/dist/agent/refresh-stubs.d.ts +9 -0
  8. package/packages/client/dist/agent/refresh-stubs.js +2 -2
  9. package/packages/client/dist/agent/update-agent-yaml.js +1 -1
  10. package/packages/client/dist/agent/update-description.d.ts +23 -0
  11. package/packages/client/dist/agent/update-description.js +1 -2
  12. package/packages/client/dist/cli.js +14 -6
  13. package/packages/client/dist/commands/activate.js +8 -8
  14. package/packages/client/dist/commands/auth-doctor.d.ts +24 -0
  15. package/packages/client/dist/commands/auth-doctor.js +7 -0
  16. package/packages/client/dist/commands/invoke.d.ts +3 -1
  17. package/packages/client/dist/commands/invoke.js +101 -95
  18. package/packages/client/dist/config/profile-directory.d.ts +24 -0
  19. package/packages/client/dist/config/profile-directory.js +1 -1
  20. package/packages/client/dist/config/project-root.d.ts +40 -0
  21. package/packages/client/dist/config/project-root.js +1 -0
  22. package/packages/client/dist/errors/error-messages.js +2 -2
  23. package/packages/client/dist/git/epic-operational-state.d.ts +18 -0
  24. package/packages/client/dist/git/epic-operational-state.js +2 -2
  25. package/packages/client/dist/license/license-client.d.ts +2 -1
  26. package/packages/client/dist/license/license-client.js +1 -1
  27. package/packages/client/dist/migrations/epic-lifecycle-backfill.d.ts +7 -0
  28. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -3
  29. package/packages/shared/dist/executable-graph-catalog/contracts.js +6 -6
  30. package/packages/shared/dist/invocation/diagnose-degraded-continuation.d.ts +14 -0
  31. package/packages/shared/dist/invocation/diagnose-degraded-continuation.js +39 -0
  32. package/packages/shared/dist/invocation/diagnose-degraded-continuation.test.d.ts +1 -0
  33. package/packages/shared/dist/invocation/diagnose-degraded-continuation.test.js +26 -0
  34. package/packages/shared/dist/invocation/index.d.ts +1 -0
  35. package/packages/shared/dist/invocation/index.js +1 -0
  36. package/targets-stubs/antigravity/gemini.md +1 -1
  37. package/targets-stubs/antigravity/neocortex.md +15 -1
  38. package/targets-stubs/antigravity/skill/SKILL.md +18 -4
  39. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  40. package/targets-stubs/claude-code/neocortex-root.md +13 -5
  41. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  42. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  43. package/targets-stubs/claude-code/neocortex.md +13 -5
  44. package/targets-stubs/codex/AGENTS.md +20 -21
  45. package/targets-stubs/codex/neocortex.toml +15 -1
  46. package/targets-stubs/cursor/agent.md +19 -5
  47. package/targets-stubs/deepseek-harness/SKILL.md +15 -1
  48. package/targets-stubs/gemini-cli/README.md +7 -5
  49. package/targets-stubs/gemini-cli/agent.md +19 -5
  50. package/targets-stubs/gemini-cli/agents/neocortex.md +19 -5
  51. package/targets-stubs/gemini-cli/gemini.md +8 -7
  52. package/targets-stubs/gemini-cli/install-gemini.sh +29 -11
  53. package/targets-stubs/grok/README.md +5 -0
  54. package/targets-stubs/grok/SKILL.md +16 -1
  55. package/targets-stubs/grok/install-grok.sh +15 -6
  56. package/targets-stubs/kimi/neocortex.md +15 -1
  57. package/targets-stubs/lib/managed-config-merge.js +276 -23
  58. package/targets-stubs/lib/managed-profile.sh +38 -0
  59. package/targets-stubs/openclaw/SKILL.md +20 -17
  60. package/targets-stubs/opencode/neocortex-root.md +20 -22
  61. package/targets-stubs/opencode/neocortex.md +20 -22
  62. package/targets-stubs/vscode/neocortex.agent.md +19 -5
@@ -41,24 +41,42 @@ install_gemini() {
41
41
  local project_install=true
42
42
  neocortex_is_user_home "$dest_dir" && project_install=false
43
43
 
44
- # 1. Keep the legacy root-capable profile at a collision-free path. Native
45
- # delegated tasks own agents/neocortex.md and refresh must never overwrite it.
46
- if [ -f "$gemini_target/agent.md" ]; then
47
- neocortex_managed_profile "$source_dir" "$gemini_target/agent.md" "$gemini_home/agents/neocortex-root.md" "$gemini_base" "profile-gemini-neocortex-root" || failures=$((failures + 1))
48
- neocortex_managed_report "[GEMINI]" "$gemini_home/agents/neocortex-root.md (root agent stub)"
49
- fi
50
-
51
- # 2. Copy native subagent profile to user and project scopes when present.
52
- # Gemini CLI subagent reference: https://geminicli.com/docs/core/subagents/
44
+ # 1. Public topology is one discoverable orchestrator. The historical
45
+ # neocortex-root alias is retired only when ownership is proven.
53
46
  if [ -f "$gemini_target/agents/neocortex.md" ]; then
54
47
  neocortex_managed_profile "$source_dir" "$gemini_target/agents/neocortex.md" "$gemini_home/agents/neocortex.md" "$gemini_base" "profile-gemini-neocortex" || failures=$((failures + 1))
55
- neocortex_managed_report "[GEMINI]" "$gemini_home/agents/neocortex.md (native subagent)"
48
+ neocortex_managed_report "[GEMINI]" "$gemini_home/agents/neocortex.md (orchestrator)"
56
49
 
57
50
  if [ "$project_install" = true ] && [ -d "$dest_dir" ] && [ "$dest_dir/.gemini/agents/neocortex.md" != "$gemini_home/agents/neocortex.md" ]; then
58
51
  mkdir -p "$dest_dir/.gemini/agents"
59
52
  neocortex_managed_profile "$source_dir" "$gemini_target/agents/neocortex.md" "$dest_dir/.gemini/agents/neocortex.md" "$dest_dir" "project-gemini-neocortex" || failures=$((failures + 1))
60
- neocortex_managed_report "[GEMINI]" ".gemini/agents/neocortex.md (project subagent)"
53
+ neocortex_managed_report "[GEMINI]" ".gemini/agents/neocortex.md (project orchestrator)"
54
+ fi
55
+ fi
56
+
57
+ neocortex_managed_retire "$source_dir" "$gemini_home/agents/neocortex-root.md" "$gemini_base" "profile-gemini-neocortex-root" || failures=$((failures + 1))
58
+ neocortex_managed_report "[GEMINI]" "$gemini_home/agents/neocortex-root.md (historical alias)"
59
+
60
+ # 2. The isolated child is an explicit opt-in, never a default public
61
+ # profile. A previous managed child converges away when the flag is absent.
62
+ if [ "${INSTALL_SENTINEL:-false}" = true ] && [ -f "$gemini_target/agents/neocortex-sentinel.md" ]; then
63
+ neocortex_managed_profile "$source_dir" "$gemini_target/agents/neocortex-sentinel.md" "$gemini_home/agents/neocortex-sentinel.md" "$gemini_base" "profile-gemini-neocortex-sentinel" || failures=$((failures + 1))
64
+ neocortex_managed_report "[GEMINI]" "$gemini_home/agents/neocortex-sentinel.md (optional child)"
65
+ else
66
+ neocortex_managed_retire "$source_dir" "$gemini_home/agents/neocortex-sentinel.md" "$gemini_base" "profile-gemini-neocortex-sentinel" || failures=$((failures + 1))
67
+ neocortex_managed_report "[GEMINI]" "$gemini_home/agents/neocortex-sentinel.md (optional child)"
68
+ fi
69
+ if [ "$project_install" = true ] && [ -d "$dest_dir" ]; then
70
+ if [ "${INSTALL_SENTINEL:-false}" = true ] && [ -f "$gemini_target/agents/neocortex-sentinel.md" ]; then
71
+ mkdir -p "$dest_dir/.gemini/agents"
72
+ neocortex_managed_profile "$source_dir" "$gemini_target/agents/neocortex-sentinel.md" "$dest_dir/.gemini/agents/neocortex-sentinel.md" "$dest_dir" "project-gemini-neocortex-sentinel" || failures=$((failures + 1))
73
+ neocortex_managed_report "[GEMINI]" ".gemini/agents/neocortex-sentinel.md (optional project child)"
74
+ else
75
+ neocortex_managed_retire "$source_dir" "$dest_dir/.gemini/agents/neocortex-sentinel.md" "$dest_dir" "project-gemini-neocortex-sentinel" || failures=$((failures + 1))
76
+ neocortex_managed_report "[GEMINI]" ".gemini/agents/neocortex-sentinel.md (optional project child)"
61
77
  fi
78
+ neocortex_managed_retire "$source_dir" "$dest_dir/.gemini/agents/neocortex-root.md" "$dest_dir" "project-gemini-neocortex-root" || failures=$((failures + 1))
79
+ neocortex_managed_report "[GEMINI]" ".gemini/agents/neocortex-root.md (historical project alias)"
62
80
  fi
63
81
 
64
82
  # 3. Copy GEMINI.md stub to project root
@@ -9,5 +9,10 @@ Installs the public Neocortex Skill globally at
9
9
  neocortex --targets=grok
10
10
  ```
11
11
 
12
+ The default installs only the public orchestrator skill. The isolated
13
+ `neocortex-sentinel` agent is available through the explicit
14
+ `--install-sentinel` opt-in; a previously managed sentinel is retired on the
15
+ next default reconcile while unknown or user-edited files are preserved.
16
+
12
17
  Grok reads project instructions from `AGENTS.md`; Neocortex keeps
13
18
  `NEOCORTEX.md` as canonical project memory.
@@ -14,7 +14,7 @@ Ambient platform/tool metadata, assistant notes, conversation history, raw logs,
14
14
  Then run:
15
15
 
16
16
  ```bash
17
- neocortex-client invoke --args "{USER_ARGS}" --project-root "$(git rev-parse --show-toplevel 2>/dev/null || pwd -P)" --format plain
17
+ neocortex-client invoke --args "{USER_ARGS}" --format plain
18
18
  ```
19
19
 
20
20
  Follow stdout exactly. Never treat `*` commands as Grok tools, include ambient
@@ -22,6 +22,21 @@ conversation metadata in `--args`, or expose private prompts, credentials, logs,
22
22
  server implementation details, or proprietary workflow logic. On a non-zero
23
23
  exit, report the public error and stop for user input.
24
24
 
25
+ ## Degraded diagnose continuation
26
+
27
+ Inspect `metadata.diagnose` only when the explicit selected payload's canonical
28
+ trigger is `diagnose` and `assertDiagnoseDegradedContinuation` accepts the exact
29
+ `DiagnoseDegradedContinuation/1.0` object. Unknown, missing, or extra fields,
30
+ wrong literals, an absent contract, or an unrelated degraded reason authorizes
31
+ no additional inspection or action.
32
+
33
+ For an admitted continuation, the current agent alone may inspect only the
34
+ explicit request and public local read-only evidence. Return probable cause,
35
+ inspected evidence, limitation, and a safe plan. Do not claim protected workflow
36
+ execution, spawn or delegate, reinvoke Neocortex, create tasks, or write files.
37
+ Never include protected prompts, raw logs, secrets, PII, private URLs, ambient
38
+ conversation history, or asset-derived text.
39
+
25
40
  For an explicitly supplied oversized story or prompt, `--stdin` or `--args-file`
26
41
  is an optional large-input compatibility path. Do not force migration from
27
42
  `--args`, do not combine these input modes, and never use them for ambient
@@ -50,11 +50,9 @@ install_grok() {
50
50
  neocortex_managed_report "[GROK]" ".grok/skills/neocortex/SKILL.md (project skill)"
51
51
  fi
52
52
 
53
- # P228.04 / P229.09: published per-story child agent type (`spawn_subagent`
54
- # with subagent_type "neocortex-sentinel"); managed, non-overwriting, drift
55
- # preserved. The legacy child `agents/neocortex.md` is retired only after
56
- # the sentinel is in place and only when its hash matches the manifest.
57
- if [ -f "$grok_target/agents/neocortex-sentinel.md" ]; then
53
+ # The public skill is the orchestrator. The isolated child is opt-in and a
54
+ # prior managed child is retired conservatively when the flag is absent.
55
+ if [ "${INSTALL_SENTINEL:-false}" = true ] && [ -f "$grok_target/agents/neocortex-sentinel.md" ]; then
58
56
  mkdir -p "$grok_home/agents"
59
57
  if neocortex_managed_profile "$source_dir" "$grok_target/agents/neocortex-sentinel.md" "$grok_home/agents/neocortex-sentinel.md" "$grok_base" "profile-grok-agent-neocortex-sentinel"; then
60
58
  neocortex_managed_report "[GROK]" "$grok_home/agents/neocortex-sentinel.md (global child agent)"
@@ -73,6 +71,13 @@ install_grok() {
73
71
  neocortex_managed_report "[GROK]" ".grok/agents/neocortex-sentinel.md (project child agent)"
74
72
  fi
75
73
  fi
74
+ else
75
+ neocortex_managed_retire "$source_dir" "$grok_home/agents/neocortex-sentinel.md" "$grok_base" "profile-grok-agent-neocortex-sentinel" || failures=$((failures + 1))
76
+ neocortex_managed_report "[GROK]" "$grok_home/agents/neocortex-sentinel.md (optional child agent)"
77
+ if ! neocortex_is_user_home "$dest_dir" && [ -d "$dest_dir" ]; then
78
+ neocortex_managed_retire "$source_dir" "$dest_dir/.grok/agents/neocortex-sentinel.md" "$dest_dir" "project-grok-agent-neocortex-sentinel" || failures=$((failures + 1))
79
+ neocortex_managed_report "[GROK]" ".grok/agents/neocortex-sentinel.md (optional project child agent)"
80
+ fi
76
81
  fi
77
82
 
78
83
  if command -v node >/dev/null 2>&1; then
@@ -88,6 +93,10 @@ install_grok() {
88
93
  echo "[GROK] ERROR: $failures managed file(s) could not be installed; existing files were preserved." >&2
89
94
  return 1
90
95
  fi
91
- echo "[GROK] Installed Neocortex Skill and child agent for Grok Build."
96
+ if [ "${INSTALL_SENTINEL:-false}" = true ]; then
97
+ echo "[GROK] Installed Neocortex orchestrator skill and optional child agent for Grok Build."
98
+ else
99
+ echo "[GROK] Installed Neocortex orchestrator skill for Grok Build."
100
+ fi
92
101
  return 0
93
102
  }
@@ -57,12 +57,26 @@ Ambient platform/tool metadata, assistant notes, conversation history, raw logs,
57
57
  ```bash
58
58
  neocortex-client invoke \
59
59
  --args "{DELEGATED_PROMPT}" \
60
- --project-root "$(git rev-parse --show-toplevel 2>/dev/null || pwd -P)" \
61
60
  --format plain
62
61
  ```
63
62
 
64
63
  Then follow stdout exactly.
65
64
 
65
+ ## Degraded diagnose continuation
66
+
67
+ Inspect `metadata.diagnose` only when the explicit selected payload's canonical
68
+ trigger is `diagnose` and `assertDiagnoseDegradedContinuation` accepts the exact
69
+ `DiagnoseDegradedContinuation/1.0` object. Unknown, missing, or extra fields,
70
+ wrong literals, an absent contract, or an unrelated degraded reason authorizes
71
+ no additional inspection or action.
72
+
73
+ For an admitted continuation, the current agent alone may inspect only the
74
+ explicit request and public local read-only evidence. Return probable cause,
75
+ inspected evidence, limitation, and a safe plan. Do not claim protected workflow
76
+ execution, spawn or delegate, reinvoke Neocortex, create tasks, or write files.
77
+ Never include protected prompts, raw logs, secrets, PII, private URLs, ambient
78
+ conversation history, or asset-derived text.
79
+
66
80
  Large input compatibility is optional and must not weaken isolation: keep using
67
81
  `--args` for normal delegated prompts. If the root agent passes an oversized
68
82
  server-authorized delegated prompt through a safe temporary file or stdin, use
@@ -8,7 +8,8 @@ const crypto = require('node:crypto');
8
8
  const fs = require('node:fs');
9
9
  const path = require('node:path');
10
10
 
11
- const SCHEMA_VERSION = 1;
11
+ const SCHEMA_VERSION = 2;
12
+ const LEGACY_SCHEMA_VERSION = 1;
12
13
  const EVIDENCE = '[P201-EV-INSTALLER]';
13
14
  const POLICY_ID = 'neocortex-config/subagent-approval-policy';
14
15
  const POLICY_KEY = 'subagentApprovalPolicy';
@@ -100,7 +101,13 @@ function atomicWrite(file, bytes, mode = 0o600) {
100
101
  `.${path.basename(file)}.neocortex-tmp-${process.pid}-${crypto.randomBytes(6).toString('hex')}`,
101
102
  );
102
103
  try {
103
- fs.writeFileSync(temp, bytes, { mode });
104
+ const fd = fs.openSync(temp, 'wx', mode);
105
+ try {
106
+ fs.writeFileSync(fd, bytes);
107
+ fs.fsyncSync(fd);
108
+ } finally {
109
+ fs.closeSync(fd);
110
+ }
104
111
  try { fs.chmodSync(temp, mode); } catch { /* best effort */ }
105
112
  fs.renameSync(temp, file);
106
113
  try { fs.chmodSync(file, mode); } catch { /* best effort */ }
@@ -129,12 +136,14 @@ function loadManifest(manifestFile, baseDir) {
129
136
  }
130
137
  if (
131
138
  !parsed || typeof parsed !== 'object' || Array.isArray(parsed) ||
132
- parsed.schemaVersion !== SCHEMA_VERSION || parsed.evidence !== EVIDENCE ||
139
+ ![LEGACY_SCHEMA_VERSION, SCHEMA_VERSION].includes(parsed.schemaVersion) || parsed.evidence !== EVIDENCE ||
133
140
  !parsed.entries || typeof parsed.entries !== 'object' || Array.isArray(parsed.entries)
134
141
  ) {
135
142
  throw new ManagedConfigError('managed-manifest-invalid', 'Managed manifest schema is invalid.', 2);
136
143
  }
137
- return parsed;
144
+ return parsed.schemaVersion === LEGACY_SCHEMA_VERSION
145
+ ? { ...parsed, schemaVersion: SCHEMA_VERSION }
146
+ : parsed;
138
147
  }
139
148
 
140
149
  function saveManifest(manifestFile, baseDir, manifest, dryRun) {
@@ -148,7 +157,17 @@ function backupBytes(baseDir, id, bytes, options = {}) {
148
157
  const backupDir = path.join(path.resolve(baseDir), '.neocortex', 'backups', 'managed-config');
149
158
  const backupFile = path.join(backupDir, `${sanitizeId(id)}-${stamp}-${hash.slice(0, 12)}.bak`);
150
159
  const location = resolveWithinBase(baseDir, backupFile, 'backup');
151
- if (!options.dryRun) atomicWrite(location.resolved, bytes, 0o600);
160
+ if (!options.dryRun) {
161
+ atomicWrite(location.resolved, bytes, 0o600);
162
+ const readback = fs.readFileSync(location.resolved);
163
+ if (sha256(readback) !== hash) {
164
+ throw new ManagedConfigError(
165
+ 'managed-backup-verification-failed',
166
+ 'Managed backup readback did not match the bound preimage.',
167
+ 3,
168
+ );
169
+ }
170
+ }
152
171
  return { backupFile: location.resolved, backupRelativePath: location.relative, backupHash: hash };
153
172
  }
154
173
 
@@ -331,9 +350,16 @@ function settleLegacyCopy(input, manifest, allowedHashes) {
331
350
  * manifest owners are removed only when the bytes match a recorded
332
351
  * `installedHash`; anything else is preserved.
333
352
  */
334
- function retireLegacy({ destination, manifestFile, baseDir, id, dryRun }) {
353
+ function retireLegacy({ destination, manifestFile, baseDir, id, dryRun, knownHashes = [] }) {
335
354
  const manifest = loadManifest(manifestFile, baseDir);
336
- const settled = settleLegacyCopy({ legacyCopyPath: destination, baseDir, manifestFile, dryRun }, manifest, []);
355
+ const boundedKnownHashes = Array.isArray(knownHashes)
356
+ ? knownHashes.filter((value) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)).slice(0, 32)
357
+ : [];
358
+ const settled = settleLegacyCopy(
359
+ { legacyCopyPath: destination, baseDir, manifestFile, dryRun },
360
+ manifest,
361
+ boundedKnownHashes,
362
+ );
337
363
  if (!settled || settled.action === 'none') {
338
364
  return resultFor(id, null, 'none', 'agent-profile-legacy-absent', { dryRun: dryRun === true });
339
365
  }
@@ -507,6 +533,49 @@ function managedLinesDigest(bytes) {
507
533
  return sha256(Buffer.from(managedLinesCanonical(bytes), 'utf8'));
508
534
  }
509
535
 
536
+ function managedLayout(bytes) {
537
+ const text = Buffer.isBuffer(bytes) ? bytes.toString('utf8') : String(bytes ?? '');
538
+ const lines = splitManagedLines(text);
539
+ const managed = lines
540
+ .map((line, index) => (line.managed ? { index, kind: line.managed.kind, cr: line.cr } : null))
541
+ .filter(Boolean);
542
+ return {
543
+ lines,
544
+ managed,
545
+ digest: sha256(Buffer.from(managed.map((line) => `${line.kind}:${line.cr === '\r' ? 'crlf' : 'lf'}`).join('\n'))),
546
+ };
547
+ }
548
+
549
+ /**
550
+ * Replace only a closed, uniquely identified set of whole managed lines.
551
+ * Every non-managed byte comes from the current file. Ambiguous layouts fail
552
+ * closed instead of attempting a fuzzy or three-way merge.
553
+ */
554
+ function mergeManagedProfileBytes(currentBytes, desiredBytes) {
555
+ const current = managedLayout(currentBytes);
556
+ const desired = managedLayout(desiredBytes);
557
+ if (current.managed.length === 0 || current.managed.length !== desired.managed.length) return null;
558
+ const currentKinds = current.managed.map((line) => line.kind);
559
+ const desiredKinds = desired.managed.map((line) => line.kind);
560
+ if (currentKinds.some((kind, index) => kind !== desiredKinds[index])) return null;
561
+ if (new Set(currentKinds).size !== currentKinds.length) return null;
562
+ if (current.managed.some((line, index) => line.cr !== desired.managed[index].cr)) return null;
563
+
564
+ const merged = current.lines.map((line) => line.raw);
565
+ current.managed.forEach((line, index) => {
566
+ merged[line.index] = desired.lines[desired.managed[index].index].raw;
567
+ });
568
+ return {
569
+ bytes: Buffer.from(merged.join('\n'), 'utf8'),
570
+ layoutDigest: current.digest,
571
+ userRegionDigest: managedLinesDigest(currentBytes),
572
+ };
573
+ }
574
+
575
+ function prefixedDigest(bytes) {
576
+ return `sha256:${sha256(bytes)}`;
577
+ }
578
+
510
579
  function padBanner(inner) {
511
580
  return `│${inner}${' '.repeat(Math.max(0, BANNER_INNER_WIDTH - inner.length))}│`;
512
581
  }
@@ -730,6 +799,8 @@ function writeManagedBytes(input) {
730
799
  legacyBaseDir = null,
731
800
  agentRoles = false,
732
801
  agentRoleId = null,
802
+ contentVersion = null,
803
+ faultInjection = null,
733
804
  now,
734
805
  } = input;
735
806
  let safeId = sanitizeId(id);
@@ -739,6 +810,7 @@ function writeManagedBytes(input) {
739
810
  ? AGENT_ROLE_BY_ID.get(agentRoleId ? sanitizeId(agentRoleId) : safeId) || null
740
811
  : null;
741
812
  const target = resolveWithinBase(baseDir, destination, 'destination');
813
+ const manifestPreimage = fs.existsSync(manifestFile) ? fs.readFileSync(manifestFile) : null;
742
814
  const manifest = loadManifest(manifestFile, baseDir);
743
815
  let ownerAdopted = false;
744
816
  if (adoptExistingOwner && !manifest.entries[safeId]) {
@@ -782,12 +854,30 @@ function writeManagedBytes(input) {
782
854
  }
783
855
  }
784
856
 
785
- const desiredHash = sha256(desiredBytes);
786
- const desiredDigest = isProfile ? managedLinesDigest(desiredBytes) : null;
787
- const digestField = isProfile ? { managedLinesDigest: desiredDigest } : {};
857
+ const sourceBytes = Buffer.from(desiredBytes);
858
+ const sourceDigest = prefixedDigest(sourceBytes);
859
+ let committedBytes = sourceBytes;
860
+ let desiredHash = sha256(committedBytes);
861
+ let desiredDigest = isProfile ? managedLinesDigest(committedBytes) : null;
862
+ let classification = 'unchanged';
863
+ const profileDigestFields = () => (isProfile ? {
864
+ managedLinesDigest: desiredDigest,
865
+ sourceDigest,
866
+ // Canonical non-managed region of the packaged source (before operator
867
+ // customization); a later selective merge requires the new source to keep it.
868
+ sourceRegionDigest: managedLinesDigest(sourceBytes),
869
+ installedDigest: prefixedDigest(committedBytes),
870
+ userRegionDigest: desiredDigest,
871
+ managedLayoutDigest: managedLayout(committedBytes).digest,
872
+ ...(contentVersion ? { contentVersion: String(contentVersion) } : {}),
873
+ } : {});
874
+ let digestField = profileDigestFields();
788
875
  const exists = fs.existsSync(target.resolved);
789
876
  const currentBytes = exists ? fs.readFileSync(target.resolved) : null;
790
877
  const currentHash = currentBytes ? sha256(currentBytes) : null;
878
+ if (isProfile && entry && currentHash === entry.installedHash && currentHash !== desiredHash) {
879
+ classification = 'managed-lines-only';
880
+ }
791
881
  const legacy = isProfile ? readLegacyDuplicates(legacyBaseDir, baseDir, target.resolved) : null;
792
882
  const priorInstalledHash = entry?.installedHash || null;
793
883
 
@@ -863,6 +953,79 @@ function writeManagedBytes(input) {
863
953
  isProfile && !ownershipEvidence
864
954
  ) {
865
955
  ownershipEvidence = managedDeltaEvidence(currentBytes, desiredBytes, entry);
956
+ if (ownershipEvidence) classification = 'managed-lines-only';
957
+ // P231.05: selective merge needs recorded layout evidence (schema-2
958
+ // layout digest, or at least a schema-1 managed-lines digest). A legacy
959
+ // entry without either stays ambiguous drift; no heuristic adoption.
960
+ // The packaged source itself must change only managed lines: when both the
961
+ // source and the operator changed non-managed bytes the result would be a
962
+ // free-form three-way merge, so the destination stays preserved.
963
+ const recordedSourceRegion = typeof entry.sourceRegionDigest === 'string'
964
+ ? entry.sourceRegionDigest
965
+ : entry.managedLinesDigest;
966
+ const layoutEvidence = typeof recordedSourceRegion === 'string' &&
967
+ managedLinesDigest(desiredBytes) === recordedSourceRegion;
968
+ if (
969
+ !ownershipEvidence && !migrationNeeded && layoutEvidence &&
970
+ (!roleRow || !entry.agentRole || entry.agentRole === roleRow.role)
971
+ ) {
972
+ const merged = mergeManagedProfileBytes(currentBytes, desiredBytes);
973
+ // A merge that changes no byte is not an update: the operator bytes stay
974
+ // as user drift and are never blessed into the manifest.
975
+ if (merged && !merged.bytes.equals(currentBytes) && (typeof entry.managedLayoutDigest !== 'string' || entry.managedLayoutDigest === merged.layoutDigest)) {
976
+ committedBytes = merged.bytes;
977
+ desiredHash = sha256(committedBytes);
978
+ desiredDigest = managedLinesDigest(committedBytes);
979
+ digestField = profileDigestFields();
980
+ // Closed taxonomy: an unchanged recorded user region means only managed
981
+ // lines drifted; any other non-managed delta is operator customization.
982
+ const regionUnchanged = typeof entry.userRegionDigest === 'string' &&
983
+ entry.userRegionDigest === merged.userRegionDigest;
984
+ classification = regionUnchanged ? 'managed-lines-only' : 'user-customized';
985
+ ownershipEvidence = regionUnchanged ? 'managed-lines-delta' : 'managed-user-customization';
986
+ }
987
+ }
988
+ }
989
+
990
+ // P231.05 (C11): the destination still holds exactly the bytes last
991
+ // committed, but those bytes carried operator customization (the recorded
992
+ // user region differs from the recorded packaged-source region). Committing
993
+ // the raw source would drop that customization on a replay or an upgrade, so
994
+ // the same managed-lines merge runs under the same evidence gates. A
995
+ // same-source replay is a byte no-op; a source that also changed non-managed
996
+ // bytes, a role migration or an ambiguous layout preserves the destination.
997
+ if (
998
+ isProfile && entry && currentHash === entry.installedHash && !allowOwnedDriftMerge &&
999
+ typeof entry.userRegionDigest === 'string' && typeof entry.sourceRegionDigest === 'string' &&
1000
+ entry.userRegionDigest !== entry.sourceRegionDigest
1001
+ ) {
1002
+ const sourceRegionKept = managedLinesDigest(desiredBytes) === entry.sourceRegionDigest;
1003
+ const roleKept = !roleRow || !entry.agentRole || entry.agentRole === roleRow.role;
1004
+ const merged = sourceRegionKept && roleKept && !migrationNeeded
1005
+ ? mergeManagedProfileBytes(currentBytes, desiredBytes) : null;
1006
+ if (!merged || (typeof entry.managedLayoutDigest === 'string' && entry.managedLayoutDigest !== merged.layoutDigest)) {
1007
+ return resultFor(
1008
+ safeId,
1009
+ target.relative,
1010
+ 'skipped',
1011
+ migrationNeeded ? 'agent-profile-migration-drift' : 'user-drift-preserved',
1012
+ {
1013
+ classification: 'user-customized',
1014
+ beforeHash: currentHash,
1015
+ installedHash: entry.installedHash,
1016
+ desiredHash,
1017
+ ...(migrationNeeded ? { previousRole: priorRole, nextStep: 'move-aside-and-rerun' } : {}),
1018
+ ...extra,
1019
+ dryRun,
1020
+ },
1021
+ );
1022
+ }
1023
+ committedBytes = merged.bytes;
1024
+ desiredHash = sha256(committedBytes);
1025
+ desiredDigest = managedLinesDigest(committedBytes);
1026
+ digestField = profileDigestFields();
1027
+ classification = 'user-customized';
1028
+ if (!merged.bytes.equals(currentBytes)) ownershipEvidence = 'managed-user-customization';
866
1029
  }
867
1030
 
868
1031
  if (entry && currentHash !== entry.installedHash && !allowOwnedDriftMerge && !ownershipEvidence) {
@@ -879,6 +1042,7 @@ function writeManagedBytes(input) {
879
1042
  });
880
1043
  }
881
1044
  return resultFor(safeId, target.relative, 'skipped', 'user-drift-preserved', {
1045
+ classification: 'ambiguous-drift',
882
1046
  beforeHash: currentHash,
883
1047
  installedHash: entry.installedHash,
884
1048
  desiredHash,
@@ -914,13 +1078,20 @@ function writeManagedBytes(input) {
914
1078
  };
915
1079
  saveManifest(manifestFile, baseDir, manifest, dryRun);
916
1080
  } else if (
917
- isProfile && (entry.managedLinesDigest !== desiredDigest || (roleRow && entry.agentRole !== roleRow.role))
1081
+ isProfile && (
1082
+ entry.managedLinesDigest !== desiredDigest ||
1083
+ entry.sourceDigest !== sourceDigest ||
1084
+ entry.sourceRegionDigest !== managedLinesDigest(sourceBytes) ||
1085
+ entry.installedDigest !== prefixedDigest(committedBytes) ||
1086
+ (roleRow && entry.agentRole !== roleRow.role)
1087
+ )
918
1088
  ) {
919
1089
  // Backfill: the hash is exact, only the digest (and P228.19 role) is recorded.
920
1090
  manifest.entries[safeId] = { ...entry, ...digestField, ...roleFields };
921
1091
  saveManifest(manifestFile, baseDir, manifest, dryRun);
922
1092
  }
923
1093
  return resultFor(safeId, target.relative, dryRun ? 'planned-noop' : 'noop', 'managed-content-current', {
1094
+ classification,
924
1095
  beforeHash: currentHash,
925
1096
  installedHash: desiredHash,
926
1097
  ...(ownershipEvidence ? { ownershipEvidence } : {}),
@@ -965,28 +1136,91 @@ function writeManagedBytes(input) {
965
1136
  });
966
1137
  }
967
1138
 
1139
+ const invokeFault = (name) => {
1140
+ const hook = faultInjection && faultInjection[name];
1141
+ if (typeof hook === 'function') hook({ destination: target.resolved, manifestFile });
1142
+ else if (hook === true) throw new ManagedConfigError(`managed-fault-${name}`, `Synthetic fault at ${name}.`, 3);
1143
+ };
1144
+ invokeFault('beforeCommit');
1145
+ const freshTargetBytes = fs.existsSync(target.resolved) ? fs.readFileSync(target.resolved) : null;
1146
+ if ((freshTargetBytes ? sha256(freshTargetBytes) : null) !== currentHash) {
1147
+ return resultFor(safeId, target.relative, 'skipped', 'managed-preimage-conflict', {
1148
+ classification: 'ambiguous-drift', beforeHash: currentHash, dryRun,
1149
+ });
1150
+ }
1151
+ const freshManifestBytes = fs.existsSync(manifestFile) ? fs.readFileSync(manifestFile) : null;
1152
+ if (
1153
+ (freshManifestBytes === null) !== (manifestPreimage === null) ||
1154
+ (freshManifestBytes && manifestPreimage && !freshManifestBytes.equals(manifestPreimage))
1155
+ ) {
1156
+ return resultFor(safeId, target.relative, 'skipped', 'managed-manifest-cas-conflict', {
1157
+ classification: 'ambiguous-drift', beforeHash: currentHash, dryRun,
1158
+ });
1159
+ }
1160
+
968
1161
  let backup = null;
969
1162
  if (currentBytes) backup = backupBytes(baseDir, safeId, currentBytes, { dryRun, now });
970
1163
  const action = exists ? (entry ? 'updated' : 'legacy-migrated') : 'created';
971
- if (!dryRun) atomicWrite(target.resolved, desiredBytes, 0o600);
972
-
973
- manifest.entries[safeId] = {
1164
+ const nextEntry = {
974
1165
  ...(entry || {}),
975
1166
  kind,
976
1167
  relativePath: target.relative,
977
1168
  installedHash: desiredHash,
978
1169
  previousHash: currentHash,
1170
+ previousDigest: currentBytes ? prefixedDigest(currentBytes) : null,
979
1171
  backupRelativePath: backup?.backupRelativePath || null,
980
1172
  backupHash: backup?.backupHash || null,
1173
+ backupDigest: backup?.backupHash ? `sha256:${backup.backupHash}` : null,
981
1174
  createdByApply: !exists,
982
1175
  action,
983
1176
  ...digestField,
984
1177
  ...roleFields,
1178
+ classification,
985
1179
  updatedAt: nowIso({ now }),
986
1180
  };
987
- saveManifest(manifestFile, baseDir, manifest, dryRun);
988
- const reasonCode = migrationNeeded ? 'agent-profile-role-migrated' : 'managed-content-applied';
1181
+ manifest.entries[safeId] = nextEntry;
1182
+
1183
+ if (!dryRun) {
1184
+ atomicWrite(target.resolved, committedBytes, 0o600);
1185
+ try {
1186
+ if (sha256(fs.readFileSync(target.resolved)) !== desiredHash) {
1187
+ throw new ManagedConfigError('managed-target-readback-failed', 'Managed target readback failed.', 3);
1188
+ }
1189
+ invokeFault('afterTargetReplace');
1190
+ const manifestBeforeCommit = fs.existsSync(manifestFile) ? fs.readFileSync(manifestFile) : null;
1191
+ if (
1192
+ (manifestBeforeCommit === null) !== (manifestPreimage === null) ||
1193
+ (manifestBeforeCommit && manifestPreimage && !manifestBeforeCommit.equals(manifestPreimage))
1194
+ ) {
1195
+ throw new ManagedConfigError('managed-manifest-cas-conflict', 'Managed manifest changed before commit.', 3);
1196
+ }
1197
+ saveManifest(manifestFile, baseDir, manifest, false);
1198
+ if (loadManifest(manifestFile, baseDir).entries[safeId]?.installedHash !== desiredHash) {
1199
+ throw new ManagedConfigError('managed-manifest-readback-failed', 'Managed manifest readback failed.', 3);
1200
+ }
1201
+ } catch (error) {
1202
+ const currentPostimage = fs.existsSync(target.resolved) ? fs.readFileSync(target.resolved) : null;
1203
+ if (currentPostimage && sha256(currentPostimage) === desiredHash && currentBytes) {
1204
+ atomicWrite(target.resolved, currentBytes, 0o600);
1205
+ } else if (!currentBytes && currentPostimage && sha256(currentPostimage) === desiredHash) {
1206
+ fs.unlinkSync(target.resolved);
1207
+ } else {
1208
+ throw new ManagedConfigError(
1209
+ 'managed-manual-recovery-required',
1210
+ 'Managed postimage changed during recovery; automatic restore was refused.',
1211
+ 3,
1212
+ );
1213
+ }
1214
+ throw error;
1215
+ }
1216
+ }
1217
+ const reasonCode = migrationNeeded
1218
+ ? 'agent-profile-role-migrated'
1219
+ : classification === 'user-customized' ? 'customization-preserved' : 'managed-content-applied';
989
1220
  return resultFor(safeId, target.relative, dryRun ? `planned-${action}` : action, reasonCode, {
1221
+ classification,
1222
+ sourceDigest,
1223
+ installedDigest: prefixedDigest(committedBytes),
990
1224
  beforeHash: currentHash,
991
1225
  installedHash: desiredHash,
992
1226
  backupRelativePath: backup?.backupRelativePath || null,
@@ -1186,14 +1420,15 @@ function reconcile(options) {
1186
1420
  const [id, entry] = matches[0];
1187
1421
  const installedBytes = fs.readFileSync(target.resolved);
1188
1422
  const installedHash = sha256(installedBytes);
1189
- if (!options.dryRun) {
1190
- entry.installedHash = installedHash;
1191
- if (entry.kind === 'profile') entry.managedLinesDigest = managedLinesDigest(installedBytes);
1192
- entry.action = 'post-process-reconciled';
1193
- entry.updatedAt = nowIso(options);
1194
- saveManifest(options.manifestFile, options.baseDir, manifest, false);
1423
+ if (installedHash !== entry.installedHash) {
1424
+ return resultFor(id, target.relative, 'skipped', 'drift-preserved', {
1425
+ classification: 'ambiguous-drift',
1426
+ installedHash,
1427
+ dryRun: options.dryRun === true,
1428
+ });
1195
1429
  }
1196
- return resultFor(id, target.relative, options.dryRun ? 'planned-reconcile' : 'reconciled', 'managed-post-process-recorded', {
1430
+ return resultFor(id, target.relative, options.dryRun ? 'planned-noop' : 'noop', 'managed-content-current', {
1431
+ classification: 'unchanged',
1197
1432
  installedHash,
1198
1433
  dryRun: options.dryRun === true,
1199
1434
  });
@@ -1204,6 +1439,20 @@ function usage() {
1204
1439
  process.exitCode = 64;
1205
1440
  }
1206
1441
 
1442
+ /**
1443
+ * P231.05 AC4: Shell and PowerShell share one content-version authority, the
1444
+ * package that ships this helper (`targets-stubs/` beside `package.json`).
1445
+ * Absence or an unreadable manifest only omits the field; it never blocks.
1446
+ */
1447
+ function packagedContentVersion() {
1448
+ try {
1449
+ const parsed = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8'));
1450
+ return typeof parsed.version === 'string' && /^[0-9A-Za-z.+-]{1,64}$/.test(parsed.version) ? parsed.version : null;
1451
+ } catch {
1452
+ return null;
1453
+ }
1454
+ }
1455
+
1207
1456
  function runCli(argv = process.argv.slice(2)) {
1208
1457
  const [command, ...args] = argv;
1209
1458
  const dryRun = args.includes('--dry-run');
@@ -1231,6 +1480,7 @@ function runCli(argv = process.argv.slice(2)) {
1231
1480
  adoptExistingOwner: args.includes('--adopt-legacy'),
1232
1481
  tierLabel: args.find((arg) => arg.startsWith('--tier='))?.slice('--tier='.length),
1233
1482
  legacyBaseDir: args.find((arg) => arg.startsWith('--legacy-base='))?.slice('--legacy-base='.length) || null,
1483
+ contentVersion: args.find((arg) => arg.startsWith('--version='))?.slice('--version='.length) || packagedContentVersion(),
1234
1484
  });
1235
1485
  } else if (command === 'policy') {
1236
1486
  const [configFile, manifestFile, baseDir] = args;
@@ -1298,4 +1548,7 @@ module.exports = {
1298
1548
  isManagedLinesOnlyDelta,
1299
1549
  managedLinesCanonical,
1300
1550
  managedLinesDigest,
1551
+ managedLayout,
1552
+ mergeManagedProfileBytes,
1553
+ packagedContentVersion,
1301
1554
  };
@@ -134,12 +134,50 @@ neocortex_managed_profile() {
134
134
  return 1
135
135
  }
136
136
 
137
+ # Retire a historical managed profile only when the manifest or an explicit
138
+ # helper fingerprint proves ownership. Unknown/user-edited bytes are preserved.
139
+ # The top-level installer already exposes managed_retire_file; standalone
140
+ # adapters use the same dependency-free helper directly.
141
+ neocortex_managed_retire() {
142
+ local source_root="$1"
143
+ local destination="$2"
144
+ local base_dir="$3"
145
+ local managed_id="$4"
146
+ NEOCORTEX_MANAGED_ACTION=""
147
+ NEOCORTEX_MANAGED_REASON=""
148
+ if command -v managed_retire_file >/dev/null 2>&1; then
149
+ managed_retire_file "$destination" "$managed_id" "$base_dir"
150
+ return $?
151
+ fi
152
+ local helper="$source_root/targets-stubs/lib/managed-config-merge.js"
153
+ local manifest="$base_dir/.neocortex/managed-config-manifest.json"
154
+ if [ -f "$helper" ] && command -v node >/dev/null 2>&1; then
155
+ local output status dry=""
156
+ [ "${DRY_RUN:-false}" = true ] && dry="--dry-run"
157
+ output="$(node "$helper" retire-legacy "$destination" "$manifest" "$base_dir" "$managed_id" $dry 2>&1)"
158
+ status=$?
159
+ neocortex_managed_parse "$output"
160
+ [ "$status" -eq 0 ] || NEOCORTEX_MANAGED_ACTION="failed"
161
+ [ "$NEOCORTEX_MANAGED_ACTION" != "failed" ]
162
+ return $?
163
+ fi
164
+ NEOCORTEX_MANAGED_ACTION="skipped"
165
+ NEOCORTEX_MANAGED_REASON="managed-helper-unavailable"
166
+ return 0
167
+ }
168
+
137
169
  # Report the last neocortex_managed_profile outcome with an adapter prefix.
138
170
  # Usage: neocortex_managed_report "[CODEX]" "~/.codex/AGENTS.md (global)"
139
171
  neocortex_managed_report() {
140
172
  local prefix="$1"
141
173
  local label="$2"
142
174
  case "$NEOCORTEX_MANAGED_ACTION" in
175
+ removed|planned-removed)
176
+ echo "$prefix Retired: $label" ;;
177
+ none)
178
+ : ;;
179
+ preserved)
180
+ echo "$prefix Preserved local changes: $label ($NEOCORTEX_MANAGED_REASON)" >&2 ;;
143
181
  noop|planned-noop)
144
182
  echo "$prefix Up to date: $label" ;;
145
183
  created|updated|legacy-migrated|restored|planned-*)