@cortex-agent/server 2026.9.9 → 2026.9.10

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.
@@ -11,9 +11,9 @@ Root directory for project context. All project state, experiment records, knowl
11
11
  | `projects/` | Project context | One subdirectory per active project |
12
12
  | `scans/` | Knowledge scan reports | Named by date `YYYY-MM-DD.md`, each scan outputs here |
13
13
  | `ideas/` | Idea incubation library | Directions in Incubating status, promoted to project when mature |
14
- | `retrospectives/` | Experience distillation reports | Mined by `/deep-retrospective` from historical logs for cross-session knowledge, named as `YYYY-MM-DD-<topic>.md` |
14
+ | `retrospectives/` | Experience distillation reports | Distilled from historical logs for cross-session knowledge, named as `YYYY-MM-DD-<topic>.md` |
15
15
  | `user/` | User profile | Cross-project user personal preferences (identity, communication style, output format, etc.), maintained by `/user-learn`, hard limit 3KB |
16
- | `PENDING_APPROVALS.md` | Approval queue | Operations requiring user confirmation, written by need-approval, managed by /approval |
16
+ | `PENDING_APPROVALS.md` | Approval queue | Operations requiring user confirmation, managed by /approval |
17
17
 
18
18
  ## Lookup Rules
19
19
 
@@ -10,7 +10,7 @@ User-level memory directory. Stores user personal preferences and context across
10
10
 
11
11
  ## Rules
12
12
 
13
- - `USER.md` is maintained by the agent (`/user-learn` skill), user corrects via `/feedback`
13
+ - `USER.md` is maintained by the agent (`/user-learn` skill); the user corrects it by saying so in chat
14
14
  - Injected only into plain direct conversation turns (the thread-free chat path); multi-agent thread steps never carry the user profile
15
15
  - Injected by default; set environment variable `CORTEX_DISABLE_USER_CONTEXT=1` to disable
16
16
  - File hard limit 3KB, compress rather than grow when approaching the limit
@@ -18,4 +18,4 @@ User-level memory directory. Stores user personal preferences and context across
18
18
  ## Lookup Rules
19
19
 
20
20
  - **Find user preferences** -> `USER.md`
