@sema-agent/settings-schema 27.2.0 → 29.0.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 (221) hide show
  1. package/CHANGELOG.md +753 -0
  2. package/README.md +88 -12
  3. package/conformance/VERSION +1 -1
  4. package/conformance/cases/c01-entry-salvage-then-typo/expected.json +1 -1
  5. package/conformance/cases/c02-hosts-clamp-stacked/expected.json +1 -1
  6. package/conformance/cases/c03-literal-dotted-top-key/expected.json +1 -1
  7. package/conformance/cases/c04-all-bad-collection-not-salvaged/expected.json +1 -1
  8. package/conformance/cases/c07-hooks-is-not-a-config-domain/expected.json +1 -1
  9. package/conformance/cases/c08-limits-unknown-carried-64/expected.json +1 -1
  10. package/conformance/cases/c09-limits-unknown-carried-65/expected.json +1 -1
  11. package/conformance/cases/c10-record-key-secret-redacted-twice/expected.json +1 -1
  12. package/conformance/cases/c11-unicode-unknown-keys/expected.json +1 -1
  13. package/conformance/cases/c12-prototype-name-top-keys/expected.json +1 -1
  14. package/conformance/cases/c13-models-field-null/expected.json +1 -1
  15. package/conformance/cases/c14-models-field-empty-array/expected.json +1 -1
  16. package/conformance/cases/c15-models-field-number/expected.json +1 -1
  17. package/conformance/cases/c18-wire-envelope-not-an-object/expected.json +1 -1
  18. package/conformance/cases/c19-wire-envelope-no-version/expected.json +1 -1
  19. package/conformance/cases/c21-governance-empty-object-wins/expected.json +1 -1
  20. package/conformance/cases/c23-mixed-validity-models/expected.json +1 -1
  21. package/conformance/cases/c24-valid-entries-with-unknown-keys/expected.json +1 -1
  22. package/conformance/cases/c25-published-roundtrip-zero-warnings/expected.json +1 -1
  23. package/conformance/cases/c26-hosts-array-1024/expected.json +1 -1
  24. package/conformance/cases/c27-hosts-array-1025/expected.json +1 -1
  25. package/conformance/cases/c28-large-document-over-1mb/expected.json +1 -1
  26. package/conformance/cases/c29-salvage-then-domain-refine-fails/expected.json +1 -1
  27. package/conformance/cases/c30-version-triple-a-first/expected.json +1 -1
  28. package/conformance/cases/c31-version-triple-b-changed/expected.json +1 -1
  29. package/conformance/cases/c32-version-triple-a-restored/expected.json +1 -1
  30. package/conformance/cases/c33-limits-nested-carried-key/expected.json +1 -1
  31. package/conformance/cases/c34-skills-content-vs-manifest/expected.json +1 -1
  32. package/conformance/cases/c36-skills-entry-without-content/expected.json +1 -1
  33. package/conformance/cases/c38-remote-exec-is-a-non-domain-file/expected.json +1 -1
  34. package/conformance/cases/c39-hidden-file-in-config-d/expected.json +1 -1
  35. package/conformance/cases/c40-s712-identity-only-what-reads-out/expected.json +1 -1
  36. package/conformance/cases/c41-s792-encoded-pem-identity/expected.json +1 -1
  37. package/conformance/cases/c42-s792-unknown-key-secret-redacted/expected.json +1 -1
  38. package/conformance/cases/c43-s792-form-and-deep-encoded-pem/expected.json +1 -1
  39. package/conformance/cases/c44-s792-utf8-escape-glued-token/expected.json +1 -1
  40. package/conformance/cases/c45-s792-identity-bounds-and-decode-depth/expected.json +1 -1
  41. package/conformance/cases/c46-s811-host-name-url-userinfo-withheld/expected.json +1 -1
  42. package/conformance/cases/c47-s811-roles-key-url-userinfo-withheld/expected.json +1 -1
  43. package/conformance/cases/c48-s935-model-headers-transported/expected.json +1 -1
  44. package/conformance/cases/c49-s935-model-headers-secret-entry-dropped/expected.json +1 -1
  45. package/conformance/cases/c50-s784-lane-host-legal/expected.json +1 -1
  46. package/conformance/cases/c51-s784-lane-e2b-legal/expected.json +1 -1
  47. package/conformance/cases/c52-s784-lane-k8s-legal/expected.json +1 -1
  48. package/conformance/cases/c53-s784-lane-ssh-legal/expected.json +1 -1
  49. package/conformance/cases/c54-s784-lane-adb-legal/expected.json +1 -1
  50. package/conformance/cases/c55-s784-lane-local-docker-legal/expected.json +1 -1
  51. package/conformance/cases/c56-s784-lane-device-legal/expected.json +1 -1
  52. package/conformance/cases/c57-s784-g1-enabled-no-lane/expected.json +1 -1
  53. package/conformance/cases/c58-s784-g2-multitenant-host/expected.json +1 -1
  54. package/conformance/cases/c59-s784-g3-k8s-missing-image/expected.json +1 -1
  55. package/conformance/cases/c60-s784-g3-e2b-missing-key/expected.json +1 -1
  56. package/conformance/cases/c61-s784-g3-other-lane-key/expected.json +1 -1
  57. package/conformance/cases/c62-s784-g7a-session-tidb/expected.json +1 -1
  58. package/conformance/cases/c63-s784-host-two-replicas/expected.json +1 -1
  59. package/conformance/cases/c64-s784-multitenant-local-store/expected.json +1 -1
  60. package/conformance/cases/c65-s784-pg-without-db/expected.json +1 -1
  61. package/conformance/cases/c66-s784-memory-backend-mismatch/expected.json +1 -1
  62. package/conformance/cases/c67-s784-retired-field-loud/expected.json +1 -1
  63. package/conformance/cases/c68-s784-device-local-store/expected.json +1 -1
  64. package/conformance/cases/c69-deep-encoded-token-past-every-reading/expected.json +1 -1
  65. package/conformance/cases/c70-rewritten-token-in-front-of-encoded-pem-header/expected.json +1 -1
  66. package/conformance/cases/c71-one-scanner-write-reads-display-forms/expected.json +1 -1
  67. package/conformance/cases/c72-dangling-reference-write-seat-refuses/expected.json +1 -1
  68. package/conformance/cases/c73-projects-extended-registration-reads/expected.json +1 -1
  69. package/conformance/cases/c74-projects-over-bound-refused/expected.json +3 -72
  70. package/conformance/cases/c75-projects-patch-remote-uniqueness/expected.json +3 -72
  71. package/conformance/cases/c76-projects-entry-salvage-nested/expected.json +1 -1
  72. package/conformance/cases/c77-prompts-center-artifact-carried/expected.json +1 -1
  73. package/conformance/cases/c78-prompts-empty-bindings-refused/expected.json +1 -1
  74. package/conformance/cases/c79-prompts-bad-worker-artifact-not-salvaged/expected.json +1 -1
  75. package/conformance/cases/c80-prompts-wire-v2-verbatim/expected.json +1 -1
  76. package/conformance/cases/c81-prompts-declaration-bindings-refused/expected.json +1 -1
  77. package/conformance/cases/c82-prompts-v1-catalog-refused/expected.json +1 -1
  78. package/conformance/cases/c83-prompts-bad-overlay-not-salvaged/expected.json +1 -1
  79. package/conformance/cases/c84-sandbox-git-block-carried-verbatim/expected.json +1 -1
  80. package/conformance/cases/c85-sandbox-git-refused-block-still-carried/expected.json +1 -1
  81. package/conformance/cases/c86-a2a-peers-legal/expected.json +1 -1
  82. package/conformance/cases/c87-a2a-credential-refs-not-partially-salvaged/expected.json +1 -1
  83. package/conformance/cases/c88-projects-content-attestation-carried/expected.json +1 -1
  84. package/conformance/cases/c89-projects-content-attestation-malformed/expected.json +1 -1
  85. package/conformance/cases/c90-mcp-assertion-credential-carried/expected.json +143 -0
  86. package/conformance/cases/c90-mcp-assertion-credential-carried/input.json +30 -0
  87. package/conformance/cases/c90-mcp-assertion-credential-carried/meta.json +6 -0
  88. package/conformance/cases/c91-mcp-assertion-header-retired-entry-dropped/expected.json +105 -0
  89. package/conformance/cases/c91-mcp-assertion-header-retired-entry-dropped/input.json +27 -0
  90. package/conformance/cases/c91-mcp-assertion-header-retired-entry-dropped/meta.json +6 -0
  91. package/conformance/cases/c92-mcp-principal-header-with-assertion-dropped/expected.json +105 -0
  92. package/conformance/cases/c92-mcp-principal-header-with-assertion-dropped/input.json +31 -0
  93. package/conformance/cases/c92-mcp-principal-header-with-assertion-dropped/meta.json +6 -0
  94. package/conformance/cases/c93-mcp-header-refs-with-credentials-dropped/expected.json +105 -0
  95. package/conformance/cases/c93-mcp-header-refs-with-credentials-dropped/input.json +33 -0
  96. package/conformance/cases/c93-mcp-header-refs-with-credentials-dropped/meta.json +6 -0
  97. package/conformance/cases/c94-mcp-credentials-env-kind-dropped/expected.json +105 -0
  98. package/conformance/cases/c94-mcp-credentials-env-kind-dropped/input.json +32 -0
  99. package/conformance/cases/c94-mcp-credentials-env-kind-dropped/meta.json +6 -0
  100. package/conformance/cases/c95-mcp-credentials-audience-not-connector-id-dropped/expected.json +105 -0
  101. package/conformance/cases/c95-mcp-credentials-audience-not-connector-id-dropped/input.json +30 -0
  102. package/conformance/cases/c95-mcp-credentials-audience-not-connector-id-dropped/meta.json +6 -0
  103. package/conformance/cases/c96-mcp-credentials-extra-member-dropped/expected.json +105 -0
  104. package/conformance/cases/c96-mcp-credentials-extra-member-dropped/input.json +31 -0
  105. package/conformance/cases/c96-mcp-credentials-extra-member-dropped/meta.json +6 -0
  106. package/conformance/cases/cc01-mcp-toolfaces-non-object/expected.json +1 -1
  107. package/conformance/cases/cc02-mcp-source-key-is-transported/expected.json +1 -1
  108. package/conformance/cases/cc03-model-compat-unknown-subkey/expected.json +1 -1
  109. package/conformance/cases/cli01-model-name-nfc-vs-nfd/expected.json +1 -1
  110. package/conformance/cases/cli02-control-and-zero-width-chars/expected.json +1 -1
  111. package/conformance/cases/cli03-credential-pasted-into-unknown-key/expected.json +1 -1
  112. package/conformance/cases/cli04-env-value-with-newline/expected.json +1 -1
  113. package/conformance/cases/cli05-long-and-prefix-colliding-names/expected.json +1 -1
  114. package/conformance/cases/t01-absent-domain-key-not-null/expected.json +1 -1
  115. package/conformance/cases/t03-prototype-name-key-not-swallowed/expected.json +1 -1
  116. package/conformance/cases/t04-secret-literal-never-in-warning-value/expected.json +1 -1
  117. package/conformance/cases/z01-every-domain-empty-object/expected.json +1 -1
  118. package/conformance/cases/z02-every-domain-unknown-key/expected.json +1 -1
  119. package/dist/api/auth-bridge.js +4 -3
  120. package/dist/api/auth.js +6 -5
  121. package/dist/api/credentials.js +14 -15
  122. package/dist/api/lifecycle-events.d.ts +266 -0
  123. package/dist/api/lifecycle-events.js +169 -0
  124. package/dist/api/pull-token.js +2 -1
  125. package/dist/api/scopes.js +5 -4
  126. package/dist/api/wire-scalars.d.ts +13 -0
  127. package/dist/api/wire-scalars.js +15 -0
  128. package/dist/atomic-write.d.ts +4 -0
  129. package/dist/atomic-write.js +26 -3
  130. package/dist/center-refs.js +3 -2
  131. package/dist/config-d-file.d.ts +1 -1
  132. package/dist/config-dir-io.d.ts +1 -1
  133. package/dist/config-dir-io.js +3 -2
  134. package/dist/config-document-refusal.d.ts +5 -5
  135. package/dist/config-document-refusal.js +2 -1
  136. package/dist/config-fns.d.ts +5 -5
  137. package/dist/config-fns.js +17 -16
  138. package/dist/config-root-documents.d.ts +1 -1
  139. package/dist/config-root-documents.js +4 -3
  140. package/dist/config-root-node.d.ts +1 -1
  141. package/dist/config-root-node.js +5 -3
  142. package/dist/conformance/corpus.d.ts +1 -1
  143. package/dist/conformance/derive.d.ts +16 -8
  144. package/dist/conformance/derive.js +41 -24
  145. package/dist/conformance/index.d.ts +1 -1
  146. package/dist/conformance/index.js +1 -1
  147. package/dist/conformance/run.js +8 -9
  148. package/dist/conformance/types.js +4 -3
  149. package/dist/connector-authorize-url.d.ts +23 -0
  150. package/dist/connector-authorize-url.js +129 -0
  151. package/dist/connector-id.d.ts +23 -0
  152. package/dist/connector-id.js +27 -0
  153. package/dist/cross-domain.js +6 -5
  154. package/dist/cross-session.js +3 -2
  155. package/dist/deep-freeze.d.ts +26 -0
  156. package/dist/deep-freeze.js +69 -0
  157. package/dist/default-model.js +2 -1
  158. package/dist/device-relay.d.ts +1 -1
  159. package/dist/device-relay.js +1 -1
  160. package/dist/env-model-table.js +2 -1
  161. package/dist/execution-lane-index.d.ts +1 -1
  162. package/dist/execution-lane-index.js +5 -4
  163. package/dist/execution-lanes.d.ts +2 -2
  164. package/dist/execution-lanes.js +18 -17
  165. package/dist/file-edit.d.ts +44 -0
  166. package/dist/file-edit.js +70 -1
  167. package/dist/file-store.d.ts +12 -7
  168. package/dist/file-store.js +72 -59
  169. package/dist/fleet.js +14 -13
  170. package/dist/hooks-config.d.ts +12 -12
  171. package/dist/hooks-config.js +16 -15
  172. package/dist/hooks.d.ts +20 -10
  173. package/dist/hooks.js +30 -19
  174. package/dist/http-hook-allowlists.js +2 -1
  175. package/dist/index.d.ts +4 -0
  176. package/dist/index.js +6 -2
  177. package/dist/mcp-entry-credential.d.ts +47 -0
  178. package/dist/mcp-entry-credential.js +73 -0
  179. package/dist/mcp-request-entry.d.ts +32 -13
  180. package/dist/mcp-request-entry.js +106 -59
  181. package/dist/mcp-server-policy.js +3 -2
  182. package/dist/migration-receipt.d.ts +3 -3
  183. package/dist/migration-receipt.js +4 -3
  184. package/dist/one-time-migrations.d.ts +2 -2
  185. package/dist/one-time-migrations.js +75 -57
  186. package/dist/own-key-read.d.ts +3 -1
  187. package/dist/plain-json-object.d.ts +6 -3
  188. package/dist/plain-json-object.js +6 -3
  189. package/dist/portable-domains.d.ts +18 -12
  190. package/dist/portable-domains.js +21 -15
  191. package/dist/reserved-member-name.d.ts +1 -1
  192. package/dist/reserved-member-name.js +3 -2
  193. package/dist/resolve-roster.js +3 -2
  194. package/dist/retired-envs.js +3 -6
  195. package/dist/retired-role-words.d.ts +1 -1
  196. package/dist/retired-role-words.js +4 -6
  197. package/dist/safety-merge-spec.d.ts +11 -4
  198. package/dist/safety-merge-spec.js +5 -4
  199. package/dist/scheduler-store-node.d.ts +5 -2
  200. package/dist/scheduler-store-node.js +8 -5
  201. package/dist/secret-scan.js +1 -1
  202. package/dist/settings-sources.js +6 -5
  203. package/dist/settings-units.js +3 -2
  204. package/dist/sha256.d.ts +5 -0
  205. package/dist/sha256.js +7 -0
  206. package/dist/skills-manifest.js +2 -2
  207. package/dist/types.d.ts +89 -19
  208. package/dist/types.js +57 -65
  209. package/dist/ui-language.js +4 -3
  210. package/dist/url-credential.js +4 -3
  211. package/dist/url-shape.d.ts +1 -1
  212. package/dist/url-shape.js +5 -4
  213. package/dist/web-admin-credential.js +2 -1
  214. package/dist/web-admin-env.d.ts +1 -1
  215. package/dist/web-admin-env.js +4 -3
  216. package/docs/API-SURFACE.md +47 -7
  217. package/docs/CONFORMANCE.md +6 -4
  218. package/docs/CONSUMER-INTEGRATION.md +131 -6
  219. package/llms-full.txt +46 -24
  220. package/llms.txt +27 -13
  221. package/package.json +3 -2
