@ornexus/neocortex 4.65.1 → 4.66.1

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 (150) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1206 -1193
  3. package/install.ps1 +243 -77
  4. package/install.sh +221 -102
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/platform-detector.js +1 -1
  7. package/packages/client/dist/agent/refresh-stubs.d.ts +50 -0
  8. package/packages/client/dist/agent/refresh-stubs.js +2 -2
  9. package/packages/client/dist/cli.js +5 -4
  10. package/packages/client/dist/commands/doctor.d.ts +26 -1
  11. package/packages/client/dist/commands/doctor.js +2 -2
  12. package/packages/client/dist/commands/invoke.d.ts +183 -5
  13. package/packages/client/dist/commands/invoke.js +94 -87
  14. package/packages/client/dist/commands/planning-qa.d.ts +64 -0
  15. package/packages/client/dist/commands/planning-qa.js +1 -0
  16. package/packages/client/dist/commands/refactor-control.js +3 -3
  17. package/packages/client/dist/commands/story-checkpoint.d.ts +3 -1
  18. package/packages/client/dist/commands/story-checkpoint.js +1 -1
  19. package/packages/client/dist/commands/story-worktree.d.ts +1 -1
  20. package/packages/client/dist/commands/story-worktree.js +1 -1
  21. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +64 -1
  22. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -3
  23. package/packages/client/dist/git/epic-lifecycle-evidence.d.ts +184 -0
  24. package/packages/client/dist/git/epic-lifecycle-evidence.js +6 -0
  25. package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
  26. package/packages/client/dist/git/git-lifecycle-store.js +9 -8
  27. package/packages/client/dist/git/governance-runtime-store.d.ts +172 -0
  28. package/packages/client/dist/git/governance-runtime-store.js +3 -0
  29. package/packages/client/dist/git/story-worktree-cleanup.js +1 -1
  30. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  31. package/packages/client/dist/git/story-worktree-manager.d.ts +39 -0
  32. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  33. package/packages/client/dist/git/story-write-set-extension.d.ts +62 -0
  34. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  35. package/packages/client/dist/memory/shared-project-memory-types.d.ts +39 -2
  36. package/packages/client/dist/memory/shared-project-memory-types.js +2 -2
  37. package/packages/client/dist/policy/subagent-approval-policy.js +1 -1
  38. package/packages/client/dist/private-execution/codex-executor.d.ts +21 -1
  39. package/packages/client/dist/private-execution/codex-executor.js +4 -4
  40. package/packages/client/dist/private-execution/delivery.d.ts +17 -11
  41. package/packages/client/dist/private-execution/delivery.js +8 -6
  42. package/packages/client/dist/private-execution/diagnosis-root-review.d.ts +89 -0
  43. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -2
  44. package/packages/client/dist/private-execution/frozen-handoff.js +3 -3
  45. package/packages/client/dist/private-execution/harness-adapters/antigravity.d.ts +9 -0
  46. package/packages/client/dist/private-execution/harness-adapters/antigravity.js +1 -0
  47. package/packages/client/dist/private-execution/harness-adapters/claude-code.d.ts +8 -0
  48. package/packages/client/dist/private-execution/harness-adapters/claude-code.js +1 -0
  49. package/packages/client/dist/private-execution/harness-adapters/codex.d.ts +7 -0
  50. package/packages/client/dist/private-execution/harness-adapters/codex.js +1 -0
  51. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.d.ts +8 -0
  52. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.js +1 -0
  53. package/packages/client/dist/private-execution/harness-adapters/cursor.d.ts +9 -0
  54. package/packages/client/dist/private-execution/harness-adapters/cursor.js +1 -0
  55. package/packages/client/dist/private-execution/harness-adapters/deepseek.d.ts +9 -0
  56. package/packages/client/dist/private-execution/harness-adapters/deepseek.js +1 -0
  57. package/packages/client/dist/private-execution/harness-adapters/gemini.d.ts +8 -0
  58. package/packages/client/dist/private-execution/harness-adapters/gemini.js +1 -0
  59. package/packages/client/dist/private-execution/harness-adapters/grok.d.ts +9 -0
  60. package/packages/client/dist/private-execution/harness-adapters/grok.js +1 -0
  61. package/packages/client/dist/private-execution/harness-adapters/index.d.ts +73 -0
  62. package/packages/client/dist/private-execution/harness-adapters/index.js +1 -0
  63. package/packages/client/dist/private-execution/harness-adapters/kimi.d.ts +9 -0
  64. package/packages/client/dist/private-execution/harness-adapters/kimi.js +1 -0
  65. package/packages/client/dist/private-execution/harness-adapters/openclaw.d.ts +9 -0
  66. package/packages/client/dist/private-execution/harness-adapters/openclaw.js +1 -0
  67. package/packages/client/dist/private-execution/harness-adapters/opencode.d.ts +7 -0
  68. package/packages/client/dist/private-execution/harness-adapters/opencode.js +1 -0
  69. package/packages/client/dist/private-execution/harness-ephemeral-home.d.ts +19 -0
  70. package/packages/client/dist/private-execution/harness-ephemeral-home.js +1 -0
  71. package/packages/client/dist/private-execution/harness-executor.d.ts +79 -0
  72. package/packages/client/dist/private-execution/harness-executor.js +1 -0
  73. package/packages/client/dist/private-execution/harness-process.d.ts +43 -0
  74. package/packages/client/dist/private-execution/harness-process.js +1 -0
  75. package/packages/client/dist/private-execution/isolated-admission.js +12 -12
  76. package/packages/client/dist/private-execution/isolated-workspace.d.ts +16 -1
  77. package/packages/client/dist/private-execution/isolated-workspace.js +1 -1
  78. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +75 -1
  79. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -5
  80. package/packages/client/dist/private-execution/planning-generation-checkpoint.d.ts +9 -1
  81. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +4 -4
  82. package/packages/client/dist/private-execution/planning-research-checkpoint.d.ts +9 -1
  83. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -4
  84. package/packages/client/dist/private-execution/root-memory-request.d.ts +4 -1
  85. package/packages/client/dist/private-execution/root-memory-request.js +1 -1
  86. package/packages/client/dist/runner/epic-background-dispatcher.d.ts +3 -1
  87. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -1
  88. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -1
  89. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -22
  90. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +6 -10
  91. package/packages/client/dist/runner/headless/managed-profile.d.ts +20 -0
  92. package/packages/client/dist/runner/headless/managed-profile.js +1 -1
  93. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -2
  94. package/packages/client/dist/runner/headless/run-yoloop.d.ts +40 -0
  95. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  96. package/packages/client/dist/runner/headless/types.d.ts +20 -0
  97. package/packages/client/dist/runner/headless/types.js +2 -2
  98. package/packages/client/dist/state/project-state-snapshot.d.ts +10 -0
  99. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  100. package/packages/client/dist/state/structural-dag-projection.d.ts +26 -0
  101. package/packages/client/dist/state/structural-dag-projection.js +1 -1
  102. package/packages/client/dist/yoloop/target-normalization.js +1 -1
  103. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +67 -0
  104. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  105. package/packages/shared/dist/compatibility/index.js +96 -0
  106. package/packages/shared/dist/planning/diagnosis-state.js +105 -1
  107. package/packages/shared/dist/project-memory-targets.js +36 -5
  108. package/targets-stubs/antigravity/README.md +1 -1
  109. package/targets-stubs/antigravity/gemini.md +1 -1
  110. package/targets-stubs/antigravity/install-antigravity.sh +1 -1
  111. package/targets-stubs/antigravity/mcp-config.json +0 -3
  112. package/targets-stubs/antigravity/neocortex.md +25 -13
  113. package/targets-stubs/antigravity/skill/SKILL.md +4 -4
  114. package/targets-stubs/claude-code/.mcp.json +0 -4
  115. package/targets-stubs/claude-code/neocortex-root.agent.yaml +2 -4
  116. package/targets-stubs/claude-code/neocortex-root.md +33 -43
  117. package/targets-stubs/claude-code/neocortex-sentinel.md +261 -0
  118. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -3
  119. package/targets-stubs/claude-code/neocortex.md +61 -84
  120. package/targets-stubs/codex/AGENTS.md +19 -18
  121. package/targets-stubs/codex/README.md +1 -1
  122. package/targets-stubs/codex/config-mcp.toml +0 -3
  123. package/targets-stubs/codex/neocortex-sentinel.toml +87 -0
  124. package/targets-stubs/codex/neocortex.toml +23 -44
  125. package/targets-stubs/cursor/README.md +1 -1
  126. package/targets-stubs/cursor/agent.md +26 -15
  127. package/targets-stubs/cursor/mcp.json +0 -3
  128. package/targets-stubs/deepseek-harness/SKILL.md +11 -8
  129. package/targets-stubs/gemini-cli/README.md +1 -1
  130. package/targets-stubs/gemini-cli/agent.md +25 -12
  131. package/targets-stubs/gemini-cli/agents/neocortex-sentinel.md +75 -0
  132. package/targets-stubs/gemini-cli/agents/neocortex.md +280 -49
  133. package/targets-stubs/gemini-cli/settings-mcp.json +0 -3
  134. package/targets-stubs/grok/SKILL.md +13 -1
  135. package/targets-stubs/grok/agents/neocortex-sentinel.md +64 -0
  136. package/targets-stubs/grok/config-mcp.toml +0 -3
  137. package/targets-stubs/grok/install-grok.sh +51 -1
  138. package/targets-stubs/kimi/mcp.json +0 -6
  139. package/targets-stubs/kimi/neocortex.md +21 -8
  140. package/targets-stubs/lib/managed-config-merge.js +301 -6
  141. package/targets-stubs/lib/managed-profile.sh +12 -1
  142. package/targets-stubs/lib/mcp-merge.js +122 -8
  143. package/targets-stubs/openclaw/SKILL.md +33 -4
  144. package/targets-stubs/opencode/neocortex-root.md +41 -41
  145. package/targets-stubs/opencode/neocortex-sentinel.md +115 -0
  146. package/targets-stubs/opencode/neocortex.md +292 -67
  147. package/targets-stubs/opencode/opencode-mcp.json +0 -7
  148. package/targets-stubs/vscode/README.md +1 -1
  149. package/targets-stubs/vscode/mcp.json +0 -4
  150. package/targets-stubs/vscode/neocortex.agent.md +29 -18