21
- - **Modify user preferences** -> `/user-learn` or `/feedback`
21
+ - **Modify user preferences** -> `/user-learn`
@@ -1,17 +1,5 @@
1
1
  {
2
2
  "tasks": [
3
- {
4
- "id": "seed0004",
5
- "type": "interval",
6
- "intervalMs": 86400000,
7
- "message": "[Scheduled Task] Execute /orient full — comprehensive situational assessment. Full project scan, machine state, cross-session patterns, task inventory, mission gap analysis, gravity signals, compound opportunities, risks.",
8
- "channel": "__ADMIN_CHANNEL__",
9
- "profile": null,
10
- "preCheck": "bash agent-server/src/orient-precheck.sh",
11
- "target": { "kind": "fresh" },
12
- "isPaused": false,
13
- "createdAt": 0
14
- },
15
3
  {
16
4
  "id": "seed0005",
17
5
  "type": "daily",
@@ -20,7 +8,9 @@
20
8
  "message": "Daily auth expiry scan at 08:30 local time: warn before daytime use while avoiding midnight maintenance activity.",
21
9
  "channel": "__ADMIN_CHANNEL__",
22
10
  "profile": null,
23
- "target": { "kind": "fresh" },
11
+ "target": {
12
+ "kind": "fresh"
13
+ },
24
14
  "isPaused": false,
25
15
  "createdAt": 0
26
16
  }
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "cortex-system",
3
- "version": "0.4.0",
4
- "description": "Cortex system skill bundle — orient / evolve / schedule / compound / approval and other system-level skills. The commission skill moved to cortex-commission, which loads only in commission mode."
3
+ "version": "0.5.0",
4
+ "description": "Cortex system skill bundle — approval / client-manage / project-init / schedule / task / thread / user-learn. The commission skill lives in cortex-commission, which loads only in commission mode."
5
5
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "cortex-system",
4
- "version": "0.4.0",
5
- "description": "Cortex system skill bundle — orient / evolve / schedule / compound / approval and other system-level skills. The commission skill moved to cortex-commission, which loads only in commission mode."
4
+ "version": "0.5.0",
5
+ "description": "Cortex system skill bundle — approval / client-manage / project-init / schedule / task / thread / user-learn. The commission skill lives in cortex-commission, which loads only in commission mode."
6
6
  }
@@ -71,7 +71,7 @@ When the user responds with approval/rejection:
71
71
 
72
72
  ## Step 4: Cleanup
73
73
 
74
- If all entries in PENDING_APPROVALS.md are resolved (no `Status: pending` remaining), the file stays as a historical log. Old resolved entries can be cleaned up periodically during `/evolve`.
74
+ If all entries in PENDING_APPROVALS.md are resolved (no `Status: pending` remaining), the file stays as a historical log. Old resolved entries can be pruned whenever the log gets long enough to slow a read.
75
75
 
76
76
  ## Principles
77
77
  - Present enough context for the user to decide quickly — no back-and-forth needed
@@ -61,17 +61,17 @@ mcp__cortex__cortex_schedule_resume({ id })
61
61
 
62
62
  **Worked examples:**
63
63
 
64
- > User: "Remind me to run /orient every morning at 9, send results to current channel"
64
+ > User: "Give me a status roundup of this project every morning at 9, in this channel"
65
65
  >
66
- > Call `mcp__cortex__cortex_schedule_add({ type: 'daily', time: '09:00', message: '/orient', target: 'current-project' })` — done. No need to call `cortex_context` first; the shorthand resolves automatically.
66
+ > Call `mcp__cortex__cortex_schedule_add({ type: 'daily', time: '09:00', message: 'Review STATUS.md and the actionable task queue for this project, then post a short roundup', target: 'current-project' })` — done. No need to call `cortex_context` first; the shorthand resolves automatically.
67
67
 
68
68
  > User: "Report training status in this thread after 30 minutes"
69
69
  >
70
70
  > Call `mcp__cortex__cortex_schedule_add({ type: 'once', delay: '30m', message: 'Check training results on <machine> and report', target: 'current-thread' })` — the schedule continues the current thread (valid while it is running/waiting), so prior context is intact.
71
71
 
72
- > User: "Run deep retrospective every Monday at 9 PM"
72
+ > User: "Mine last week's sessions for lessons every Monday at 9 PM"
73
73
  >
74
- > Call `mcp__cortex__cortex_schedule_add({ type: 'weekly', dayOfWeek: 'mon', time: '21:00', message: '/deep-retrospective' })` — `target` defaults to `fresh`, which is the right choice for a standalone weekly job.
74
+ > Call `mcp__cortex__cortex_schedule_add({ type: 'weekly', dayOfWeek: 'mon', time: '21:00', message: 'Read this week\'s session logs and record any recurring failure or lesson worth keeping' })` — `target` defaults to `fresh`, which is the right choice for a standalone weekly job.
75
75
 
76
76
  If `current-thread` is requested but the context lacks the field, the tool throws — it does NOT silently fall back to fresh. Re-issue with `target: 'fresh'` if that's actually what you want.
77
77
 
@@ -139,7 +139,7 @@ Interpret the user's natural language description to determine:
139
139
  **Interpretation examples:**
140
140
  - "Check GPU status every 30 minutes" → interval, 30m, "Check GPU status (nvidia-smi) and report a one-line summary"
141
141
  - "Generate a daily project report every morning at 9" → daily, 09:00, "Generate a brief daily status report for all active projects"
142
- - "Do retrospection every Monday at 9 PM" → weekly, mon 21:00, "Execute /deep-retrospective — weekly knowledge mining"
142
+ - "Do retrospection every Monday at 9 PM" → weekly, mon 21:00, "Mine this week's session logs for recurring failures and lessons worth keeping"
143
143
  - "Remind me to check training results in 2 hours" → once, 2h, "Check training results on <machine> and report to user"
144
144
 
145
145
  **Compute the new task object** using the canonical schedule CLI add command. The CLI currently defaults `channel` to `cli` unless an explicit channel override is provided.
@@ -147,7 +147,7 @@ Interpret the user's natural language description to determine:
147
147
  Examples:
148
148
  - `npx tsx agent-server/src/schedule-cli.ts add interval 30m "Check GPU status on <machine> (nvidia-smi) and report a one-line summary"`
149
149
  - `npx tsx agent-server/src/schedule-cli.ts add daily 09:00 "Generate a brief daily status report for all active projects"`
150
- - `npx tsx agent-server/src/schedule-cli.ts add weekly mon 21:00 "Execute /deep-retrospective — weekly knowledge mining"`
150
+ - `npx tsx agent-server/src/schedule-cli.ts add weekly mon 21:00 "Mine this week's session logs for recurring failures and lessons worth keeping"`
151
151
  - `npx tsx agent-server/src/schedule-cli.ts add once 2h "Check training results on <machine> and report to user"`
152
152
 
153
153
  Confirm the plan in the output before writing, showing:
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: user-learn
3
- description: "Use when the user states a personal preference, communication style, or working habit that should persist across sessions. Also trigger when /feedback identifies a user-personal directive or tuning request. Examples: 'speak Chinese', 'no emoji', 'I prefer bullet points', 'call me X'."
3
+ description: "Use when the user states a personal preference, communication style, or working habit that should persist across sessions. Examples: 'speak Chinese', 'no emoji', 'I prefer bullet points', 'call me X'."
4
4
  allowed-tools: Read, Edit, Bash, Grep, Glob
5
5
  metadata:
6
6
  author: "Cortex"
@@ -28,4 +28,4 @@ Search command: `grep -r "EXP-035" context/`
28
28
  | knowledge/K-005.md | needs-update | "data scaling most effective" | Needs modality distinction |
29
29
  ```
30
30
 
31
- Search + classification takes about 5 minutes. Corrections without Downstream Impact are flagged in the compound step.
31
+ Search + classification takes about 5 minutes. Corrections without Downstream Impact are still worth a one-line note, so a later reader can see the check was done.
@@ -10,7 +10,7 @@ The project's "constitution": defines goals and success conditions. It is the ba
10
10
  ## Hard Constraints
11
11
 
12
12
  - **Stable file**: Can only be modified after user confirmation. Cortex must not rewrite or expand scope on its own.
13
- - **Modification trigger condition**: User explicitly directs reorient / pivot / scope change. Do not touch in any other case.
13
+ - **Modification trigger condition**: User explicitly directs a re-orientation, pivot, or scope change. Do not touch in any other case.
14
14
  - **Limit: 100 lines AND 8KB**. Too long means content that belongs in roadmap/STATUS or a project-pitch document has been mixed in; trimming also requires user confirmation.
15
15
 
16
16
  ## Required Sections
@@ -45,4 +45,4 @@ The project's "constitution": defines goals and success conditions. It is the ba
45
45
 
46
46
  ## Modification Process
47
47
 
48
- For major reorient-type changes: first use the `reorient` skill to jointly update STATUS / roadmap / project CORTEX.md to avoid context inconsistency.
48
+ For major re-orientations: update STATUS / roadmap / project CORTEX.md in the same pass to avoid context inconsistency.
@@ -5,7 +5,7 @@ paths:
5
5
 
6
6
  # OVERVIEW.md Convention
7
7
 
8
- Cross-project global view: one-line status per project + current focus. Primary input for `/orient`.
8
+ Cross-project global view: one-line status per project + current focus. Primary input whenever a session needs to re-establish where everything stands.
9
9
 
10
10
  ## Hard Constraints
11
11
 
@@ -9,7 +9,7 @@ Project roadmap and milestones. The machine uses this to determine phase progres
9
9
 
10
10
  ## Hard Constraints
11
11
 
12
- - **Stable file**: Milestone structure changes should be triggered by reorient/decision.
12
+ - **Stable file**: Milestone structure changes should be triggered by a re-orientation or a recorded decision.
13
13
  - **Each milestone must contain testable verification conditions** (checklist format). A milestone without a checklist is invalid.
14
14
  - Completed milestones are retained with check marks, not deleted (for reviewing roadmap history).
15
15
  - Length suggestion: ≤ 250 lines. If exceeded, consider splitting sub-projects or archiving completed phases.
@@ -333,8 +333,8 @@ function optionalServerConfig(entry, server) {
333
333
  return [];
334
334
  }
335
335
  }
336
- function portableRuntimeDetail(selection, backend, runtimeDir, includePortableMcp) {
337
- const skills = materializedSkills(selection, portableSkills(selection), runtimeDir, backend);
336
+ function portableRuntimeDetail(selection, backend, runtimeDir, includePortableMcp, claims) {
337
+ const skills = materializedSkills(selection, claimPortableSkills(selection, portableSkills(selection), claims), runtimeDir, backend);
338
338
  return {
339
339
  namespace: portableNamespace(selection.entry),
340
340
  skills,
@@ -386,7 +386,7 @@ function addClassifiedSelection(absolute, real, entry, roots, result, preserved)
386
386
  if (entry?.kind === 'portable')
387
387
  return addPortableSelection(entry, roots, result);
388
388
  if (entry?.kind === 'legacy') {
389
- result.selectedLegacySkillNames.push(...entry.skills.map((skill) => skill.name));
389
+ result.selectedLegacySkills.push(...entry.skills.map((skill) => ({ name: skill.name, pluginId: entry.id })));
390
390
  }
391
391
  const preservedPath = real ?? absolute;
392
392
  if (preserved.has(preservedPath))
@@ -397,7 +397,7 @@ function addClassifiedSelection(absolute, real, entry, roots, result, preserved)
397
397
  function classifySelections(entries, roots, dataDir, selectedPluginDirs) {
398
398
  const lookup = catalogEntriesByPath(entries, roots);
399
399
  const result = {
400
- items: [], portableSelections: new Map(), selectedLegacySkillNames: [],
400
+ items: [], portableSelections: new Map(), selectedLegacySkills: [],
401
401
  };
402
402
  const preserved = new Set();
403
403
  for (const value of selectedPluginDirs) {
@@ -413,9 +413,30 @@ function addUniqueName(seen, name, label) {
413
413
  throw new Error(`Duplicate portable ${label}: ${name}`);
414
414
  seen.add(name);
415
415
  }
416
- function collectSkillNames(detail, skillNames) {
417
- for (const skill of detail.skills)
418
- addUniqueName(skillNames, skill.name, 'skill name');
416
+ /** Keep only the skills whose names are still unclaimed, naming both sides of every drop so the
417
+ * loser is diagnosable from the log alone. */
418
+ function claimPortableSkills(selection, skills, claims) {
419
+ const kept = [];
420
+ for (const skill of skills) {
421
+ const owner = claims.get(skill.name);
422
+ if (owner !== undefined) {
423
+ log.warn(`Skipping skill '${skill.name}' from plugin '${selection.entry.id}': `
424
+ + `'${owner}' is already selected and provides that name.`);
425
+ continue;
426
+ }
427
+ claims.set(skill.name, selection.entry.id);
428
+ kept.push(skill);
429
+ }
430
+ return kept;
431
+ }
432
+ /** A failed projection empties a plugin's skill list after it staked its claims. Hand those names
433
+ * back, so a plugin that lost a name to one that ended up providing nothing can still supply it. */
434
+ function releaseUnusedClaims(claims, pluginId, skills) {
435
+ const live = new Set(skills.map((skill) => skill.name));
436
+ for (const [name, owner] of claims) {
437
+ if (owner === pluginId && !live.has(name))
438
+ claims.delete(name);
439
+ }
419
440
  }
420
441
  function collectMcpNames(detail, mcpNames) {
421
442
  for (const server of detail.mcpServers)
@@ -424,21 +445,28 @@ function collectMcpNames(detail, mcpNames) {
424
445
  function collectPortableDetails(portableSelections, backend, runtimeDir, includePortableMcp) {
425
446
  const details = new Map();
426
447
  const namespaces = new Set();
427
- const skillNames = new Set();
448
+ const claims = new Map();
428
449
  const mcpNames = new Set();
429
450
  for (const [id, selection] of portableSelections) {
430
- const detail = portableRuntimeDetail(selection, backend, runtimeDir, includePortableMcp);
451
+ const detail = portableRuntimeDetail(selection, backend, runtimeDir, includePortableMcp, claims);
431
452
  addUniqueName(namespaces, detail.namespace, 'MCP namespace');
432
- collectSkillNames(detail, skillNames);
453
+ releaseUnusedClaims(claims, id, detail.skills);
433
454
  collectMcpNames(detail, mcpNames);
434
455
  details.set(id, detail);
435
456
  }
436
- return { details, skillNames };
437
- }
438
- function assertLegacySkillCollisions(skillNames, legacySkillNames) {
439
- for (const name of legacySkillNames) {
440
- if (skillNames.has(name))
441
- throw new Error(`Duplicate portable skill name: ${name}`);
457
+ return { details, skillClaims: claims };
458
+ }
459
+ /** A legacy plugin is handed to the backend as a whole directory, so a single skill cannot be
460
+ * dropped out of it the way a portable one can. Report the overlap and let the backend resolve it:
461
+ * PI takes the first skill path, which is the portable copy, and Claude Code keeps both apart under
462
+ * their `<plugin>:<skill>` identities. */
463
+ function warnLegacySkillCollisions(claims, legacySkills) {
464
+ for (const { name, pluginId } of legacySkills) {
465
+ const owner = claims.get(name);
466
+ if (owner === undefined)
467
+ continue;
468
+ log.warn(`Skill '${name}' is provided by both portable plugin '${owner}' and legacy plugin `
469
+ + `'${pluginId}'. Deselect one of them to make the choice explicit.`);
442
470
  }
443
471
  }
444
472
  function addPortablePaths(detail, backend, paths) {
@@ -485,6 +513,6 @@ export function resolvePluginRuntime(options) {
485
513
  if (classified.items.length === 0)
486
514
  return {};
487
515
  const portable = collectPortableDetails(classified.portableSelections, options.backend, runtimeDir, portableMcpEnabled(options.mcpComposition));
488
- assertLegacySkillCollisions(portable.skillNames, classified.selectedLegacySkillNames);
516
+ warnLegacySkillCollisions(portable.skillClaims, classified.selectedLegacySkills);
489
517
  return resolvedRuntime(options.backend, classified.items, portable.details);
490
518
  }
package/dist/entry/app.js CHANGED
@@ -94,6 +94,7 @@ import { loadHookRegistry } from '../store/hook-registry.js';
94
94
  import { emitCortexEvent, initHookBus } from '../core/hook-bus.js';
95
95
  import { CORTEX_VERSION } from '../core/version.js';
96
96
  import { syncManagedPlugins } from '../store/plugin-sync.js';
97
+ import { retireTemplatePluginRefs } from '../store/plugin-retirement.js';
97
98
  import { costRepo } from '../store/cost-repo.js';
98
99
  import { getProfileConfigRevision, PROFILES_FILE, profileRepo, startProfileWatcher, setAdminNotifier as setProfileNotifier } from '../store/profile-repo.js';
99
100
  import { sessionStore } from '../store/session-registry-repo.js';
@@ -436,6 +437,17 @@ process.on('SIGTERM', async () => {
436
437
  // A sealed production trial declares no plugins and keeps its attested config immutable.
437
438
  if (syncManagedAssets)
438
439
  await syncManagedPlugins();
440
+ // Deploying a plugin is only half of shipping it: config/thread-templates/ is written by
441
+ // `cortex init` and never by an upgrade, so an install created before a plugin was added or
442
+ // retired keeps referencing the old set. One-shot rewrite, guarded by its own versions.json key.
443
+ if (syncManagedAssets) {
444
+ try {
445
+ await retireTemplatePluginRefs();
446
+ }
447
+ catch (e) {
448
+ log.warn(`Startup: retireTemplatePluginRefs failed: ${e.message}`);
449
+ }
450
+ }
439
451
  // DR-0012 §3.6: clean up orphan TUI tmux sessions from a previous agent-server lifetime.
440
452
  // We can't re-adopt them (sessionKey↔tmux mapping was never persisted) so the honest move
441
453
  // is to kill any leftovers — otherwise a later session that reuses the same sessionId will
@@ -0,0 +1,41 @@
1
+ /** versions.json key guarding this one-shot rewrite. Present → already run; the user is free to
2
+ * re-add a retired plugin dir by hand afterwards without us stripping it again on next boot. */
3
+ export declare const TEMPLATE_PLUGIN_REFS_KEY = "config/thread-templates/agents";
4
+ /** Plugins that no longer ship, with the last version that did.
5
+ *
6
+ * `lastShippedVersion` is the customization discriminator. A deployed copy at or below it is the
7
+ * stock copy we put there, so dropping its reference loses nothing the user wrote. A copy above it
8
+ * was re-versioned locally — someone is maintaining that plugin themselves, and its reference is
9
+ * left alone. Files on disk are never deleted either way: an unreferenced plugin is inert, and a
10
+ * wrongly-deleted one is unrecoverable. */
11
+ export declare const RETIRED_TEMPLATE_PLUGINS: ReadonlyArray<{
12
+ name: string;
13
+ lastShippedVersion: string;
14
+ }>;
15
+ /** Plugin dirs that started shipping after older installs were created, keyed by the agent files
16
+ * whose shipped definition carries them. Deployed templates are never rewritten by an upgrade, so
17
+ * without this a newly bundled plugin lands in DATA_DIR/plugins and is never loaded by anything. */
18
+ export declare const ADDED_TEMPLATE_PLUGIN_DIRS: ReadonlyArray<{
19
+ agents: readonly string[];
20
+ dir: string;
21
+ }>;
22
+ export interface RetirementOptions {
23
+ /** Override DATA_DIR. Tests point this at a temp tree; production passes nothing. */
24
+ dataDir?: string;
25
+ /** Override DATA_DIR/plugins. Defaults to `<dataDir>/plugins`. */
26
+ pluginsDir?: string;
27
+ /** Override the versions.json directory. Defaults to `<dataDir>/data`. */
28
+ storeDir?: string;
29
+ }
30
+ /**
31
+ * One-shot rewrite of deployed agent templates so they match the plugin set that actually ships.
32
+ *
33
+ * Drops pluginDirs entries pointing at a retired plugin whose deployed copy is missing (a dead
34
+ * pointer) or stock (ours to retire), and adds plugin dirs that began shipping after the install
35
+ * was created. Locally customized retired plugins keep their references. Nothing on disk is
36
+ * deleted, and agent files the rewrite does not change are not rewritten at all.
37
+ *
38
+ * Guarded by a versions.json sentinel so it runs exactly once per install: afterwards the user can
39
+ * re-add any of these dirs by hand and it stays. Returns the agent file names that changed.
40
+ */
41
+ export declare function retireTemplatePluginRefs(opts?: RetirementOptions): Promise<string[]>;
@@ -0,0 +1,154 @@
1
+ // input: DATA_DIR/config/thread-templates/agents/*.json + DATA_DIR/plugins + versions.json sentinel
2
+ // output: retireTemplatePluginRefs() — drops references to retired plugins from deployed agent
3
+ // templates and adds plugin dirs that shipped after the install was created
4
+ // pos: Startup asset-sync sibling to syncManagedPlugins; supplies the half of plugin retirement
5
+ // that plugin-sync cannot do. plugin-sync owns DATA_DIR/plugins (copy shipped files, prune
6
+ // RETIRED_PLUGIN_PATHS); this owns the *references* to those plugins. Without it a plugin
7
+ // that stops shipping keeps loading forever on existing installs — nothing deletes the
8
+ // deployed copy, and config/thread-templates/ is only ever written by `cortex init`, which
9
+ // an upgrade does not run (postinstall restarts the daemon, it does not re-init).
10
+ //
11
+ // CONVENTION: retiring or moving a plugin takes THREE edits, not one.
12
+ // 1. remove it from defaults/plugins/ and from the shipped templates' pluginDirs
13
+ // 2. add it to RETIRED_TEMPLATE_PLUGINS here, with the last version you shipped
14
+ // 3. if individual skills moved between plugins, add RETIRED_PLUGIN_PATHS entries in
15
+ // plugin-sync.ts so the old copy stops competing with the new one
16
+ // Step 1 alone is a no-op for every existing install.
17
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
18
+ import * as fs from 'node:fs/promises';
19
+ import * as path from 'node:path';
20
+ import { DATA_DIR, PLUGINS_DIR, STORE_DIR } from '../core/paths.js';
21
+ import { atomicWrite } from '../core/atomic-write.js';
22
+ import { CORTEX_VERSION } from '../core/version.js';
23
+ import { createLogger } from '../core/log.js';
24
+ import { parsePluginVersion } from './plugin-sync.js';
25
+ import { compareCalVer, loadVersionsFrom, saveVersionsTo } from './version-migrations.js';
26
+ const log = createLogger('plugin-retirement');
27
+ /** versions.json key guarding this one-shot rewrite. Present → already run; the user is free to
28
+ * re-add a retired plugin dir by hand afterwards without us stripping it again on next boot. */
29
+ export const TEMPLATE_PLUGIN_REFS_KEY = 'config/thread-templates/agents';
30
+ /** Plugins that no longer ship, with the last version that did.
31
+ *
32
+ * `lastShippedVersion` is the customization discriminator. A deployed copy at or below it is the
33
+ * stock copy we put there, so dropping its reference loses nothing the user wrote. A copy above it
34
+ * was re-versioned locally — someone is maintaining that plugin themselves, and its reference is
35
+ * left alone. Files on disk are never deleted either way: an unreferenced plugin is inert, and a
36
+ * wrongly-deleted one is unrecoverable. */
37
+ export const RETIRED_TEMPLATE_PLUGINS = [
38
+ // Trimmed from the bundled set in 2026.9.8 (commit e50411c58).
39
+ { name: 'cortex-common', lastShippedVersion: '0.1.5' },
40
+ { name: 'cortex-coder', lastShippedVersion: '0.1.2' },
41
+ { name: 'cortex-stage-gate', lastShippedVersion: '0.1.4' },
42
+ ];
43
+ /** Plugin dirs that started shipping after older installs were created, keyed by the agent files
44
+ * whose shipped definition carries them. Deployed templates are never rewritten by an upgrade, so
45
+ * without this a newly bundled plugin lands in DATA_DIR/plugins and is never loaded by anything. */
46
+ export const ADDED_TEMPLATE_PLUGIN_DIRS = [
47
+ // cortex-commission split out of cortex-system in 2026.9.8; loads only where commissions start.
48
+ { agents: ['main', 'direct', 'direct-web'], dir: 'plugins/cortex-commission' },
49
+ ];
50
+ /** Which retired plugin a pluginDirs entry points at, or null if it points elsewhere.
51
+ * Only direct children of DATA_DIR/plugins count — an entry aimed anywhere else is the user's
52
+ * own layout and not ours to rewrite. */
53
+ function retiredNameOf(entry, dataDir) {
54
+ const abs = path.isAbsolute(entry) ? entry : path.resolve(dataDir, entry);
55
+ const rel = path.relative(path.join(dataDir, 'plugins'), abs);
56
+ if (!rel || rel.startsWith('..') || rel.includes(path.sep))
57
+ return null;
58
+ return RETIRED_TEMPLATE_PLUGINS.some((p) => p.name === rel) ? rel : null;
59
+ }
60
+ /** Classify the deployed copy of a retired plugin. A manifest we cannot read counts as customized:
61
+ * the safe default when we cannot prove the copy is ours is to leave it wired up. */
62
+ async function classifyRetired(pluginsDir, name, lastShippedVersion) {
63
+ let manifest;
64
+ try {
65
+ manifest = await fs.readFile(path.join(pluginsDir, name, '.claude-plugin', 'plugin.json'), 'utf8');
66
+ }
67
+ catch (e) {
68
+ return e.code === 'ENOENT' ? 'absent' : 'customized';
69
+ }
70
+ const deployed = parsePluginVersion(manifest);
71
+ if (!deployed)
72
+ return 'customized';
73
+ return compareCalVer(deployed, lastShippedVersion) <= 0 ? 'stock' : 'customized';
74
+ }
75
+ async function listAgentFiles(agentsDir) {
76
+ try {
77
+ return (await fs.readdir(agentsDir)).filter((f) => f.endsWith('.json')).sort();
78
+ }
79
+ catch (e) {
80
+ if (e.code !== 'ENOENT') {
81
+ log.warn(`cannot read ${agentsDir}: ${e.message}`);
82
+ }
83
+ return [];
84
+ }
85
+ }
86
+ /**
87
+ * One-shot rewrite of deployed agent templates so they match the plugin set that actually ships.
88
+ *
89
+ * Drops pluginDirs entries pointing at a retired plugin whose deployed copy is missing (a dead
90
+ * pointer) or stock (ours to retire), and adds plugin dirs that began shipping after the install
91
+ * was created. Locally customized retired plugins keep their references. Nothing on disk is
92
+ * deleted, and agent files the rewrite does not change are not rewritten at all.
93
+ *
94
+ * Guarded by a versions.json sentinel so it runs exactly once per install: afterwards the user can
95
+ * re-add any of these dirs by hand and it stays. Returns the agent file names that changed.
96
+ */
97
+ export async function retireTemplatePluginRefs(opts = {}) {
98
+ const dataDir = opts.dataDir ?? DATA_DIR;
99
+ const pluginsDir = opts.pluginsDir ?? (opts.dataDir ? path.join(opts.dataDir, 'plugins') : PLUGINS_DIR);
100
+ const storeDir = opts.storeDir ?? (opts.dataDir ? path.join(opts.dataDir, 'data') : STORE_DIR);
101
+ const versionsFile = path.join(storeDir, 'versions.json');
102
+ const versions = await loadVersionsFrom(versionsFile);
103
+ if (versions[TEMPLATE_PLUGIN_REFS_KEY])
104
+ return [];
105
+ const agentsDir = path.join(dataDir, 'config', 'thread-templates', 'agents');
106
+ const files = await listAgentFiles(agentsDir);
107
+ // Classify each retired plugin once, not once per file.
108
+ const states = new Map();
109
+ for (const { name, lastShippedVersion } of RETIRED_TEMPLATE_PLUGINS) {
110
+ states.set(name, await classifyRetired(pluginsDir, name, lastShippedVersion));
111
+ }
112
+ const changed = [];
113
+ for (const file of files) {
114
+ const absPath = path.join(agentsDir, file);
115
+ let agent;
116
+ try {
117
+ agent = JSON.parse(await fs.readFile(absPath, 'utf8'));
118
+ }
119
+ catch (e) {
120
+ log.warn(`skipping ${file}: ${e.message}`);
121
+ continue;
122
+ }
123
+ const dirs = agent.pluginDirs;
124
+ if (!Array.isArray(dirs) || !dirs.every((d) => typeof d === 'string'))
125
+ continue;
126
+ const kept = dirs.filter((entry) => {
127
+ const name = retiredNameOf(entry, dataDir);
128
+ if (!name)
129
+ return true;
130
+ const state = states.get(name);
131
+ if (state === 'customized')
132
+ return true;
133
+ log.info(`${file}: dropping ${entry} (${state} retired plugin)`);
134
+ return false;
135
+ });
136
+ const agentName = file.replace(/\.json$/, '');
137
+ for (const { agents, dir } of ADDED_TEMPLATE_PLUGIN_DIRS) {
138
+ if (!agents.includes(agentName) || kept.includes(dir))
139
+ continue;
140
+ kept.push(dir);
141
+ log.info(`${file}: adding ${dir}`);
142
+ }
143
+ if (kept.length === dirs.length && kept.every((d, i) => d === dirs[i]))
144
+ continue;
145
+ agent.pluginDirs = kept;
146
+ await atomicWrite(absPath, JSON.stringify(agent, null, 2) + '\n');
147
+ changed.push(file);
148
+ }
149
+ versions[TEMPLATE_PLUGIN_REFS_KEY] = CORTEX_VERSION;
150
+ await saveVersionsTo(versionsFile, versions);
151
+ if (changed.length > 0)
152
+ log.info(`rewrote plugin refs in ${changed.length} agent template(s)`);
153
+ return changed;
154
+ }
@@ -27,6 +27,9 @@ const MANIFEST_REL = path.join('.claude-plugin', 'plugin.json');
27
27
  export const RETIRED_PLUGIN_PATHS = [
28
28
  // Moved to cortex-commission, which loads only in commission mode (DR-0037 v2).
29
29
  ['cortex-system', 'skills/commission'],
30
+ // Moved to cortex-system in 2026.9.8. Left in place it shadows the maintained copy: an install
31
+ // that still loads cortex-stage-gate would offer two skills named `task` with diverged content.
32
+ ['cortex-stage-gate', 'skills/task'],
30
33
  ];
31
34
  /** Remove retired paths from the deployed tree. Returns the plugin-relative ids actually removed. */
32
35
  export async function pruneRetiredPluginPaths(dstDir) {
@@ -30,6 +30,10 @@ export declare function upsertMarkerBlock(content: string, block: string): strin
30
30
  * customized away from the shipped wording simply won't match and is left untouched,
31
31
  * preserving their edits. */
32
32
  export declare function applyReplacements(content: string, pairs: ReadonlyArray<readonly [string, string]>): string;
33
+ /** Exported for plugin-retirement.ts, which guards its own one-shot rewrite with a sentinel key
34
+ * in the same versions.json. Keeping one reader means one definition of "corrupt → reset". */
35
+ export declare function loadVersionsFrom(filePath: string): Promise<Record<string, string>>;
36
+ export declare function saveVersionsTo(filePath: string, versions: Record<string, string>): Promise<void>;
33
37
  export interface MigrationOptions {
34
38
  /** Override DATA_DIR (user config location). Defaults to the real CORTEX_HOME. */
35
39
  dataDir?: string;
@@ -373,7 +373,9 @@ const migrations = [
373
373
  })),
374
374
  ];
375
375
  // ── Versions file I/O ──────────────────────────────────────────
376
- async function loadVersionsFrom(filePath) {
376
+ /** Exported for plugin-retirement.ts, which guards its own one-shot rewrite with a sentinel key
377
+ * in the same versions.json. Keeping one reader means one definition of "corrupt → reset". */
378
+ export async function loadVersionsFrom(filePath) {
377
379
  try {
378
380
  const raw = await fs.readFile(filePath, 'utf8');
379
381
  const parsed = JSON.parse(raw);
@@ -396,7 +398,7 @@ async function loadVersionsFrom(filePath) {
396
398
  throw err;
397
399
  }
398
400
  }
399
- async function saveVersionsTo(filePath, versions) {
401
+ export async function saveVersionsTo(filePath, versions) {
400
402
  await atomicWrite(filePath, JSON.stringify(versions, null, 2) + '\n');
401
403
  }
402
404
  // ── Defaults loader ────────────────────────────────────────────
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortex-agent/server",
3
- "version": "2026.9.9",
3
+ "version": "2026.9.10",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Autonomous agent system for long-running projects — mission-driven, multi-agent pipelines, self-evolving skills.",
@@ -1 +1 @@
1
- import{i,a as f}from"./index-DMImrhdJ.js";var o;(function(n){n.Year="year",n.Month="month",n.TwoWeeks="twoWeeks",n.Week="week",n.Day="day",n.Hour="hour",n.Minute="minute",n.Second="second"})(o||(o={}));class s{static at(t,e=!1,a=!1){return{at:{date:t,repeating:e,allowWhileIdle:a},interval:void 0,every:void 0}}static interval(t,e=!1){return{at:void 0,interval:{interval:t,allowWhileIdle:e},every:void 0}}static every(t,e,a=!1){return{at:void 0,interval:void 0,every:{interval:t,count:e,allowWhileIdle:a}}}}var c;(function(n){n[n.None=0]="None",n[n.Min=1]="Min",n[n.Low=2]="Low",n[n.Default=3]="Default",n[n.High=4]="High"})(c||(c={}));var r;(function(n){n[n.Secret=-1]="Secret",n[n.Private=0]="Private",n[n.Public=1]="Public"})(r||(r={}));async function l(){return window.Notification.permission!=="default"?await Promise.resolve(window.Notification.permission==="granted"):await i("plugin:notification|is_permission_granted")}async function w(){return await window.Notification.requestPermission()}function d(n){typeof n=="string"?new window.Notification(n):new window.Notification(n.title,n)}async function g(n){await i("plugin:notification|register_action_types",{types:n})}async function v(){return await i("plugin:notification|get_pending")}async function y(n){await i("plugin:notification|cancel",{notifications:n})}async function p(){await i("plugin:notification|cancel")}async function P(){return await i("plugin:notification|get_active")}async function _(n){await i("plugin:notification|remove_active",{notifications:n})}async function m(){await i("plugin:notification|remove_active")}async function N(n){await i("plugin:notification|create_channel",{...n})}async function h(n){await i("plugin:notification|delete_channel",{id:n})}async function A(){return await i("plugin:notification|listChannels")}async function k(n){return await f("notification","notification",n)}async function M(n){return await f("notification","actionPerformed",n)}export{c as Importance,s as Schedule,o as ScheduleEvery,r as Visibility,P as active,y as cancel,p as cancelAll,A as channels,N as createChannel,l as isPermissionGranted,M as onAction,k as onNotificationReceived,v as pending,g as registerActionTypes,_ as removeActive,m as removeAllActive,h as removeChannel,w as requestPermission,d as sendNotification};
1
+ import{i,a as f}from"./index-TPdC4ItK.js";var o;(function(n){n.Year="year",n.Month="month",n.TwoWeeks="twoWeeks",n.Week="week",n.Day="day",n.Hour="hour",n.Minute="minute",n.Second="second"})(o||(o={}));class s{static at(t,e=!1,a=!1){return{at:{date:t,repeating:e,allowWhileIdle:a},interval:void 0,every:void 0}}static interval(t,e=!1){return{at:void 0,interval:{interval:t,allowWhileIdle:e},every:void 0}}static every(t,e,a=!1){return{at:void 0,interval:void 0,every:{interval:t,count:e,allowWhileIdle:a}}}}var c;(function(n){n[n.None=0]="None",n[n.Min=1]="Min",n[n.Low=2]="Low",n[n.Default=3]="Default",n[n.High=4]="High"})(c||(c={}));var r;(function(n){n[n.Secret=-1]="Secret",n[n.Private=0]="Private",n[n.Public=1]="Public"})(r||(r={}));async function l(){return window.Notification.permission!=="default"?await Promise.resolve(window.Notification.permission==="granted"):await i("plugin:notification|is_permission_granted")}async function w(){return await window.Notification.requestPermission()}function d(n){typeof n=="string"?new window.Notification(n):new window.Notification(n.title,n)}async function g(n){await i("plugin:notification|register_action_types",{types:n})}async function v(){return await i("plugin:notification|get_pending")}async function y(n){await i("plugin:notification|cancel",{notifications:n})}async function p(){await i("plugin:notification|cancel")}async function P(){return await i("plugin:notification|get_active")}async function _(n){await i("plugin:notification|remove_active",{notifications:n})}async function m(){await i("plugin:notification|remove_active")}async function N(n){await i("plugin:notification|create_channel",{...n})}async function h(n){await i("plugin:notification|delete_channel",{id:n})}async function A(){return await i("plugin:notification|listChannels")}async function k(n){return await f("notification","notification",n)}async function M(n){return await f("notification","actionPerformed",n)}export{c as Importance,s as Schedule,o as ScheduleEvery,r as Visibility,P as active,y as cancel,p as cancelAll,A as channels,N as createChannel,l as isPermissionGranted,M as onAction,k as onNotificationReceived,v as pending,g as registerActionTypes,_ as removeActive,m as removeAllActive,h as removeChannel,w as requestPermission,d as sendNotification};