@ornexus/neocortex 4.65.1 → 4.66.0

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 (98) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -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/invoke.d.ts +35 -5
  11. package/packages/client/dist/commands/invoke.js +86 -84
  12. package/packages/client/dist/commands/planning-qa.d.ts +7 -0
  13. package/packages/client/dist/commands/planning-qa.js +1 -0
  14. package/packages/client/dist/commands/refactor-control.js +3 -3
  15. package/packages/client/dist/commands/story-checkpoint.d.ts +1 -1
  16. package/packages/client/dist/commands/story-checkpoint.js +1 -1
  17. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +13 -1
  18. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -3
  19. package/packages/client/dist/git/git-lifecycle-store.d.ts +14 -0
  20. package/packages/client/dist/git/git-lifecycle-store.js +8 -8
  21. package/packages/client/dist/git/governance-runtime-store.d.ts +172 -0
  22. package/packages/client/dist/git/governance-runtime-store.js +3 -0
  23. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  24. package/packages/client/dist/memory/shared-project-memory-types.d.ts +39 -2
  25. package/packages/client/dist/memory/shared-project-memory-types.js +2 -2
  26. package/packages/client/dist/policy/subagent-approval-policy.js +1 -1
  27. package/packages/client/dist/private-execution/codex-executor.d.ts +8 -1
  28. package/packages/client/dist/private-execution/delivery.d.ts +17 -11
  29. package/packages/client/dist/private-execution/delivery.js +8 -6
  30. package/packages/client/dist/private-execution/diagnosis-root-review.d.ts +89 -0
  31. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -2
  32. package/packages/client/dist/private-execution/frozen-handoff.js +3 -3
  33. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +75 -1
  34. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -5
  35. package/packages/client/dist/private-execution/planning-generation-checkpoint.d.ts +9 -1
  36. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +4 -4
  37. package/packages/client/dist/private-execution/planning-research-checkpoint.d.ts +9 -1
  38. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -4
  39. package/packages/client/dist/private-execution/root-memory-request.d.ts +4 -1
  40. package/packages/client/dist/private-execution/root-memory-request.js +1 -1
  41. package/packages/client/dist/runner/epic-background-dispatcher.d.ts +3 -1
  42. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -1
  43. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -1
  44. package/packages/client/dist/runner/headless/managed-profile.d.ts +20 -0
  45. package/packages/client/dist/runner/headless/managed-profile.js +1 -1
  46. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -2
  47. package/packages/client/dist/runner/headless/run-yoloop.d.ts +40 -0
  48. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  49. package/packages/client/dist/runner/headless/types.d.ts +20 -0
  50. package/packages/client/dist/runner/headless/types.js +2 -2
  51. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  52. package/packages/client/dist/yoloop/target-normalization.js +1 -1
  53. package/packages/shared/dist/compatibility/index.js +68 -0
  54. package/packages/shared/dist/planning/diagnosis-state.js +105 -1
  55. package/packages/shared/dist/project-memory-targets.js +36 -5
  56. package/targets-stubs/antigravity/README.md +1 -1
  57. package/targets-stubs/antigravity/gemini.md +1 -1
  58. package/targets-stubs/antigravity/install-antigravity.sh +1 -1
  59. package/targets-stubs/antigravity/mcp-config.json +0 -3
  60. package/targets-stubs/antigravity/neocortex.md +25 -13
  61. package/targets-stubs/antigravity/skill/SKILL.md +4 -4
  62. package/targets-stubs/claude-code/.mcp.json +0 -4
  63. package/targets-stubs/claude-code/neocortex-root.agent.yaml +2 -4
  64. package/targets-stubs/claude-code/neocortex-root.md +33 -43
  65. package/targets-stubs/claude-code/neocortex-sentinel.md +261 -0
  66. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -3
  67. package/targets-stubs/claude-code/neocortex.md +61 -84
  68. package/targets-stubs/codex/AGENTS.md +19 -18
  69. package/targets-stubs/codex/README.md +1 -1
  70. package/targets-stubs/codex/config-mcp.toml +0 -3
  71. package/targets-stubs/codex/neocortex-sentinel.toml +87 -0
  72. package/targets-stubs/codex/neocortex.toml +23 -44
  73. package/targets-stubs/cursor/README.md +1 -1
  74. package/targets-stubs/cursor/agent.md +26 -15
  75. package/targets-stubs/cursor/mcp.json +0 -3
  76. package/targets-stubs/deepseek-harness/SKILL.md +11 -8
  77. package/targets-stubs/gemini-cli/README.md +1 -1
  78. package/targets-stubs/gemini-cli/agent.md +25 -12
  79. package/targets-stubs/gemini-cli/agents/neocortex-sentinel.md +75 -0
  80. package/targets-stubs/gemini-cli/agents/neocortex.md +280 -49
  81. package/targets-stubs/gemini-cli/settings-mcp.json +0 -3
  82. package/targets-stubs/grok/SKILL.md +12 -0
  83. package/targets-stubs/grok/agents/neocortex.md +64 -0
  84. package/targets-stubs/grok/config-mcp.toml +0 -3
  85. package/targets-stubs/grok/install-grok.sh +14 -1
  86. package/targets-stubs/kimi/mcp.json +0 -6
  87. package/targets-stubs/kimi/neocortex.md +21 -8
  88. package/targets-stubs/lib/managed-config-merge.js +281 -6
  89. package/targets-stubs/lib/managed-profile.sh +12 -1
  90. package/targets-stubs/lib/mcp-merge.js +110 -5
  91. package/targets-stubs/openclaw/SKILL.md +33 -4
  92. package/targets-stubs/opencode/neocortex-root.md +41 -41
  93. package/targets-stubs/opencode/neocortex-sentinel.md +115 -0
  94. package/targets-stubs/opencode/neocortex.md +292 -67
  95. package/targets-stubs/opencode/opencode-mcp.json +0 -7
  96. package/targets-stubs/vscode/README.md +1 -1
  97. package/targets-stubs/vscode/mcp.json +0 -4
  98. package/targets-stubs/vscode/neocortex.agent.md +29 -18