@@ -164,6 +164,207 @@ function resultFor(id, relativePath, action, reasonCode, details = {}) {
164
164
  };
165
165
  }
166
166
 
167
+ /*
168
+ * P228.19 (P228-CON-MANIFEST-MIGRATION): managed IDs bound to agent roles.
169
+ * `neocortex` becomes the orchestrator, `neocortex-sentinel` the story child
170
+ * and `neocortex-root` stays as alias. One table shared by every writer
171
+ * (refresh, install.sh, install.ps1, adapters through this helper).
172
+ */
173
+ function agentRoleRows(platform, ext, ids, scopes) {
174
+ const rows = [];
175
+ for (const scope of scopes) {
176
+ const prefix = scope === 'project' ? 'project' : 'profile';
177
+ const sentinelId = `${prefix}-${ids.sentinel}`;
178
+ const sentinelFile = `neocortex-sentinel.${ext}`;
179
+ rows.push({ managedId: sentinelId, platform, scope, role: 'sentinel', file: sentinelFile, name: 'neocortex-sentinel', sentinelId, sentinelFile });
180
+ rows.push({ managedId: `${prefix}-${ids.orchestrator}`, platform, scope, role: 'orchestrator', file: `neocortex.${ext}`, name: 'neocortex', sentinelId, sentinelFile });
181
+ if (ids.alias && (scope === 'user' || ids.projectAlias)) {
182
+ rows.push({ managedId: `${prefix}-${ids.alias}`, platform, scope, role: 'alias', file: `neocortex-root.${ext}`, name: 'neocortex-root', sentinelId, sentinelFile });
183
+ }
184
+ }
185
+ return rows;
186
+ }
187
+
188
+ const AGENT_ROLE_TABLE = Object.freeze([
189
+ ...agentRoleRows('claude-code', 'md', {
190
+ sentinel: 'claude-neocortex-sentinel-agent',
191
+ orchestrator: 'claude-neocortex-agent',
192
+ alias: 'claude-neocortex-root-agent',
193
+ }, ['user', 'project']),
194
+ ...agentRoleRows('opencode', 'md', {
195
+ sentinel: 'opencode-neocortex-sentinel',
196
+ orchestrator: 'opencode-neocortex',
197
+ alias: 'opencode-neocortex-root',
198
+ projectAlias: true,
199
+ }, ['user', 'project']),
200
+ ...agentRoleRows('codex', 'toml', {
201
+ sentinel: 'codex-neocortex-sentinel',
202
+ orchestrator: 'codex-neocortex',
203
+ }, ['user', 'project']),
204
+ ].map((row) => Object.freeze(row)));
205
+
206
+ const AGENT_ROLE_BY_ID = new Map(AGENT_ROLE_TABLE.map((row) => [row.managedId, row]));
207
+ const AGENT_NAME_SCAN_MAX_FILES = 256;
208
+ const AGENT_NAME_SCAN_MAX_BYTES = 64 * 1024;
209
+
210
+ function agentRoleFor(id) {
211
+ try { return AGENT_ROLE_BY_ID.get(sanitizeId(id)) || null; } catch { return null; }
212
+ }
213
+
214
+ /** `name` declared by an agent profile: YAML frontmatter (.md) or top-level TOML key. */
215
+ function readAgentName(bytes, fileName) {
216
+ const text = Buffer.isBuffer(bytes) ? bytes.toString('utf8') : String(bytes || '');
217
+ const clean = text.replace(/^/, '').replace(/\r\n/g, '\n');
218
+ if (fileName.endsWith('.toml')) {
219
+ const topLevel = clean.split(/^\s*\[/m)[0];
220
+ const match = /^name[ \t]*=[ \t]*["']([^"'\n]+)["'][ \t]*$/m.exec(topLevel);
221
+ return match ? match[1].trim() : null;
222
+ }
223
+ if (!clean.startsWith('---\n')) return null;
224
+ const end = clean.indexOf('\n---', 4);
225
+ if (end < 0) return null;
226
+ const match = /^name:[ \t]*["']?([^"'\n]+?)["']?[ \t]*$/m.exec(clean.slice(4, end));
227
+ return match ? match[1].trim() : null;
228
+ }
229
+
230
+ function readHead(file) {
231
+ const fd = fs.openSync(file, 'r');
232
+ try {
233
+ const buffer = Buffer.alloc(AGENT_NAME_SCAN_MAX_BYTES);
234
+ const read = fs.readSync(fd, buffer, 0, AGENT_NAME_SCAN_MAX_BYTES, 0);
235
+ return buffer.subarray(0, read);
236
+ } finally {
237
+ fs.closeSync(fd);
238
+ }
239
+ }
240
+
241
+ /** Another top-level profile in the destination dir declaring the same name (spec T4). */
242
+ function findAgentNameCollision(target, desiredBytes) {
243
+ const fileName = path.basename(target.resolved);
244
+ const desiredName = readAgentName(desiredBytes, fileName);
245
+ if (!desiredName) return null;
246
+ const dir = path.dirname(target.resolved);
247
+ let names;
248
+ try { names = fs.readdirSync(dir).sort(); } catch { return null; }
249
+ const ext = path.extname(fileName);
250
+ let scanned = 0;
251
+ for (const name of names) {
252
+ if (name === fileName || path.extname(name) !== ext || name.startsWith('.')) continue;
253
+ if (scanned >= AGENT_NAME_SCAN_MAX_FILES) break;
254
+ scanned += 1;
255
+ const candidate = path.join(dir, name);
256
+ let stat;
257
+ try { stat = fs.lstatSync(candidate); } catch { continue; }
258
+ if (!stat.isFile() || stat.isSymbolicLink()) continue;
259
+ let head;
260
+ try { head = readHead(candidate); } catch { continue; }
261
+ if (readAgentName(head, name) === desiredName) {
262
+ const relativeDir = path.posix.dirname(target.relative);
263
+ return relativeDir === '.' ? name : `${relativeDir}/${name}`;
264
+ }
265
+ }
266
+ return null;
267
+ }
268
+
269
+ /** Spec T1.2 / AM-03: the sentinel of the same scope is installed and unchanged. */
270
+ function sentinelReady(manifest, roleRow, baseDir, target, dryRun) {
271
+ // The sentinel lives beside the orchestrator; it is found by path so a
272
+ // writer-specific id (for example a derived refresh id) still counts.
273
+ const relativeDir = path.posix.dirname(target.relative);
274
+ const siblingRelative = relativeDir === '.' ? roleRow.sentinelFile : `${relativeDir}/${roleRow.sentinelFile}`;
275
+ const owners = Object.values(manifest.entries)
276
+ .filter((candidate) => candidate && candidate.relativePath === siblingRelative);
277
+ const entry = owners.length === 1 ? owners[0] : null;
278
+ if (owners.length > 1) return false;
279
+ if (entry && typeof entry.relativePath === 'string' && entry.installedHash) {
280
+ try {
281
+ const location = resolveWithinBase(baseDir, path.join(baseDir, entry.relativePath), 'destination');
282
+ const stat = fs.lstatSync(location.resolved);
283
+ if (stat.isFile() && sha256(fs.readFileSync(location.resolved)) === entry.installedHash) return true;
284
+ } catch { /* not ready */ }
285
+ return false;
286
+ }
287
+ if (!dryRun) return false;
288
+ const planned = path.join(path.dirname(target.resolved), roleRow.sentinelFile);
289
+ return !fs.existsSync(planned);
290
+ }
291
+
292
+ /** AM-04: remove a nested legacy copy only when its hash is a known managed hash. */
293
+ function settleLegacyCopy(input, manifest, allowedHashes) {
294
+ const { legacyCopyPath, baseDir, manifestFile, dryRun } = input;
295
+ if (!legacyCopyPath) return null;
296
+ let location;
297
+ try { location = resolveWithinBase(baseDir, legacyCopyPath, 'legacy copy'); } catch {
298
+ return { action: 'preserved', reasonCode: 'agent-profile-legacy-copy-preserved' };
299
+ }
300
+ let stat = null;
301
+ try { stat = fs.lstatSync(location.resolved); } catch { stat = null; }
302
+ if (!stat) return { action: 'none' };
303
+ if (!stat.isFile() || stat.isSymbolicLink()) {
304
+ return { action: 'preserved', reasonCode: 'agent-profile-legacy-copy-preserved', relativePath: location.relative };
305
+ }
306
+ const copyHash = sha256(fs.readFileSync(location.resolved));
307
+ const owners = Object.entries(manifest.entries)
308
+ .filter(([, entry]) => entry && entry.relativePath === location.relative);
309
+ const known = new Set([...allowedHashes].filter(Boolean));
310
+ for (const [, entry] of owners) if (entry.installedHash) known.add(entry.installedHash);
311
+ if (!known.has(copyHash)) {
312
+ return { action: 'preserved', reasonCode: 'agent-profile-legacy-copy-preserved', relativePath: location.relative };
313
+ }
314
+ if (!dryRun) {
315
+ fs.unlinkSync(location.resolved);
316
+ if (owners.length > 0) {
317
+ for (const [ownerId] of owners) delete manifest.entries[ownerId];
318
+ saveManifest(manifestFile, baseDir, manifest, false);
319
+ }
320
+ }
321
+ return {
322
+ action: dryRun ? 'planned-removed' : 'removed',
323
+ reasonCode: 'agent-profile-legacy-copy-removed',
324
+ relativePath: location.relative,
325
+ };
326
+ }
327
+
328
+ /**
329
+ * P229.09 (R4): retire a renamed managed profile (for example the Grok child
330
+ * `agents/neocortex.md`, now `neocortex-sentinel.md`). The file and its
331
+ * manifest owners are removed only when the bytes match a recorded
332
+ * `installedHash`; anything else is preserved.
333
+ */
334
+ function retireLegacy({ destination, manifestFile, baseDir, id, dryRun }) {
335
+ const manifest = loadManifest(manifestFile, baseDir);
336
+ const settled = settleLegacyCopy({ legacyCopyPath: destination, baseDir, manifestFile, dryRun }, manifest, []);
337
+ if (!settled || settled.action === 'none') {
338
+ return resultFor(id, null, 'none', 'agent-profile-legacy-absent', { dryRun: dryRun === true });
339
+ }
340
+ return resultFor(id, settled.relativePath || null, settled.action, settled.reasonCode, { dryRun: dryRun === true });
341
+ }
342
+
343
+ /**
344
+ * P228.19 AM-09: true when the destination still holds the legacy child and
345
+ * would be rewritten as orchestrator. Writers use it to avoid carrying the
346
+ * child's host frontmatter (for example `mode: subagent`) into the new role.
347
+ */
348
+ function agentRoleMigrationPending(options) {
349
+ const roleRow = agentRoleFor(options.agentRoleId || options.id);
350
+ if (!roleRow || roleRow.role !== 'orchestrator') return false;
351
+ try {
352
+ const target = resolveWithinBase(options.baseDir, options.destination, 'destination');
353
+ if (!fs.existsSync(target.resolved)) return false;
354
+ const manifest = loadManifest(options.manifestFile, options.baseDir);
355
+ let entry = manifest.entries[sanitizeId(options.id)];
356
+ if (!entry) {
357
+ const owners = Object.values(manifest.entries)
358
+ .filter((candidate) => candidate && candidate.relativePath === target.relative);
359
+ entry = owners.length === 1 ? owners[0] : null;
360
+ }
361
+ if (!entry) return isKnownLegacyProfile(fs.readFileSync(target.resolved));
362
+ return (entry.agentRole || 'child') !== 'orchestrator';
363
+ } catch {
364
+ return false;
365
+ }
366
+ }
367
+
167
368
  function isKnownLegacyProfile(bytes) {
168
369
  const content = bytes?.toString('utf8') || '';
169
370
  if (!/neocortex/i.test(content)) return false;
@@ -527,9 +728,16 @@ function writeManagedBytes(input) {
527
728
  allowOwnedDriftMerge = false,
528
729
  adoptExistingOwner = false,
529
730
  legacyBaseDir = null,
731
+ agentRoles = false,
732
+ agentRoleId = null,
530
733
  now,
531
734
  } = input;
532
735
  let safeId = sanitizeId(id);
736
+ // P228.19 AM-02: the role comes from the requested id (or an explicit role
737
+ // id, AM-08), before any adoption of an older owner id for the same file.
738
+ const roleRow = kind === 'profile' && agentRoles
739
+ ? AGENT_ROLE_BY_ID.get(agentRoleId ? sanitizeId(agentRoleId) : safeId) || null
740
+ : null;
533
741
  const target = resolveWithinBase(baseDir, destination, 'destination');
534
742
  const manifest = loadManifest(manifestFile, baseDir);
535
743
  let ownerAdopted = false;
@@ -561,6 +769,19 @@ function writeManagedBytes(input) {
561
769
  }
562
770
  }
563
771
 
772
+ const roleFields = roleRow ? { agentRole: roleRow.role } : {};
773
+ if (roleRow) {
774
+ extra.agentRole = roleRow.role;
775
+ const collision = findAgentNameCollision(target, desiredBytes);
776
+ if (collision) {
777
+ return resultFor(safeId, target.relative, 'skipped', 'agent-profile-name-collision', {
778
+ collisionRelativePath: collision,
779
+ ...extra,
780
+ dryRun,
781
+ });
782
+ }
783
+ }
784
+
564
785
  const desiredHash = sha256(desiredBytes);
565
786
  const desiredDigest = isProfile ? managedLinesDigest(desiredBytes) : null;
566
787
  const digestField = isProfile ? { managedLinesDigest: desiredDigest } : {};
@@ -592,6 +813,21 @@ function writeManagedBytes(input) {
592
813
  const hashes = new Set([finalHash, currentHash, priorInstalledHash].filter(Boolean));
593
814
  return { duplicateBase: settleLegacyDuplicates(legacy, hashes, { dryRun, now, adoptedIds, blockedIds }) };
594
815
  };
816
+ // P228.19 AM-04: nested legacy copy removed only with a known managed hash.
817
+ const priorPreviousHash = entry?.previousHash || null;
818
+ const legacyCopyResult = (finalHash) => {
819
+ const settled = settleLegacyCopy(input, manifest, [finalHash, currentHash, priorInstalledHash, priorPreviousHash]);
820
+ return settled ? { legacyCopy: settled } : {};
821
+ };
822
+
823
+ // P228.19 spec T2: role migration is needed when the installed role differs.
824
+ // An orchestrator entry without agentRole is the legacy child.
825
+ let priorRole = null;
826
+ if (roleRow && exists) {
827
+ if (entry) priorRole = entry.agentRole || (roleRow.role === 'orchestrator' ? 'child' : roleRow.role);
828
+ else if (roleRow.role === 'orchestrator' && isKnownLegacyProfile(currentBytes)) priorRole = 'child';
829
+ }
830
+ const migrationNeeded = Boolean(roleRow && priorRole && priorRole !== roleRow.role);
595
831
 
596
832
  // P227.14 T1: an owned destination that disappeared is restored.
597
833
  if (isProfile && entry && !exists) {
@@ -607,6 +843,7 @@ function writeManagedBytes(input) {
607
843
  createdByApply: true,
608
844
  action: 'restored',
609
845
  ...digestField,
846
+ ...roleFields,
610
847
  updatedAt: nowIso({ now }),
611
848
  };
612
849
  saveManifest(manifestFile, baseDir, manifest, dryRun);
@@ -616,6 +853,7 @@ function writeManagedBytes(input) {
616
853
  ownershipEvidence: 'managed-destination-missing',
617
854
  ...extra,
618
855
  ...settle(desiredHash),
856
+ ...legacyCopyResult(desiredHash),
619
857
  dryRun,
620
858
  });
621
859
  }
