dsh-taskbridge 1.8.0 → 1.9.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 (50) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +246 -231
  3. package/antigravity/agents/dsh-taskbridge.md +17 -14
  4. package/antigravity/skills/dsh-taskbridge/SKILL.md +40 -27
  5. package/bin/dsh-delegate-codex-agent.js +9 -4
  6. package/codex/skills/dsh-taskbridge/SKILL.md +131 -0
  7. package/codex/skills/dsh-taskbridge/rules-reference-96027c387cb9b7587efa4aa3836235d86db1108068e007dc08196e807ca25e5d.md +114 -0
  8. package/docs/INTRODUCTION.md +148 -119
  9. package/docs/INTRODUCTION.zh.md +151 -134
  10. package/docs/antigravity-integration.md +47 -42
  11. package/docs/assets/taskbridge-workflow.en.svg +72 -0
  12. package/docs/assets/taskbridge-workflow.zh.png +0 -0
  13. package/docs/claude-code.md +18 -18
  14. package/docs/codex-integration.md +139 -113
  15. package/docs/conversation-placement.md +7 -6
  16. package/docs/releases/1.8.0.zh.md +16 -16
  17. package/docs/releases/1.8.1.zh.md +24 -0
  18. package/docs/releases/1.9.0.zh.md +31 -0
  19. package/docs/runtime-compatibility.md +7 -9
  20. package/docs/silent-wait.md +17 -26
  21. package/docs/taskbridge-upgrade.md +4 -4
  22. package/lib/client.d.ts +74 -3
  23. package/lib/client.js +7 -7
  24. package/locale/en.json +7 -7
  25. package/locale/zh.json +7 -7
  26. package/package.json +11 -4
  27. package/src/antigravity/installer.js +1099 -1046
  28. package/src/antigravity/seam.js +142 -142
  29. package/src/client/api.js +258 -16
  30. package/src/client/index.jsx +130 -26
  31. package/src/client/task-cleanup.js +130 -5
  32. package/src/codex/agent-ownership.js +72 -12
  33. package/src/codex/installer.js +691 -268
  34. package/src/config/defaults.js +11 -15
  35. package/src/http/execution-plane.js +17 -0
  36. package/src/http/user-plane.js +17 -1
  37. package/src/index.d.ts +9 -1
  38. package/src/index.js +86 -64
  39. package/src/jobs/engine.js +279 -5
  40. package/src/jobs/history.js +18 -2
  41. package/src/jobs/plan-store.js +83 -0
  42. package/src/jobs/record-cleanup.js +714 -195
  43. package/src/mcp/server.js +271 -38
  44. package/src/mcp/wait.js +34 -15
  45. package/src/runtime/agent-runner.js +1 -0
  46. package/src/runtime/permissions.js +18 -0
  47. package/src/runtime/session-placement.js +36 -1
  48. package/src/runtime/worker-prompt.js +14 -9
  49. package/src/workspace/worktrees.js +155 -1
  50. package/codex/dsh-taskbridge.toml +0 -170
@@ -1,13 +1,16 @@
1
- // Codex integration: install the companion custom agent and register this
2
- // package's stdio MCP server in Codex.
1
+ // Codex integration: install the native Codex skill and register this
2
+ // package's stdio MCP server in Codex, while safely retiring untouched
3
+ // legacy managed subagent files (`agents/dsh-taskbridge.toml` and
4
+ // `agents/dsh-delegate.toml`) from 0.1.6–1.8.x releases.
3
5
  //
4
6
  // Scope, stated once and enforced below
5
7
  // -------------------------------------
6
- // This module owns exactly two things in a Codex home:
8
+ // This module owns exactly two active targets in a Codex home:
7
9
  //
8
- // 1. `$CODEX_HOME/agents/dsh-taskbridge.toml` — a *managed copy* of the shipped
9
- // template `codex/dsh-taskbridge.toml`. Ownership is proved by content, never by
10
- // the file name or a version line alone:
10
+ // 1. `$CODEX_HOME/skills/dsh-taskbridge/SKILL.md` — a *managed copy* of the shipped
11
+ // template `codex/skills/dsh-taskbridge/SKILL.md` and the reference it links to.
12
+ // Ownership is proved by content,
13
+ // never by the file name or a version marker alone:
11
14
  // * a file that is the same text as the template this build would write is
12
15
  // `installed` (and removable). "Same text" admits exactly one difference: CRLF
13
16
  // versus LF line terminators (including a mixed spelling of the same lines).
@@ -81,7 +84,7 @@
81
84
  // say what the file can and cannot guarantee.
82
85
 
83
86
  import { lstatSync } from 'node:fs';
84
- import { link, lstat, mkdir, open, readFile, readlink, realpath, stat, unlink } from 'node:fs/promises';
87
+ import { link, lstat, mkdir, open, readFile, readlink, realpath, rmdir, stat, unlink } from 'node:fs/promises';
85
88
  import { execFile } from 'node:child_process';
86
89
  import { createHash, randomBytes } from 'node:crypto';
87
90
  import { homedir } from 'node:os';
@@ -89,7 +92,15 @@ import { basename, delimiter, dirname, isAbsolute, join, parse, resolve, sep } f
89
92
  import { fileURLToPath } from 'node:url';
90
93
 
91
94
  import { writeFileAtomic } from '../config/store.js';
92
- import { recallTemplateDigest, rememberTemplateDigest, digestLf } from './agent-ownership.js';
95
+ import {
96
+ chainPathsOf,
97
+ ownershipRecordPath,
98
+ recallSkillTemplateDigest,
99
+ recallTemplateDigest,
100
+ rememberSkillTemplateDigest,
101
+ skillOwnershipRecordPath,
102
+ digestLf,
103
+ } from './agent-ownership.js';
93
104
  import {
94
105
  TomlDocument,
95
106
  TomlSyntaxError,
@@ -100,7 +111,12 @@ import {
100
111
  tomlValueType,
101
112
  } from './toml.js';
102
113
 
103
- /** Agent file name inside `$CODEX_HOME/agents`. */
114
+ /** Native Codex skill directory and file name inside `$CODEX_HOME/skills`. */
115
+ export const SKILL_DIR_NAME = 'dsh-taskbridge';
116
+ export const SKILL_FILENAME = 'SKILL.md';
117
+ export const SKILL_RELATIVE_PATH = join('skills', SKILL_DIR_NAME, SKILL_FILENAME);
118
+
119
+ /** Legacy retired subagent file names inside `$CODEX_HOME/agents` (recognised for safe cleanup). */
104
120
  export const AGENT_FILENAME = 'dsh-taskbridge.toml';
105
121
  export const LEGACY_AGENT_FILENAME = 'dsh-delegate.toml';
106
122
 
@@ -522,10 +538,47 @@ export const KNOWN_AGENT_TEMPLATES = [
522
538
  // Published 1.7.1 companion before the 1.8.0 black-box simplification, in LF and CRLF.
523
539
  { version: '1.7.1', sha256: '5a55b978c3de4f7cec8922d1af5302ef46b0bcbda867bfe53faebac1980eb1b3' },
524
540
  { version: '1.7.1', sha256: '026157837e2a99c5a265badb2ca6dc77be1ddcac28871e5949b80e61c949bfa0' },
541
+ // Published 1.8.0 companion before the 1.8.1 dual-client symmetry and Q&A boundary refinement, in LF and CRLF.
542
+ { version: '1.8.0', sha256: 'ba3c964cad6b9ae395dbe0d74971a430795fd8927a4a5daeb6a45617823a9cab' },
543
+ { version: '1.8.0', sha256: '6f732230068f3230f9ad1c6a92d30d677f717dd0b0ebd92abb73ed7578f956dd' },
544
+ // Published 1.8.1 companion before the 1.9.0 migration to native Codex Skill, in LF and CRLF.
545
+ { version: '1.8.1', sha256: 'dc09680bcf6927ca1019554f1e841a176ac7035236f329ce008f45be06b9fb82' },
546
+ { version: '1.8.1', sha256: 'addc76a5c9c47e64e2b7f30750e0bcbdfefe060dc6a2d5e3ebcf93252e072850' },
547
+ // Local 1.8.2-test2 companion before the 1.9.0 migration to native Codex Skill, in LF and CRLF.
548
+ { version: '1.8.2-test2', sha256: '596177b7c3fe8fa446d50f670a546a2ae884a717c476eaaae63e637124b10d64' },
549
+ { version: '1.8.2-test2', sha256: '6452e8672fd3628fe6a5650e21bb4bb9925e7ff0d090bae9330427325975d915' },
550
+ ];
551
+
552
+ /** Exact shipped `skills/dsh-taskbridge/SKILL.md` files of earlier 1.9+ builds (SHA-256). */
553
+ export const KNOWN_SKILL_TEMPLATES = [
554
+ // Local 1.9.0-test1 native Codex skill before layered integrations/ refactor, in LF and CRLF.
555
+ { version: '1.9.0-test1', sha256: '815ec71d75e8089dd1d726b5bb07cd7ad2e3a3dec444e7dca76b83cce064b565' },
556
+ { version: '1.9.0-test1', sha256: '9777da3423c1a5c8d6cf50f0f161ab0f6e5b064708670f32abf6e6c4a4fffda0' },
557
+ // Local test packages with layered integration rules, in LF and CRLF.
558
+ { version: '1.9.0-test2', sha256: '5ed46037522e854fb31c6bfb3ecefc751e85a4d1a445b2e0830cee40b0738d5b' },
559
+ { version: '1.9.0-test2', sha256: '71b84788ab13749776f0ffa97d2be77e0b0296d1deff59b556eccdb95f681271' },
560
+ { version: '1.9.0-test3', sha256: 'd381022187327e9aff453588239b1664f6b9b7fc2f895e11701d4148e1330b82' },
561
+ { version: '1.9.0-test3', sha256: '5a0b5100b67a35600ead1c3b75d2e03a92e1fee10709e46e8ddd93661b59ddfc' },
562
+ { version: '1.9.0-test4', sha256: 'f67b394705485d3dd3e7219bde9f05d7720410eeeaa234c5da6dc68f89e3c7ca' },
563
+ { version: '1.9.0-test4', sha256: '7740c10f5f84f6fa309bdba67c10721dda6754b66f6b56236ca400ba6b9644af' },
564
+ { version: '1.9.0-test5', sha256: '709e7c18aef5c54e371f6830ac9c837fbfcb5963b26e4019ef5f9e491864df24' },
565
+ { version: '1.9.0-test5', sha256: '6e30655cb97200c3a3bbf6545ad90da1cc3e464363646e506f3075825cedf55d' },
566
+ { version: '1.9.0-pre', sha256: 'd8878f88e60a4d46079f7fde93408d21c1e517c76d1bad86a7814d40603d729d' },
567
+ { version: '1.9.0-pre', sha256: 'e2b8ec097cdedcbbbdf811870d566cb1fb36f6882d579db67a0f33f08c78da98' },
568
+ { version: '1.9.0-pre', sha256: '64560e14664ab0b932c36a5e2560c35ef5acf7cdbf38acf522e87e8aefbd53b7' },
569
+ { version: '1.9.0-pre', sha256: 'db1526280a0618a379db8dbe1c71840204a5957907a92b20bd3f43fd00971c0f' },
570
+ { version: '1.9.0-test6', sha256: 'c2477b9233f4f9b4e36c59f8544f607249b2f96be0aeba0a013525e18c4eab38' },
571
+ { version: '1.9.0-test6', sha256: '238366a0ebaa543d6b09fd1a94d5507a22d5ba0d19fee32539c429d1ded2182c' },
572
+ { version: '1.9.0-preview', sha256: 'eefe1134216d3d73901ec8e279e8752b4281dd191343e180fb76c671055c4523' },
573
+ { version: '1.9.0-preview', sha256: '0f28427153bda6e696fc6203d3ac885067ac22902b716e6ecbce6a2a0e693148' },
574
+ { version: '1.9.0-preview2', sha256: 'bc1a1be12d5117efe52ed5c10e4d25cac4713b9746c41096cc6f5e75efada40d' },
575
+ { version: '1.9.0-preview2', sha256: '6a2684b21762157edf3b32ddccea81d6327b117454cdb74e0c7260803f46d4be' },
576
+ { version: '1.9.0-preview3', sha256: 'c3b3d6ad273f55ec822cde3f6635f875103c339d65821601d3baaddac85af4d7' },
577
+ { version: '1.9.0-preview3', sha256: '1237d095f32a0c4ac1d5dde8f05f11b6edf17d863ff1bb67ab63a17f6ac2fe3b' },
525
578
  ];
526
579
 
527
- /** The `version = "…"` line of an agent file, at column 0. */
528
- const VERSION_LINE = /^version[ \t]*=[ \t]*"([^"]*)"\r?$/mu;
580
+ /** The version provenance comment line inside a shipped Markdown Codex skill file. */
581
+ const SKILL_VERSION_LINE = /^<!-- dsh-taskbridge-version: ([^>\r\n]+) -->\r?$/mu;
529
582
 