@@ -164,6 +164,192 @@ 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
+ * P228.19 AM-09: true when the destination still holds the legacy child and
330
+ * would be rewritten as orchestrator. Writers use it to avoid carrying the
331
+ * child's host frontmatter (for example `mode: subagent`) into the new role.
332
+ */
333
+ function agentRoleMigrationPending(options) {
334
+ const roleRow = agentRoleFor(options.agentRoleId || options.id);
335
+ if (!roleRow || roleRow.role !== 'orchestrator') return false;
336
+ try {
337
+ const target = resolveWithinBase(options.baseDir, options.destination, 'destination');
338
+ if (!fs.existsSync(target.resolved)) return false;
339
+ const manifest = loadManifest(options.manifestFile, options.baseDir);
340
+ let entry = manifest.entries[sanitizeId(options.id)];
341
+ if (!entry) {
342
+ const owners = Object.values(manifest.entries)
343
+ .filter((candidate) => candidate && candidate.relativePath === target.relative);
344
+ entry = owners.length === 1 ? owners[0] : null;
345
+ }
346
+ if (!entry) return isKnownLegacyProfile(fs.readFileSync(target.resolved));
347
+ return (entry.agentRole || 'child') !== 'orchestrator';
348
+ } catch {
349
+ return false;
350
+ }
351
+ }
352
+
167
353
  function isKnownLegacyProfile(bytes) {
168
354
  const content = bytes?.toString('utf8') || '';
169
355
  if (!/neocortex/i.test(content)) return false;
@@ -527,9 +713,16 @@ function writeManagedBytes(input) {
527
713
  allowOwnedDriftMerge = false,
528
714
  adoptExistingOwner = false,
529
715
  legacyBaseDir = null,
716
+ agentRoles = false,
717
+ agentRoleId = null,
530
718
  now,
531
719
  } = input;
532
720
  let safeId = sanitizeId(id);
721
+ // P228.19 AM-02: the role comes from the requested id (or an explicit role
722
+ // id, AM-08), before any adoption of an older owner id for the same file.
723
+ const roleRow = kind === 'profile' && agentRoles
724
+ ? AGENT_ROLE_BY_ID.get(agentRoleId ? sanitizeId(agentRoleId) : safeId) || null
725
+ : null;
533
726
  const target = resolveWithinBase(baseDir, destination, 'destination');
534
727
  const manifest = loadManifest(manifestFile, baseDir);
535
728
  let ownerAdopted = false;
@@ -561,6 +754,19 @@ function writeManagedBytes(input) {
561
754
  }
562
755
  }