@@ -21,6 +21,50 @@ export declare function domainFilePath(root: string, domain: DomainName): string
21
21
  * leaves a half-written config.d/<domain>.json; a new file takes the contract-document mode (0o644), an existing one keeps its own.
22
22
  * VALIDATES first (throws on invalid — never persists garbage); persists the parsed + defaulted value so the file is canonical. */
23
23
  export declare function writeDomainFile<K extends DomainName>(root: string, domain: K, value: unknown): Promise<DomainConfig[K]>;
24
+ /** The answer of {@link writeDomainFileIf} — a closed, discriminated union on `status` (switch over it exhaustively):
25
+ * · `written` — the file's bytes matched the expected digest and the new document was written; `value` is the parsed + defaulted document that was written, `digest` is the digest of the bytes now on disk
26
+ * (feed it straight back as the next call's `expected`, no re-read needed). `lockLeft` is present only when the write landed but the lock file could not be removed afterwards: it names that file
27
+ * (every later conditional write answers `locked` until it is deleted); a failed clean-up never replaces the outcome;
28
+ * · `stale` — the file's bytes did not match: nothing was written, not a byte of the file changed. `current` is the digest of the bytes on disk now, or `null` when the file is not there
29
+ * (re-read, re-apply the change on top of what is there, and call again);
30
+ * · `locked` — the lock file is held: nothing was written and the file was not read. `lock` is the lock file's absolute path. A lock left behind by a writer that crashed is never taken over
31
+ * (there is no safe way to tell it from a live holder): delete the file named by `lock` once no writer is running, its text is the holder's pid. */
32
+ export type ConditionalWriteResult<K extends DomainName> = {
33
+ readonly status: "written";
34
+ readonly value: DomainConfig[K];
35
+ readonly digest: string;
36
+ readonly lockLeft?: string;
37
+ } | {
38
+ readonly status: "stale";
39
+ readonly current: string | null;
40
+ } | {
41
+ readonly status: "locked";
42
+ readonly lock: string;
43
+ };
44
+ /** WRITE a domain file ATOMICALLY **only if it still holds what the caller read** — the compare-and-write form of {@link writeDomainFile}, for read-modify-write callers whose edit must not overwrite a change
45
+ * made after their read (a lost update).
46
+ *
47
+ * `expected` is the digest of the file's **bytes** as the caller read them — every byte, whatever it decodes to — in the package's one digest spelling (`sha256:<64 lowercase hex>`, minted by
48
+ * `contentDigest` from `@sema-agent/settings-schema/sha256`, which takes the `Buffer` that `readFile` returned), or `null` when the file was absent. Anything else is a `TypeError` (a malformed digest
49
+ * would never match and be mistaken for a concurrent change). Digest the bytes you PARSED — read the file once, digest that `Buffer` and parse `buffer.toString("utf8")` — never a second read.
50
+ * (For a file that is valid UTF-8 the digest of its decoded text is the same digest, so a caller that digests the text it read is right too; a text decoded from bytes that are not valid UTF-8 has lost
51
+ * those bytes — each bad sequence became U+FFFD — and digests differently from the file.)
52
+ *
53
+ * Order (the same checks as {@link writeDomainFile} come first, so a refused write never takes a lock or touches a byte): the name guard → the `expected` form → the whole-document verdict
54
+ * (`parseDomain`; throws on a value the contract refuses, the same sentence as the unconditional writer) → create `config.d` if it is missing → take the lock → re-read the file under the lock →
55
+ * compare digests → write atomically (the package's one atomic writer: same directory, same mode rules, a symbolic link is written through) → remove the lock. Removal is attempted on every path that
56
+ * took the lock, success or failure; a failure after the lock is thrown as it is, and a failure to remove the lock never replaces the outcome (see `lockLeft` in {@link ConditionalWriteResult}).
57
+ *
58
+ * The lock is the hidden file `.<file>.lock` beside the file that is actually written — for a plain `config.d/<domain>.json` that is `config.d/.<domain>.json.lock`; when the domain file is a symbolic
59
+ * link it sits beside the link's real target, so two roots whose links point at one real file share one lock. Created exclusively (the package's existing create-only-if-absent primitive — the same
60
+ * one the root-level decision document uses), holding the writer's pid. A held lock answers `locked` and nothing else happens; there is no wait and no retry, the caller decides. The hidden,
61
+ * non-`.json` name keeps it out of every `config.d` scan.
62
+ *
63
+ * What it does NOT do: the lock and the digest coordinate callers of THIS function. An unconditional {@link writeDomainFile}, `writeBundle`, the directory migration or a hand edit takes no lock and can still land between
64
+ * this call's re-read and its write; the only protection against those is that the compare happens under the lock, microseconds before the rename.
65
+ *
66
+ * Resolves `{ status: "written" | "stale" | "locked", … }` ({@link ConditionalWriteResult}); rejects on invalid input, an unreadable file and file-system failures. */
67
+ export declare function writeDomainFileIf<K extends DomainName>(root: string, domain: K, value: unknown, expected: string | null): Promise<ConditionalWriteResult<K>>;
24
68
  export interface RequiredEnvName {
25
69
  envName: string;
26
70
  refs: {
package/dist/file-edit.js CHANGED
@@ -5,11 +5,13 @@
5
5
  *
6
6
  * Validation uses the SAME zod schemas as the server's parseDomain → identical rules on both sides.
7
7
  */
8
+ import { unlinkSync } from "node:fs";
8
9
  import { mkdir } from "node:fs/promises";
9
10
  import path from "node:path";
10
- import { writeFileAtomic } from "./atomic-write.js";
11
+ import { createFileExclusive, readBytesIfPresent, resolveSymlinkTarget, writeFileAtomic } from "./atomic-write.js";
11
12
  import { emptyDocument, guardedSafeParse } from "./own-key-read.js";
12
13
  import { collectEnvRefs } from "./secret-refs.js";
14
+ import { SHA256_DIGEST_RE, contentDigest } from "./sha256.js";
13
15
  import { REMOTE_EXEC_DOCUMENT, RemoteExecSpec } from "./remote-exec.js";
14
16
  import { configDDocumentText } from "./config-d-file.js";
15
17
  import { buildQuotedIssue, fixed } from "./quoted-issue.js";
@@ -69,6 +71,73 @@ export async function writeDomainFile(root, domain, value) {
69
71
  writeFileAtomic(path.join(dir, `${domain}.json`), configDDocumentText(parsed), "config-document");
70
72
  return parsed;
71
73
  }
74
+ /** Remove the lock this call created: `true` = it is gone (an already-missing lock counts — someone cleaned it), `false` = it could not be removed and is still there. Never throws: a clean-up failure
75
+ * must not replace the outcome it follows (a landed write, or the error that ended the call); a lock left behind is reported by the result (`lockLeft`) and by every later call (`locked`). */
76
+ function releaseLock(lock) {
77
+ try {
78
+ unlinkSync(lock);
79
+ return true;
80
+ }
81
+ catch (e) {
82
+ return e.code === "ENOENT";
83
+ }
84
+ }
85
+ /** WRITE a domain file ATOMICALLY **only if it still holds what the caller read** — the compare-and-write form of {@link writeDomainFile}, for read-modify-write callers whose edit must not overwrite a change
86
+ * made after their read (a lost update).
87
+ *
88
+ * `expected` is the digest of the file's **bytes** as the caller read them — every byte, whatever it decodes to — in the package's one digest spelling (`sha256:<64 lowercase hex>`, minted by
89
+ * `contentDigest` from `@sema-agent/settings-schema/sha256`, which takes the `Buffer` that `readFile` returned), or `null` when the file was absent. Anything else is a `TypeError` (a malformed digest
90
+ * would never match and be mistaken for a concurrent change). Digest the bytes you PARSED — read the file once, digest that `Buffer` and parse `buffer.toString("utf8")` — never a second read.
91
+ * (For a file that is valid UTF-8 the digest of its decoded text is the same digest, so a caller that digests the text it read is right too; a text decoded from bytes that are not valid UTF-8 has lost
92
+ * those bytes — each bad sequence became U+FFFD — and digests differently from the file.)
93
+ *
94
+ * Order (the same checks as {@link writeDomainFile} come first, so a refused write never takes a lock or touches a byte): the name guard → the `expected` form → the whole-document verdict
95
+ * (`parseDomain`; throws on a value the contract refuses, the same sentence as the unconditional writer) → create `config.d` if it is missing → take the lock → re-read the file under the lock →
96
+ * compare digests → write atomically (the package's one atomic writer: same directory, same mode rules, a symbolic link is written through) → remove the lock. Removal is attempted on every path that
97
+ * took the lock, success or failure; a failure after the lock is thrown as it is, and a failure to remove the lock never replaces the outcome (see `lockLeft` in {@link ConditionalWriteResult}).
98
+ *
99
+ * The lock is the hidden file `.<file>.lock` beside the file that is actually written — for a plain `config.d/<domain>.json` that is `config.d/.<domain>.json.lock`; when the domain file is a symbolic
100
+ * link it sits beside the link's real target, so two roots whose links point at one real file share one lock. Created exclusively (the package's existing create-only-if-absent primitive — the same
101
+ * one the root-level decision document uses), holding the writer's pid. A held lock answers `locked` and nothing else happens; there is no wait and no retry, the caller decides. The hidden,
102
+ * non-`.json` name keeps it out of every `config.d` scan.
103
+ *
104
+ * What it does NOT do: the lock and the digest coordinate callers of THIS function. An unconditional {@link writeDomainFile}, `writeBundle`, the directory migration or a hand edit takes no lock and can still land between
105
+ * this call's re-read and its write; the only protection against those is that the compare happens under the lock, microseconds before the rename.
106
+ *
107
+ * Resolves `{ status: "written" | "stale" | "locked", … }` ({@link ConditionalWriteResult}); rejects on invalid input, an unreadable file and file-system failures. */
108
+ export async function writeDomainFileIf(root, domain, value, expected) {
109
+ assertDomainName(domain); // a stray non-domain key fails LOUD + clear, as in writeDomainFile
110
+ if (expected !== null && !(typeof expected === "string" && SHA256_DIGEST_RE.test(expected))) {
111
+ throw new TypeError(`writeDomainFileIf: \`expected\` must be null (the file was absent when read) or a "sha256:<64 lowercase hex>" digest of the text that was read, not ${expected === undefined ? "undefined" : typeof expected === "string" ? "another string" : `a ${typeof expected}`}`);
112
+ }
113
+ const parsed = parseDomain(domain, value); // the one whole-document verdict, before any lock or byte
114
+ const dir = path.join(root, "config.d");
115
+ const file = path.join(dir, `${domain}.json`);
116
+ await mkdir(dir, { recursive: true });
117
+ const real = resolveSymlinkTarget(file); // the file that is actually written (a link is followed; a dangling link throws the package's one sentence, before any lock)
118
+ const lock = path.join(path.dirname(real), `.${path.basename(real)}.lock`); // keyed by the real destination: aliases of one file share one lock
119
+ if (createFileExclusive(lock, `${process.pid}\n`, "config-document") === "present")
120
+ return { status: "locked", lock }; // not ours: never touched
121
+ let outcome;
122
+ try {
123
+ const present = await readBytesIfPresent(file, [dir]); // under the lock; the raw bytes (no decoding); the one absence rule (a dangling link is loud, not absent)
124
+ const current = present === undefined ? null : contentDigest(present);
125
+ if (current !== expected) {
126
+ outcome = { status: "stale", current };
127
+ }
128
+ else {
129
+ const text = configDDocumentText(parsed);
130
+ writeFileAtomic(file, text, "config-document");
131
+ outcome = { status: "written", value: parsed, digest: contentDigest(text) };
132
+ }
133
+ }
134
+ finally {
135
+ const released = releaseLock(lock); // never throws: the error in flight (if any) stays the error
136
+ if (outcome?.status === "written" && !released)
137
+ outcome = { ...outcome, lockLeft: lock };
138
+ }
139
+ return outcome;
140
+ }
72
141
  /** LIST every env-NAME the current local config requires (across models/workers/mcp/a2a + the
73
142
  * remote-exec backend), marking which are MISSING from the resolved env — the TOC "you still need to set
74
143
  * these secrets" panel. Reuses collectEnvRefs for the domain side, then appends the remoteExec secret refs. */
@@ -2,7 +2,7 @@ import { type EffectiveReadWarning } from "./config-fns.js";
2
2
  import type { ConfigDocumentRefusal } from "./config-document-refusal.js";
3
3
  import type { ConfigReader } from "./reader.js";
4
4
  import { type DomainConfig, type DomainName, type EffectiveConfig, type RetiredDomainName } from "./types.js";
5
- export { NON_PORTABLE_DOMAIN_REASONS, PORTABLE_DOMAINS, type PortableDomain } from "./portable-domains.js";
5
+ export { LOCAL_READ_DOMAINS, NON_PORTABLE_DOMAIN_REASONS, PORTABLE_DOMAINS, type LocalReadDomain, type PortableDomain } from "./portable-domains.js";
6
6
  /** `config.d/` 里**合法存在但不是域文档**的文件名(不进 `"unread-config-file"` 告警)。`remote-exec`
7
7
  * 不是 `DOMAIN_SCHEMAS` 成员(resolver 不读它),按 service 表决住在这个目录,由 loadRemoteExec 读
8
8
  * ——**它有自己的校验路径**(读盘与域文档同一只 `config.d` 文档读法,值判是 `RemoteExecSpec`),所以既不是「未知文件」也不是「域文件」。
@@ -30,7 +30,7 @@ export type FileConfigRead =
30
30
  readonly effective: EffectiveConfig;
31
31
  readonly warnings: readonly EffectiveReadWarning[];
32
32
  }
33
- /** 至少一份文档在文件层被拒:`refusals` = 整棵目录的拒单(次序确定:retired 域文档在前,按墓碑表的声明次序;便携域按 `PORTABLE_DOMAINS` 的次序);
33
+ /** 至少一份文档在文件层被拒:`refusals` = 整棵目录的拒单(次序确定:retired 域文档在前,按墓碑表的声明次序;本地读取域按 `LOCAL_READ_DOMAINS` 的次序);
34
34
  * `version` = 这一次读到的整棵目录的内容版本(被拒的文档以坏文档的指纹参与 —— 与宽容读的坏文件哨兵同一只:同样的坏内容同一个数、坏内容变了换数、
35
35
  * 绝不与「文件缺席」同数);`warnings` = 没人读的文件(装配没有发生)。 */
36
36
  | {
@@ -58,9 +58,10 @@ export declare class FileConfigStore implements ConfigReader {
58
58
  * `has(domain) ? parse : undefined`. Only an ABSENT file (ENOENT with nothing at the path; a dangling symlink is not absence) is absence → undefined. A present `{}` IS a set
59
59
  * domain → parsed with defaults. A present file that is empty or whitespace-only (a half-write) throws as a corrupt file,
60
60
  * as do bad JSON, a non-object, an unreadable file and one nested too deep (the same reading as getEffective / readBundle).
61
- * (getEffective still fills defaults for absent domains; getDomain is the per-domain "was this ever set?" probe.) */
61
+ * (getEffective still fills defaults for absent domains; getDomain is the per-domain "was this ever set?" probe.)
62
+ * A per-domain single read: it does not consult {@link LOCAL_READ_DOMAINS} (the enumerating reads — `getEffective` / `read()` / `getVersion()` — do), so the bundle helpers put the portable-set gate in front of it. */
62
63
  getDomain<K extends DomainName>(domain: K): Promise<DomainConfig[K] | undefined>;
63
- /** All portable domains → EffectiveConfig. The PAYLOAD and its `version` come from ONE raws snapshot (no
64
+ /** All local-read domains → EffectiveConfig. The PAYLOAD and its `version` come from ONE raws snapshot (no
64
65
  * re-read between them — else a concurrent atomic rename could pair payload A with version B and a consumer
65
66
  * would skip the change). `updatedAt` = max file mtime (informational; the content-hash version is the
66
67
  * authoritative change-detector).
@@ -81,14 +82,18 @@ export declare class FileConfigStore implements ConfigReader {
81
82
  tolerant: true;
82
83
  }): Promise<TolerantEffective>;
83
84
  /** Stable version number for the current files: same files ⇒ same number ⇒ a consumer's "skip re-apply if
84
- * version unchanged" works locally too. */
85
+ * version unchanged" works locally too. It is the number `read()` carries for the same tree (one snapshot reading, {@link #snapshot}) ——
86
+ * answered for every tree, including one with a document refused at the file layer (29.0.0; it threw before): that document joins as its
87
+ * fingerprint sentinel, never as absence. Shape (schema) does not enter the version: a gated domain that reads but fails its schema has a
88
+ * version here while `read()` / `getEffective()` throw for it. */
85
89
  getVersion(): Promise<number>;
86
90
  /**
87
- * **单读口**(16.0.0):一次读整棵 `config.d`(全部便携域 + retired 域的墓碑文档,每份只读一次),交一个结局({@link FileConfigRead})——
91
+ * **单读口**(16.0.0):一次读整棵 `config.d`(全部本地读取域 + retired 域的墓碑文档,每份只读一次),交一个结局({@link FileConfigRead})——
88
92
  * · 每份文档在文件层都读得进 ⇒ `effective`:与严读 `getEffective()` 逐位同;读侧告警交成数据(没人读的文件 + 装配告警,不经 `onWarning`);
89
93
  * · 有文档在文件层被拒(空 / 坏 JSON / 不是对象 / 读不出 / 过深;带事实的 retired 域文档是墓碑拒,带迁移编号)⇒ `refused`:整棵目录的拒单与这一次读到的内容版本。
90
94
  * 严读与 `readBundle` 读的是同一只文件读法(`./config-d-file` 的读数)—— 同一种坏形同一个词、同一句话;区别只在渲染:严读遇到第一份坏文档就抛,本方法把整个目录读完、逐份交出。
91
- * 文件层之外的拒(读得出、过不了门控域的 schema)照严读抛 —— 那是判形,不在拒单里。拒单、版本、effective、告警都出自这一次读到的字节:没有「先抛、再重探」的第二次读。
95
+ * 文件层之外的拒(读得出、过不了门控域的 schema)照严读抛 —— 那是判形,不在拒单里;判形不进版本,那棵树的版本 `getVersion()` 照答。拒单、版本、effective、告警都出自这一次读到的字节:没有「先抛、再重探」的第二次读。
96
+ * 版本与 `getVersion()` 是同一个数(同一只快照读法 {@link #snapshot})。
92
97
  */
93
98
  read(): Promise<FileConfigRead>;
94
99
  }
@@ -1,13 +1,15 @@
1
1
  /**
2
- * FileConfigStore — a local, single-machine config source for the TOC desktop/CLI. Reads the PORTABLE domains
2
+ * FileConfigStore — a local, single-machine config source for the TOC desktop/CLI. Reads the LOCAL-READ domains ({@link LOCAL_READ_DOMAINS})
3
3
  * from `<root>/config.d/<domain>.json` (one file per domain, each = exactly that domain's zod object) and
4
4
  * resolves them into an {@link EffectiveConfig} via the SAME pure `buildEffective`/`parseDomain` the server
5
5
  * stores use. Implements ONLY the narrow {@link ConfigReader} (3 methods) — no publish/RBAC/worker-status.
6
6
  *
7
7
  * LOCAL FILE LAYOUT (the TOC owns the root, e.g. `~/.ai-agent/` or a project-local `.ai-agent/`):
8
- * <root>/config.d/<domain>.json for every domain in {@link PORTABLE_DOMAINS} — that constant is the
8
+ * <root>/config.d/<domain>.json for every domain in {@link LOCAL_READ_DOMAINS} — that constant is the
9
9
  * AUTHORITY; do NOT hand-copy the list here (the hand-written enumeration that used to sit
10
10
  * on this line silently missed `prompts` for three releases — 对抗复审 复审 round2 F5).
11
+ * It is {@link PORTABLE_DOMAINS} plus `projects`: the local set answers "which documents does this store read",
12
+ * the portable set answers "which domains travel in a bundle" — two questions, two constants.
11
13
  * <root>/.env secret VALUES (KEY=value) — the ONLY file holding secrets; gitignored, never read here.
12
14
  *
13
15
  * Rules:
@@ -17,31 +19,35 @@
17
19
  * "absent/defaults" the file must be missing, not empty. A valid `{}` object IS a set domain (→ defaults).
18
20
  * - `read()` (16.0.0) is the ONE read that answers both ways: the effective config + its read warnings as data when every
19
21
  * document reads, or the typed refusal list of the whole directory + its version when one does not — every document read once.
20
- * - Non-portable domains are OMITTED on a single machine and resolve to their schema defaults (`{workers:[]}`
21
- * etc.) — no stubbing needed. 逐域为什么被排除见 {@link NON_PORTABLE_DOMAIN_REASONS}(禁裸排除)。
22
+ * - Domains outside the local-read set (`workers` / `hosts` / `systems` / `entitlement`) are OMITTED on a single machine and resolve to their schema defaults (`{workers:[]}`
23
+ * etc.) — no stubbing needed; their files are named by an `"unread-config-file"` warning. 逐域为什么被排除见 {@link NON_PORTABLE_DOMAIN_REASONS}(禁裸排除)。
22
24
  * - A RETIRED domain's file (`config.d/runtime.json`, see `RETIRED_DOMAINS`) is read only for its tombstone: carrying facts ⇒
23
25
  * every read entry (`getDomain`, `getEffective` — and so `exportBundle`) throws `RetiredDomainError` (`refuseRetiredDomainFiles`, shared with `readBundle`) (the sentence names where the facts live today — `governance` and `limits`); `{}` carries nothing and is left alone. It is never an "unread file".
24
26
  * - The JSON files only ever carry env-NAMEs (the ENV_NAME boundary holds locally too); `.env` holds values.
25
- * - `getVersion()` = a stable content hash of all portable files → a u53 number, so a consumer's
26
- * "skip re-apply if version unchanged" works locally. `getEffective().updatedAt` = the max file mtime,
27
+ * - `getVersion()` = a stable content hash of all local-read files (and the retired domains' tombstone documents) → a u53 number, so a consumer's
28
+ * "skip re-apply if version unchanged" works locally. It is the one content version of the tree: `read()` carries the same number
29
+ * (one file-level snapshot; a refused document joins as its fingerprint, never as absence), and so does `getEffective().version`
30
+ * whenever that read returns. `getEffective().updatedAt` = the max file mtime,
27
31
  * passed EXPLICITLY into buildEffective (the determinism refactor) so identical files ⇒ identical bytes.
28
32
  */
29
33
  import { readdir, stat } from "node:fs/promises";
30
34
  import path from "node:path";
31
35
  import { RetiredDomainError, buildEffective, DOMAIN_READ_FALLBACK, parseDomainLoud, refuseRetiredDomain } from "./config-fns.js";
32
36
  import { RETIRED_DOMAIN_NAMES, configDPath, configDVersionOf, corruptDocumentRaw, readConfigDFile, readConfigDFileReading, refuseRetiredDomainFiles } from "./config-d-file.js";
33
- import { PORTABLE_DOMAINS } from "./portable-domains.js";
37
+ import { LOCAL_READ_DOMAINS } from "./portable-domains.js";
34
38
  import { REMOTE_EXEC_DOCUMENT } from "./remote-exec.js";
35
39
  import { isDomainName, isRetiredDomainName } from "./types.js";
36
- // 便携域表的定义住在纯叶 ./portable-domains.ts(14.6.0;零 node 依赖,主桶模块可 import);这里原名转出口,`./node` 子路径逐名不变。
37
- export { NON_PORTABLE_DOMAIN_REASONS, PORTABLE_DOMAINS } from "./portable-domains.js";
40
+ import { deepFreeze } from "./deep-freeze.js";
41
+ // 域集合表的定义住在纯叶 ./portable-domains.ts(14.6.0;零 node 依赖,主桶模块可 import);这里原名转出口,`./node` 子路径逐名不变。
42
+ // 便携域集(搬运义:bundle 的默认集)与本地读取域集(本地读取义:本文件读哪些域)是两只常量 —— 本文件里按「读」枚举的各处读后者,不读前者。
43
+ export { LOCAL_READ_DOMAINS, NON_PORTABLE_DOMAIN_REASONS, PORTABLE_DOMAINS } from "./portable-domains.js";
38
44
  /** `config.d/` 里**合法存在但不是域文档**的文件名(不进 `"unread-config-file"` 告警)。`remote-exec`
39
45
  * 不是 `DOMAIN_SCHEMAS` 成员(resolver 不读它),按 service 表决住在这个目录,由 loadRemoteExec 读
40
46
  * ——**它有自己的校验路径**(读盘与域文档同一只 `config.d` 文档读法,值判是 `RemoteExecSpec`),所以既不是「未知文件」也不是「域文件」。
41
47
  *
42
48
  * **导出**(3.0.0):一致性门的语料派生要按同一张表给本地腿的文件分类(域文件 / 专用文件 / 忽略),
43
49
  * 手抄一份必漂 —— 漂了的那一天,门会把一个合法的 `remote-exec.json` 报成未知文件。 */
44
- export const NON_DOMAIN_CONFIG_FILES = new Set([`${REMOTE_EXEC_DOCUMENT}.json`]);
50
+ export const NON_DOMAIN_CONFIG_FILES = deepFreeze(new Set([`${REMOTE_EXEC_DOCUMENT}.json`]));
45
51
  export class FileConfigStore {
46
52
  root;
47
53
  opts;
@@ -62,9 +68,9 @@ export class FileConfigStore {
62
68
  * file (nothing at the path — ENOENT and not a dangling symlink) → undefined = the domain is ABSENT (the ONLY way to mean "use defaults"); a present file that is EMPTY/whitespace-only,
63
69
  * or parses to anything but a JSON OBJECT, is CORRUPT → throw, FAIL CLOSED (an empty present file is a half-write/truncation, NOT
64
70
  * "absent": treating it as absent would silently DROP a published domain — e.g. a truncated governance.json drops its
65
- * commandPolicy/autonomy guardrails). This also keeps getVersion in lock-step with getEffective/getDomain: stableStringify collapses
66
- * `undefined` (absent) and `null` to the SAME bytes, so an empty/null file that resolved to undefined would hash IDENTICALLY to
67
- * "domain absent" and a version-gated poller would skip a change getEffective/getDomain actually FAIL on. R17 + R(0.1.27 整体复审). */
71
+ * commandPolicy/autonomy guardrails). The version never reads a corrupt file as absence either: stableStringify collapses
72
+ * `undefined` (absent) and `null` to the SAME bytes, so the version snapshot ({@link #snapshot}) puts a refused document in as its
73
+ * fingerprint sentinel — a version-gated poller sees the change that getEffective/getDomain FAIL on. R17 + R(0.1.27 整体复审). */
68
74
  async #readDomainRaw(domain) {
69
75
  return readConfigDFile(this.root, domain); // the shared reader guards the name (configDPath)
70
76
  }
@@ -76,7 +82,7 @@ export class FileConfigStore {
76
82
  * 闭集 —— 文件在、进程跑、限额还是 env 老值,**零告警**(「域缺席」与「文件不存在」在下游逐字同形)。
77
83
  * 修法方向是**响亮,不是收紧**:未登记文件照旧不读(拒收会让一个无害的散落文件打死整个部署),但必须
78
84
  * 说出来。两类分开报,因为处置不同:`not-a-domain` = 名字打错 / 消费方开了本包还不认识的域(要来本包
79
- * 登记);`non-portable-domain` = 域认识但单机 lane 刻意不读(理由见 {@link NON_PORTABLE_DOMAIN_REASONS})。
85
+ * 登记);`non-portable-domain` = 域认识但本地读取集({@link LOCAL_READ_DOMAINS})刻意不含它(workers / hosts / systems / entitlement;理由见 {@link NON_PORTABLE_DOMAIN_REASONS};`projects` 不在此列 —— 它在本地读取集里,被读)。
80
86
  *
81
87
  * 只在挂了 `onWarning` 时才 readdir —— 没接通道的调用方不该为一条没人听的警告付 IO(诚实登记:
82
88
  * 因此本门的响亮程度取决于消费方接不接这个座)。忽略:隐藏文件(含 file-edit 原子写的 `.<域>.json.*.tmp`
@@ -105,7 +111,7 @@ export class FileConfigStore {
105
111
  if (name.startsWith(".") || !name.endsWith(".json") || NON_DOMAIN_CONFIG_FILES.has(name))
106
112
  continue;
107
113
  const base = name.slice(0, -".json".length);
108
- if (PORTABLE_DOMAINS.includes(base))
114
+ if (LOCAL_READ_DOMAINS.includes(base))
109
115
  continue; // 真被读的域
110
116
  if (isRetiredDomainName(base))
111
117
  continue; // retired 域:由墓碑判(带事实 ⇒ getEffective 抛),不是「没人读的文件」
@@ -115,19 +121,48 @@ export class FileConfigStore {
115
121
  }
116
122
  return out;
117
123
  }
118
- /** Raw (unparsed) values for every PORTABLE domain and every retired domain (the latter for the tombstone), keyed by
119
- * name (absent → undefined). Both feed the version hash: a retired file appearing / changing flips `getEffective`
120
- * between a refusal and a read, so a version-gated poller must see it. */
121
- async #readAllRaw() {
122
- const out = {};
123
- await Promise.all([...PORTABLE_DOMAINS, ...RETIRED_DOMAIN_NAMES].map(async (d) => { out[d] = await this.#readDomainRaw(d); }));
124
- return out;
124
+ /**
125
+ * 整棵目录的**一次文件层读数**(retired 域的墓碑文档 + 全部本地读取域,每份只读一次)—— 内容版本的入参与拒单都出自它,`read()` 与 `getVersion()` 读这同一只:
126
+ * · 版本入参 `raws`:在场 ⇒ 原文解析后的值;缺席 ⇒ `undefined`;在文件层被拒 ⇒ 那份坏文档的指纹哨兵(`corruptDocumentRaw`:绝不与缺席同数,坏内容变了换数)。
127
+ * retired 域文档进版本:它出现 / 变了,读的结局就在拒与读之间翻,按版本轮询的消费方必须看得到。
128
+ * · `refusals`:文件层的拒(次序 = 读的次序:retired 域在前,本地读取域按 `LOCAL_READ_DOMAINS`)+ 带事实的墓碑。
129
+ */
130
+ async #snapshot() {
131
+ const documents = [...RETIRED_DOMAIN_NAMES, ...LOCAL_READ_DOMAINS];
132
+ const readings = await Promise.all(documents.map((d) => readConfigDFileReading(this.root, d)));
133
+ const raws = {};
134
+ const refusals = [];
135
+ documents.forEach((document, i) => {
136
+ const reading = readings[i];
137
+ switch (reading.status) {
138
+ case "absent":
139
+ raws[document] = undefined;
140
+ return;
141
+ case "refused":
142
+ raws[document] = corruptDocumentRaw(reading);
143
+ refusals.push({ document, reason: reading.reason, error: reading.error });
144
+ return;
145
+ case "present":
146
+ raws[document] = reading.value;
147
+ if (isRetiredDomainName(document)) {
148
+ const tombstone = tombstoneOf(document, reading.value);
149
+ if (tombstone !== undefined)
150
+ refusals.push(tombstone);
151
+ }
152
+ return;
153
+ default: {
154
+ const unhandled = reading;
155
+ throw new Error(`FileConfigStore: unhandled reading ${String(unhandled)}`);
156
+ }
157
+ }
158
+ });
159
+ return { raws, refusals };
125
160
  }
126
- /** The max mtime (ISO) across the present portable files, or the epoch when none exist — so `updatedAt`
161
+ /** The max mtime (ISO) across the present local-read files, or the epoch when none exist — so `updatedAt`
127
162
  * is deterministic for a given set of files (not the wall clock). */
128
163
  async #maxMtimeIso() {
129
164
  let maxMs = 0;
130
- await Promise.all(PORTABLE_DOMAINS.map(async (d) => {
165
+ await Promise.all(LOCAL_READ_DOMAINS.map(async (d) => {
131
166
  try {
132
167
  const s = await stat(this.domainPath(d));
133
168
  if (s.mtimeMs > maxMs)
@@ -145,7 +180,8 @@ export class FileConfigStore {
145
180
  * `has(domain) ? parse : undefined`. Only an ABSENT file (ENOENT with nothing at the path; a dangling symlink is not absence) is absence → undefined. A present `{}` IS a set
146
181
  * domain → parsed with defaults. A present file that is empty or whitespace-only (a half-write) throws as a corrupt file,
147
182
  * as do bad JSON, a non-object, an unreadable file and one nested too deep (the same reading as getEffective / readBundle).
148
- * (getEffective still fills defaults for absent domains; getDomain is the per-domain "was this ever set?" probe.) */
183
+ * (getEffective still fills defaults for absent domains; getDomain is the per-domain "was this ever set?" probe.)
184
+ * A per-domain single read: it does not consult {@link LOCAL_READ_DOMAINS} (the enumerating reads — `getEffective` / `read()` / `getVersion()` — do), so the bundle helpers put the portable-set gate in front of it. */
149
185
  async getDomain(domain) {
150
186
  await refuseRetiredDomainFiles(this.root); // every read entry asks the tombstone first (exportBundle reads through here)
151
187
  const raw = await this.#readDomainRaw(domain);
@@ -166,7 +202,7 @@ export class FileConfigStore {
166
202
  if (opts?.tolerant !== true) {
167
203
  const [retired] = await Promise.all([refuseRetiredDomainFiles(this.root), this.#warnUnreadFiles()]); // 两条读法同一门(0.19.0)
168
204
  const raws = { ...retired };
169
- await Promise.all(PORTABLE_DOMAINS.map(async (d) => { raws[d] = await this.#readDomainRaw(d); }));
205
+ await Promise.all(LOCAL_READ_DOMAINS.map(async (d) => { raws[d] = await this.#readDomainRaw(d); }));
170
206
  const updatedAt = await this.#maxMtimeIso();
171
207
  return buildEffective(this.#versionOf(raws), (d) => raws[d], updatedAt, this.opts.onWarning);
172
208
  }
@@ -177,7 +213,7 @@ export class FileConfigStore {
177
213
  const raws = { ...retired };
178
214
  const hashRaws = { ...retired };
179
215
  const domainErrors = [];
180
- await Promise.all(PORTABLE_DOMAINS.map(async (d) => {
216
+ await Promise.all(LOCAL_READ_DOMAINS.map(async (d) => {
181
217
  // 与严读同一只文件读法(读数):被拒的读数交 `thrown`(gate 域原样抛)或 `error` 句(其余域单列进 domainErrors)—— 坏文件的指纹就是这一次读到的字节,不是事后的第二次读。
182
218
  const reading = await readConfigDFileReading(this.root, d);
183
219
  if (reading.status !== "refused") {
@@ -197,46 +233,23 @@ export class FileConfigStore {
197
233
  return { effective, domainErrors };
198
234
  }
199
235
  /** Stable version number for the current files: same files ⇒ same number ⇒ a consumer's "skip re-apply if
200
- * version unchanged" works locally too. */
236
+ * version unchanged" works locally too. It is the number `read()` carries for the same tree (one snapshot reading, {@link #snapshot}) ——
237
+ * answered for every tree, including one with a document refused at the file layer (29.0.0; it threw before): that document joins as its
238
+ * fingerprint sentinel, never as absence. Shape (schema) does not enter the version: a gated domain that reads but fails its schema has a
239
+ * version here while `read()` / `getEffective()` throw for it. */
201
240
  async getVersion() {
202
- return this.#versionOf(await this.#readAllRaw());
241
+ return this.#versionOf((await this.#snapshot()).raws);
203
242
  }
204
243
  /**
205
- * **单读口**(16.0.0):一次读整棵 `config.d`(全部便携域 + retired 域的墓碑文档,每份只读一次),交一个结局({@link FileConfigRead})——
244
+ * **单读口**(16.0.0):一次读整棵 `config.d`(全部本地读取域 + retired 域的墓碑文档,每份只读一次),交一个结局({@link FileConfigRead})——
206
245
  * · 每份文档在文件层都读得进 ⇒ `effective`:与严读 `getEffective()` 逐位同;读侧告警交成数据(没人读的文件 + 装配告警,不经 `onWarning`);
207
246
  * · 有文档在文件层被拒(空 / 坏 JSON / 不是对象 / 读不出 / 过深;带事实的 retired 域文档是墓碑拒,带迁移编号)⇒ `refused`:整棵目录的拒单与这一次读到的内容版本。
208
247
  * 严读与 `readBundle` 读的是同一只文件读法(`./config-d-file` 的读数)—— 同一种坏形同一个词、同一句话;区别只在渲染:严读遇到第一份坏文档就抛,本方法把整个目录读完、逐份交出。
209
- * 文件层之外的拒(读得出、过不了门控域的 schema)照严读抛 —— 那是判形,不在拒单里。拒单、版本、effective、告警都出自这一次读到的字节:没有「先抛、再重探」的第二次读。
248
+ * 文件层之外的拒(读得出、过不了门控域的 schema)照严读抛 —— 那是判形,不在拒单里;判形不进版本,那棵树的版本 `getVersion()` 照答。拒单、版本、effective、告警都出自这一次读到的字节:没有「先抛、再重探」的第二次读。
249
+ * 版本与 `getVersion()` 是同一个数(同一只快照读法 {@link #snapshot})。
210
250
  */
211
251
  async read() {
212
- const documents = [...RETIRED_DOMAIN_NAMES, ...PORTABLE_DOMAINS];
213
- const [readings, unread] = await Promise.all([Promise.all(documents.map((d) => readConfigDFileReading(this.root, d))), this.#unreadFiles()]);
214
- const raws = {};
215
- const refusals = [];
216
- documents.forEach((document, i) => {
217
- const reading = readings[i];
218
- switch (reading.status) {
219
- case "absent":
220
- raws[document] = undefined;
221
- return;
222
- case "refused":
223
- raws[document] = corruptDocumentRaw(reading);
224
- refusals.push({ document, reason: reading.reason, error: reading.error });
225
- return;
226
- case "present":
227
- raws[document] = reading.value;
228
- if (isRetiredDomainName(document)) {
229
- const tombstone = tombstoneOf(document, reading.value);
230
- if (tombstone !== undefined)
231
- refusals.push(tombstone);
232
- }
233
- return;
234
- default: {
235
- const unhandled = reading;
236
- throw new Error(`FileConfigStore.read: unhandled reading ${String(unhandled)}`);
237
- }
238
- }
239
- });
252
+ const [{ raws, refusals }, unread] = await Promise.all([this.#snapshot(), this.#unreadFiles()]);
240
253
  const version = this.#versionOf(raws);
241
254
  if (refusals.length > 0)
242
255
  return { kind: "refused", refusals, version, warnings: unread };
package/dist/fleet.js CHANGED
@@ -24,6 +24,7 @@ import { parseDeclared } from "./declared-capture.js";
24
24
  import { dataDescriptor, isolatedObject, readDeclaredKey, ownValueOf } from "./own-key-read.js";
25
25
  import { isPlainJsonObject } from "./plain-json-object.js";
26
26
  import { buildQuotedIssue } from "./quoted-issue.js";
27
+ import { deepFreeze } from "./deep-freeze.js";
27
28
  // ── Web-admin's fleet endpoints (paths, one spelling) ─────────────────────────────────────────────────────
28
29
  /**
29
30
  * Web-admin's `/api/fleet/*` endpoints that are addressed from outside web-admin, relative to its origin. ONE spelling: whoever
@@ -41,13 +42,13 @@ import { buildQuotedIssue } from "./quoted-issue.js";
41
42
  * with the URL-encoded host id); the other values have none and are the path itself. A prefix router (an Ingress rule) takes the
42
43
  * template up to its first `{`.
43
44
  */
44
- export const FLEET_PATHS = {
45
+ export const FLEET_PATHS = deepFreeze({
45
46
  instances: "/api/fleet/instances",
46
47
  usage: "/api/fleet/usage",
47
48
  quotaLeases: "/api/fleet/leases",
48
49
  servingLease: "/api/fleet/live/serving-lease",
49
50
  hostPlanner: "/api/fleet/live/host-planner/{host}",
50
- };
51
+ });
51
52
  /**
52
53
  * The LIVENESS group — the fleet endpoints a web-admin answers without its readiness gate and without its config-governance gates
53
54
  * (they read no config domain and take service credentials only), so that a web-admin whose management face is refused never turns
@@ -60,11 +61,11 @@ export const FLEET_PATHS = {
60
61
  * `@sema-agent/settings-schema/fleet-paths.json` is `{ "FLEET_PATHS": …, "FLEET_LIVE_PATHS": … }`, written from these values at
61
62
  * build time — never edited by hand.
62
63
  */
63
- export const FLEET_LIVE_PATHS = [FLEET_PATHS.instances, FLEET_PATHS.servingLease, FLEET_PATHS.hostPlanner];
64
+ export const FLEET_LIVE_PATHS = deepFreeze([FLEET_PATHS.instances, FLEET_PATHS.servingLease, FLEET_PATHS.hostPlanner]);
64
65
  // ── Domain 1: drain protocol (graceful rolling update — the ground every form stands on) ──────────────────
65
66
  /** Lifecycle of a draining instance. `running`→`draining` on the stop signal; `drained` once in-flight hits
66
67
  * zero (clean) or the grace deadline forces the issue. Exit always follows `drained`. */
67
- export const DRAIN_PHASES = ["running", "draining", "drained"];
68
+ export const DRAIN_PHASES = deepFreeze(["running", "draining", "drained"]);
68
69
  /** Shipped default (server 1.96.0): generous by design — the only unrecoverable loss on restart is the
69
70
  * interactive turn currently streaming, so we wait long rather than cut short. Deployments override via
70
71
  * DRAIN_GRACE_MS; web-admin overrides per-worker through the worker spec. */
@@ -137,7 +138,7 @@ const Generation = z.string().refine(isCanonicalGeneration, buildQuotedIssue `a
137
138
  * Only a fleet member says it: an engine without a generation has no lease and carries no `leaseState` at all (there is no
138
139
  * fifth word for "not a member" — absence is that).
139
140
  */
140
- export const LEASE_STATES = ["none", "granted", "expired", "denied"];
141
+ export const LEASE_STATES = deepFreeze(["none", "granted", "expired", "denied"]);
141
142
  export const LeaseState = z.enum(LEASE_STATES);
142
143
  /**
143
144
  * "This instance must restart to apply config" — the engine's OWN observation (S-741), defined ONCE. It is part of the engine's
@@ -266,18 +267,18 @@ function readSignalBody(body, pick, schema) {
266
267
  * reads as unset (it falls back down the role chain and the engine says so once) — no reading refuses a model plane for it, so it was never
267
268
  * an engine group refusal. A reader still holding it gets it dropped by {@link readModelRefusals} like any code outside the set.
268
269
  */
269
- export const MODEL_ENTRY_REFUSAL_CODES = ["config.model_no_brain", "config.model_entry_invalid", "config.model_route_refused"];
270
+ export const MODEL_ENTRY_REFUSAL_CODES = deepFreeze(["config.model_no_brain", "config.model_entry_invalid", "config.model_route_refused"]);
270
271
  export const ModelEntryRefusalCode = z.enum(MODEL_ENTRY_REFUSAL_CODES);
271
272
  /** The env-model-table confirmation gate's group-refusal code (see {@link MODEL_PLANE_REFUSAL_CODES}). */
272
273
  export const CATALOG_REPLACES_ENV_MODELS_CODE = "config.catalog_replaces_env_models";
273
- export const MODEL_PLANE_REFUSAL_CODES = [
274
+ export const MODEL_PLANE_REFUSAL_CODES = deepFreeze([
274
275
  "config.default_model_missing",
275
276
  "config.model_refused_name_minted",
276
277
  "config.model_route_endpoint_missing",
277
278
  "config.gateway_fallback_without_primary",
278
279
  CATALOG_REPLACES_ENV_MODELS_CODE,
279
280
  "config.model_catalog_refused",
280
- ];
281
+ ]);
281
282
  export const ModelPlaneRefusalCode = z.enum(MODEL_PLANE_REFUSAL_CODES);
282
283
  /**
283
284
  * "This instance does not serve part (or all) of the model catalog it was handed" — the engine's OWN per-host verdict
@@ -445,7 +446,7 @@ export const InstanceHealth = z
445
446
  * - `observer-not-ready` — the reconciler's own observation vetoes it (stored rows only; the SECOND source, AND-merged).
446
447
  * - `draining` — the engine says it is draining.
447
448
  * - `not-ready` — the engine says it is not ready. */
448
- export const NOT_ROUTABLE_CODES = ["no-engine-signal", "stale", "observer-not-ready", "draining", "not-ready"];
449
+ export const NOT_ROUTABLE_CODES = deepFreeze(["no-engine-signal", "stale", "observer-not-ready", "draining", "not-ready"]);
449
450
  const notRoutable = (code) => {
450
451
  switch (code) {
451
452
  case "no-engine-signal":
@@ -652,7 +653,7 @@ export const ServingLeaseRequest = z.object({
652
653
  * - `retired` — web-admin has retired this instance (or the worker it belongs to).
653
654
  * Only {@link ServingLeaseResponse}'s `denied` arm carries a reason; `unknown` has none, by shape.
654
655
  */
655
- export const SERVING_LEASE_DENIED_REASONS = ["superseded", "retired"];
656
+ export const SERVING_LEASE_DENIED_REASONS = deepFreeze(["superseded", "retired"]);
656
657
  export const ServingLeaseDeniedReason = z.enum(SERVING_LEASE_DENIED_REASONS);
657
658
  const ServingLeaseGranted = z.object({ verdict: z.literal("granted"), ttlMs: INTEGER.positive() });
658
659
  const ServingLeaseDenied = z.object({ verdict: z.literal("denied"), reason: ServingLeaseDeniedReason });
@@ -691,7 +692,7 @@ const ServingLeaseDeniedRead = z.object({
691
692
  const ServingLeaseReadFace = z.discriminatedUnion("verdict", [ServingLeaseGranted, ServingLeaseDeniedRead, ServingLeaseUnknown]);
692
693
  /** The verdict words as a runtime list. `satisfies` bites a word the union does not have; the converse (a union arm missing
693
694
  * from this list) is pinned by a test that reads the union's discriminators. */
694
- export const SERVING_LEASE_VERDICTS = ["granted", "denied", "unknown"];
695
+ export const SERVING_LEASE_VERDICTS = deepFreeze(["granted", "denied", "unknown"]);
695
696
  /** Web-admin side: the request body of a serving-lease renewal. Shape mismatch / non-object / throwing accessor ⇒ `undefined`,
696
697
  * never throws (same guarded reader as every other read in this file). */
697
698
  export function readServingLeaseRequest(body) {
@@ -830,7 +831,7 @@ export const DrainRequest = z.object({
830
831
  });
831
832
  /** What a drain request leaves the engine in: `draining` — this call put it into draining; `already_draining` — it already was
832
833
  * (the same action repeated), and the receipt reports the first call's facts. */
833
- export const DRAIN_RECEIPT_STATES = ["draining", "already_draining"];
834
+ export const DRAIN_RECEIPT_STATES = deepFreeze(["draining", "already_draining"]);
834
835
  export const DrainReceiptState = z.enum(DRAIN_RECEIPT_STATES);
835
836
  /** The drain endpoint's answer: the engine's draining fact ({@link EngineDraining} — the same object {@link EngineSignal}
836
837
  * carries as `draining`, extended, not copied) plus how this call found the engine. */
@@ -844,7 +845,7 @@ export function readDrainReceipt(body) {
844
845
  return readSignalBody(body, WHOLE_BODY, DrainReceipt);
845
846
  }
846
847
  // ── Domain 3: dispatch policy (traffic + failover + LB — three domains, one gateway) ──────────────────────
847
- export const DISPATCH_STRATEGIES = ["round-robin", "least-inflight", "consistent-hash"];
848
+ export const DISPATCH_STRATEGIES = deepFreeze(["round-robin", "least-inflight", "consistent-hash"]);
848
849
  /** Per-worker dispatch policy (web-admin-configured; the gateway is OPTIONAL — D3: TOC/self-maintained TOB go
849
850
  * direct, sema-managed fleets route through /api/dispatch). Strategy is an enum on purpose: a new LB
850
851
  * algorithm is a new value, not a new skeleton. */
@@ -108,8 +108,8 @@ declare const HOOK_SHELLS: readonly ["bash", "powershell"];
108
108
  * The row order also decides which field an already-bad entry names (the first wrong one), so a column added later goes at the TAIL of its row (after the shared fields): adding one never
109
109
  * moves an answer the table already gave.
110
110
  */
111
- export declare const HOOK_ENTRY_FIELDS: Readonly<{
112
- command: Readonly<{
111
+ export declare const HOOK_ENTRY_FIELDS: {
112
+ readonly command: {
113
113
  readonly rewakeMessage: "nonEmpty?";
114
114
  readonly rewakeSummary: "nonEmpty?";
115
115
  readonly cloud: "any?";
@@ -123,8 +123,8 @@ export declare const HOOK_ENTRY_FIELDS: Readonly<{
123
123
  readonly async: "boolean?";
124
124
  readonly asyncRewake: "boolean?";
125
125
  readonly onFailure: "onFailure?";
126
- }>;
127
- prompt: Readonly<{
126
+ };
127
+ readonly prompt: {
128
128
  readonly continueOnBlock: "boolean?";
129
129
  readonly if: "string?";
130
130
  readonly timeout: "seconds?";
@@ -132,16 +132,16 @@ export declare const HOOK_ENTRY_FIELDS: Readonly<{
132
132
  readonly once: "boolean?";
133
133
  readonly prompt: "text";
134
134
  readonly model: "string?";
135
- }>;
136
- agent: Readonly<{
135
+ };
136
+ readonly agent: {
137
137
  readonly if: "string?";
138
138
  readonly timeout: "seconds?";
139
139
  readonly statusMessage: "string?";
140
140
  readonly once: "boolean?";
141
141
  readonly prompt: "text";
142
142
  readonly model: "string?";
143
- }>;
144
- http: Readonly<{
143
+ };
144
+ readonly http: {
145
145
  readonly cloud: "any?";
146
146
  readonly if: "string?";
147
147
  readonly timeout: "seconds?";
@@ -151,8 +151,8 @@ export declare const HOOK_ENTRY_FIELDS: Readonly<{
151
151
  readonly headers: "stringRecord?";
152
152
  readonly allowedEnvVars: "stringList?";
153
153
  readonly onFailure: "onFailure?";
154
- }>;
155
- mcp_tool: Readonly<{
154
+ };
155
+ readonly mcp_tool: {
156
156
  readonly if: "string?";
157
157
  readonly timeout: "seconds?";
158
158
  readonly statusMessage: "string?";
@@ -160,8 +160,8 @@ export declare const HOOK_ENTRY_FIELDS: Readonly<{
160
160
  readonly server: "string";
161
161
  readonly tool: "string";
162
162
  readonly input: "record?";
163
- }>;
164
- }>;
163
+ };
164
+ };
165
165
  /** The type of {@link HOOK_ENTRY_FIELDS}: per entry type, field name → field kind (literal types). */
166
166
  export type HookEntryFields = typeof HOOK_ENTRY_FIELDS;
167
167
  type HookFieldBaseValue<B> = B extends "text" | "nonEmpty" | "string" ? string : B extends "shell" ? (typeof HOOK_SHELLS)[number] : B extends "onFailure" ? HookOnFailure : B extends "any" ? unknown : B extends "boolean" ? boolean : B extends "seconds" ? number : B extends "stringRecord" ? Record<string, string> : B extends "stringList" | "argv" ? string[] : B extends "record" ? Record<string, unknown> : never;