530
583
  /**
531
584
  * Read agent text with CRLF terminators folded to LF.
@@ -575,29 +628,23 @@ function sameAgentText(contents, template) {
575
628
  * Everything else still fails too: an added or removed line, a comment, a trailing space, a tab,
576
629
  * a BOM, a changed version line or any other edit hashes to nothing in the table.
577
630
  * @param {string} contents - installed file text.
578
- * @param {object} [options] - `ignoreVersion`: compare with the version line masked, used only
579
- * to explain *why* a file is `modified` in the status note. It never grants refresh or removal.
580
631
  * @returns {boolean} true when the file is a known published build of this template.
581
632
  */
582
- export function isKnownPriorTemplate(contents, { ignoreVersion = false } = {}) {
633
+ export function isKnownPriorTemplate(contents) {
583
634
  if (typeof contents !== 'string') return false;
584
- const known = (text) => KNOWN_AGENT_TEMPLATES.some((entry) => entry.sha256 === digest(text));
635
+ const known = (text) => {
636
+ const sha256 = digest(text);
637
+ return KNOWN_AGENT_TEMPLATES.some((entry) => entry.sha256 === sha256)
638
+ || KNOWN_SKILL_TEMPLATES.some((entry) => entry.sha256 === sha256);
639
+ };
585
640
  if (known(contents)) return true;
586
641
  const lf = normalizeLineEndings(contents);
587
642
  // A leftover `\r` means the file has a CR no spelling fold accounts for, so no equivalent
588
- // digest may claim it. This guard wraps ONLY the equivalent branch; the diagnosis below is
589
- // still reachable for such a file.
590
- if (!lf.includes('\r')) {
591
- if (known(lf)) return true;
592
- const crlf = lf.replace(/\n/gu, '\r\n');
593
- if (crlf !== contents && known(crlf)) return true;
594
- }
595
- if (!ignoreVersion) return false;
596
- // Explanation-only path: the same body with the version line stripped still has to
597
- // match a known build, which distinguishes "operator edited a managed file" from
598
- // "this file was never ours".
599
- const stripped = contents.replace(VERSION_LINE, 'version = "\u0000"');
600
- return KNOWN_AGENT_TEMPLATES.some((entry) => entry.sha256 === digest(stripped));
643
+ // digest may claim it.
644
+ if (lf.includes('\r')) return false;
645
+ if (lf !== contents && known(lf)) return true;
646
+ const crlf = lf.replace(/\n/gu, '\r\n');
647
+ return crlf !== contents && known(crlf);
601
648
  }
602
649
 
603
650
  /** Stable states reported for the agent file. */
@@ -651,7 +698,8 @@ const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..'
651
698
  * declare before its entry point can be adopted by an automatic migration.
652
699
  */
653
700
  const PACKAGE_NAME = 'dsh-taskbridge';
654
- const TEMPLATE_PATH = join(PACKAGE_ROOT, 'codex', AGENT_FILENAME);
701
+ const TEMPLATE_PATH = join(PACKAGE_ROOT, 'codex', 'skills', SKILL_DIR_NAME, SKILL_FILENAME);
702
+ const SKILL_REFERENCE_LINK = /\]\((rules-reference-([0-9a-f]{64})\.md)\)/u;
655
703
  const PACKAGE_MANIFEST_PATH = join(PACKAGE_ROOT, 'package.json');
656
704
 
657
705
  /** Bound on a Codex config document this module is willing to edit. */