@@ -628,6 +866,18 @@ function writeManagedBytes(input) {
628
866
  }
629
867
 
630
868
  if (entry && currentHash !== entry.installedHash && !allowOwnedDriftMerge && !ownershipEvidence) {
869
+ // P228.19 spec T3: drift on a role being migrated has its own reason code.
870
+ if (migrationNeeded) {
871
+ return resultFor(safeId, target.relative, 'skipped', 'agent-profile-migration-drift', {
872
+ beforeHash: currentHash,
873
+ installedHash: entry.installedHash,
874
+ desiredHash,
875
+ previousRole: priorRole,
876
+ nextStep: 'move-aside-and-rerun',
877
+ ...extra,
878
+ dryRun,
879
+ });
880
+ }
631
881
  return resultFor(safeId, target.relative, 'skipped', 'user-drift-preserved', {
632
882
  beforeHash: currentHash,
633
883
  installedHash: entry.installedHash,
@@ -649,6 +899,7 @@ function writeManagedBytes(input) {
649
899
  createdByApply: false,
650
900
  action: 'adopted-identical',
651
901
  ...digestField,
902
+ ...roleFields,
652
903
  updatedAt: nowIso({ now }),
653
904
  };
654
905
  saveManifest(manifestFile, baseDir, manifest, dryRun);
@@ -658,12 +909,15 @@ function writeManagedBytes(input) {
658
909
  installedHash: desiredHash,
659
910
  action: ownershipEvidence === 'managed-duplicate-base-adopted' ? entry.action : 'post-process-reconciled',
660
911
  ...digestField,
912
+ ...roleFields,
661
913
  updatedAt: nowIso({ now }),
662
914
  };
663
915
  saveManifest(manifestFile, baseDir, manifest, dryRun);
664
- } else if (isProfile && entry.managedLinesDigest !== desiredDigest) {
665
- // Backfill: the hash is exact, only the digest is recorded.
666
- manifest.entries[safeId] = { ...entry, ...digestField };
916
+ } else if (
917
+ isProfile && (entry.managedLinesDigest !== desiredDigest || (roleRow && entry.agentRole !== roleRow.role))
918
+ ) {
919
+ // Backfill: the hash is exact, only the digest (and P228.19 role) is recorded.
920
+ manifest.entries[safeId] = { ...entry, ...digestField, ...roleFields };
667
921
  saveManifest(manifestFile, baseDir, manifest, dryRun);
668
922
  }
669
923
  return resultFor(safeId, target.relative, dryRun ? 'planned-noop' : 'noop', 'managed-content-current', {
@@ -672,6 +926,7 @@ function writeManagedBytes(input) {
672
926
  ...(ownershipEvidence ? { ownershipEvidence } : {}),
673
927
  ...extra,
674
928
  ...settle(desiredHash),
929
+ ...legacyCopyResult(desiredHash),
675
930
  dryRun,
676
931
  });
677
932
  }
@@ -680,9 +935,31 @@ function writeManagedBytes(input) {
680
935
  kind === 'policy' || isKnownLegacyProfile(currentBytes)
681
936
  );
682
937
  if (exists && !entry && !legacyAdoptionAllowed) {
683
- return resultFor(safeId, target.relative, 'skipped', 'unmanaged-content-preserved', {
938
+ // P228.19 spec T3: an unknown file on the orchestrator path is user content.
939
+ const orchestratorPath = roleRow && roleRow.role === 'orchestrator';
940
+ return resultFor(
941
+ safeId,
942
+ target.relative,
943
+ 'skipped',
944
+ orchestratorPath ? 'agent-profile-migration-drift' : 'unmanaged-content-preserved',
945
+ {
946
+ beforeHash: currentHash,
947
+ desiredHash,
948
+ ...(orchestratorPath ? { nextStep: 'move-aside-and-rerun' } : {}),
949
+ ...extra,
950
+ dryRun,
951
+ },
952
+ );
953
+ }
954
+
955
+ // P228.19 spec T1.2: never turn the old child into the orchestrator before
956
+ // the sentinel of the same scope is installed (the scope keeps a child).
957
+ if (migrationNeeded && !sentinelReady(manifest, roleRow, baseDir, target, dryRun)) {
958
+ return resultFor(safeId, target.relative, 'skipped', 'agent-profile-sentinel-missing', {
684
959
  beforeHash: currentHash,
685
960
  desiredHash,
961
+ previousRole: priorRole,
962
+ nextStep: 'install-sentinel-and-rerun',
686
963
  ...extra,
687
964
  dryRun,
688
965
  });
@@ -704,16 +981,20 @@ function writeManagedBytes(input) {
704
981
  createdByApply: !exists,
705
982
  action,
706
983
  ...digestField,
984
+ ...roleFields,
707
985
  updatedAt: nowIso({ now }),
708
986
  };
709
987
  saveManifest(manifestFile, baseDir, manifest, dryRun);
710
- return resultFor(safeId, target.relative, dryRun ? `planned-${action}` : action, 'managed-content-applied', {
988
+ const reasonCode = migrationNeeded ? 'agent-profile-role-migrated' : 'managed-content-applied';
989
+ return resultFor(safeId, target.relative, dryRun ? `planned-${action}` : action, reasonCode, {
711
990
  beforeHash: currentHash,
712
991
  installedHash: desiredHash,
713
992
  backupRelativePath: backup?.backupRelativePath || null,
993
+ ...(migrationNeeded ? { previousRole: priorRole } : {}),
714
994
  ...(ownershipEvidence ? { ownershipEvidence } : {}),
715
995
  ...extra,
716
996
  ...settle(desiredHash),
997
+ ...legacyCopyResult(desiredHash),
717
998
  dryRun,
718
999
  });
719
1000
  }
@@ -919,7 +1200,7 @@ function reconcile(options) {
919
1200
  }
920
1201
 
921
1202
  function usage() {
922
- console.error('Usage: managed-config-merge.js profile <source> <dest> <manifest> <base> <id> [--dry-run] [--adopt-legacy] [--tier=<Free|Pro|Enterprise>] [--legacy-base=<dir>] | resolve-base <platform-home> <default-base> | policy <config> <manifest> <base> [--dry-run] | rollback <manifest> <base> <id> [--dry-run] | reconcile <dest> <manifest> <base> [--dry-run]');
1203
+ console.error('Usage: managed-config-merge.js profile <source> <dest> <manifest> <base> <id> [--dry-run] [--adopt-legacy] [--tier=<Free|Pro|Enterprise>] [--legacy-base=<dir>] [--legacy-copy=<path>] | resolve-base <platform-home> <default-base> | policy <config> <manifest> <base> [--dry-run] | rollback <manifest> <base> <id> [--dry-run] | reconcile <dest> <manifest> <base> [--dry-run] | retire-legacy <dest> <manifest> <base> <id> [--dry-run]');
923
1204
  process.exitCode = 64;
924
1205
  }
925
1206
 
@@ -931,7 +1212,12 @@ function runCli(argv = process.argv.slice(2)) {
931
1212
  if (command === 'profile') {
932
1213
  const [sourceFile, destination, manifestFile, baseDir, id] = args;
933
1214
  if (!sourceFile || !destination || !manifestFile || !baseDir || !id) return usage();
1215
+ // P228.19 AM-01: role semantics only when the sentinel stub ships beside the source.
1216
+ const roleRow = agentRoleFor(id);
1217
+ const agentRoles = Boolean(roleRow && fs.existsSync(path.join(path.dirname(sourceFile), roleRow.sentinelFile)));
934
1218
  result = applyProfile({
1219
+ agentRoles,
1220
+ legacyCopyPath: args.find((arg) => arg.startsWith('--legacy-copy='))?.slice('--legacy-copy='.length) || null,
935
1221
  sourceFile,
936
1222
  destination,
937
1223
  manifestFile,
@@ -963,6 +1249,10 @@ function runCli(argv = process.argv.slice(2)) {
963
1249
  const [destination, manifestFile, baseDir] = args;
964
1250
  if (!destination || !manifestFile || !baseDir) return usage();
965
1251
  result = reconcile({ destination, manifestFile, baseDir, dryRun });
1252
+ } else if (command === 'retire-legacy') {
1253
+ const [destination, manifestFile, baseDir, id] = args;
1254
+ if (!destination || !manifestFile || !baseDir || !id) return usage();
1255
+ result = retireLegacy({ destination, manifestFile, baseDir, id, dryRun });
966
1256
  } else {
967
1257
  return usage();
968
1258
  }
@@ -985,6 +1275,10 @@ function runCli(argv = process.argv.slice(2)) {
985
1275
  if (require.main === module) process.exitCode = runCli();
986
1276
 
987
1277
  module.exports = {
1278
+ AGENT_ROLE_TABLE,
1279
+ agentRoleFor,
1280
+ agentRoleMigrationPending,
1281
+ readAgentName,
988
1282
  EVIDENCE,
989
1283
  ManagedConfigError,
990
1284
  POLICY_ID,
@@ -995,6 +1289,7 @@ module.exports = {
995
1289
  applyTierLabel,
996
1290
  reconcile,
997
1291
  resolveManagedBase,
1292
+ retireLegacy,
998
1293
  rollback,
999
1294
  runCli,
1000
1295
  sha256,
@@ -146,7 +146,18 @@ neocortex_managed_report() {
146
146
  echo "$prefix Installed: $label" ;;
147
147
  skipped)
148
148
  echo "$prefix Preserved local changes: $label ($NEOCORTEX_MANAGED_REASON)" >&2
149
- echo "$prefix To take the new version, move the file aside and re-run the installer." >&2 ;;
149
+ # P228.19 (P228-CON-MANIFEST-MIGRATION): role-migration reason codes
150
+ # carry an explicit next step.
151
+ case "$NEOCORTEX_MANAGED_REASON" in
152
+ agent-profile-migration-drift)
153
+ echo "$prefix Next step: move the file aside and re-run the installer (backup under .neocortex/backups/managed-config/)." >&2 ;;
154
+ agent-profile-sentinel-missing)
155
+ echo "$prefix Next step: install neocortex-sentinel for this scope (run install.sh) and re-run; the current child is kept." >&2 ;;
156
+ agent-profile-name-collision)
157
+ echo "$prefix Next step: rename the other profile that declares the same name and re-run the installer." >&2 ;;
158
+ *)
159
+ echo "$prefix To take the new version, move the file aside and re-run the installer." >&2 ;;
160
+ esac ;;
150
161
  *)
151
162
  echo "$prefix FAILED: $label ($NEOCORTEX_MANAGED_REASON)" >&2 ;;
152
163
  esac
@@ -10,13 +10,23 @@ const crypto = require('crypto');
10
10
 
11
11
  const MANAGED_SERVERS = [
12
12
  'playwright',
13
- 'context7',
14
13
  'browser_use',
15
14
  'figma',
16
15
  'shadcn',
17
16
  'chrome-devtools',
18
17
  ];
19
18
 
19
+ // P228.08: servers the Neocortex no longer manages. An installed entry is
20
+ // retired only with ownership proof (claimed fingerprint + secret-free managed
21
+ // shape); anything else stays and only the claim is released.
22
+ const RETIRED_MANAGED_SERVERS = [
23
+ 'context7',
24
+ ];
25
+
26
+ const RETIRABLE_JSON_KEYS = new Set(['type', 'url', 'httpUrl', 'serverUrl', 'headers', 'command', 'args', 'env', 'environment']);
27
+ const RETIRABLE_TOML_KEYS = new Set(['command', 'args', 'url', 'http_url', 'server_url']);
28
+ const PLACEHOLDER_VALUE = /^\$\{(?:env:)?[A-Z][A-Z0-9_]*\}$/;
29
+
20
30
  function usage() {
21
31
  console.error('Usage: mcp-merge.js json <stub> <dest> <rootKey> <target> | toml <stub> <dest> <target>');
22
32
  process.exit(64);
@@ -200,6 +210,76 @@ function planSemanticMerge(existing, baseline, managed, ownership, target) {
200
210
  return { next, entries: nextOwned, blockers, added, updated, deduplicated };
201
211
  }
202
212
 
213
+ function isSecretFreeJsonShape(entry) {
214
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return false;
215
+ for (const [key, value] of Object.entries(entry)) {
216
+ if (!RETIRABLE_JSON_KEYS.has(key)) return false;
217
+ if (key === 'headers' || key === 'env' || key === 'environment') {
218
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
219
+ if (Object.values(value).some((item) => typeof item !== 'string' || !PLACEHOLDER_VALUE.test(item))) return false;
220
+ }
221
+ }
222
+ return true;
223
+ }
224
+
225
+ function tomlSectionKeys(section) {
226
+ const keys = [];
227
+ for (const line of section.split(/\r?\n/).slice(1)) {
228
+ const trimmed = line.trim();
229
+ if (!trimmed || trimmed.startsWith('#')) continue;
230
+ const match = trimmed.match(/^([A-Za-z0-9_-]+)\s*=/);
231
+ keys.push(match ? match[1] : null);
232
+ }
233
+ return keys;
234
+ }
235
+
236
+ /**
237
+ * Decide what happens to each retired server (P228.08 ADR-3):
238
+ * no claim -> user-owned, untouched; claim without entry -> release;
239
+ * claim + same fingerprint + secret-free shape -> remove; otherwise keep the
240
+ * entry, release the claim and warn.
241
+ */
242
+ function planRetirement(existingEntries, ownershipEntries, isSecretFreeShape) {
243
+ const remove = [];
244
+ const release = [];
245
+ const warnings = [];
246
+ for (const name of RETIRED_MANAGED_SERVERS) {
247
+ const claim = ownershipEntries[name];
248
+ if (!claim) continue;
249
+ if (!Object.prototype.hasOwnProperty.call(existingEntries, name)) {
250
+ release.push(name);
251
+ continue;
252
+ }
253
+ const current = existingEntries[name];
254
+ const owned = typeof claim.fingerprint === 'string' && fingerprint(current) === claim.fingerprint;
255
+ if (owned && isSecretFreeShape(name)) {
256
+ remove.push(name);
257
+ } else {
258
+ release.push(name);
259
+ warnings.push(`MCP_RETIRED_ENTRY_USER_MODIFIED:${name}`);
260
+ }
261
+ }
262
+ return { remove, release, warnings };
263
+ }
264
+
265
+ function withoutNames(entries, names) {
266
+ const next = { ...entries };
267
+ for (const name of names) delete next[name];
268
+ return next;
269
+ }
270
+
271
+ function backupRetired(file, target) {
272
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
273
+ const backupPath = `${file}.neocortex-backup-retired-${stamp}`;
274
+ fs.copyFileSync(file, backupPath);
275
+ console.log(`[${target}] Retired MCP entry backup created: ${backupPath}`);
276
+ }
277
+
278
+ function reportRetirement(retirement, target) {
279
+ for (const name of retirement.remove) console.log(`[${target}] mcp-retired-entry-removed:${name} (ownership proven)`);
280
+ for (const reason of retirement.warnings) console.log(`[${target}] WARN: ${reason}; entry kept, ownership released.`);
281
+ }
282
+
203
283
  function mergeJson(stubFile, destFile, rootKey, target, managedTopLevelCsv = '') {
204
284
  const stubResult = readJson(stubFile, target);
205
285
  if (!stubResult.ok) return 1;
@@ -239,14 +319,25 @@ function mergeJson(stubFile, destFile, rootKey, target, managedTopLevelCsv = '')
239
319
  migratedTopLevel.push(name);
240
320
  }
241
321
 
242
- const plan = planSemanticMerge(existing[rootKey], baseline, managed, ownership.value, target);
322
+ const retirement = planRetirement(existing[rootKey], ownership.value.entries,
323
+ (name) => isSecretFreeJsonShape(existing[rootKey][name]));
324
+ const retiredNames = [...retirement.remove, ...retirement.release];
325
+ const plan = planSemanticMerge(
326
+ withoutNames(existing[rootKey], retirement.remove),
327
+ baseline,
328
+ managed,
329
+ { ...ownership.value, entries: withoutNames(ownership.value.entries, retiredNames) },
330
+ target,
331
+ );
243
332
  if (plan.blockers.length) return 3;
333
+ reportRetirement(retirement, target);
244
334
  existing[rootKey] = plan.next;
245
335
  for (const name of migratedTopLevel) delete existing[name];
246
336
 
247
337
  const next = stableJson(existing);
248
338
  const nextOwnership = stableJson({ ...ownership.value, entries: plan.entries });
249
339
  if (next !== existingResult.text) {
340
+ if (retirement.remove.length > 0) backupRetired(destFile, target);
250
341
  if (migratedTopLevel.length > 0) {
251
342
  const stamp = new Date().toISOString().replace(/[:.]/g, '-');
252
343
  const structuralBackup = `${destFile}.neocortex-backup-structural-${stamp}`;
@@ -262,11 +353,20 @@ function mergeJson(stubFile, destFile, rootKey, target, managedTopLevelCsv = '')
262
353
  return 0;
263
354
  }
264
355
 
356
+ // P229.09 (R5): `[table]` and `[[array.of.tables]]` are both section headers
357
+ // (TOML v1.0.0). Array tables are never managed; they only end a section.
358
+ const TABLE_HEADER = /^\[[^[\]][^\]]*\]$/;
359
+ const ARRAY_TABLE_HEADER = /^\[\[[^[\]]+\]\]$/;
360
+
361
+ function isTomlSectionHeader(line) {
362
+ return TABLE_HEADER.test(line) || ARRAY_TABLE_HEADER.test(line);
363
+ }
364
+
265
365
  function looksInvalidToml(text) {
266
366
  for (const line of text.split(/\r?\n/)) {
267
367
  const trimmed = line.trim();
268
368
  if (!trimmed || trimmed.startsWith('#')) continue;
269
- if (trimmed.startsWith('[') && !/^\[[^\]]+\]$/.test(trimmed)) return `invalid table header: ${trimmed}`;
369
+ if (trimmed.startsWith('[') && !isTomlSectionHeader(trimmed)) return `invalid table header: ${trimmed}`;
270
370
  const quotes = (trimmed.match(/(?<!\\)"/g) || []).length;
271
371
  if (quotes % 2 !== 0) return `unbalanced quote: ${trimmed}`;
272
372
  }
@@ -288,7 +388,7 @@ function splitManagedTomlSections(text) {
288
388
  flush();
289
389
  currentName = match[1];
290
390
  current = [line];
291
- } else if (/^\[[^\]]+\]$/.test(line)) {
391
+ } else if (isTomlSectionHeader(line)) {
292
392
  flush();
293
393
  currentName = null;
294
394
  current = [];
@@ -315,7 +415,7 @@ function removeManagedTomlSections(text, managed) {
315
415
  for (const line of lines) {
316
416
  const match = line.match(/^\[mcp_servers\.([^\]]+)\]$/);
317
417
  if (match) skipping = managed.includes(match[1]);
318
- else if (/^\[[^\]]+\]$/.test(line)) skipping = false;
418
+ else if (isTomlSectionHeader(line)) skipping = false;
319
419
  if (!skipping) out.push(line);
320
420
  }
321
421
  return out.join('\n').replace(/[ \t\n]*$/, '\n');
@@ -352,10 +452,23 @@ function mergeToml(stubFile, destFile, target) {
352
452
 
353
453
  const existingSections = splitManagedTomlSections(existing);
354
454
  const existingEntries = Object.fromEntries([...existingSections].map(([name, section]) => [name, tomlEntry(section)]));
355
- const plan = planSemanticMerge(existingEntries, baseline, managed, ownership.value, target);
455
+ const retirement = planRetirement(existingEntries, ownership.value.entries, (name) => {
456
+ const keys = tomlSectionKeys(existingSections.get(name));
457
+ const hasSubtable = [...existingSections.keys()].some((candidate) => candidate.startsWith(`${name}.`));
458
+ return !hasSubtable && keys.every((key) => key !== null && RETIRABLE_TOML_KEYS.has(key));
459
+ });
460
+ const retiredNames = [...retirement.remove, ...retirement.release];
461
+ const plan = planSemanticMerge(
462
+ withoutNames(existingEntries, retirement.remove),
463
+ baseline,
464
+ managed,
465
+ { ...ownership.value, entries: withoutNames(ownership.value.entries, retiredNames) },
466
+ target,
467
+ );
356
468
  if (plan.blockers.length) return 3;
357
- const namesToRemove = managed.filter((name) => !Object.prototype.hasOwnProperty.call(plan.next, name)
358
- || Object.prototype.hasOwnProperty.call(plan.entries, name));
469
+ reportRetirement(retirement, target);
470
+ const namesToRemove = [...managed.filter((name) => !Object.prototype.hasOwnProperty.call(plan.next, name)
471
+ || Object.prototype.hasOwnProperty.call(plan.entries, name)), ...retirement.remove];
359
472
  const namesToAppend = managed.filter((name) => Object.prototype.hasOwnProperty.call(plan.entries, name));
360
473
  const preserved = removeManagedTomlSections(existing, namesToRemove).replace(/\n*# Neocortex MCP Servers\s*\n*$/, '\n');
361
474
  const managedBlock = namesToAppend.map((name) => stubSections.get(name).trimEnd()).join('\n\n');
@@ -364,6 +477,7 @@ function mergeToml(stubFile, destFile, target) {
364
477
  : `${preserved.trimEnd()}\n`;
365
478
  const nextOwnership = stableJson({ ...ownership.value, entries: plan.entries });
366
479
  if (next !== existing) {
480
+ if (retirement.remove.length > 0) backupRetired(destFile, target);
367
481
  atomicWrite(destFile, next);
368
482
  console.log(`[${target}] Merged MCP config into: ${destFile} (managed ${namesToAppend.length}, deduplicated ${plan.deduplicated}, preserved unknown sections)`);
369
483
  } else {