563
756
 
757
+ const roleFields = roleRow ? { agentRole: roleRow.role } : {};
758
+ if (roleRow) {
759
+ extra.agentRole = roleRow.role;
760
+ const collision = findAgentNameCollision(target, desiredBytes);
761
+ if (collision) {
762
+ return resultFor(safeId, target.relative, 'skipped', 'agent-profile-name-collision', {
763
+ collisionRelativePath: collision,
764
+ ...extra,
765
+ dryRun,
766
+ });
767
+ }
768
+ }
769
+
564
770
  const desiredHash = sha256(desiredBytes);
565
771
  const desiredDigest = isProfile ? managedLinesDigest(desiredBytes) : null;
566
772
  const digestField = isProfile ? { managedLinesDigest: desiredDigest } : {};
@@ -592,6 +798,21 @@ function writeManagedBytes(input) {
592
798
  const hashes = new Set([finalHash, currentHash, priorInstalledHash].filter(Boolean));
593
799
  return { duplicateBase: settleLegacyDuplicates(legacy, hashes, { dryRun, now, adoptedIds, blockedIds }) };
594
800
  };
801
+ // P228.19 AM-04: nested legacy copy removed only with a known managed hash.
802
+ const priorPreviousHash = entry?.previousHash || null;
803
+ const legacyCopyResult = (finalHash) => {
804
+ const settled = settleLegacyCopy(input, manifest, [finalHash, currentHash, priorInstalledHash, priorPreviousHash]);
805
+ return settled ? { legacyCopy: settled } : {};
806
+ };
807
+
808
+ // P228.19 spec T2: role migration is needed when the installed role differs.
809
+ // An orchestrator entry without agentRole is the legacy child.
810
+ let priorRole = null;
811
+ if (roleRow && exists) {
812
+ if (entry) priorRole = entry.agentRole || (roleRow.role === 'orchestrator' ? 'child' : roleRow.role);
813
+ else if (roleRow.role === 'orchestrator' && isKnownLegacyProfile(currentBytes)) priorRole = 'child';
814
+ }
815
+ const migrationNeeded = Boolean(roleRow && priorRole && priorRole !== roleRow.role);
595
816
 
596
817
  // P227.14 T1: an owned destination that disappeared is restored.
597
818
  if (isProfile && entry && !exists) {
@@ -607,6 +828,7 @@ function writeManagedBytes(input) {
607
828
  createdByApply: true,
608
829
  action: 'restored',
609
830
  ...digestField,
831
+ ...roleFields,
610
832
  updatedAt: nowIso({ now }),
611
833
  };
612
834
  saveManifest(manifestFile, baseDir, manifest, dryRun);
@@ -616,6 +838,7 @@ function writeManagedBytes(input) {
616
838
  ownershipEvidence: 'managed-destination-missing',
617
839
  ...extra,
618
840
  ...settle(desiredHash),
841
+ ...legacyCopyResult(desiredHash),
619
842
  dryRun,
620
843
  });
621
844
  }
@@ -628,6 +851,18 @@ function writeManagedBytes(input) {
628
851
  }
629
852
 