@@ -1102,25 +1150,65 @@ async function inspectFile(path) {
1102
1150
  * `unknown` means the platform could not say whether the directory is a link.
1103
1151
  */
1104
1152
  export async function inspectDirectory(path) {
1105
- let info;
1106
- try {
1107
- info = await lstat(path);
1108
- } catch (error) {
1109
- if (error?.code === 'ENOENT') return { kind: 'missing' };
1110
- if (error?.code === 'ENOTDIR') return { kind: 'other' };
1111
- throw error;
1153
+ const results = await inspectDirectories([path]);
1154
+ return results.get(path) ?? { kind: 'unknown' };
1155
+ }
1156
+
1157
+ /**
1158
+ * Inspect multiple directory paths in ONE batched platform attribute call on Windows.
1159
+ * @param {string[]} paths - directory paths to inspect.
1160
+ * @returns {Promise<Map<string, { kind: 'missing' | 'directory' | 'link' | 'other' | 'unknown', target?: string }>>}
1161
+ */
1162
+ export async function inspectDirectories(paths) {
1163
+ const unique = [];
1164
+ const seen = new Set();
1165
+ for (const path of paths) {
1166
+ if (typeof path === 'string' && path !== '' && !seen.has(path)) {
1167
+ seen.add(path);
1168
+ unique.push(path);
1169
+ }
1112
1170
  }
1113
- if (info.isSymbolicLink()) return { kind: 'link', target: await readLinkTarget(path) };
1114
- if (!info.isDirectory()) return { kind: 'other' };
1115
- const kinds = await windowsDirectoryKinds([path]);
1116
- const kind = kinds.get(path);
1117
- // A junction is reported by Node as a plain directory; only the attribute proves it.
1118
- // `unknown` (the platform could not answer) is reported as itself: callers must
1119
- // refuse, and must not describe it as a link they never saw.
1120
- if (kind === 'missing') return { kind: 'missing' };
1121
- if (kind === 'unknown') return { kind: 'unknown' };
1122
- if (kind !== 'directory') return { kind: 'link', target: await readLinkTarget(path) };
1123
- return { kind: 'directory' };
1171
+ const results = new Map();
1172
+ const toCheck = [];
1173
+ for (const path of unique) {
1174
+ let info;
1175
+ try {
1176
+ info = await lstat(path);
1177
+ } catch (error) {
1178
+ if (error?.code === 'ENOENT') {
1179
+ results.set(path, { kind: 'missing' });
1180
+ continue;
1181
+ }
1182
+ if (error?.code === 'ENOTDIR') {
1183
+ results.set(path, { kind: 'other' });
1184
+ continue;
1185
+ }
1186
+ throw error;
1187
+ }
1188
+ if (info.isSymbolicLink()) {
1189
+ results.set(path, { kind: 'link', target: await readLinkTarget(path) });
1190
+ continue;
1191
+ }
1192
+ if (!info.isDirectory()) {
1193
+ results.set(path, { kind: 'other' });
1194
+ continue;
1195
+ }
1196
+ toCheck.push(path);
1197
+ }
1198
+ if (toCheck.length > 0) {
1199
+ const kinds = await windowsDirectoryKinds(toCheck);
1200
+ for (const path of toCheck) {
1201
+ const kind = kinds.get(path);
1202
+ // A junction is reported by Node as a plain directory; only the attribute proves it.
1203
+ // `unknown` (the platform could not answer) is reported as itself: callers must
1204
+ // refuse, and must not describe it as a link they never saw.
1205
+ if (kind === 'missing') results.set(path, { kind: 'missing' });
1206
+ else if (kind === 'unknown') results.set(path, { kind: 'unknown' });
1207
+ else if (kind !== 'directory') results.set(path, { kind: 'link', target: await readLinkTarget(path) });
1208
+ else results.set(path, { kind: 'directory' });
1209
+ }
1210
+ }
1211
+ return results;
1124
1212
  }
1125
1213
 
1126
1214
  /**
@@ -1337,19 +1425,60 @@ async function readAgentState(path, template, recordedDigest = null) {
1337
1425
  if (existing.kind === 'missing') return { state: AGENT_STATES.missing, present: false, reason: null, contents: null };
1338
1426
  if (existing.kind === 'other') return { state: AGENT_STATES.conflict, present: true, reason: 'not-a-regular-file', contents: null };
1339
1427
  const contents = existing.contents;
1340
- if (sameAgentText(contents, template)) return { state: AGENT_STATES.installed, present: true, reason: null, contents };
1341
- if (isKnownPriorTemplate(contents)) return { state: AGENT_STATES.outdated, present: true, reason: null, contents };
1342
- if (typeof recordedDigest === 'string' && recordedDigest !== '' && digestLf(contents) === recordedDigest) {
1343
- return { state: AGENT_STATES.outdated, present: true, reason: null, contents, recorded: true };
1344
- }
1428
+ const current = sameAgentText(contents, template);
1429
+ const known = !current && isKnownPriorTemplate(contents);
1430
+ const recorded = !current && !known && recordedDigest !== null && digestLf(contents) === recordedDigest;
1431
+ if (current || known || recorded) {
1432
+ const reference = skillReference(path, contents);
1433
+ if (reference !== null) {
1434
+ const installed = await inspectFile(reference.path);
1435
+ if (installed.kind === 'missing' && current) {
1436
+ return { state: AGENT_STATES.outdated, present: true, reason: 'reference-missing', contents };
1437
+ }
1438
+ if (referenceConflicts(reference, installed)) {
1439
+ return { state: AGENT_STATES.modified, present: true, reason: 'reference-operator-owned', contents };
1440
+ }
1441
+ }
1442
+ const state = current ? AGENT_STATES.installed : AGENT_STATES.outdated;
1443
+ return { state, present: true, reason: null, contents, recorded };
1444
+ }
1445
+ const normalizedContents = normalizeLineEndings(contents);
1446
+ const normalizedTemplate = normalizeLineEndings(template);
1447
+ const sameBodyDifferentVersion = !normalizedContents.includes('\r')
1448
+ && normalizedContents.replace(SKILL_VERSION_LINE, '<!-- dsh-taskbridge-version: \u0000 -->')
1449
+ === normalizedTemplate.replace(SKILL_VERSION_LINE, '<!-- dsh-taskbridge-version: \u0000 -->');
1345
1450
  return {
1346
1451
  state: AGENT_STATES.modified,
1347
1452
  present: true,
1348
- reason: isKnownPriorTemplate(contents, { ignoreVersion: true }) ? 'edited' : 'unknown-content',
1453
+ reason: sameBodyDifferentVersion ? 'edited' : 'unknown-content',
1349
1454
  contents,
1350
1455
  };
1351
1456
  }
1352
1457
 
1458
+ function createBatchedKindClassifier(cache = new Map()) {
1459
+ const classifyMany = async (paths) => {
1460
+ const missing = [];
1461
+ for (const path of paths) {
1462
+ if (typeof path === 'string' && path !== '' && !cache.has(path)) missing.push(path);
1463
+ }
1464
+ if (missing.length > 0) {
1465
+ const inspected = await inspectDirectories(missing);
1466
+ for (const [path, info] of inspected.entries()) {
1467
+ cache.set(path, info.kind);
1468
+ }
1469
+ }
1470
+ const out = new Map();
1471
+ for (const path of paths) out.set(path, cache.get(path) ?? 'unknown');
1472
+ return out;
1473
+ };
1474
+ const classify = async (path) => {
1475
+ if (cache.has(path)) return cache.get(path);
1476
+ const out = await classifyMany([path]);
1477
+ return out.get(path) ?? 'unknown';
1478
+ };
1479
+ return { classify, classifyMany, cache };
1480
+ }
1481
+
1353
1482
  /**
1354
1483
  * The template digest this plugin last proved it wrote into one Codex home, or null.
1355
1484
  *
@@ -1358,22 +1487,78 @@ async function readAgentState(path, template, recordedDigest = null) {
1358
1487
  * file is classified. Nothing is created and nothing is written here.
1359
1488
  * @param {string} home - the REAL, pinned Codex home.
1360
1489
  * @param {Record<string, string | undefined>} env - environment (for `DSH_HOME`).
1490
+ * @param {{ classify: Function, classifyMany: Function }} [batch] - optional shared classifier cache.
1361
1491
  * @returns {Promise<string | null>} LF digest, or null.
1362
1492
  */
1363
- async function recallRecordedTemplate(home, env) {
1493
+ async function recallRecordedTemplate(home, env, batch = createBatchedKindClassifier()) {
1364
1494
  if (typeof home !== 'string' || home.trim() === '' || !isAbsolute(home)) return null;
1365
1495
  try {
1366
- return await recallTemplateDigest({ codexHome: home, env, classify: (path) => inspectDirectory(path).then((info) => info.kind) });
1496
+ return await recallTemplateDigest({
1497
+ codexHome: home,
1498
+ env,
1499
+ classify: batch.classify,
1500
+ classifyMany: batch.classifyMany,
1501
+ });
1502
+ } catch {
1503
+ return null;
1504
+ }
1505
+ }
1506
+
1507
+ async function recallRecordedSkillTemplate(home, env, batch = createBatchedKindClassifier()) {
1508
+ if (typeof home !== 'string' || home.trim() === '' || !isAbsolute(home)) return null;
1509
+ try {
1510
+ return await recallSkillTemplateDigest({
1511
+ codexHome: home,
1512
+ env,
1513
+ classify: batch.classify,
1514
+ classifyMany: batch.classifyMany,
1515
+ });
1367
1516
  } catch {
1368
1517
  return null;
1369
1518
  }
1370
1519
  }
1371
1520
 
1372
1521
  /**
1373
- * Record the template digest after a write this action just made, proved against the file.
1522
+ * Inspect legacy Codex subagent files (`agents/dsh-taskbridge.toml` and `agents/dsh-delegate.toml`)
1523
+ * so untouched prior installs can be migrated to the native skill and safely retired, while
1524
+ * operator-edited files are preserved untouched and surfaced as notes.
1525
+ */
1526
+ async function inspectLegacyAgents(home, recordedAgentDigest = null) {
1527
+ const filenames = [AGENT_FILENAME, LEGACY_AGENT_FILENAME];
1528
+ const entries = [];
1529
+ for (const filename of filenames) {
1530
+ const filePath = join(home, 'agents', filename);
1531
+ const inspected = await inspectFile(filePath);
1532
+ if (inspected.kind === 'missing') continue;
1533
+ if (inspected.kind === 'other') {
1534
+ entries.push({ filename, path: filePath, state: 'conflict', expect: null });
1535
+ continue;
1536
+ }
1537
+ const contents = inspected.contents;
1538
+ const isManaged = isKnownPriorTemplate(contents)
1539
+ || (typeof recordedAgentDigest === 'string' && recordedAgentDigest !== '' && digestLf(contents) === recordedAgentDigest);
1540
+ entries.push({
1541
+ filename,
1542
+ path: filePath,
1543
+ state: isManaged ? 'managed-legacy' : 'modified-legacy',
1544
+ expect: isManaged ? contents : null,
1545
+ });
1546
+ }
1547
+ const state = entries.some((entry) => entry.state === 'managed-legacy')
1548
+ ? 'managed-legacy'
1549
+ : entries.some((entry) => entry.state === 'modified-legacy')
1550
+ ? 'modified-legacy'
1551
+ : entries.some((entry) => entry.state === 'conflict')
1552
+ ? 'conflict'
1553
+ : 'absent';
1554
+ return { state, entries };
1555
+ }
1556
+
1557
+ /**
1558
+ * Record the skill template digest after a write this action just made, proved against the file.
1374
1559
  *
1375
1560
  * Called only from `install` and from the startup `refreshKnownAgentTemplate`, and only after the
1376
- * write reported success: it re-reads the agent file, requires it to be exactly the rendered
1561
+ * write reported success: it re-reads the skill file, requires it to be exactly the rendered
1377
1562
  * template, and records the digest of THOSE bytes. `repair`, `remove` and `status` never reach
1378
1563
  * this. A failed record is a lost proof for the next release, never a failed install.
1379
1564
  * @param {object} before - the status the write was planned from.
@@ -1383,99 +1568,177 @@ async function recordAgentTemplate(before) {
1383
1568
  const env = before[INTERNAL_ENV];
1384
1569
  if (env === undefined) return;
1385
1570
  try {
1386
- await rememberTemplateDigest({
1571
+ const classify = (path) => inspectDirectory(path).then((info) => info.kind);
1572
+ const classifyMany = async (paths) => {
1573
+ const inspected = await inspectDirectories(paths);
1574
+ const out = new Map();
1575
+ for (const path of paths) out.set(path, inspected.get(path)?.kind ?? 'unknown');
1576
+ return out;
1577
+ };
1578
+ await rememberSkillTemplateDigest({
1387
1579
  codexHome: before.codexHome,
1388
1580
  env,
1389
1581
  template: renderAgentFile(await readAgentTemplate(), before.packageVersion),
1390
- agentPath: before.agent.path,
1582
+ skillPath: before.agent.path,
1391
1583
  readFile: async (path) => (await inspectFile(path)).contents,
1392
1584
  writeFileAtomic,
1393
1585
  mkdir,
1394
- classify: (path) => inspectDirectory(path).then((info) => info.kind),
1586
+ classify,
1587
+ classifyMany,
1395
1588
  });
1396
1589
  } catch {
1397
1590
  // A proof that cannot be recorded must never fail the install that produced it, and a
1398
- // refused record (a linked ancestor, a damaged file) is no record: the agent file stays
1591
+ // refused record (a linked ancestor, a damaged file) is no record: the skill file stays
1399
1592
  // classified by its own content.
1400
1593
  }
1401
1594
  }
1402
1595
 
1403
- /**
1404
- * Inspect the two directories that bound what this module may write.
1405
- *
1406
- * `$CODEX_HOME` and `$CODEX_HOME/agents` are the only places the managed files may
1407
- * live. A link at either (a POSIX symlink, or a Windows junction/reparse point that
1408
- * `lstat` reports as a plain directory) means the final path string no longer names
1409
- * a location inside the Codex home, so it is refused before anything is created or
1410
- * removed — `mkdir(recursive)` would otherwise walk through the link.
1411
- *
1412
- * A directory whose identity cannot be established (`unknown`) is refused too: the
1413
- * alternative is to assume it is safe, and an assumption is what this check exists to
1414
- * remove. Both paths are inspected in one batch, so a normal Windows home costs one
1415
- * child process, not two.
1416
- * @param {string} home - resolved Codex home.
1417
- * @returns {Promise<{
1418
- * blocked: boolean,
1419
- * link: 'codex-home' | 'agents' | null,
1420
- * unknown: boolean,
1421
- * home: { kind: string, target?: string },
1422
- * agents: { kind: string, target?: string },
1423
- * }>} boundary state.
1424
- */
1596
+ async function isLstatPlainDirectory(path) {
1597
+ try {
1598
+ const info = await lstat(path);
1599
+ return !info.isSymbolicLink() && info.isDirectory();
1600
+ } catch {
1601
+ return false;
1602
+ }
1603
+ }
1604
+
1425
1605
  export async function inspectCodexBoundary(home) {
1606
+ const skillsPath = join(home, 'skills');
1607
+ const skillDirPath = join(skillsPath, SKILL_DIR_NAME);
1426
1608
  const agentsPath = join(home, 'agents');
1427
- const homeInfo = await inspectDirectory(home);
1609
+ const candidates = [home];
1610
+ if (await isLstatPlainDirectory(home)) {
1611
+ candidates.push(skillsPath, agentsPath);
1612
+ if (await isLstatPlainDirectory(skillsPath)) {
1613
+ candidates.push(skillDirPath);
1614
+ }
1615
+ }
1616
+ const inspected = await inspectDirectories(candidates);
1617
+ const homeInfo = inspected.get(home) ?? { kind: 'unknown' };
1428
1618
  if (homeInfo.kind === 'link') {
1429
- // Reached only when the caller did NOT pin the root first (a direct caller of this
1430
- // public helper). The installer's own entries resolve a selected root link through
1431
- // {@link pinCodexHome} and then inspect the REAL directory, so this branch keeps the
1432
- // conservative answer for an unpinned call: below an unresolved link nothing is
1433
- // written and nothing below it is even inspected.
1434
- return { blocked: true, link: 'codex-home', unknown: false, home: homeInfo, agents: { kind: 'unchecked' } };
1619
+ return {
1620
+ blocked: true,
1621
+ link: 'codex-home',
1622
+ unknown: false,
1623
+ home: homeInfo,
1624
+ skills: { kind: 'unchecked' },
1625
+ skillDir: { kind: 'unchecked' },
1626
+ agents: { kind: 'unchecked' },
1627
+ };
1628
+ }
1629
+ const skillsInfo = homeInfo.kind === 'directory'
1630
+ ? (inspected.get(skillsPath) ?? { kind: 'unknown' })
1631
+ : { kind: 'unchecked' };
1632
+ if (skillsInfo.kind === 'link') {
1633
+ return {
1634
+ blocked: true,
1635
+ link: 'skills',
1636
+ unknown: false,
1637
+ home: homeInfo,
1638
+ skills: skillsInfo,
1639
+ skillDir: { kind: 'unchecked' },
1640
+ agents: { kind: 'unchecked' },
1641
+ };
1642
+ }
1643
+ const skillDirInfo = skillsInfo.kind === 'directory'
1644
+ ? (inspected.get(skillDirPath) ?? { kind: 'unknown' })
1645
+ : { kind: 'unchecked' };
1646
+ if (skillDirInfo.kind === 'link') {
1647
+ return {
1648
+ blocked: true,
1649
+ link: 'skill-dir',
1650
+ unknown: false,
1651
+ home: homeInfo,
1652
+ skills: skillsInfo,
1653
+ skillDir: skillDirInfo,
1654
+ agents: { kind: 'unchecked' },
1655
+ };
1435
1656
  }
1436
1657
  const agentsInfo = homeInfo.kind === 'directory'
1437
- ? await inspectDirectory(agentsPath)
1658
+ ? (inspected.get(agentsPath) ?? { kind: 'unknown' })
1438
1659
  : { kind: 'unchecked' };
1439
1660
  if (agentsInfo.kind === 'link') {
1440
- return { blocked: true, link: 'agents', unknown: false, home: homeInfo, agents: agentsInfo };
1661
+ return {
1662
+ blocked: true,
1663
+ link: 'agents',
1664
+ unknown: false,
1665
+ home: homeInfo,
1666
+ skills: skillsInfo,
1667
+ skillDir: skillDirInfo,
1668
+ agents: agentsInfo,
1669
+ };
1441
1670
  }
1442
- // A home that exists but could not be classified, or an `agents` entry that could
1443
- // not be, is reported and refused for the same reason.
1444
- if (homeInfo.kind === 'unknown' || agentsInfo.kind === 'unknown') {
1445
- return { blocked: true, link: null, unknown: true, home: homeInfo, agents: agentsInfo };
1671
+ if (
1672
+ homeInfo.kind === 'unknown'
1673
+ || skillsInfo.kind === 'unknown'
1674
+ || skillDirInfo.kind === 'unknown'
1675
+ || agentsInfo.kind === 'unknown'
1676
+ ) {
1677
+ return {
1678
+ blocked: true,
1679
+ link: null,
1680
+ unknown: true,
1681
+ home: homeInfo,
1682
+ skills: skillsInfo,
1683
+ skillDir: skillDirInfo,
1684
+ agents: agentsInfo,
1685
+ };
1446
1686
  }
1447
- return { blocked: false, link: null, unknown: false, home: homeInfo, agents: agentsInfo };
1687
+ return {
1688
+ blocked: false,
1689
+ link: null,
1690
+ unknown: false,
1691
+ home: homeInfo,
1692
+ skills: skillsInfo,
1693
+ skillDir: skillDirInfo,
1694
+ agents: agentsInfo,
1695
+ };
1448
1696
  }
1449
1697
 
1450
- /**
1451
- * Does a link stand between the Codex home and the managed files?
1452
- *
1453
- * The status document carries the answer (`boundary.blocked`) because it is read with
1454
- * exactly the same inspect call; this turns that fact into a refusal in the shape
1455
- * every action reports. Re-reading the status is what makes the check current: it is
1456
- * re-done at the start of every writing action.
1457
- * @param {object} status - a status document from {@link readCodexStatus}.
1458
- * @returns {{ target: string, code: string, message: string, path: string, reason: string }} refusal.
1459
- */
1460
1698
  function linkedBoundaryRefusal(status) {
1461
1699
  if (status.boundary?.unknown === true) {
1462
1700
  return {
1463
1701
  target: 'agent',
1464
1702
  code: 'AGENT_PATH_CONFLICT',
1465
- message: 'the Codex home or agents directory could not be verified as a real directory and was not written',
1466
- path: join(status.codexHome, 'agents'),
1703
+ message: 'the Codex home, skills or agents directory could not be verified as a real directory and was not written',
1704
+ path: join(status.codexHome, 'skills'),
1467
1705
  reason: 'boundary-unverified',
1468
1706
  };
1469
1707
  }
1470
- const isHome = status.boundary?.link === 'codex-home';
1708
+ const linkKind = status.boundary?.link;
1709
+ if (linkKind === 'codex-home') {
1710
+ return {
1711
+ target: 'agent',
1712
+ code: 'AGENT_PATH_CONFLICT',
1713
+ message: 'the Codex home is a link or reparse point, so nothing below it is written or removed',
1714
+ path: status.codexHome,
1715
+ reason: 'codex-home-is-link',
1716
+ };
1717
+ }
1718
+ if (linkKind === 'skills') {
1719
+ return {
1720
+ target: 'agent',
1721
+ code: 'AGENT_PATH_CONFLICT',
1722
+ message: 'the skills directory is a link or reparse point, so nothing inside it is written or removed',
1723
+ path: join(status.codexHome, 'skills'),
1724
+ reason: 'skills-dir-is-link',
1725
+ };
1726
+ }
1727
+ if (linkKind === 'skill-dir') {
1728
+ return {
1729
+ target: 'agent',
1730
+ code: 'AGENT_PATH_CONFLICT',
1731
+ message: 'the skills/dsh-taskbridge directory is a link or reparse point, so nothing inside it is written or removed',
1732
+ path: join(status.codexHome, 'skills', SKILL_DIR_NAME),
1733
+ reason: 'skill-dir-is-link',
1734
+ };
1735
+ }
1471
1736
  return {
1472
1737
  target: 'agent',
1473
1738
  code: 'AGENT_PATH_CONFLICT',
1474
- message: isHome
1475
- ? 'the Codex home is a link or reparse point, so nothing below it is written or removed'
1476
- : 'the agents directory is a link or reparse point, so nothing inside it is written or removed',
1477
- path: isHome ? status.codexHome : join(status.codexHome, 'agents'),
1478
- reason: isHome ? 'codex-home-is-link' : 'agents-dir-is-link',
1739
+ message: 'the agents directory is a link or reparse point, so nothing inside it is written or removed',
1740
+ path: join(status.codexHome, 'agents'),
1741
+ reason: 'agents-dir-is-link',
1479
1742
  };
1480
1743
  }
1481
1744
 
@@ -2694,8 +2957,14 @@ export function removeMcpEntry(document) {
2694
2957
  * @returns {string} file contents, LF-terminated.
2695
2958
  */
2696
2959
  export function renderAgentFile(template, version) {
2697
- const marker = `version = ${renderString(version)}`;
2698
2960
  const text = normalizeLineEndings(template);
2961
+ if (SKILL_VERSION_LINE.test(text)) {
2962
+ return text.replace(SKILL_VERSION_LINE, `<!-- dsh-taskbridge-version: ${version} -->`);
2963
+ }
2964
+ if (/^---\n[\s\S]*?\n---\n/u.test(text)) {
2965
+ return text.replace(/^(---\n[\s\S]*?\n---\n)/u, `$1<!-- dsh-taskbridge-version: ${version} -->\n`);
2966
+ }
2967
+ const marker = `version = ${renderString(version)}`;
2699
2968
  if (/^version = ".*"$/mu.test(text)) return text.replace(/^version = ".*"$/mu, marker);
2700
2969
  // Keep the provenance header first, then the version marker, then the rest.
2701
2970
  const lines = text.split('\n');
@@ -2705,6 +2974,8 @@ export function renderAgentFile(template, version) {
2705
2974
  return lines.join('\n');
2706
2975
  }
2707
2976
 
2977
+ export { renderAgentFile as renderSkillFile };
2978
+
2708
2979
  /**
2709
2980
  * Read and parse the Codex config, or return an empty document.
2710
2981
  * @param {string} configPath - config file path.
@@ -2754,30 +3025,60 @@ export async function readCodexStatus({
2754
3025
  // against that real path.
2755
3026
  const pinned = await pinCodexHome(selected);
2756
3027
  const home = pinned.real;
2757
- const agentPath = join(home, 'agents', AGENT_FILENAME);
3028
+ const skillPath = join(home, 'skills', SKILL_DIR_NAME, SKILL_FILENAME);
2758
3029
  const configPath = join(home, 'config.toml');
2759
3030
  const packageVersionValue = version ?? await readPackageVersion();
2760
3031
  const template = renderAgentFile(await readAgentTemplate(), packageVersionValue);
2761
- // The boundary first: a link at the Codex home or at `agents` means the agent path
2762
- // does not name a file this plugin may touch, whatever `lstat` would say about it.
2763
3032
  const boundary = pinned.error === null
2764
3033
  ? await inspectCodexBoundary(home)
2765
- // A root that could not be pinned is refused WITHOUT inspecting anything below it:
2766
- // the alias does not lead to a usable directory, so there is nothing to classify and
2767
- // nothing may be created through it.
2768
- : { blocked: true, link: null, unknown: false, home: { kind: 'link' }, agents: { kind: 'unchecked' } };
3034
+ : {
3035
+ blocked: true,
3036
+ link: null,
3037
+ unknown: false,
3038
+ home: { kind: 'link' },
3039
+ skills: { kind: 'unchecked' },
3040
+ skillDir: { kind: 'unchecked' },
3041
+ agents: { kind: 'unchecked' },
3042
+ };
3043
+ const boundaryReason = boundary.unknown === true
3044
+ ? 'boundary-unverified'
3045
+ : (pinned.error?.reason ?? (
3046
+ boundary.link === 'codex-home' ? 'codex-home-is-link'
3047
+ : boundary.link === 'skills' ? 'skills-dir-is-link'
3048
+ : boundary.link === 'skill-dir' ? 'skill-dir-is-link'
3049
+ : 'agents-dir-is-link'
3050
+ ));
3051
+ const skillPathBlocked = !boundary.blocked && (boundary.skills?.kind === 'other' || boundary.skillDir?.kind === 'other');
3052
+ const ownershipBatch = createBatchedKindClassifier();
3053
+ const needSkillRecord = !boundary.blocked && !skillPathBlocked;
3054
+ const needAgentRecord = !boundary.blocked && boundary.agents?.kind === 'directory';
3055
+ if (needSkillRecord || needAgentRecord) {
3056
+ const primeDirs = [];
3057
+ const skillRecPath = needSkillRecord ? skillOwnershipRecordPath(home, env) : null;
3058
+ const agentRecPath = needAgentRecord ? ownershipRecordPath(home, env) : null;
3059
+ for (const recPath of [skillRecPath, agentRecPath]) {
3060
+ if (recPath !== null) primeDirs.push(...chainPathsOf(dirname(recPath)));
3061
+ }
3062
+ if (primeDirs.length > 0) await ownershipBatch.classifyMany(primeDirs);
3063
+ }
2769
3064
  const agent = boundary.blocked
2770
3065
  ? {
2771
3066
  state: AGENT_STATES.conflict,
2772
3067
  present: false,
2773
- reason: boundary.unknown === true
2774
- ? 'boundary-unverified'
2775
- // A selected ROOT that could not be pinned reports WHY (missing target, not a
2776
- // directory) instead of the generic "is a link".
2777
- : (pinned.error?.reason ?? (boundary.link === 'codex-home' ? 'codex-home-is-link' : 'agents-dir-is-link')),
3068
+ reason: boundaryReason,
2778
3069
  contents: null,
2779
3070
  }
2780
- : await readAgentState(agentPath, template, await recallRecordedTemplate(home, env));
3071
+ : skillPathBlocked
3072
+ ? {
3073
+ state: AGENT_STATES.conflict,
3074
+ present: true,
3075
+ reason: 'not-a-regular-file',
3076
+ contents: null,
3077
+ }
3078
+ : await readAgentState(skillPath, template, await recallRecordedSkillTemplate(home, env, ownershipBatch));
3079
+ const legacyAgents = needAgentRecord
3080
+ ? await inspectLegacyAgents(home, await recallRecordedTemplate(home, env, ownershipBatch))
3081
+ : { state: 'absent', entries: [] };
2781
3082
  // A READ never writes: this function classifies the files and records nothing. The template
2782
3083
  // digest is recorded only by `install` and by the startup `refreshKnownAgentTemplate`, after
2783
3084
  // those actions themselves wrote and re-proved the file.
@@ -2820,16 +3121,10 @@ export async function readCodexStatus({
2820
3121
  */
2821
3122
  let configFingerprint = null;
2822
3123
  if (boundary.blocked) {
2823
- // A link (or an unverifiable directory) at `$CODEX_HOME` or `$CODEX_HOME/agents`
2824
- // bounds EVERY write this module makes, not only the agent file. The MCP entry is
2825
- // described by the same verdict instead of by a read-through of the link: reporting
2826
- // it as `outdated` from inside the linked tree, and then refusing to write, is how a
2827
- // link would have been followed for a READ. Nothing below the boundary is examined.
2828
3124
  mcp = {
2829
3125
  state: MCP_STATES.conflict,
2830
3126
  previous: null,
2831
- reason: boundary.unknown === true ? 'boundary-unverified'
2832
- : (boundary.link === 'codex-home' ? 'codex-home-is-link' : 'agents-dir-is-link'),
3127
+ reason: boundaryReason,
2833
3128
  ownedValues: {},
2834
3129
  marked: false,
2835
3130
  drift: null,
@@ -2869,10 +3164,11 @@ export async function readCodexStatus({
2869
3164
  codexHomeSelected: pinned.selected,
2870
3165
  codexHomeLinked: pinned.linked,
2871
3166
  codexHomeLinkTarget: pinned.linkTarget,
2872
- agentPath,
3167
+ agentPath: skillPath,
2873
3168
  configPath,
2874
3169
  packageVersionValue,
2875
3170
  agent,
3171
+ legacyAgents,
2876
3172
  mcp,
2877
3173
  desired,
2878
3174
  script,
@@ -2917,6 +3213,7 @@ function buildStatus({
2917
3213
  configPath,
2918
3214
  packageVersionValue,
2919
3215
  agent,
3216
+ legacyAgents = { state: 'absent', entries: [] },
2920
3217
  mcp,
2921
3218
  desired,
2922
3219
  script,
@@ -2930,43 +3227,36 @@ function buildStatus({
2930
3227
  }) {
2931
3228
  const agentOk = agent.state === AGENT_STATES.installed;
2932
3229
  const mcpOk = mcp.state === MCP_STATES.configured;
3230
+ const skillTarget = {
3231
+ kind: 'skill',
3232
+ path: agentPath,
3233
+ state: agent.state,
3234
+ installed: agentOk,
3235
+ managed: agent.state !== AGENT_STATES.conflict && agent.state !== AGENT_STATES.modified,
3236
+ reason: agent.reason ?? null,
3237
+ expect: agent.contents ?? null,
3238
+ recorded: agent.recorded === true,
3239
+ };
2933
3240
  return {
2934
3241
  codexHome,
2935
- // The selected spelling and whether it was a root link, kept beside the REAL path so
2936
- // an operator who configured a junction recognises the answer without guessing.
2937
3242
  codexHomeSelected: codexHomeSelected ?? codexHome,
2938
3243
  codexHomeLinked: codexHomeLinked === true,
2939
3244
  codexHomeLinkTarget,
2940
3245
  packageVersion: packageVersionValue,
2941
- // Whether the two directories that bound every write are real directories. A link
2942
- // at either one is a stable diagnosis, not an installation state: install, repair
2943
- // and remove all refuse while `blocked` is true.
2944
3246
  boundary: boundary === null
2945
- ? { blocked: false, link: null, unknown: false, home: 'unknown', agents: 'unknown' }
3247
+ ? { blocked: false, link: null, unknown: false, home: 'unknown', skills: 'unknown', skillDir: 'unknown', agents: 'unknown' }
2946
3248
  : {
2947
3249
  blocked: boundary.blocked === true,
2948
3250
  link: boundary.blocked === true ? boundary.link : null,
2949
3251
  unknown: boundary.unknown === true,
2950
3252
  home: boundary.home.kind,
3253
+ skills: boundary.skills?.kind ?? 'unknown',
3254
+ skillDir: boundary.skillDir?.kind ?? 'unknown',
2951
3255
  agents: boundary.agents.kind,
2952
3256
  },
2953
- agent: {
2954
- path: agentPath,
2955
- state: agent.state,
2956
- // Stated once here so no caller has to infer it from a state name.
2957
- installed: agentOk,
2958
- managed: agent.state !== AGENT_STATES.conflict && agent.state !== AGENT_STATES.modified,
2959
- reason: agent.reason ?? null,
2960
- // The exact bytes a refresh is allowed to replace. Internal: `installManaged`
2961
- // re-reads the file and compares against this immediately before its rename, so
2962
- // a file edited between the status read and the write is never replaced.
2963
- expect: agent.contents ?? null,
2964
- // True when this file was recognised through the template digest recorded for THIS home
2965
- // rather than through the enumerated published history. It never reaches a response
2966
- // (`publicCodexStatus` strips it) and it never makes a state: an unproved file is still
2967
- // `modified`.
2968
- recorded: agent.recorded === true,
2969
- },
3257
+ skill: skillTarget,
3258
+ agent: skillTarget,
3259
+ legacyAgents,
2970
3260
  mcp: {
2971
3261
  path: configPath,
2972
3262
  exists: configPathInfo.exists === true,
@@ -2975,28 +3265,15 @@ function buildStatus({
2975
3265
  configured: mcpOk,
2976
3266
  previous: mcp.previous,
2977
3267
  reason: mcp.reason,
2978
- // WHICH owned facts are stale, as a list of stable names (`tool_timeout_sec`,
2979
- // `args`, `command`, `env`) — or null when nothing is stale. A state name alone
2980
- // ("outdated") does not tell an operator, or the panel, what would change.
2981
3268
  drift: mcp.drift ?? null,
2982
- // The digest of the whole config this classification was derived from. It travels
2983
- // with the status only so the write path can prove the file has not changed since;
2984
- // `publicCodexStatus` strips it, and it is a hash, never the text.
2985
3269
  fingerprint: configFingerprint,
2986
- // True only when the entry carries the plugin marker, i.e. when a later
2987
- // `remove` may delete it. Values alone never establish ownership.
2988
3270
  marked: mcp.marked === true,
2989
- // `null` when no Node.js executable could be proved; `resolved: false` says so
2990
- // explicitly so a consumer never has to test for `null` alone.
2991
3271
  desired,
2992
3272
  node,
2993
3273
  nodeResolved: node !== null,
2994
- // Why the executable could not be resolved (`MCP_EXECUTABLE_UNRESOLVED`), or
2995
- // null. The app executable is never substituted for it.
2996
3274
  nodeError,
2997
3275
  script: script.script,
2998
3276
  scriptExists: script.exists,
2999
- // Only written to the file when DSH uses a non-default location.
3000
3277
  discoveryFile: discovery.path,
3001
3278
  discoveryPinned: discovery.pin,
3002
3279
  },
@@ -3004,45 +3281,60 @@ function buildStatus({
3004
3281
  ? { readable: true, error: null }
3005
3282
  : { readable: false, error: configError },
3006
3283
  ready: agentOk && mcpOk && configError === null && node !== null,
3007
- // What this action cannot do, stated where the operator sees the result.
3008
- notes: buildNotes({ agent, mcp, script, configError, nodeError }),
3284
+ notes: buildNotes({ agent, legacyAgents, mcp, script, configError, nodeError }),
3009
3285
  };
3010
3286
  }
3011
3287
 
3012
- /**
3013
- * Operator-facing limitations of the current state.
3014
- * @param {object} parts - collected facts.
3015
- * @returns {object[]} `[{ code, text }]`.
3016
- */
3017
- function buildNotes({ agent, mcp, script, configError, nodeError = null }) {
3288
+ function buildNotes({ agent, legacyAgents = { state: 'absent', entries: [] }, mcp, script, configError, nodeError = null }) {
3018
3289
  const notes = [];
3019
3290
  if (agent.state === AGENT_STATES.modified) {
3020
3291
  notes.push({
3021
3292
  code: 'AGENT_USER_MODIFIED',
3022
- text: `已存在内容不同的 agents/${AGENT_FILENAME},本插件不会覆盖或删除它。`
3023
- + (agent.reason === 'edited'
3024
- // The bytes are one of this plugin's own templates with something changed — a
3025
- // single character, an added note, or only the version line. Saying WHICH keeps
3026
- // the operator from guessing, and never suggests deleting a file they may want.
3027
- ? '它与本插件发布过的某个模板只在个别字节上不同(可能只改了 version 行,或加了一处你自己的说明);改回该发布版本的原样内容后,本插件会自动更新它,否则由你继续管理。'
3028
- : '它不是本插件发布过的模板,因此插件不会把它当作自己的文件;由你继续管理即可。'),
3293
+ text: agent.reason === 'reference-operator-owned'
3294
+ ? 'Codex 技能的规则附页与发布内容不同。插件将保留入口和附页,由你继续管理。'
3295
+ : `已存在内容不同的 skills/${SKILL_DIR_NAME}/${SKILL_FILENAME},本插件不会覆盖或删除它。`
3296
+ + (agent.reason === 'edited'
3297
+ ? '它与本插件发布过的某个技能模板只在个别字节上不同(可能只改了版本注释或加了你自己的说明);改回该发布版本的原样内容后,本插件会自动更新它,否则由你继续管理。'
3298
+ : '它不是本插件发布过的技能模板,因此插件不会把它当作自己的文件;由你继续管理即可。'),
3029
3299
  });
3030
3300
  }
3031
3301
  if (agent.state === AGENT_STATES.conflict) {
3032
- // `AGENT_PATH_CONFLICT` covers two different physical situations, and the
3033
- // operator needs to know which one: a link on the way to the file (home or
3034
- // `agents/`), or a final path that is not a regular file (a link, a directory).
3035
3302
  const text = agent.reason === 'codex-home-is-link'
3036
- ? `Codex home 本身是链接(符号链接或 Windows reparse point/junction),本插件不会穿过它写入或删除 agents/${AGENT_FILENAME}。`
3037
- : agent.reason === 'agents-dir-is-link'
3038
- ? `agents 目录是链接(符号链接或 Windows reparse point/junction),本插件不会穿过它写入或删除 ${AGENT_FILENAME}。`
3039
- : agent.reason === 'boundary-unverified'
3040
- ? 'Codex home 或 agents 目录无法确认是真实目录(可能缺少 Windows PowerShell),本插件不会写入或删除任何文件。'
3041
- : `agents/${AGENT_FILENAME} 不是普通文件(可能是链接或目录),本插件不会改动它。`;
3303
+ ? `Codex home 本身是链接(符号链接或 Windows reparse point/junction),本插件不会穿过它写入或删除 skills/${SKILL_DIR_NAME}/${SKILL_FILENAME}。`
3304
+ : agent.reason === 'skills-dir-is-link'
3305
+ ? `skills 目录是链接(符号链接或 Windows reparse point/junction),本插件不会穿过它写入或删除 ${SKILL_DIR_NAME}/${SKILL_FILENAME}。`
3306
+ : agent.reason === 'skill-dir-is-link'
3307
+ ? `skills/${SKILL_DIR_NAME} 目录是链接(符号链接或 Windows reparse point/junction),本插件不会穿过它写入或删除 ${SKILL_FILENAME}。`
3308
+ : agent.reason === 'agents-dir-is-link'
3309
+ ? `agents 目录是链接(符号链接或 Windows reparse point/junction),本插件不会穿过它写入或删除任何文件。`
3310
+ : agent.reason === 'boundary-unverified'
3311
+ ? 'Codex home、skills 或 agents 目录无法确认是真实目录(可能缺少 Windows PowerShell),本插件不会写入或删除任何文件。'
3312
+ : `skills/${SKILL_DIR_NAME}/${SKILL_FILENAME} 不是普通文件(可能是链接或目录),本插件不会改动它。`;
3042
3313
  notes.push({ code: 'AGENT_PATH_CONFLICT', text });
3043
3314
  }
3044
3315
  if (agent.state === AGENT_STATES.outdated) {
3045
- notes.push({ code: 'AGENT_OUTDATED', text: '已安装的 agent 是旧版本(与某个已发布版本逐字节相同)。插件下次启动时会自动刷新为当前版本;也可以点「安装 / 更新 Codex 集成」立即更新。' });
3316
+ notes.push({
3317
+ code: 'AGENT_OUTDATED',
3318
+ text: agent.reason === 'reference-missing'
3319
+ ? 'Codex 技能缺少规则附页。插件启动时会补齐,也可以点「安装 / 更新 TaskBridge 技能」恢复。'
3320
+ : '已安装的技能文件是旧版本(与某个已发布版本逐字节相同)。插件下次启动时会自动刷新为当前版本;也可以点「安装 / 更新 TaskBridge 技能」立即更新。',
3321
+ });
3322
+ }
3323
+ const managedLegacy = legacyAgents.entries.filter((entry) => entry.state === 'managed-legacy');
3324
+ if (managedLegacy.length > 0) {
3325
+ const list = managedLegacy.map((entry) => `agents/${entry.filename}`).join('、');
3326
+ notes.push({
3327
+ code: 'LEGACY_AGENT_MIGRATION_PENDING',
3328
+ text: `检测到旧版托管子智能体(${list})。1.9.0 起 Codex 改用原生技能 skills/${SKILL_DIR_NAME}/${SKILL_FILENAME} 在当前会话单链直等(避免 spawn_agent + wait_agent 短轮询);插件下次启动或点「安装 / 更新 TaskBridge 技能」时会自动迁移并移除未修改的旧子智能体文件。`,
3329
+ });
3330
+ }
3331
+ const modifiedLegacy = legacyAgents.entries.filter((entry) => entry.state === 'modified-legacy');
3332
+ if (modifiedLegacy.length > 0) {
3333
+ const list = modifiedLegacy.map((entry) => `agents/${entry.filename}`).join('、');
3334
+ notes.push({
3335
+ code: 'LEGACY_AGENT_USER_MODIFIED',
3336
+ text: `检测到已被手动修改的旧子智能体文件(${list}),本插件已原样保留不删。若你不希望 Codex 在主会话中派生旧子智能体触发 wait_agent 轮询,可手动将其移走或删除,改用原生技能 skills/${SKILL_DIR_NAME}/${SKILL_FILENAME}。`,
3337
+ });
3046
3338
  }
3047
3339
  if (mcp.state === MCP_STATES.conflict) {
3048
3340
  notes.push({
@@ -3050,9 +3342,9 @@ function buildNotes({ agent, mcp, script, configError, nodeError = null }) {
3050
3342
  text: mcp.reason === 'unmanaged-entry'
3051
3343
  ? `config.toml 中已有同名的 mcp_servers.${MCP_SERVER_NAME} 条目,但没有本插件的托管标记注释,视为你自己写的:本插件不会更新或删除它;请自行删除或改名后再点安装。`
3052
3344
  : (mcp.reason === UNMANAGED_EXACT_REASON
3053
- ? `config.toml 中已有同名的 mcp_servers.${MCP_SERVER_NAME} 条目,内容与当前插件应写入的条目完全一致(命令、入口脚本、参数、超时与环境项都相同),只缺托管标记注释。点「仅修复 MCP 配置」只会补上这一行标记,不改动其他内容;「安装 / 更新 Codex 集成」不会替你接管它。`
3345
+ ? `config.toml 中已有同名的 mcp_servers.${MCP_SERVER_NAME} 条目,内容与当前插件应写入的条目完全一致(命令、入口脚本、参数、超时与环境项都相同),只缺托管标记注释。点「仅修复 MCP 配置」只会补上这一行标记,不改动其他内容;「安装 / 更新 TaskBridge 技能」不会替你接管它。`
3054
3346
  : (mcp.reason === 'args-shape-not-ours'
3055
- ? `config.toml 中已有的 mcp_servers.${MCP_SERVER_NAME} 条目带托管标记,但入口脚本与当前安装不同。若那是本插件的另一处真实安装,点「安装 / 更新 Codex 集成」或「仅修复 MCP 配置」会在证明后采纳;否则本插件不会替换它。`
3347
+ ? `config.toml 中已有的 mcp_servers.${MCP_SERVER_NAME} 条目带托管标记,但入口脚本与当前安装不同。若那是本插件的另一处真实安装,点「安装 / 更新 TaskBridge 技能」或「仅修复 MCP 配置」会在证明后采纳;否则本插件不会替换它。`
3056
3348
  : `config.toml 中已有同名的 mcp_servers.${MCP_SERVER_NAME} 条目,但内容不是本插件写入的形态(${mcp.reason ?? 'unknown'})。本插件不会替换它;请自行删除或改名后再点安装。`)),
3057
3349
  });
3058
3350
  }
@@ -3072,7 +3364,7 @@ function buildNotes({ agent, mcp, script, configError, nodeError = null }) {
3072
3364
  if (drift.includes('env')) reasons.push(`其 env.${DISCOVERY_ENV_VAR} 与当前发现文件不一致`);
3073
3365
  notes.push({
3074
3366
  code: 'MCP_ENTRY_OUTDATED',
3075
- text: `已安装的 mcp_servers.${MCP_SERVER_NAME} 是本插件写入的托管条目,但已经过期:${reasons.length === 0 ? '需要更新' : reasons.join(';')}。插件下次启动时会自动在原地更新它;也可以点「安装 / 更新 Codex 集成」立即更新。`,
3367
+ text: `已安装的 mcp_servers.${MCP_SERVER_NAME} 是本插件写入的托管条目,但已经过期:${reasons.length === 0 ? '需要更新' : reasons.join(';')}。插件下次启动时会自动在原地更新它;也可以点「安装 / 更新 TaskBridge 技能」立即更新。`,
3076
3368
  });
3077
3369
  }
3078
3370
  if (configError !== null) {
@@ -3206,11 +3498,29 @@ async function installManaged(before, outcome) {
3206
3498
  await installMcpEntry(before, outcome);
3207
3499
  }
3208
3500
 
3209
- /** Move a previously installed, unchanged companion to the public TaskBridge name. */
3501
+ /**
3502
+ * Safely retire untouched legacy Codex subagent files (`agents/dsh-taskbridge.toml` and
3503
+ * `agents/dsh-delegate.toml`) after migrating to the native skill `skills/dsh-taskbridge/SKILL.md`.
3504
+ * User-modified files are NEVER deleted; every unlink re-proves byte-exact ownership immediately
3505
+ * before deleting.
3506
+ */
3210
3507
  async function migrateLegacyAgent(before, outcome, { removeOnly = false } = {}) {
3211
- const legacyPath = join(before.codexHome, 'agents', LEGACY_AGENT_FILENAME);
3212
- const legacy = await inspectFile(legacyPath);
3213
- if (legacy.kind !== 'file' || !isKnownPriorTemplate(legacy.contents)) return;
3508
+ if (before.boundary?.blocked === true) return;
3509
+ const managedEntries = (before.legacyAgents?.entries ?? []).filter((entry) => entry.state === 'managed-legacy');
3510
+ if (managedEntries.length === 0) return;
3511
+
3512
+ // Re-prove at least one legacy managed file STILL matches its exact inspected bytes
3513
+ // before creating or updating the native skill, so a concurrent user edit between
3514
+ // `plan` and migration never triggers an unwanted skill creation or file deletion.
3515
+ const liveEntries = [];
3516
+ for (const entry of managedEntries) {
3517
+ const currentLegacy = await inspectFile(entry.path);
3518
+ if (currentLegacy.kind === 'file' && typeof entry.expect === 'string' && currentLegacy.contents === entry.expect) {
3519
+ liveEntries.push(entry);
3520
+ }
3521
+ }
3522
+ if (liveEntries.length === 0) return;
3523
+
3214
3524
  if (!removeOnly) {
3215
3525
  if (before.agent.state === AGENT_STATES.missing) {
3216
3526
  const current = await inspectFile(before.agent.path);
@@ -3218,12 +3528,28 @@ async function migrateLegacyAgent(before, outcome, { removeOnly = false } = {})
3218
3528
  }
3219
3529
  const template = renderAgentFile(await readAgentTemplate(), before.packageVersion);
3220
3530
  const current = await inspectFile(before.agent.path);
3221
- if (current.kind !== 'file' || current.contents !== template) return;
3531
+ const reference = skillReference(before.agent.path, template);
3532
+ const installed = reference === null ? null : await inspectFile(reference.path);
3533
+ const referenceReady = installed === null
3534
+ || (installed.kind === 'file' && !referenceConflicts(reference, installed));
3535
+ const skillReady = current.kind === 'file'
3536
+ && ((sameAgentText(current.contents, template) && referenceReady)
3537
+ || before.agent.state === AGENT_STATES.modified);
3538
+ if (!skillReady) return;
3539
+ }
3540
+
3541
+ for (const entry of liveEntries) {
3542
+ const currentLegacy = await inspectFile(entry.path);
3543
+ if (currentLegacy.kind !== 'file' || typeof entry.expect !== 'string' || currentLegacy.contents !== entry.expect) {
3544
+ continue;
3545
+ }
3546
+ try {
3547
+ await unlink(entry.path);
3548
+ if (!outcome.changed.includes('legacyAgent')) outcome.changed.push('legacyAgent');
3549
+ } catch (error) {
3550
+ if (error?.code !== 'ENOENT') throw error;
3551
+ }
3222
3552
  }
3223
- const currentLegacy = await inspectFile(legacyPath);
3224
- if (currentLegacy.kind !== 'file' || currentLegacy.contents !== legacy.contents) return;
3225
- await unlink(legacyPath);
3226
- if (!outcome.changed.includes('agent')) outcome.changed.push('agent');
3227
3553
  }
3228
3554
 
3229
3555
  /**
@@ -3287,6 +3613,51 @@ export async function refreshKnownAgentTemplate(options = {}) {
3287
3613
  return { changed, refused, status };
3288
3614
  }
3289
3615
 
3616
+ function skillReference(entryPath, entry) {
3617
+ const match = entry?.match(SKILL_REFERENCE_LINK);
3618
+ if (!match) return null;
3619
+ const [, name, sha256] = match;
3620
+ return { name, sha256, path: join(dirname(entryPath), name) };
3621
+ }
3622
+
3623
+ function referenceConflicts(reference, inspected) {
3624
+ return inspected.kind !== 'missing'
3625
+ && (inspected.kind !== 'file' || digestLf(inspected.contents) !== reference.sha256);
3626
+ }
3627
+
3628
+ function skillReferenceRefusal(path, reason) {
3629
+ return {
3630
+ target: 'agent',
3631
+ code: reason === 'reference-operator-owned' ? 'AGENT_USER_MODIFIED' : 'AGENT_PATH_CONFLICT',
3632
+ path,
3633
+ reason,
3634
+ message: 'the Codex skill reference could not be installed or removed safely',
3635
+ };
3636
+ }
3637
+
3638
+ // Publish a new reference alongside any older one. Replacing the entry switches versions;
3639
+ // Codex sessions which already loaded the old entry can still read their reference.
3640
+ async function installSkillReference(reference, outcome) {
3641
+ if (reference === null) return 'unchanged';
3642
+ const packaged = await inspectFile(join(dirname(TEMPLATE_PATH), reference.name));
3643
+ if (packaged.kind !== 'file' || digestLf(packaged.contents) !== reference.sha256) {
3644
+ outcome.refused.push(skillReferenceRefusal(reference.path,
3645
+ packaged.kind === 'missing' ? 'reference-not-packaged' : 'reference-template-mismatch'));
3646
+ return 'refused';
3647
+ }
3648
+ const current = await inspectFile(reference.path);
3649
+ if (referenceConflicts(reference, current)) {
3650
+ outcome.refused.push(skillReferenceRefusal(reference.path, 'reference-operator-owned'));
3651
+ return 'refused';
3652
+ }
3653
+ if (current.kind === 'file') return 'unchanged';
3654
+ if (await createFileExclusive(reference.path, packaged.contents) === 'created') return 'created';
3655
+ const raced = await inspectFile(reference.path);
3656
+ if (raced.kind === 'file' && !referenceConflicts(reference, raced)) return 'unchanged';
3657
+ outcome.refused.push(skillReferenceRefusal(reference.path, 'reference-created-concurrently'));
3658
+ return 'refused';
3659
+ }
3660
+
3290
3661
  /**
3291
3662
  * Install or refresh the managed agent file without touching the MCP entry.
3292
3663
  *
@@ -3296,51 +3667,80 @@ export async function refreshKnownAgentTemplate(options = {}) {
3296
3667
  */
3297
3668
  async function installManagedAgent(before, outcome) {
3298
3669
  const { agent } = before;
3299
- if (agent.state === AGENT_STATES.missing || agent.state === AGENT_STATES.outdated) {
3300
- const template = renderAgentFile(await readAgentTemplate(), before.packageVersion);
3301
- await mkdir(dirname(agent.path), { recursive: true, mode: 0o700 });
3302
- if (agent.state === AGENT_STATES.missing) {
3303
- // First installation: exclusive. A file that appeared between the status read
3304
- // and this write belongs to whoever created it, and is reported, not replaced.
3305
- const created = await createFileExclusive(agent.path, template);
3306
- if (created === 'exists') {
3307
- outcome.refused.push({
3308
- target: 'agent',
3309
- code: 'AGENT_PATH_CONFLICT',
3310
- message: 'an agent file appeared while installing and was left untouched',
3311
- path: agent.path,
3312
- reason: 'created-concurrently',
3313
- });
3314
- return;
3315
- }
3316
- await recordAgentTemplate(before);
3317
- outcome.changed.push('agent');
3318
- } else {
3319
- // A refresh replaces a byte-exact known build of our own file. Re-check right
3320
- // before writing: if the file changed in the meantime it is no longer that
3321
- // known build, and the rename must not overwrite it.
3322
- const current = await inspectFile(agent.path);
3323
- if (current.kind !== 'file' || current.contents !== before.agent.expect) {
3324
- outcome.refused.push({
3325
- target: 'agent',
3326
- code: 'AGENT_USER_MODIFIED',
3327
- message: 'the agent file changed while updating and was left untouched',
3328
- path: agent.path,
3329
- });
3330
- return;
3331
- }
3332
- await writeFileAtomic(agent.path, template);
3333
- await recordAgentTemplate(before);
3334
- outcome.changed.push('agent');
3670
+ if (agent.state === AGENT_STATES.installed) return;
3671
+ if (agent.state === AGENT_STATES.modified || agent.state === AGENT_STATES.conflict) {
3672
+ if (agent.reason === 'reference-operator-owned') {
3673
+ outcome.refused.push(skillReferenceRefusal(skillReference(agent.path, agent.expect).path, agent.reason));
3674
+ return;
3335
3675
  }
3336
- } else if (agent.state === AGENT_STATES.modified || agent.state === AGENT_STATES.conflict) {
3337
3676
  outcome.refused.push({
3338
3677
  target: 'agent',
3339
3678
  code: agent.state === AGENT_STATES.modified ? 'AGENT_USER_MODIFIED' : 'AGENT_PATH_CONFLICT',
3340
3679
  message: 'an agent file with different contents already exists and was left untouched',
3341
3680
  path: agent.path,
3342
3681
  });
3682
+ return;
3683
+ }
3684
+
3685
+ const boundary = await inspectCodexBoundary(before.codexHome);
3686
+ if (boundary.blocked) {
3687
+ outcome.refused.push(linkedBoundaryRefusal({ ...before, boundary }));
3688
+ return;
3689
+ }
3690
+ if (boundary.skills.kind === 'other' || boundary.skillDir.kind === 'other') {
3691
+ outcome.refused.push(skillReferenceRefusal(agent.path, 'reference-boundary-changed'));
3692
+ return;
3343
3693
  }
3694
+ if (boundary.skillDir.kind !== 'directory') {
3695
+ await mkdir(dirname(agent.path), { recursive: true, mode: 0o700 });
3696
+ const liveBoundary = await inspectCodexBoundary(before.codexHome);
3697
+ if (liveBoundary.blocked || liveBoundary.skillDir.kind !== 'directory') {
3698
+ outcome.refused.push(skillReferenceRefusal(agent.path, 'reference-boundary-changed'));
3699
+ return;
3700
+ }
3701
+ }
3702
+
3703
+ const template = renderAgentFile(await readAgentTemplate(), before.packageVersion);
3704
+ const previous = skillReference(agent.path, agent.expect);
3705
+ const reference = await installSkillReference(skillReference(agent.path, template), outcome);
3706
+ if (reference === 'refused') return;
3707
+
3708
+ if (agent.state === AGENT_STATES.missing) {
3709
+ const created = await createFileExclusive(agent.path, template);
3710
+ if (created === 'exists') {
3711
+ outcome.refused.push({
3712
+ target: 'agent',
3713
+ code: 'AGENT_PATH_CONFLICT',
3714
+ message: 'an agent file appeared while installing and was left untouched',
3715
+ path: agent.path,
3716
+ reason: 'created-concurrently',
3717
+ });
3718
+ return;
3719
+ }
3720
+ } else {
3721
+ if (previous !== null && referenceConflicts(previous, await inspectFile(previous.path))) {
3722
+ outcome.refused.push(skillReferenceRefusal(previous.path, 'reference-operator-owned'));
3723
+ return;
3724
+ }
3725
+ const current = await inspectFile(agent.path);
3726
+ if (current.kind !== 'file' || current.contents !== agent.expect) {
3727
+ outcome.refused.push({
3728
+ target: 'agent',
3729
+ code: 'AGENT_USER_MODIFIED',
3730
+ message: 'the agent file changed while updating and was left untouched',
3731
+ path: agent.path,
3732
+ });
3733
+ return;
3734
+ }
3735
+ if (sameAgentText(current.contents, template)) {
3736
+ // Restored a missing reference for the current entry. Its ownership record still applies.
3737
+ if (reference === 'created') outcome.changed.push('agent');
3738
+ return;
3739
+ }
3740
+ await writeFileAtomic(agent.path, template);
3741
+ }
3742
+ await recordAgentTemplate(before);
3743
+ outcome.changed.push('agent');
3344
3744
  }
3345
3745
 
3346
3746
  /**
@@ -3579,7 +3979,7 @@ async function upgradeOutdatedMcpEntry(before, outcome, options = {}) {
3579
3979
  );
3580
3980
  if (gate.owned !== true) {
3581
3981
  refuse('MCP_ENTRY_CONFLICT',
3582
- 'the stale mcp_servers.dsh-delegate entry is not one this plugin can prove is its own, so it was left untouched; use 安装 / 更新 Codex 集成 to replace it explicitly',
3982
+ 'the stale mcp_servers.dsh-delegate entry could not be verified as owned and was left untouched. 安装 / 更新 TaskBridge 技能 can update entries from a verifiable previous installation',
3583
3983
  { reason: gate.reason });
3584
3984
  return;
3585
3985
  }
@@ -3887,6 +4287,7 @@ export async function removeManagedAgentFile(agent) {
3887
4287
  }
3888
4288
  try {
3889
4289
  await unlink(agent.path);
4290
+ await rmdir(dirname(agent.path)).catch(() => {});
3890
4291
  } catch (error) {
3891
4292
  if (error?.code === 'ENOENT') {
3892
4293
  // Raced away between the read and the unlink; still not a change of ours.
@@ -3921,16 +4322,33 @@ export async function removeManagedAgentFile(agent) {
3921
4322
  async function removeManaged(before, outcome) {
3922
4323
  const { agent, mcp } = before;
3923
4324
  if (agent.state === AGENT_STATES.installed || agent.state === AGENT_STATES.outdated) {
3924
- const verdict = await removeManagedAgentFile(agent);
3925
- if (verdict.code === null) outcome.changed.push('agent');
3926
- else outcome.refused.push(verdict);
4325
+ const reference = skillReference(agent.path, agent.expect);
4326
+ const verdict = reference !== null && referenceConflicts(reference, await inspectFile(reference.path))
4327
+ ? skillReferenceRefusal(reference.path, 'reference-operator-owned')
4328
+ : await removeManagedAgentFile(agent);
4329
+ if (verdict.code === null) {
4330
+ outcome.changed.push('agent');
4331
+ if (reference !== null) {
4332
+ const current = await inspectFile(reference.path);
4333
+ if (referenceConflicts(reference, current)) {
4334
+ outcome.refused.push(skillReferenceRefusal(reference.path, 'reference-operator-owned'));
4335
+ } else if (current.kind === 'file') {
4336
+ const removed = await removeManagedAgentFile({ path: reference.path, expect: current.contents });
4337
+ if (removed.code !== null) outcome.refused.push(removed);
4338
+ }
4339
+ }
4340
+ } else outcome.refused.push(verdict);
3927
4341
  } else if (agent.state === AGENT_STATES.modified) {
3928
- outcome.refused.push({
3929
- target: 'agent',
3930
- code: 'AGENT_USER_MODIFIED',
3931
- message: 'the agent file differs from the managed template and was left untouched',
3932
- path: agent.path,
3933
- });
4342
+ if (agent.reason === 'reference-operator-owned') {
4343
+ outcome.refused.push(skillReferenceRefusal(skillReference(agent.path, agent.expect).path, agent.reason));
4344
+ } else {
4345
+ outcome.refused.push({
4346
+ target: 'agent',
4347
+ code: 'AGENT_USER_MODIFIED',
4348
+ message: 'the agent file differs from the managed template and was left untouched',
4349
+ path: agent.path,
4350
+ });
4351
+ }
3934
4352
  } else if (agent.state === AGENT_STATES.conflict) {
3935
4353
  outcome.refused.push({
3936
4354
  target: 'agent',
@@ -3993,24 +4411,29 @@ async function removeManaged(before, outcome) {
3993
4411
  export function publicCodexStatus(status) {
3994
4412
  if (status === null || typeof status !== 'object') return status;
3995
4413
  const { expect: _ignored, recorded: _record, ...agent } = status.agent ?? {};
3996
- // `mcp.fingerprint` is the write path's receipt for the exact config bytes it plans to
3997
- // replace. It is a digest, not content, but it is an internal planning fact like
3998
- // `agent.expect`, so it does not belong in a response an operator or a page reads.
4414
+ const { expect: _skillIgnored, recorded: _skillRecord, ...skill } = status.skill ?? agent;
4415
+ const legacyAgents = status.legacyAgents && typeof status.legacyAgents === 'object'
4416
+ ? {
4417
+ state: status.legacyAgents.state ?? 'absent',
4418
+ entries: Array.isArray(status.legacyAgents.entries)
4419
+ ? status.legacyAgents.entries.map(({ expect: _legacyExpect, ...entry }) => entry)
4420
+ : [],
4421
+ }
4422
+ : { state: 'absent', entries: [] };
3999
4423
  const { fingerprint: _receipt, ...mcp } = status.mcp ?? {};
4000
- return { ...status, agent, mcp };
4424
+ return { ...status, skill, agent, legacyAgents, mcp };
4001
4425
  }
4002
4426
 
4003
4427
  /**
4004
- * Load the shipped agent template without the version marker, for diagnostics.
4005
- *
4006
- * Exported so a test can assert the shipped dispatch rules independently of the
4007
- * installed copy.
4008
- * @returns {Promise<{ text: string, instructions: string }>} template text and its developer instructions.
4428
+ * Load the shipped Codex skill template (or legacy TOML template) and its instruction body.
4429
+ * @returns {Promise<{ text: string, instructions: string }>} template text and instructions.
4009
4430
  */
4010
4431
  export async function readAgentInstructions() {
4011
4432
  const text = await readAgentTemplate();
4012
- const match = /developer_instructions = """([\s\S]*?)"""/u.exec(text);
4013
- return { text, instructions: match === null ? '' : match[1] };
4433
+ const tomlMatch = /developer_instructions = """([\s\S]*?)"""/u.exec(text);
4434
+ if (tomlMatch !== null) return { text, instructions: tomlMatch[1] };
4435
+ const stripped = normalizeLineEndings(text).replace(/^---\n[\s\S]*?\n---\n/u, '');
4436
+ return { text, instructions: stripped };
4014
4437
  }
4015
4438
 
4016
4439
  /**