dsh-taskbridge 1.6.0 → 1.7.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 (66) hide show
  1. package/CHANGELOG.md +10 -1
  2. package/README.md +41 -41
  3. package/THIRD_PARTY_NOTICES.txt +23 -0
  4. package/codex/dsh-taskbridge.toml +140 -71
  5. package/docs/INTRODUCTION.md +44 -22
  6. package/docs/INTRODUCTION.zh.md +32 -26
  7. package/docs/codex-integration.md +90 -10
  8. package/docs/contracts-stage-b.md +4 -4
  9. package/docs/conversation-placement.md +25 -7
  10. package/docs/plugin-market.md +1 -1
  11. package/docs/releases/1.7.0.zh.md +11 -0
  12. package/docs/runtime-compatibility.md +4 -11
  13. package/docs/silent-wait.md +69 -31
  14. package/docs/taskbridge-upgrade.md +1 -1
  15. package/docs/worker-permissions.md +4 -14
  16. package/docs/workspace-grouping.md +126 -0
  17. package/lib/client.d.ts +365 -3
  18. package/lib/client.js +260 -5
  19. package/locale/en.json +1 -1
  20. package/locale/zh.json +1 -1
  21. package/package.json +7 -19
  22. package/src/client/api.js +550 -90
  23. package/src/client/index.jsx +699 -307
  24. package/src/client/sidebar.jsx +6 -5
  25. package/src/client/styles.js +251 -0
  26. package/src/client/task-cleanup.js +304 -0
  27. package/src/client/task-records-table.jsx +217 -0
  28. package/src/client/task-view.js +226 -10
  29. package/src/client/workspace-groups.js +482 -0
  30. package/src/client/workspaces-browser.jsx +770 -0
  31. package/src/codex/agent-ownership.js +270 -0
  32. package/src/codex/installer.js +525 -35
  33. package/src/codex/seam.js +5 -0
  34. package/src/config/defaults.js +63 -17
  35. package/src/config/settings.js +60 -62
  36. package/src/config/validate.js +126 -71
  37. package/src/http/respond.js +8 -0
  38. package/src/http/user-plane.js +197 -2
  39. package/src/index.js +50 -42
  40. package/src/jobs/activity.js +968 -78
  41. package/src/jobs/engine.js +784 -230
  42. package/src/jobs/history.js +188 -12
  43. package/src/jobs/plan-store.js +5 -0
  44. package/src/jobs/record-cleanup.js +196 -0
  45. package/src/jobs/task-tree.js +5 -3
  46. package/src/jobs/title.js +129 -12
  47. package/src/mcp/server.js +16 -8
  48. package/src/mcp/wait.js +64 -5
  49. package/src/runtime/agent-runner.js +53 -15
  50. package/src/runtime/worker-prompt.js +53 -0
  51. package/src/workspace/locks.js +288 -167
  52. package/docs/releases/1.4.0-token-benchmark.zh.md +0 -40
  53. package/docs/releases/1.4.0.zh.md +0 -54
  54. package/docs/releases/1.4.1.zh.md +0 -59
  55. package/docs/releases/1.4.2.zh.md +0 -23
  56. package/docs/releases/1.5.0-token-benchmark.zh.md +0 -73
  57. package/docs/releases/1.5.0.zh.md +0 -51
  58. package/docs/releases/1.5.1.zh.md +0 -70
  59. package/docs/releases/1.5.2.zh.md +0 -30
  60. package/docs/releases/1.5.3-test.1.zh.md +0 -28
  61. package/docs/releases/1.5.3-test.2.zh.md +0 -24
  62. package/docs/releases/1.5.3.zh.md +0 -33
  63. package/docs/releases/1.5.4.zh.md +0 -25
  64. package/src/review/preset.js +0 -868
  65. package/src/review/prompts.js +0 -145
  66. package/src/review/reviewer.js +0 -933
@@ -89,6 +89,7 @@ import { basename, delimiter, dirname, isAbsolute, join, parse, resolve, sep } f
89
89
  import { fileURLToPath } from 'node:url';
90
90
 
91
91
  import { writeFileAtomic } from '../config/store.js';