630
853
  if (entry && currentHash !== entry.installedHash && !allowOwnedDriftMerge && !ownershipEvidence) {
854
+ // P228.19 spec T3: drift on a role being migrated has its own reason code.
855
+ if (migrationNeeded) {
856
+ return resultFor(safeId, target.relative, 'skipped', 'agent-profile-migration-drift', {
857
+ beforeHash: currentHash,
858
+ installedHash: entry.installedHash,
859
+ desiredHash,
860
+ previousRole: priorRole,
861
+ nextStep: 'move-aside-and-rerun',
862
+ ...extra,
863
+ dryRun,
864
+ });
865
+ }
631
866
  return resultFor(safeId, target.relative, 'skipped', 'user-drift-preserved', {
632
867
  beforeHash: currentHash,
633
868
  installedHash: entry.installedHash,
@@ -649,6 +884,7 @@ function writeManagedBytes(input) {
649
884
  createdByApply: false,
650
885
  action: 'adopted-identical',
651
886
  ...digestField,
887
+ ...roleFields,
652
888
  updatedAt: nowIso({ now }),
653
889
  };
654
890
  saveManifest(manifestFile, baseDir, manifest, dryRun);
@@ -658,12 +894,15 @@ function writeManagedBytes(input) {
658
894
  installedHash: desiredHash,
659
895
  action: ownershipEvidence === 'managed-duplicate-base-adopted' ? entry.action : 'post-process-reconciled',
660
896
  ...digestField,
897
+ ...roleFields,
661
898
  updatedAt: nowIso({ now }),
662
899
  };
663
900
  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 };
901
+ } else if (
902
+ isProfile && (entry.managedLinesDigest !== desiredDigest || (roleRow && entry.agentRole !== roleRow.role))
903
+ ) {
904
+ // Backfill: the hash is exact, only the digest (and P228.19 role) is recorded.
905
+ manifest.entries[safeId] = { ...entry, ...digestField, ...roleFields };
667
906
  saveManifest(manifestFile, baseDir, manifest, dryRun);
668
907
  }
669
908
  return resultFor(safeId, target.relative, dryRun ? 'planned-noop' : 'noop', 'managed-content-current', {
@@ -672,6 +911,7 @@ function writeManagedBytes(input) {
672
911
  ...(ownershipEvidence ? { ownershipEvidence } : {}),
673
912
  ...extra,
674
913
  ...settle(desiredHash),
914
+ ...legacyCopyResult(desiredHash),
675
915
  dryRun,
676
916
  });
677
917
  }
@@ -680,9 +920,31 @@ function writeManagedBytes(input) {
680
920
  kind === 'policy' || isKnownLegacyProfile(currentBytes)
681
921
  );
682
922
  if (exists && !entry && !legacyAdoptionAllowed) {
683
- return resultFor(safeId, target.relative, 'skipped', 'unmanaged-content-preserved', {
923
+ // P228.19 spec T3: an unknown file on the orchestrator path is user content.
924
+ const orchestratorPath = roleRow && roleRow.role === 'orchestrator';
925
+ return resultFor(
926
+ safeId,
927
+ target.relative,
928
+ 'skipped',
929
+ orchestratorPath ? 'agent-profile-migration-drift' : 'unmanaged-content-preserved',
930
+ {
931
+ beforeHash: currentHash,
932
+ desiredHash,
933
+ ...(orchestratorPath ? { nextStep: 'move-aside-and-rerun' } : {}),
934
+ ...extra,
935
+ dryRun,
936
+ },
937
+ );
938
+ }
939
+
940
+ // P228.19 spec T1.2: never turn the old child into the orchestrator before
941
+ // the sentinel of the same scope is installed (the scope keeps a child).
942
+ if (migrationNeeded && !sentinelReady(manifest, roleRow, baseDir, target, dryRun)) {
943
+ return resultFor(safeId, target.relative, 'skipped', 'agent-profile-sentinel-missing', {
684
944
  beforeHash: currentHash,
685
945
  desiredHash,
946
+ previousRole: priorRole,
947
+ nextStep: 'install-sentinel-and-rerun',
686
948
  ...extra,
687
949
  dryRun,
688
950
  });
@@ -704,16 +966,20 @@ function writeManagedBytes(input) {
704
966
  createdByApply: !exists,
705
967
  action,
706
968
  ...digestField,
969
+ ...roleFields,
707
970
  updatedAt: nowIso({ now }),
708
971
  };
709
972
  saveManifest(manifestFile, baseDir, manifest, dryRun);
710
- return resultFor(safeId, target.relative, dryRun ? `planned-${action}` : action, 'managed-content-applied', {
973
+ const reasonCode = migrationNeeded ? 'agent-profile-role-migrated' : 'managed-content-applied';
974
+ return resultFor(safeId, target.relative, dryRun ? `planned-${action}` : action, reasonCode, {
711
975
  beforeHash: currentHash,
712
976
  installedHash: desiredHash,
713
977
  backupRelativePath: backup?.backupRelativePath || null,
978
+ ...(migrationNeeded ? { previousRole: priorRole } : {}),
714
979
  ...(ownershipEvidence ? { ownershipEvidence } : {}),
715
980
  ...extra,
716
981
  ...settle(desiredHash),
982
+ ...legacyCopyResult(desiredHash),
717
983
  dryRun,
718
984
  });
719
985
  }
@@ -919,7 +1185,7 @@ function reconcile(options) {
919
1185
  }
920
1186
 
921
1187
  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]');
1188
+ 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]');
923
1189
  process.exitCode = 64;
924
1190
  }
925
1191
 
@@ -931,7 +1197,12 @@ function runCli(argv = process.argv.slice(2)) {
931
1197
  if (command === 'profile') {
932
1198
  const [sourceFile, destination, manifestFile, baseDir, id] = args;
933
1199
  if (!sourceFile || !destination || !manifestFile || !baseDir || !id) return usage();
1200
+ // P228.19 AM-01: role semantics only when the sentinel stub ships beside the source.
1201
+ const roleRow = agentRoleFor(id);
1202
+ const agentRoles = Boolean(roleRow && fs.existsSync(path.join(path.dirname(sourceFile), roleRow.sentinelFile)));
934
1203
  result = applyProfile({
1204
+ agentRoles,
1205
+ legacyCopyPath: args.find((arg) => arg.startsWith('--legacy-copy='))?.slice('--legacy-copy='.length) || null,
935
1206
  sourceFile,
936
1207
  destination,
937
1208
  manifestFile,
@@ -985,6 +1256,10 @@ function runCli(argv = process.argv.slice(2)) {
985
1256
  if (require.main === module) process.exitCode = runCli();
986
1257
 
987
1258
  module.exports = {
1259
+ AGENT_ROLE_TABLE,
1260
+ agentRoleFor,
1261
+ agentRoleMigrationPending,
1262
+ readAgentName,
988
1263
  EVIDENCE,
989
1264
  ManagedConfigError,
990
1265
  POLICY_ID,
@@ -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}`;
@@ -352,10 +443,23 @@ function mergeToml(stubFile, destFile, target) {
352
443
 
353
444
  const existingSections = splitManagedTomlSections(existing);
354
445
  const existingEntries = Object.fromEntries([...existingSections].map(([name, section]) => [name, tomlEntry(section)]));
355
- const plan = planSemanticMerge(existingEntries, baseline, managed, ownership.value, target);
446
+ const retirement = planRetirement(existingEntries, ownership.value.entries, (name) => {
447
+ const keys = tomlSectionKeys(existingSections.get(name));
448
+ const hasSubtable = [...existingSections.keys()].some((candidate) => candidate.startsWith(`${name}.`));
449
+ return !hasSubtable && keys.every((key) => key !== null && RETIRABLE_TOML_KEYS.has(key));
450
+ });
451
+ const retiredNames = [...retirement.remove, ...retirement.release];
452
+ const plan = planSemanticMerge(
453
+ withoutNames(existingEntries, retirement.remove),
454
+ baseline,
455
+ managed,
456
+ { ...ownership.value, entries: withoutNames(ownership.value.entries, retiredNames) },
457
+ target,
458
+ );
356
459
  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));
460
+ reportRetirement(retirement, target);
461
+ const namesToRemove = [...managed.filter((name) => !Object.prototype.hasOwnProperty.call(plan.next, name)
462
+ || Object.prototype.hasOwnProperty.call(plan.entries, name)), ...retirement.remove];
359
463
  const namesToAppend = managed.filter((name) => Object.prototype.hasOwnProperty.call(plan.entries, name));
360
464
  const preserved = removeManagedTomlSections(existing, namesToRemove).replace(/\n*# Neocortex MCP Servers\s*\n*$/, '\n');
361
465
  const managedBlock = namesToAppend.map((name) => stubSections.get(name).trimEnd()).join('\n\n');
@@ -364,6 +468,7 @@ function mergeToml(stubFile, destFile, target) {
364
468
  : `${preserved.trimEnd()}\n`;
365
469
  const nextOwnership = stableJson({ ...ownership.value, entries: plan.entries });
366
470
  if (next !== existing) {
471
+ if (retirement.remove.length > 0) backupRetired(destFile, target);
367
472
  atomicWrite(destFile, next);
368
473
  console.log(`[${target}] Merged MCP config into: ${destFile} (managed ${namesToAppend.length}, deduplicated ${plan.deduplicated}, preserved unknown sections)`);
369
474
  } else {
@@ -10,10 +10,12 @@ user-invocable: true
10
10
  This public Skill is a thin client wrapper. All orchestration logic comes from
11
11
  the remote Neocortex server through `neocortex-client invoke`.
12
12
 
13
- `[P201-EV-OTHER-TARGETS] target=openclaw child=unsupported requestedMode=max effectiveMode=disabled approvalScope=none fallback=root-inline reason=platform-child-unsupported color=unsupported`
13
+ `[P201-EV-OTHER-TARGETS] target=openclaw child=unvalidated requestedMode=max effectiveMode=standard approvalScope=inherited fallback=shell-loop reason=platform-child-unvalidated color=unsupported`
14
14
 
15
- This Skill is not a child profile. OpenClaw must keep root ownership and must not
16
- advertise native Neocortex isolation from the presence of this file.
15
+ This Skill serves both roles: the root agent reads the sections below, and a
16
+ per-story child started with `sessions_spawn` follows "Child execution". The
17
+ child is unvalidated until a versioned smoke is recorded; the root keeps
18
+ ownership of every yoloop decision.
17
19
 
18
20
  ## Parallel Delegation Contract
19
21
 
@@ -42,7 +44,34 @@ the host's native subagent primitive when OpenClaw exposes one:
42
44
  then re-invokes `*yoloop`; server output decides integration and the next
43
45
  wave. Follow stdout and server output; never invent workflow steps.
44
46
 
45
- OpenClaw currently documents no native Neocortex child primitive, so the root keeps the root-inline fallback, but parallel delegation is used whenever the host offers it.
47
+ When the host does not expose `sessions_spawn` (for example a messaging tool
48
+ profile without it), the root keeps the shell-loop fallback, but parallel
49
+ delegation is used whenever the host offers it.
50
+
51
+ ### Native child dispatch (OpenClaw)
52
+
53
+ OpenClaw starts children with `sessions_spawn`. For each authorized story, call
54
+ it with `task` set to that story's server-authored per-story prompt and
55
+ `context: "isolated"`, without `agentId`: the child is an isolated session of
56
+ the same agent and loads this Skill. Never register or change agents in
57
+ `openclaw.json`. For a v4 `client_managed_worktree` plan, the child creates its
58
+ managed worktree with `neocortex-client story-worktree create` as described
59
+ below; do not also request a host `worktree`. Dispatch one wave in a single turn
60
+ with multiple `sessions_spawn` calls, wait for every child's announced result,
61
+ then re-invoke `*yoloop`.
62
+
63
+ ## Child execution
64
+
65
+ Read this section when your session was started by `sessions_spawn` with a
66
+ Neocortex per-story prompt. Your task is one server-authored per-story command,
67
+ for example `*yolo @docs/stories/<id>.story.md` or a `story-worktree-phase-1` /
68
+ `story-worktree-phase-2` variant. Run it verbatim through `neocortex-client
69
+ invoke --args`, follow stdout exactly and re-invoke the same per-story prompt
70
+ while the server says the story continues. If the task is an outer `*yoloop`
71
+ trigger or any root invocation, do not run it: report
72
+ `child-prompt-root-trigger` and stop. Return the server's final per-story
73
+ receipt or terminal token as your announced result. A story result is not epic
74
+ completion; the root re-invokes `*yoloop`.
46
75
 
47
76
  ### Story worktree plans (v4)
48
77