92
+ import { recallTemplateDigest, rememberTemplateDigest, digestLf } from './agent-ownership.js';
92
93
  import {
93
94
  TomlDocument,
94
95
  TomlSyntaxError,
@@ -474,6 +475,47 @@ export const KNOWN_AGENT_TEMPLATES = [
474
475
  // Exact 1.5.4 template (CRLF/LF), preserved in tests/fixtures/agent-1.5.4.toml.
475
476
  { version: '1.5.4', sha256: '94ee47a0bfc16a36c76010d1e1a2476ff6117966f5c1559b01193353199f82e8' },
476
477
  { version: '1.5.4', sha256: '8efbe5d627f72b34fb66decd7784552b5eafb0289c409bb6443ae28094351aae' },
478
+ // Exact templates from the 1.6.0 and 1.6.1-test.1 packages, before the outage rules.
479
+ { version: '1.6.0', sha256: '5802a655a88f8c526f662615889969899e86c326ef66cf40c70b5cf2fb30e3e9' },
480
+ { version: '1.6.0', sha256: '56b887cd609467c2e82f8f036d25376acc13d5df54c5eec3b30d40c7dd7e5c87' },
481
+ { version: '1.6.0', sha256: '746ab52edbc28ecc19e287f60b6502ddbd2dd3fbb8b7ae60b51f4b4a5b96a6c9' },
482
+ { version: '1.6.0', sha256: '43b1b61157fab8a7fe74db70ee3686f1fc4eb3ec7d11c70d6b521af33bbade67' },
483
+ // Companion written by the installed test.3 package (LF and CRLF).
484
+ { version: '1.6.1-test.3', sha256: 'fdd88a4461864d612998f1cc13802a45bbc2aa04b19629b0e8bc0e75c0b9bfad' },
485
+ { version: '1.6.1-test.3', sha256: '4681ee17f741a56fbb9662aa5105863ab08badf8be7d7196c4268b816fc6fe94' },
486
+ // The published 1.6.1 companion and the local 1.6.1-test.5 prerelease that
487
+ // replaced it on this machine. Both are the SAME instruction body: `codex/dsh-taskbridge.toml`
488
+ // in the 1.6.1 sources, whose digest is unchanged by this work package. They differ
489
+ // only in the stamped `version` line that {@link renderAgentFile} writes, so each is a
490
+ // distinct exact identity that has to be enumerated on its own:
491
+ //
492
+ // * `efdef5f6…` — `1.6.1` as an all-LF file (the form an LF checkout installs).
493
+ // * `5da9fd5e…` — the same template, CRLF throughout (the repository's own spelling).
494
+ // * `bf698c86…` — the packed `1.6.1-test.5` agent, i.e. this body stamped `1.6.1-test.5`
495
+ // and written by this renderer (LF, the form the installer writes).
496
+ // * `a45e12d0…` — that same test.5 file with CRLF terminators.
497
+ //
498
+ // Without them an untouched 1.6.1 or test.5 installation hashes to "unknown content"
499
+ // and is reported `modified`, i.e. "somebody else's file", which is the false conflict
500
+ // this work package removes. Every one is an exact identity: a single edited character
501
+ // — including an edited version line — hashes differently and stays the operator's.
502
+ { version: '1.6.1', sha256: 'efdef5f6e6ebcb26590ca929e674391b3c4fcdb3c017714d2322615783fdf712' },
503
+ { version: '1.6.1', sha256: '5da9fd5eb5a89fd3c76365faca78b51e34233d993605f1b55dff4b07ceb88b80' },
504
+ { version: '1.6.1-test.5', sha256: 'bf698c861e7e560c555f8350b711db88627dce4a8752b2cbebe8748b6d640d37' },
505
+ { version: '1.6.1-test.5', sha256: 'a45e12d0b234e80854e69429518a2def2d00338f968c2ecfc689307b792e4426' },
506
+ // The local `1.6.1-test.6` build. Its agent identity was verified from the release the
507
+ // operator actually installed: `dsh-taskbridge-1.6.1-test.6.tgz` (SHA-256 `71bfd28d…`)
508
+ // holds `package/codex/dsh-taskbridge.toml`, whose LF form hashes to the 1.6.1 body above
509
+ // and which that build stamped `version = "1.6.1-test.6"` and wrote with LF. Those exact
510
+ // bytes (`f4650d62…`) are preserved as `tests/fixtures/agent-1.6.1-test.6.toml`, and the
511
+ // digest was cross-checked against the installed file.
512
+ //
513
+ // Without this entry an untouched test.6 installation that has no installation record is
514
+ // reported `modified` — "somebody else's file" — so the install button can never refresh
515
+ // a file this plugin really published. Only these exact bytes qualify: a single edited
516
+ // character, an added line, or another body carrying the same version line hashes
517
+ // differently and stays the operator's file.
518
+ { version: '1.6.1-test.6', sha256: 'f4650d6250b4133f6693f11c8288e973b433bbfab02e76ebba0eda989594d7b8' },
477
519
  ];
478
520
 
479
521
  /** The `version = "…"` line of an agent file, at column 0. */
@@ -609,6 +651,17 @@ const PACKAGE_MANIFEST_PATH = join(PACKAGE_ROOT, 'package.json');
609
651
  /** Bound on a Codex config document this module is willing to edit. */
610
652
  const MAX_CONFIG_BYTES = 1024 * 1024;
611
653
 
654
+ /**
655
+ * The non-enumerable key carrying a status read's environment to the installer's write paths.
656
+ *
657
+ * It is a SYMBOL, not a property name: `JSON.stringify`, object spread, `{...status}` and any
658
+ * transport copy of the document drop it, so `DSH_HOME` — and anything else in the host
659
+ * environment — can never travel in a status response. Only the installer's own write path
660
+ * reads it, and only to locate the plugin data directory.
661
+ * @type {symbol}
662
+ */
663
+ const INTERNAL_ENV = Symbol('dsh-delegate.codex.status.env');
664
+
612
665
  /**
613
666
  * Refusal raised by the installer. Carries a stable code so the settings page can
614
667
  * explain *why* rather than only *that* something failed.
@@ -1225,14 +1278,25 @@ async function runPowershell(script, env) {
1225
1278
 
1226
1279
  /**
1227
1280
  * Read a link's target for the diagnosis, never to follow it.
1281
+ *
1282
+ * A Windows junction cannot be read back as a path with `readlink`: Node reports it as a
1283
+ * plain directory and answers `EINVAL` for both the text and the raw-bytes form (its
1284
+ * substitute is a Win32 path behind a reparse header). The caller has already PROVED the
1285
+ * entry is a reparse point from its attributes, so the diagnosis still has to be produced;
1286
+ * `realpath` is the only portable way to name what it points at. It is used for the
1287
+ * DIAGNOSIS ONLY — nothing below an unproven link is read or written.
1228
1288
  * @param {string} path - link path.
1229
- * @returns {Promise<string | undefined>} target text when the platform reports one.
1289
+ * @returns {Promise<string | undefined>} target when the platform reports one.
1230
1290
  */
1231
1291
  async function readLinkTarget(path) {
1232
1292
  try {
1233
1293
  return await readlink(path);
1234
1294
  } catch {
1235
- return undefined;
1295
+ try {
1296
+ return await realpath(path);
1297
+ } catch {
1298
+ return undefined;
1299
+ }
1236
1300
  }
1237
1301
  }
1238
1302
 
@@ -1251,17 +1315,27 @@ async function readLinkTarget(path) {
1251
1315
  * from it) is what the write and delete paths re-prove against, so a file rewritten
1252
1316
  * between the read and the write is still detected even though this classification is
1253
1317
  * line-ending tolerant.
1318
+ *
1319
+ * A file whose LF-normalized digest equals the template digest this plugin recorded for THIS
1320
+ * Codex home is `outdated` too — that is how a release whose byte form was never enumerated on
1321
+ * its own still upgrades itself instead of flipping to "somebody else's file" (see
1322
+ * `agent-ownership.js`). One changed character changes the digest, so an edited file still
1323
+ * falls through to the rule below.
1254
1324
  * @param {string} path - agent file path.
1255
1325
  * @param {string} template - template text this build would write.
1256
- * @returns {Promise<{ state: string, present: boolean, reason: string | null, contents: string | null }>} agent state and the exact bytes it was derived from.
1326
+ * @param {string | null} [recordedDigest] - the LF digest this plugin recorded for this home.
1327
+ * @returns {Promise<{ state: string, present: boolean, reason: string | null, contents: string | null, recorded?: boolean }>} agent state and the exact bytes it was derived from.
1257
1328
  */
1258
- async function readAgentState(path, template) {
1329
+ async function readAgentState(path, template, recordedDigest = null) {
1259
1330
  const existing = await inspectFile(path);
1260
1331
  if (existing.kind === 'missing') return { state: AGENT_STATES.missing, present: false, reason: null, contents: null };
1261
1332
  if (existing.kind === 'other') return { state: AGENT_STATES.conflict, present: true, reason: 'not-a-regular-file', contents: null };
1262
1333
  const contents = existing.contents;
1263
1334
  if (sameAgentText(contents, template)) return { state: AGENT_STATES.installed, present: true, reason: null, contents };
1264
1335
  if (isKnownPriorTemplate(contents)) return { state: AGENT_STATES.outdated, present: true, reason: null, contents };
1336
+ if (typeof recordedDigest === 'string' && recordedDigest !== '' && digestLf(contents) === recordedDigest) {
1337
+ return { state: AGENT_STATES.outdated, present: true, reason: null, contents, recorded: true };
1338
+ }
1265
1339
  return {
1266
1340
  state: AGENT_STATES.modified,
1267
1341
  present: true,
@@ -1270,6 +1344,56 @@ async function readAgentState(path, template) {
1270
1344
  };
1271
1345
  }
1272
1346
 
1347
+ /**
1348
+ * The template digest this plugin last proved it wrote into one Codex home, or null.
1349
+ *
1350
+ * Read-only and failure-tolerant by design: an unusable data directory, a link on the way, a
1351
+ * damaged record — and every other error — is simply "no record", so it can never change how a
1352
+ * file is classified. Nothing is created and nothing is written here.
1353
+ * @param {string} home - the REAL, pinned Codex home.
1354
+ * @param {Record<string, string | undefined>} env - environment (for `DSH_HOME`).
1355
+ * @returns {Promise<string | null>} LF digest, or null.
1356
+ */
1357
+ async function recallRecordedTemplate(home, env) {
1358
+ if (typeof home !== 'string' || home.trim() === '' || !isAbsolute(home)) return null;
1359
+ try {
1360
+ return await recallTemplateDigest({ codexHome: home, env, classify: (path) => inspectDirectory(path).then((info) => info.kind) });
1361
+ } catch {
1362
+ return null;
1363
+ }
1364
+ }
1365
+
1366
+ /**
1367
+ * Record the template digest after a write this action just made, proved against the file.
1368
+ *
1369
+ * Called only from `install` and from the startup `refreshKnownAgentTemplate`, and only after the
1370
+ * write reported success: it re-reads the agent file, requires it to be exactly the rendered
1371
+ * template, and records the digest of THOSE bytes. `repair`, `remove` and `status` never reach
1372
+ * this. A failed record is a lost proof for the next release, never a failed install.
1373
+ * @param {object} before - the status the write was planned from.
1374
+ * @returns {Promise<void>} resolves after the attempt.
1375
+ */
1376
+ async function recordAgentTemplate(before) {
1377
+ const env = before[INTERNAL_ENV];
1378
+ if (env === undefined) return;
1379
+ try {
1380
+ await rememberTemplateDigest({
1381
+ codexHome: before.codexHome,
1382
+ env,
1383
+ template: renderAgentFile(await readAgentTemplate(), before.packageVersion),
1384
+ agentPath: before.agent.path,
1385
+ readFile: async (path) => (await inspectFile(path)).contents,
1386
+ writeFileAtomic,
1387
+ mkdir,
1388
+ classify: (path) => inspectDirectory(path).then((info) => info.kind),
1389
+ });
1390
+ } catch {
1391
+ // A proof that cannot be recorded must never fail the install that produced it, and a
1392
+ // refused record (a linked ancestor, a damaged file) is no record: the agent file stays
1393
+ // classified by its own content.
1394
+ }
1395
+ }
1396
+
1273
1397
  /**
1274
1398
  * Inspect the two directories that bound what this module may write.
1275
1399
  *
@@ -1544,8 +1668,30 @@ export function classifyMcpEntry(document, desired) {
1544
1668
  const previous = { command, args, envKeys, toolTimeoutSec: null, discoveryFile: null };
1545
1669
  if (marker === null) {
1546
1670
  // Values that happen to match are still not proof the plugin wrote them; the
1547
- // marker is the only authorship proof this format carries.
1548
- return { state: MCP_STATES.conflict, previous, reason: 'unmanaged-entry', ownedValues: {}, marked: false, drift: null };
1671
+ // marker is the only authorship proof this format carries. The state is therefore
1672
+ // always `conflict`: a status read, plugin startup and `remove` never adopt it.
1673
+ //
1674
+ // The reason distinguishes ONE case: values that are already exactly what this build
1675
+ // writes (`unmanaged-entry-exact`) — the configuration the settings page shows, the
1676
+ // screenshot case, entered by hand without the marker comment. Only the MCP-only
1677
+ // repair may complete that one, by ADDING the marker and nothing else
1678
+ // ({@link emplaceMcpMarker}); any other difference keeps the plain refusal.
1679
+ //
1680
+ // "Already exactly ours" also requires the definition to be ONE unambiguous table: the
1681
+ // parser keeps every entry, so a duplicated key, an inline table plus a header, an extra
1682
+ // sub-table or an unknown field would otherwise be merged into this object and the LAST
1683
+ // value would silently win. Such a document is somebody else's and keeps the plain
1684
+ // refusal, so a marker can never be attached to a shape this plugin did not write.
1685
+ const exact = isUnambiguousOwnedDefinition(document, serverPath)
1686
+ && markerlessEntryMatchesOwnedShape(values, desired);
1687
+ return {
1688
+ state: MCP_STATES.conflict,
1689
+ previous,
1690
+ reason: exact ? UNMANAGED_EXACT_REASON : 'unmanaged-entry',
1691
+ ownedValues: {},
1692
+ marked: false,
1693
+ drift: null,
1694
+ };
1549
1695
  }
1550
1696
  // A different *command* is a different program: even if the arguments look like
1551
1697
  // ours, running (or replacing) someone else's wrapper is not this plugin's call.
@@ -1694,9 +1840,12 @@ export async function isOwnedStaleEntry(classification, desired, options = {}) {
1694
1840
  // The script proof is a FILESYSTEM proof and runs here, at gate time, so a label
1695
1841
  // computed earlier cannot stand in for it.
1696
1842
  if (isExactInstalledScript(args[0], desired.args[0])) {
1697
- return classification.state === MCP_STATES.outdated
1698
- ? { owned: true }
1699
- : { owned: false, reason: `state-${classification.state}` };
1843
+ // A proven managed entry is writable when it is `outdated` (a stale owned fact), or when
1844
+ // it is the `unmanaged-entry-exact` definition {@link emplaceMcpMarker} has just
1845
+ // re-proved — the MCP-only repair completing it with the marker line alone.
1846
+ const writable = classification.state === MCP_STATES.outdated
1847
+ || (classification.state === MCP_STATES.conflict && classification.reason === UNMANAGED_EXACT_REASON);
1848
+ return writable ? { owned: true } : { owned: false, reason: `state-${classification.state}` };
1700
1849
  }
1701
1850
  if (options.allowMovedInstall !== true) return { owned: false, reason: 'script-not-provably-ours' };
1702
1851
  if (!(await isOtherInstallationOfThisPackage(args[0], PACKAGE_NAME))) {
@@ -1707,6 +1856,104 @@ export async function isOwnedStaleEntry(classification, desired, options = {}) {
1707
1856
  : { owned: false, reason: `state-${classification.state}` };
1708
1857
  }
1709
1858
 
1859
+ /**
1860
+ * Stable `reason` value for an unmarked definition whose owned facts are ALREADY exactly
1861
+ * this build's (the entry shown on the settings page, entered without its marker).
1862
+ * @type {string}
1863
+ */
1864
+ export const UNMANAGED_EXACT_REASON = 'unmanaged-entry-exact';
1865
+
1866
+ /**
1867
+ * Is an UNMARKED definition already EXACTLY the entry this build would write?
1868
+ *
1869
+ * Strict by construction, and the only question {@link classifyMcpEntry} asks about an
1870
+ * unmarked entry beyond "is it somebody else's", because it decides whether a marker could
1871
+ * be added WITHOUT changing any owned value:
1872
+ *
1873
+ * * `command` equals the resolved Node executable;
1874
+ * * `args` is exactly ONE element, this installation's entry script;
1875
+ * * `tool_timeout_sec` is present and is the owned integer;
1876
+ * * the `env` map is exactly the owned one — every expected key with its value and no
1877
+ * additional key (an `env` key this plugin did not write is the operator's data).
1878
+ *
1879
+ * A missing field is a difference, not a default. Nothing here writes or inspects the
1880
+ * filesystem; the filesystem proof belongs to the write gate.
1881
+ * @param {Record<string, { type: string, text: string }>} values - assignments under the definition.
1882
+ * @param {object} desired - value from {@link desiredMcpCommand}.
1883
+ * @returns {boolean} true only when every owned fact already matches exactly.
1884
+ */
1885
+ function markerlessEntryMatchesOwnedShape(values, desired) {
1886
+ if (typeof desired?.command !== 'string' || !Array.isArray(desired?.args)) return false;
1887
+ if (readStringValue(values.command?.text) !== desired.command) return false;
1888
+ const args = readArrayValue(values.args?.text);
1889
+ if (args.length !== 1 || desired.args.length !== 1 || args[0] !== desired.args[0]) return false;
1890
+ if (readIntegerValue(values.tool_timeout_sec?.text) !== desired.toolTimeoutSec) return false;
1891
+ const expectedEnv = desired.env ?? {};
1892
+ const expectedKeys = Object.keys(expectedEnv).sort();
1893
+ const recordedKeys = Object.keys(values)
1894
+ .filter((key) => key.startsWith('env.'))
1895
+ .map((key) => key.slice(4))
1896
+ .sort();
1897
+ if (!sameStrings(recordedKeys, expectedKeys)) return false;
1898
+ return expectedKeys.every((key) => readStringValue(values[`env.${key}`]?.text) === expectedEnv[key]);
1899
+ }
1900
+
1901
+ /**
1902
+ * Does the document spell this server as ONE, unambiguous standard table?
1903
+ *
1904
+ * {@link classifyMcpEntry} builds its `values` object by merging what the parser reports, so
1905
+ * a document the parser accepts but TOML forbids (or that means two things at once) would
1906
+ * silently collapse into the LAST value. This check runs BEFORE that merge decision, so an
1907
+ * ambiguous definition can never be called "already exactly ours" and can never receive the
1908
+ * marker — the MCP-only repair must not take over an entry whose real value it cannot read.
1909
+ *
1910
+ * Accepted, and nothing else:
1911
+ *
1912
+ * * a single `[mcp_servers.dsh-delegate]` standard header (not `[[…]]`), the shape this
1913
+ * plugin writes itself. The inline `dsh-delegate = { … }` spelling is NOT accepted here:
1914
+ * the page renders the block form, so a hand-entered inline definition is not something
1915
+ * this path may complete;
1916
+ * * assignments that sit BENEATH that header and belong to this server — one per key, so
1917
+ * no duplicate `command`/`args`/`tool_timeout_sec`/`env.X`, and no second spelling of
1918
+ * the same key through a dotted path.
1919
+ *
1920
+ * Refused: a duplicated key of any kind, an inline table next to (or instead of) a header, a
1921
+ * definition that appears before its own header, a second header for the same path, an extra
1922
+ * table under the server (`[mcp_servers.dsh-delegate.custom]`, including an empty one), an
1923
+ * array table, and a `key = { … }` value that TOML would treat as a nested table the shape
1924
+ * check cannot see. The plain `unmanaged-entry` refusal is the answer for all of them.
1925
+ * @param {TomlDocument} document - parsed config.
1926
+ * @param {string[]} serverPath - `['mcp_servers', MCP_SERVER_NAME]`.
1927
+ * @returns {boolean} true only for the single standard table with unique keys.
1928
+ */
1929
+ function isUnambiguousOwnedDefinition(document, serverPath) {
1930
+ const { inline, headerIndex } = locateMcpDefinition(document);
1931
+ if (inline !== undefined) return false;
1932
+ if (headerIndex === -1) return false;
1933
+ const header = document.entries[headerIndex];
1934
+ if (header.kind !== 'table') return false;
1935
+ // Exactly one header for this exact path, and no table at all below it.
1936
+ const sameServer = document.entries.filter((entry) => entry.kind !== 'assignment'
1937
+ && entry.path.length >= serverPath.length
1938
+ && serverPath.every((segment, index) => entry.path[index] === segment));
1939
+ if (sameServer.length !== 1) return false;
1940
+ // Every entry that names this server from above is that one header.
1941
+ if (document.entries.some((entry) => entry !== header && entry.path.length === serverPath.length
1942
+ && samePath(entry.path, serverPath))) return false;
1943
+ const seen = new Set();
1944
+ for (const entry of document.assignmentsUnder(serverPath)) {
1945
+ if (entry === inline) continue;
1946
+ if (entry.path.length <= serverPath.length) return false;
1947
+ if (entry.startLine < header.startLine) return false;
1948
+ const key = entry.path.slice(serverPath.length).join('.');
1949
+ if (seen.has(key)) return false;
1950
+ seen.add(key);
1951
+ // A nested inline table would hide keys from {@link describeEntryShape}.
1952
+ if (tomlValueType(entry.raw) === 'table') return false;
1953
+ }
1954
+ return true;
1955
+ }
1956
+
1710
1957
  /**
1711
1958
  * The native path rules, as a value, so {@link packageEntryRoot} can also be exercised
1712
1959
  * with an explicit POSIX/Win32 rule set in tests instead of only on the host platform.
@@ -2178,6 +2425,141 @@ function renderMcpBlock(desired) {
2178
2425
  return lines;
2179
2426
  }
2180
2427
 
2428
+ /**
2429
+ * The character offset a `{ line, column }` position names in the document's exact text.
2430
+ *
2431
+ * Offsets are counted in CHARACTERS (what `String#split`, `slice` and `indexOf` use), never in
2432
+ * bytes, so a UTF-8 BOM or a non-ASCII comment shifts nothing. A position past the end of its
2433
+ * line is clamped to that line's end rather than spilling into the next one.
2434
+ * @param {string} text - the document text.
2435
+ * @param {number} line - 0-based line index, as the parser reports it (lines split on `\n`).
2436
+ * @param {number} [column] - 0-based character column.
2437
+ * @returns {number} the offset, or -1 when the line does not exist.
2438
+ */
2439
+ function offsetAt(text, line, column = 0) {
2440
+ if (!Number.isInteger(line) || line < 0) return -1;
2441
+ let cursor = 0;
2442
+ for (let index = 0; index < line; index += 1) {
2443
+ const next = text.indexOf('\n', cursor);
2444
+ if (next === -1) return -1;
2445
+ cursor = next + 1;
2446
+ }
2447
+ const end = text.indexOf('\n', cursor);
2448
+ const limit = end === -1 ? text.length : end;
2449
+ const wanted = Number.isInteger(column) && column > 0 ? column : 0;
2450
+ return Math.min(cursor + wanted, limit);
2451
+ }
2452
+
2453
+ /**
2454
+ * The line ending to use for a line inserted at `offset`.
2455
+ *
2456
+ * A marker is one inserted LINE, so it takes the ending of the line it is placed before — the
2457
+ * bytes immediately preceding `offset` when they are a `\n` or `\r\n`, otherwise the next
2458
+ * `\n` in the document. This keeps a mixed or CRLF file exactly as it was instead of
2459
+ * normalizing it, and it never depends on an "average" ending.
2460
+ * @param {string} text - the document text.
2461
+ * @param {number} offset - where the line is inserted.
2462
+ * @returns {string} `'\r\n'` or `'\n'`.
2463
+ */
2464
+ function lineEndingAt(text, offset) {
2465
+ if (text[offset - 1] === '\n') return text[offset - 2] === '\r' ? '\r\n' : '\n';
2466
+ const next = text.indexOf('\n', offset);
2467
+ return next > 0 && text[next - 1] === '\r' ? '\r\n' : '\n';
2468
+ }
2469
+
2470
+ /**
2471
+ * Add ONLY the plugin marker line directly above the server's own definition header.
2472
+ *
2473
+ * Nothing is re-serialized: the marker and one line ending are spliced into the ORIGINAL
2474
+ * text at the header line's character offset, so every existing character — a BOM, mixed CRLF
2475
+ * and LF endings, a missing final newline, the header's own indentation, comments above it —
2476
+ * is copied through untouched. Deleting the inserted line therefore restores the original
2477
+ * bytes. The marker always goes above the server's own header, never above a shared
2478
+ * `[mcp_servers]` parent, because a marker there would claim the sibling entries too.
2479
+ * @param {TomlDocument} document - parsed config with a single standard server table.
2480
+ * @param {number} startLine - the header's 0-based line as the parser reports it.
2481
+ * @returns {{ text: string, offset: number } | { text: null, reason: string }} the edit.
2482
+ */
2483
+ function insertMcpMarker(document, startLine) {
2484
+ const text = document.text;
2485
+ const offset = offsetAt(text, startLine, 0);
2486
+ if (offset === -1) return { text: null, reason: 'no-definition-line' };
2487
+ // The header line must really start there, otherwise the offset is not trustworthy.
2488
+ if (!/^\s*\[/u.test(text.slice(offset, offset + 128))) return { text: null, reason: 'header-not-at-offset' };
2489
+ const marker = `${MCP_MARKER}${lineEndingAt(text, offset)}`;
2490
+ return { text: `${text.slice(0, offset)}${marker}${text.slice(offset)}`, offset };
2491
+ }
2492
+
2493
+ /**
2494
+ * Is `next` exactly `text` with one line inserted at `offset`, and nothing else?
2495
+ * @param {string} text - original text.
2496
+ * @param {string} next - edited text.
2497
+ * @param {number} offset - insertion offset.
2498
+ * @returns {boolean} true when removing that one line gives the original back byte for byte.
2499
+ */
2500
+ function isSingleInsertedLine(text, next, offset) {
2501
+ if (typeof next !== 'string' || next.length <= text.length) return false;
2502
+ const insertedLength = next.length - text.length;
2503
+ if (next.slice(0, offset) !== text.slice(0, offset)) return false;
2504
+ if (next.slice(offset + insertedLength) !== text.slice(offset)) return false;
2505
+ const inserted = next.slice(offset, offset + insertedLength);
2506
+ return inserted === `${MCP_MARKER}${lineEndingAt(text, offset)}`;
2507
+ }
2508
+
2509
+ /**
2510
+ * May the marker be added to an unmarked definition, treating the entry as this plugin's?
2511
+ *
2512
+ * This is the write gate of the “仅修复 MCP 配置” button's marker step. It is deliberately
2513
+ * narrower than "the classifier said conflict":
2514
+ *
2515
+ * * the definition is `unmanaged-entry-exact` — every owned fact already equals what this
2516
+ * build writes, which is the only case where adding a marker changes no value;
2517
+ * * it is ONE unambiguous standard table (re-checked HERE, because the caller may have read
2518
+ * the document at a different moment): no duplicated key, no inline table beside a header,
2519
+ * no extra or empty sub-table, no unknown field;
2520
+ * * `args[0]` is this installation's exact script, proved on the filesystem here;
2521
+ * * the marker can be spliced in above the server's own header as ONE inserted line — so the
2522
+ * edit never re-serializes, normalizes a line ending or appends a missing final newline;
2523
+ * * the edited document re-classifies as `configured` and its marker is adjacent to the
2524
+ * server's own header, never to a shared `[mcp_servers]` parent.
2525
+ *
2526
+ * The uninstall boundary is the existing one: the marker is the same marker `install` writes,
2527
+ * `remove` deletes only a range it can prove, and the operator's own comments and sibling
2528
+ * entries are outside that range. Anything refused here leaves the file byte-identical.
2529
+ * @param {TomlDocument} document - parsed config.
2530
+ * @param {object} desired - value from {@link desiredMcpCommand}.
2531
+ * @returns {Promise<{ ok: true, text: string } | { ok: false, reason: string }>} verdict.
2532
+ */
2533
+ export async function emplaceMcpMarker(document, desired) {
2534
+ if (desired === null || desired === undefined) return { ok: false, reason: 'no-owned-shape' };
2535
+ const serverPath = ['mcp_servers', MCP_SERVER_NAME];
2536
+ const classification = classifyMcpEntry(document, desired);
2537
+ if (classification.state !== MCP_STATES.conflict || classification.reason !== UNMANAGED_EXACT_REASON) {
2538
+ return { ok: false, reason: classification.reason ?? `state-${classification.state}` };
2539
+ }
2540
+ if (classification.marked === true) return { ok: false, reason: 'already-marked' };
2541
+ if (!isUnambiguousOwnedDefinition(document, serverPath)) return { ok: false, reason: 'ambiguous-definition' };
2542
+ const args = Array.isArray(classification.previous?.args) ? classification.previous.args : [];
2543
+ if (args.length !== 1) return { ok: false, reason: 'args-shape-not-ours' };
2544
+ if (!isExactInstalledScript(args[0], desired.args[0])) return { ok: false, reason: 'script-not-ours' };
2545
+ // The same gate the managed refresh uses, argued from the values just proved identical to
2546
+ // the owned entry (the marker is the line being ADDED, so it cannot be the premise).
2547
+ const gate = await isOwnedStaleEntry({ ...classification, marked: true }, desired);
2548
+ if (gate.owned !== true) return { ok: false, reason: gate.reason };
2549
+ const { headerIndex } = locateMcpDefinition(document);
2550
+ const edit = insertMcpMarker(document, document.entries[headerIndex].startLine);
2551
+ if (edit.text === null) return { ok: false, reason: edit.reason };
2552
+ if (!isSingleInsertedLine(document.text, edit.text, edit.offset)) {
2553
+ return { ok: false, reason: 'edit-not-a-single-line' };
2554
+ }
2555
+ const after = new TomlDocument(edit.text);
2556
+ if (locateMcpDefinition(after).marker !== MCP_MARKER) return { ok: false, reason: 'marker-not-adjacent' };
2557
+ if (classifyMcpEntry(after, desired).state !== MCP_STATES.configured) {
2558
+ return { ok: false, reason: 'result-not-configured' };
2559
+ }
2560
+ return { ok: true, text: edit.text };
2561
+ }
2562
+
2181
2563
  /**
2182
2564
  * Apply the managed MCP entry to a config document, preserving everything else.
2183
2565
  *
@@ -2389,7 +2771,10 @@ export async function readCodexStatus({
2389
2771
  : (pinned.error?.reason ?? (boundary.link === 'codex-home' ? 'codex-home-is-link' : 'agents-dir-is-link')),
2390
2772
  contents: null,
2391
2773
  }
2392
- : await readAgentState(agentPath, template);
2774
+ : await readAgentState(agentPath, template, await recallRecordedTemplate(home, env));
2775
+ // A READ never writes: this function classifies the files and records nothing. The template
2776
+ // digest is recorded only by `install` and by the startup `refreshKnownAgentTemplate`, after
2777
+ // those actions themselves wrote and re-proved the file.
2393
2778
  const script = await resolveMcpScript();
2394
2779
  // A host with no provable Node.js runtime is a *reported* state, not a thrown
2395
2780
  // failure: the status still describes the agent file and the operator needs the
@@ -2470,7 +2855,7 @@ export async function readCodexStatus({
2470
2855
  }
2471
2856
  }
2472
2857
 
2473
- return buildStatus({
2858
+ const status = buildStatus({
2474
2859
  // The REAL directory every action uses, plus the selected spelling so an operator who
2475
2860
  // configured a junction can recognise it. `codexHome` is always the path actually
2476
2861
  // read and written.
@@ -2493,6 +2878,12 @@ export async function readCodexStatus({
2493
2878
  boundary,
2494
2879
  configFingerprint,
2495
2880
  });
2881
+ // The environment the read was taken WITH, kept beside — never inside — the document: the
2882
+ // write paths need it to reach the plugin's own data directory (`DSH_HOME`). A
2883
+ // non-enumerable property cannot be serialized, spread or returned by an HTTP transport, so
2884
+ // no environment value (and no credential in it) can ever leak through a status response.
2885
+ Object.defineProperty(status, INTERNAL_ENV, { value: env, enumerable: false, configurable: true });
2886
+ return status;
2496
2887
  }
2497
2888
 
2498
2889
  /**
@@ -2564,6 +2955,11 @@ function buildStatus({
2564
2955
  // re-reads the file and compares against this immediately before its rename, so
2565
2956
  // a file edited between the status read and the write is never replaced.
2566
2957
  expect: agent.contents ?? null,
2958
+ // True when this file was recognised through the template digest recorded for THIS home
2959
+ // rather than through the enumerated published history. It never reaches a response
2960
+ // (`publicCodexStatus` strips it) and it never makes a state: an unproved file is still
2961
+ // `modified`.
2962
+ recorded: agent.recorded === true,
2567
2963
  },
2568
2964
  mcp: {
2569
2965
  path: configPath,
@@ -2617,7 +3013,13 @@ function buildNotes({ agent, mcp, script, configError, nodeError = null }) {
2617
3013
  if (agent.state === AGENT_STATES.modified) {
2618
3014
  notes.push({
2619
3015
  code: 'AGENT_USER_MODIFIED',
2620
- text: `已存在内容不同的 agents/${AGENT_FILENAME},本插件不会覆盖或删除它;如需插件版本请先自行移动该文件。`,
3016
+ text: `已存在内容不同的 agents/${AGENT_FILENAME},本插件不会覆盖或删除它。`
3017
+ + (agent.reason === 'edited'
3018
+ // The bytes are one of this plugin's own templates with something changed — a
3019
+ // single character, an added note, or only the version line. Saying WHICH keeps
3020
+ // the operator from guessing, and never suggests deleting a file they may want.
3021
+ ? '它与本插件发布过的某个模板只在个别字节上不同(可能只改了 version 行,或加了一处你自己的说明);改回该发布版本的原样内容后,本插件会自动更新它,否则由你继续管理。'
3022
+ : '它不是本插件发布过的模板,因此插件不会把它当作自己的文件;由你继续管理即可。'),
2621
3023
  });
2622
3024
  }
2623
3025
  if (agent.state === AGENT_STATES.conflict) {
@@ -2641,9 +3043,11 @@ function buildNotes({ agent, mcp, script, configError, nodeError = null }) {
2641
3043
  code: 'MCP_ENTRY_CONFLICT',
2642
3044
  text: mcp.reason === 'unmanaged-entry'
2643
3045
  ? `config.toml 中已有同名的 mcp_servers.${MCP_SERVER_NAME} 条目,但没有本插件的托管标记注释,视为你自己写的:本插件不会更新或删除它;请自行删除或改名后再点安装。`
2644
- : (mcp.reason === 'args-shape-not-ours'
2645
- ? `config.toml 中已有的 mcp_servers.${MCP_SERVER_NAME} 条目带托管标记,但入口脚本与当前安装不同。若那是本插件的另一处真实安装,点「安装 / 更新 Codex 集成」或「仅修复 MCP 配置」会在证明后采纳;否则本插件不会替换它。`
2646
- : `config.toml 中已有同名的 mcp_servers.${MCP_SERVER_NAME} 条目,但内容不是本插件写入的形态(${mcp.reason ?? 'unknown'})。本插件不会替换它;请自行删除或改名后再点安装。`),
3046
+ : (mcp.reason === UNMANAGED_EXACT_REASON
3047
+ ? `config.toml 中已有同名的 mcp_servers.${MCP_SERVER_NAME} 条目,内容与当前插件应写入的条目完全一致(命令、入口脚本、参数、超时与环境项都相同),只缺托管标记注释。点「仅修复 MCP 配置」只会补上这一行标记,不改动其他内容;「安装 / 更新 Codex 集成」不会替你接管它。`
3048
+ : (mcp.reason === 'args-shape-not-ours'
3049
+ ? `config.toml 中已有的 mcp_servers.${MCP_SERVER_NAME} 条目带托管标记,但入口脚本与当前安装不同。若那是本插件的另一处真实安装,点「安装 / 更新 Codex 集成」或「仅修复 MCP 配置」会在证明后采纳;否则本插件不会替换它。`
3050
+ : `config.toml 中已有同名的 mcp_servers.${MCP_SERVER_NAME} 条目,但内容不是本插件写入的形态(${mcp.reason ?? 'unknown'})。本插件不会替换它;请自行删除或改名后再点安装。`)),
2647
3051
  });
2648
3052
  }
2649
3053
  if (mcp.state === MCP_STATES.outdated) {
@@ -2769,7 +3173,10 @@ export async function runCodexAction(action, {
2769
3173
  // MCP only: the agent file is not touched at all — not created, not refreshed,
2770
3174
  // not deleted. The returned status still reports its real (possibly `not-installed`
2771
3175
  // or `outdated`) state, so the page can tell the operator to run `install`.
2772
- await installMcpEntry(before, { changed, refused });
3176
+ //
3177
+ // The marker step is this button's alone: it completes an entry that is ALREADY exactly
3178
+ // this build's definition, and touches nothing else.
3179
+ await installMcpEntry(before, { changed, refused }, { allowMarkerEmplacement: true });
2773
3180
  } else {
2774
3181
  await installManaged(before, { changed, refused });
2775
3182
  }
@@ -2874,7 +3281,13 @@ export async function refreshKnownAgentTemplate(options = {}) {
2874
3281
  return { changed, refused, status };
2875
3282
  }
2876
3283
 
2877
- /** Install or refresh the managed agent file without touching the MCP entry. */
3284
+ /**
3285
+ * Install or refresh the managed agent file without touching the MCP entry.
3286
+ *
3287
+ * Both successful writes end with `recordAgentTemplate`, which re-reads the file and records the
3288
+ * template digest only when those bytes are exactly what this build renders. A refused write
3289
+ * records nothing.
3290
+ */
2878
3291
  async function installManagedAgent(before, outcome) {
2879
3292
  const { agent } = before;
2880
3293
  if (agent.state === AGENT_STATES.missing || agent.state === AGENT_STATES.outdated) {
@@ -2894,6 +3307,7 @@ async function installManagedAgent(before, outcome) {
2894
3307
  });
2895
3308
  return;
2896
3309
  }
3310
+ await recordAgentTemplate(before);
2897
3311
  outcome.changed.push('agent');
2898
3312
  } else {
2899
3313
  // A refresh replaces a byte-exact known build of our own file. Re-check right
@@ -2910,6 +3324,7 @@ async function installManagedAgent(before, outcome) {
2910
3324
  return;
2911
3325
  }
2912
3326
  await writeFileAtomic(agent.path, template);
3327
+ await recordAgentTemplate(before);
2913
3328
  outcome.changed.push('agent');
2914
3329
  }
2915
3330
  } else if (agent.state === AGENT_STATES.modified || agent.state === AGENT_STATES.conflict) {
@@ -2930,9 +3345,11 @@ async function installManagedAgent(before, outcome) {
2930
3345
  * `repair` cannot create the `agents/` directory, refresh a stale agent or remove one.
2931
3346
  * @param {object} before - status read before the change.
2932
3347
  * @param {{ changed: string[], refused: object[] }} outcome - mutable outcome.
3348
+ * @param {object} [options] - `allowMarkerEmplacement`: let an unmarked entry that is already
3349
+ * exactly this build's definition receive ONLY the marker line (the MCP-only repair).
2933
3350
  * @returns {Promise<void>} resolves after the target was attempted.
2934
3351
  */
2935
- async function installMcpEntry(before, outcome) {
3352
+ async function installMcpEntry(before, outcome, { allowMarkerEmplacement = false } = {}) {
2936
3353
  const { mcp } = before;
2937
3354
  if (mcp.scriptExists !== true) {
2938
3355
  outcome.refused.push({
@@ -2967,25 +3384,32 @@ async function installMcpEntry(before, outcome) {
2967
3384
  return;
2968
3385
  }
2969
3386
  if (mcp.state === MCP_STATES.conflict) {
2970
- // The ONE conflict an explicit `install`/`repair` may resolve: a marked entry whose
2971
- // script is a DIFFERENT path that is provably another installation of this package
2972
- // (its root's `package.json` declares our name and its `bin` is that very file). This
2973
- // is the moved-installation upgrade, and it is proved here, on the spot — the bare
2974
- // classification never grants it, and the unattended startup path never attempts it.
3387
+ // TWO conflicts an explicit action may resolve, both proved here, on the spot — the bare
3388
+ // classification never grants either, and the unattended startup path attempts neither:
3389
+ //
3390
+ // 1. a MARKED entry whose script is a DIFFERENT path that is provably another
3391
+ // installation of this package (its root's `package.json` declares our name and its
3392
+ // `bin` is that very file): the moved-installation upgrade; and
3393
+ // 2. for `repair` only, an UNMARKED entry that is ALREADY exactly this build's
3394
+ // definition: the marker line is added and no value is touched. Any other unmarked
3395
+ // entry stays refused, byte-identical.
2975
3396
  const adopted = await adoptProvedMovedInstall(before);
2976
- if (adopted === null) {
2977
- outcome.refused.push({
2978
- target: 'mcp',
2979
- code: 'MCP_ENTRY_CONFLICT',
2980
- message: mcp.reason === 'unmanaged-entry'
2981
- ? 'a same-name mcp_servers.dsh-delegate entry without the plugin marker already exists and was left untouched'
2982
- : 'a different mcp_servers.dsh-delegate entry already exists and was left untouched',
2983
- path: mcp.path,
2984
- reason: mcp.reason,
2985
- });
3397
+ if (adopted !== null) {
3398
+ await adoptMovedInstall(adopted, outcome, before);
2986
3399
  return;
2987
3400
  }
2988
- await adoptMovedInstall(adopted, outcome, before);
3401
+ if (allowMarkerEmplacement === true && await emplaceMcpMarkerFor(before, outcome)) return;
3402
+ outcome.refused.push({
3403
+ target: 'mcp',
3404
+ code: 'MCP_ENTRY_CONFLICT',
3405
+ message: mcp.reason === 'unmanaged-entry'
3406
+ ? 'a same-name mcp_servers.dsh-delegate entry without the plugin marker already exists and was left untouched'
3407
+ : mcp.reason === UNMANAGED_EXACT_REASON
3408
+ ? "a same-name mcp_servers.dsh-delegate entry matches this plugin's entry exactly but has no marker; only 仅修复 MCP 配置 may add it, and the file was left untouched"
3409
+ : 'a different mcp_servers.dsh-delegate entry already exists and was left untouched',
3410
+ path: mcp.path,
3411
+ reason: mcp.reason,
3412
+ });
2989
3413
  return;
2990
3414
  }
2991
3415
  if (mcp.state === MCP_STATES.configured) return;
@@ -3012,6 +3436,72 @@ async function installMcpEntry(before, outcome) {
3012
3436
  outcome.changed.push('mcp');
3013
3437
  }
3014
3438
 
3439
+ /**
3440
+ * Complete an unmarked definition that is ALREADY exactly this build's entry, with the
3441
+ * marker line and nothing else.
3442
+ *
3443
+ * This is the “仅修复 MCP 配置” button's marker step. The plan in `before` is only a hint:
3444
+ * every fact it relies on is re-proved against the CURRENT bytes immediately before the write:
3445
+ *
3446
+ * 1. the boundary (`$CODEX_HOME`, `agents/`) is inspected again — a link can have appeared;
3447
+ * 2. `config.toml` is re-read and its digest must equal the plan's `fingerprint`, so an
3448
+ * operator edit between the read and the write is kept instead of overwritten;
3449
+ * 3. {@link emplaceMcpMarker} re-classifies the CURRENT document, proves `args[0]` on the
3450
+ * filesystem, refuses a position the operator's own comment occupies, requires the result
3451
+ * to classify as `configured`, and requires the edit to be exactly one inserted line.
3452
+ *
3453
+ * The write is one atomic replacement built from the bytes just re-read, and it carries the
3454
+ * same one-line change. A refused step leaves the file byte-identical.
3455
+ * @param {object} before - status read before the change.
3456
+ * @param {{ changed: string[], refused: object[] }} outcome - mutable outcome.
3457
+ * @returns {Promise<boolean>} true when this step handled the entry (a change or a refusal);
3458
+ * false when it does not apply and the caller reports its own conflict.
3459
+ */
3460
+ async function emplaceMcpMarkerFor(before, outcome) {
3461
+ const { mcp } = before;
3462
+ if (mcp.state !== MCP_STATES.conflict || mcp.reason !== UNMANAGED_EXACT_REASON) return false;
3463
+ const refuse = (reason, message) => {
3464
+ outcome.refused.push({ target: 'mcp', code: 'MCP_ENTRY_CONFLICT', message, path: mcp.path, reason });
3465
+ };
3466
+ if (before.config?.readable !== true) {
3467
+ refuse('config-unreadable', 'the Codex config could not be read, so no marker was added');
3468
+ return true;
3469
+ }
3470
+ const boundary = await inspectCodexBoundary(before.codexHome);
3471
+ if (boundary.blocked === true) {
3472
+ outcome.refused.push(linkedBoundaryRefusal({ ...before, boundary }));
3473
+ return true;
3474
+ }
3475
+ let loaded;
3476
+ try {
3477
+ loaded = await loadConfig(mcp.path);
3478
+ } catch (error) {
3479
+ refuse(
3480
+ typeof error?.code === 'string' ? error.code : 'CODEX_CONFIG_UNREADABLE',
3481
+ typeof error?.message === 'string' ? error.message : 'the Codex config could not be read',
3482
+ );
3483
+ return true;
3484
+ }
3485
+ if (loaded.unreadable === true) {
3486
+ refuse('CODEX_CONFIG_UNSUPPORTED', 'the Codex config is not readable as TOML and was left untouched');
3487
+ return true;
3488
+ }
3489
+ if (typeof mcp.fingerprint !== 'string' || digest(loaded.document.text) !== mcp.fingerprint) {
3490
+ refuse('config-changed', 'config.toml changed after the entry was checked, so nothing was written');
3491
+ return true;
3492
+ }
3493
+ const emplaced = await emplaceMcpMarker(loaded.document, mcp.desired);
3494
+ if (emplaced.ok !== true) {
3495
+ refuse(emplaced.reason,
3496
+ "the mcp_servers.dsh-delegate entry is not exactly this plugin's own definition, so no marker was added and the file was left untouched");
3497
+ return true;
3498
+ }
3499
+ await mkdir(dirname(mcp.path), { recursive: true, mode: 0o700 });
3500
+ await writeFileAtomic(mcp.path, emplaced.text);
3501
+ outcome.changed.push('mcp');
3502
+ return true;
3503
+ }
3504
+
3015
3505
  /**
3016
3506
  * Upgrade ONE managed MCP entry that is already installed and merely stale.
3017
3507
  *
@@ -3496,7 +3986,7 @@ async function removeManaged(before, outcome) {
3496
3986
  */
3497
3987
  export function publicCodexStatus(status) {
3498
3988
  if (status === null || typeof status !== 'object') return status;
3499
- const { expect: _ignored, ...agent } = status.agent ?? {};
3989
+ const { expect: _ignored, recorded: _record, ...agent } = status.agent ?? {};
3500
3990
  // `mcp.fingerprint` is the write path's receipt for the exact config bytes it plans to
3501
3991
  // replace. It is a digest, not content, but it is an internal planning fact like
3502
3992
  // `agent.expect`, so it does not belong in a response an operator or a page reads.