@sema-agent/settings-schema 35.0.0 → 35.2.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 (38) hide show
  1. package/CHANGELOG.md +348 -0
  2. package/README.md +40 -12
  3. package/conformance/VERSION +1 -1
  4. package/conformance/profile/annotations.md +65 -0
  5. package/conformance/profile/loading-rules.md +193 -0
  6. package/conformance/profile/profiles/solo-auto.json +22 -0
  7. package/conformance/profile/profiles/solo-managed.json +21 -0
  8. package/conformance/profile/profiles/tenant-auto.json +36 -0
  9. package/conformance/profile/profiles/tenant-managed.json +36 -0
  10. package/conformance/profile/sema-profile.schema.json +201 -0
  11. package/conformance/profile/tools/mutations.md +62 -0
  12. package/conformance/profile/tools/validate.mjs +1190 -0
  13. package/conformance/profile/vectors/frozen-promises.json +120 -0
  14. package/conformance/profile/vectors/vectors.json +362 -0
  15. package/dist/api/connector-assertions.d.ts +186 -0
  16. package/dist/api/connector-assertions.js +148 -0
  17. package/dist/api/credentials.d.ts +30 -50
  18. package/dist/api/credentials.js +14 -14
  19. package/dist/api/refusal-table.d.ts +16 -0
  20. package/dist/api/refusal-table.js +24 -0
  21. package/dist/conformance/index.d.ts +1 -0
  22. package/dist/conformance/index.js +1 -0
  23. package/dist/conformance/profile.d.ts +55 -0
  24. package/dist/conformance/profile.js +108 -0
  25. package/dist/index.d.ts +3 -0
  26. package/dist/index.js +3 -0
  27. package/dist/mutable-copy.d.ts +48 -0
  28. package/dist/mutable-copy.js +229 -0
  29. package/dist/settings-units.d.ts +8 -0
  30. package/dist/settings-units.js +6 -4
  31. package/dist/tighten-only-seat-limits.d.ts +16 -0
  32. package/dist/tighten-only-seat-limits.js +16 -0
  33. package/docs/API-SURFACE.md +32 -3
  34. package/docs/CONFORMANCE.md +17 -0
  35. package/docs/CONSUMER-INTEGRATION.md +180 -12
  36. package/llms-full.txt +27 -9
  37. package/llms.txt +6 -2
  38. package/package.json +1 -1
@@ -0,0 +1,55 @@
1
+ /** Absolute path of the published `conformance/profile/` directory, so consumers can also read the prose files. */
2
+ export declare const PROFILE_CONFORMANCE_DIR: string;
3
+ /** Format string of the profile judgment-vectors document shipped by this package version. */
4
+ export declare const PROFILE_VECTORS_FORMAT: "sema-profile@1 judgment vectors v5";
5
+ /** Format string of the profile frozen-promises document shipped by this package version. */
6
+ export declare const PROFILE_FROZEN_PROMISES_FORMAT: "sema-profile@1 frozen promises v1";
7
+ /** Closed set of expected outcomes declared on every profile judgment vector. */
8
+ export declare const PROFILE_VECTOR_EXPECTS: readonly ["accept", "reject"];
9
+ /** Expected outcome of a profile judgment vector. */
10
+ export type ProfileVectorExpect = (typeof PROFILE_VECTOR_EXPECTS)[number];
11
+ /** Closed set of the four built-in configuration profile names shipped under `conformance/profile/profiles/`. */
12
+ export declare const BUILTIN_PROFILE_NAMES: readonly ["solo-auto", "solo-managed", "tenant-auto", "tenant-managed"];
13
+ /** Name of a built-in configuration profile shipped under `conformance/profile/profiles/`. */
14
+ export type BuiltinProfileName = (typeof BUILTIN_PROFILE_NAMES)[number];
15
+ /**
16
+ * One judgment vector from `conformance/profile/vectors/vectors.json`.
17
+ * Only the fields present on every vector in the document are typed; optional and rule-specific fields stay `unknown`.
18
+ */
19
+ export interface ProfileVector {
20
+ readonly id: string;
21
+ readonly rule: string;
22
+ readonly expect: ProfileVectorExpect;
23
+ readonly judge: string;
24
+ readonly executedBy: readonly string[];
25
+ readonly [key: string]: unknown;
26
+ }
27
+ /** Parsed `conformance/profile/vectors/vectors.json` document. */
28
+ export interface ProfileVectorsDocument {
29
+ readonly format: typeof PROFILE_VECTORS_FORMAT;
30
+ readonly vectors: readonly ProfileVector[];
31
+ readonly [key: string]: unknown;
32
+ }
33
+ /** Parsed `conformance/profile/vectors/frozen-promises.json` document. */
34
+ export interface ProfileFrozenPromises {
35
+ readonly format: typeof PROFILE_FROZEN_PROMISES_FORMAT;
36
+ readonly builtins: Readonly<Record<string, unknown>>;
37
+ readonly channelDestinations: Readonly<Record<string, unknown>>;
38
+ readonly readBeforeFold: Readonly<Record<string, unknown>>;
39
+ readonly reportClosedSets: Readonly<Record<string, unknown>>;
40
+ readonly [key: string]: unknown;
41
+ }
42
+ /** Parsed profile judgment vectors and frozen promises loaded from disk. */
43
+ export interface ProfileVectorsData {
44
+ readonly vectorsDocument: ProfileVectorsDocument;
45
+ readonly frozenPromises: ProfileFrozenPromises;
46
+ }
47
+ /** The four built-in profile JSON documents keyed by name, plus the profile JSON schema. */
48
+ export interface BuiltinProfilesAndSchema {
49
+ readonly profiles: Readonly<Record<BuiltinProfileName, Readonly<Record<string, unknown>>>>;
50
+ readonly schema: Readonly<Record<string, unknown>>;
51
+ }
52
+ /** Load and parse `vectors/vectors.json` and `vectors/frozen-promises.json` from the published profile conformance directory. */
53
+ export declare function loadProfileVectors(profileDir?: string): Promise<ProfileVectorsData>;
54
+ /** Load and parse the four built-in profiles (keyed by name) and `sema-profile.schema.json`. */
55
+ export declare function loadBuiltinProfilesAndSchema(profileDir?: string): Promise<BuiltinProfilesAndSchema>;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Configuration-profile loading/validation vectors published on the `./conformance` face.
3
+ *
4
+ * The published directory is `conformance/profile/` inside this package ({@link PROFILE_CONFORMANCE_DIR}).
5
+ * All reads are lazy (no filesystem I/O at import time), following the same root-resolution idiom as
6
+ * `DEFAULT_CORPUS_DIR`. `conformance/profile/tools/validate.mjs` ships as reference text only and is
7
+ * not executed by this module.
8
+ */
9
+ import { readFile } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { deepFreeze } from "../deep-freeze.js";
12
+ import { isJsonArray, isPlainJsonObject } from "../plain-json-object.js";
13
+ import { DEFAULT_CORPUS_DIR } from "./corpus.js";
14
+ /** Absolute path of the published `conformance/profile/` directory, so consumers can also read the prose files. */
15
+ export const PROFILE_CONFORMANCE_DIR = join(DEFAULT_CORPUS_DIR, "profile");
16
+ /** Format string of the profile judgment-vectors document shipped by this package version. */
17
+ export const PROFILE_VECTORS_FORMAT = "sema-profile@1 judgment vectors v5";
18
+ /** Format string of the profile frozen-promises document shipped by this package version. */
19
+ export const PROFILE_FROZEN_PROMISES_FORMAT = "sema-profile@1 frozen promises v1";
20
+ /** Closed set of expected outcomes declared on every profile judgment vector. */
21
+ export const PROFILE_VECTOR_EXPECTS = deepFreeze(["accept", "reject"]);
22
+ /** Closed set of the four built-in configuration profile names shipped under `conformance/profile/profiles/`. */
23
+ export const BUILTIN_PROFILE_NAMES = deepFreeze(["solo-auto", "solo-managed", "tenant-auto", "tenant-managed"]);
24
+ async function readJson(filePath) {
25
+ return JSON.parse(await readFile(filePath, "utf8"));
26
+ }
27
+ function formatFoundValue(value) {
28
+ return value === undefined ? "undefined" : JSON.stringify(value);
29
+ }
30
+ function requirePlainObject(value, where) {
31
+ if (!isPlainJsonObject(value))
32
+ throw new Error(`conformance profile: ${where} must be a JSON object`);
33
+ return value;
34
+ }
35
+ function requireNonEmptyString(value, where) {
36
+ if (typeof value !== "string" || value.length === 0) {
37
+ throw new Error(`conformance profile: ${where} must be a non-empty string`);
38
+ }
39
+ return value;
40
+ }
41
+ function requireExactFormat(value, file, supported) {
42
+ if (value !== supported) {
43
+ throw new Error(`conformance profile: ${file}#format is ${formatFoundValue(value)}, supported format is ${JSON.stringify(supported)}`);
44
+ }
45
+ return value;
46
+ }
47
+ function requireVectorExpect(value, where) {
48
+ if (typeof value !== "string" || !PROFILE_VECTOR_EXPECTS.includes(value)) {
49
+ throw new Error(`conformance profile: ${where} must be one of ${PROFILE_VECTOR_EXPECTS.join(" | ")}, found ${formatFoundValue(value)}`);
50
+ }
51
+ return value;
52
+ }
53
+ function checkProfileVector(value, index) {
54
+ const row = requirePlainObject(value, `vectors/vectors.json#vectors[${index}]`);
55
+ requireNonEmptyString(row.id, `vectors[${index}].id`);
56
+ requireNonEmptyString(row.rule, `vectors[${index}].rule`);
57
+ requireVectorExpect(row.expect, `vectors[${index}].expect`);
58
+ requireNonEmptyString(row.judge, `vectors[${index}].judge`);
59
+ if (!isJsonArray(row.executedBy) ||
60
+ row.executedBy.length === 0 ||
61
+ !row.executedBy.every((entry) => typeof entry === "string" && entry.length > 0)) {
62
+ throw new Error(`conformance profile: vectors[${index}].executedBy must be a non-empty array of non-empty strings`);
63
+ }
64
+ return row;
65
+ }
66
+ /** Load and parse `vectors/vectors.json` and `vectors/frozen-promises.json` from the published profile conformance directory. */
67
+ export async function loadProfileVectors(profileDir = PROFILE_CONFORMANCE_DIR) {
68
+ const [vectorsRaw, frozenRaw] = await Promise.all([
69
+ readJson(join(profileDir, "vectors", "vectors.json")),
70
+ readJson(join(profileDir, "vectors", "frozen-promises.json")),
71
+ ]);
72
+ const vectorsObj = requirePlainObject(vectorsRaw, "vectors/vectors.json");
73
+ const vectorsFormat = requireExactFormat(vectorsObj.format, "vectors/vectors.json", PROFILE_VECTORS_FORMAT);
74
+ if (!isJsonArray(vectorsObj.vectors) || vectorsObj.vectors.length === 0) {
75
+ throw new Error("conformance profile: vectors/vectors.json#vectors must be a non-empty array");
76
+ }
77
+ const vectors = vectorsObj.vectors.map((entry, idx) => checkProfileVector(entry, idx));
78
+ const frozenObj = requirePlainObject(frozenRaw, "vectors/frozen-promises.json");
79
+ const frozenFormat = requireExactFormat(frozenObj.format, "vectors/frozen-promises.json", PROFILE_FROZEN_PROMISES_FORMAT);
80
+ const builtins = requirePlainObject(frozenObj.builtins, "vectors/frozen-promises.json#builtins");
81
+ const channelDestinations = requirePlainObject(frozenObj.channelDestinations, "vectors/frozen-promises.json#channelDestinations");
82
+ const readBeforeFold = requirePlainObject(frozenObj.readBeforeFold, "vectors/frozen-promises.json#readBeforeFold");
83
+ const reportClosedSets = requirePlainObject(frozenObj.reportClosedSets, "vectors/frozen-promises.json#reportClosedSets");
84
+ return {
85
+ vectorsDocument: { ...vectorsObj, format: vectorsFormat, vectors },
86
+ frozenPromises: {
87
+ ...frozenObj,
88
+ format: frozenFormat,
89
+ builtins,
90
+ channelDestinations,
91
+ readBeforeFold,
92
+ reportClosedSets,
93
+ },
94
+ };
95
+ }
96
+ /** Load and parse the four built-in profiles (keyed by name) and `sema-profile.schema.json`. */
97
+ export async function loadBuiltinProfilesAndSchema(profileDir = PROFILE_CONFORMANCE_DIR) {
98
+ const [profileEntries, schemaRaw] = await Promise.all([
99
+ Promise.all(BUILTIN_PROFILE_NAMES.map(async (name) => {
100
+ const parsed = requirePlainObject(await readJson(join(profileDir, "profiles", `${name}.json`)), `profiles/${name}.json`);
101
+ return [name, parsed];
102
+ })),
103
+ readJson(join(profileDir, "sema-profile.schema.json")),
104
+ ]);
105
+ const schema = requirePlainObject(schemaRaw, "sema-profile.schema.json");
106
+ const profiles = Object.fromEntries(profileEntries);
107
+ return { profiles, schema };
108
+ }
package/dist/index.d.ts CHANGED
@@ -40,6 +40,7 @@ export * from "./api/pull-token.js";
40
40
  export * from "./api/feedback.js";
41
41
  export * from "./api/credentials.js";
42
42
  export * from "./api/lifecycle-events.js";
43
+ export * from "./api/connector-assertions.js";
43
44
  export * from "./sandbox-git.js";
44
45
  export * from "./web-admin-env.js";
45
46
  export * from "./web-admin-credential.js";
@@ -58,3 +59,5 @@ export * from "./mcp-entry-credential.js";
58
59
  export * from "./connector-authorize-url.js";
59
60
  export { REMOTE_MCP_SERVER_NAME_PREFIX } from "./mcp-server-name.js";
60
61
  export * from "./center-refs.js";
62
+ export * from "./tighten-only-seat-limits.js";
63
+ export { mutableCopyOf, type MutableCopy } from "./mutable-copy.js";
package/dist/index.js CHANGED
@@ -40,6 +40,7 @@ export * from "./api/pull-token.js"; // scope-bound token FORM + minting rule (o
40
40
  export * from "./api/feedback.js"; // /bug report wire contract: FeedbackSubmitRequest (POST body) + FeedbackWire / FeedbackListResponse + the two caps, pure/browser-safe
41
41
  export * from "./api/credentials.js"; // 14.7.0: the credential port's `sandbox_git` wire (barrel only, no subpath): SandboxGitCredentialRequest / CredentialHandleAnswer / CredentialResolveRequest / SandboxGitCredentialAnswer (per-origin SandboxGitOriginAnswer) / SandboxGitCredentialRefusal + the three word tables (SANDBOX_GIT_ORIGIN_VERDICTS → _STATES / _REASONS, SANDBOX_GIT_REFUSALS → _ERRORS, SANDBOX_GIT_PERMANENCE), pure/browser-safe
42
42
  export * from "./api/lifecycle-events.js"; // 29.0.0: the user-lifecycle-event wire (barrel only, no subpath): PRINCIPAL_LIFECYCLE_EVENT_KINDS (five words) + PrincipalLifecycleEvent (unknown keys stripped, discriminated by `kind`; the two `membership.*` arms carry `scope`) + PrincipalLifecycleEventPage { events, head, next } + LIFECYCLE_PAGE_REFUSALS (four words → status; 410 bodies carry `head`) / LifecyclePageRefusal + the reconcile pair PrincipalReconcileRequest (1–PRINCIPAL_RECONCILE_MAX_ITEMS) / PrincipalReconcileAnswer (PrincipalStanding, discriminated by `standing`), pure/browser-safe
43
+ export * from "./api/connector-assertions.js"; // the connector assertion mint's wire (barrel only, no subpath): ConnectorAssertionRequest (STRICT object, four keys) / ConnectorAssertionAnswer { assertion, expiresAt } / ConnectorAssertionRefusal (discriminated by `error`; only authorization_required carries authorizeUrl) + CONNECTOR_ASSERTION_REFUSALS → _ERRORS (the credential plane's nine shared words + the mint's own five) + compareDialTargets (same / different / unreadable, DIAL_TARGET_COMPARISONS — the mint's "same dial target?" test, not a registry dedup judge), pure/browser-safe
43
44
  export * from "./sandbox-git.js"; // 14.7.0: the sandbox git plane's origin form (isSandboxGitOrigin — a string equal to its own WHATWG origin) + the `sandboxGit` effective-config block (SandboxGitConfig: origins ≤ 16, each { origin, connectUrl }), pure/browser-safe
44
45
  export * from "./web-admin-env.js"; // WEB_ADMIN_ENV — every env name an engine reads to reach web-admin (one table; a leaf module), pure/browser-safe
45
46
  export * from "./web-admin-credential.js"; // S-698 web-admin credential FILE contract: WebAdminCredentialEnvelope (user-session envelope, strict) + parseWebAdminCredentialFile (bare / envelope / unreadable — the one discrimination law) + judgeWebAdminCredentialDeclaration(env, credential) (pick-exactly-one over the credential's WEB_ADMIN_ENV pair; WEB_ADMIN_CREDENTIALS = access | assertion), pure/browser-safe
@@ -58,6 +59,8 @@ export * from "./mcp-entry-credential.js"; // 29.0.0: the MCP http entry's crede
58
59
  export * from "./connector-authorize-url.js"; // 29.0.0: the hosted connector authorization address (connectorAuthorizeUrlOf / connectorAuthorizeUrlFlaws / CONNECTOR_AUTHORIZE_QUERY / CONNECTOR_AUTHORIZE_URL_FLAWS — one route form, the assembler and its judge in one module), pure/browser-safe
59
60
  export { REMOTE_MCP_SERVER_NAME_PREFIX } from "./mcp-server-name.js"; // the MCP server-name prefix reserved for the remote MCP servers a device executor offers (mount name = prefix + the executor's server name); the predicate and its sentence stay package-private — the request plane's MCP name judges (isUsableMcpServerName / describeBadMcpServerName) read them; the config plane's McpServerSpec.name accepts the prefix (refusing it would be a validation tightening — a major), pure/browser-safe
60
61
  export * from "./center-refs.js"; // resolveCenterRefs(refs, lookup) — THE center-roster reference resolver: one verdict word per member (missing_name / not_a_string / read_threw, CENTER_REF_FAULTS), one whole verdict (resolved / unresolved / refs_unreadable, CENTER_REFS_VERDICTS); the refs record is read by the public readPlainStringRecord, the lookup is the caller's, it reads no process.env; pure/browser-safe
62
+ export * from "./tighten-only-seat-limits.js"; // acceptance bounds the server applies to the request-face tighten-only seats (MAX_READ_DENY_STARS_PER_SEGMENT / MAX_READ_DENY_STARS_TOTAL / MAX_TIGHTEN_ONLY_SEAT_ENTRIES / MAX_READ_DENY_ENTRIES), pure/browser-safe
63
+ export { mutableCopyOf } from "./mutable-copy.js"; // THE mutable deep copy of a (deep-frozen) export — plain data (arrays / plain objects / Map / Set / Date / RegExp / primitives) rebuilt level by level, nothing frozen, the source untouched, aliases and cycles kept; functions / zod schemas / other objects / accessors (never called) / symbol keys ⇒ TypeError naming the path; MutableCopy<T> = T with readonly removed at every level; pure/browser-safe
61
64
  // NOTE: the Node-fs-backed helpers (FileConfigStore + the file editor) are NOT in this barrel — they pull
62
65
  // `node:fs`/`node:path` and would break a browser/client bundle that only wants the contract (e.g.
63
66
  // web-admin's client components import the zod types through here). Import them from the Node-only
@@ -0,0 +1,48 @@
1
+ /**
2
+ * 包根导出的表,容器层(数组 / 表 / Set / Map)都是**深冻结**的(包内冻结助手 `./deep-freeze`;表里的 RegExp 不冻):共享的闭集不许被某个读者原地改写。消费方要一份**能改的**副本时,这里是唯一的一只口 ——
3
+ * 浅拷贝(`[...X]` / `{ ...X }`)只解冻最外一层;`structuredClone` 对带 symbol 值的表(`EXTENSION_NAMESPACES` 的 `at` 里的 `ANY_INDEX`)与带函数 / zod schema 的表
4
+ * (`DOMAIN_SCHEMAS`)抛 `DataCloneError`,不说是哪一格。
5
+ *
6
+ * {@link mutableCopyOf} 的规则(纯数据 ⇒ 逐层新建的副本;别的 ⇒ 响亮拒,不交回半份):
7
+ * · **容器**逐层新建、任何一层都不冻:数组(同长;洞仍是洞)· 朴素对象(座位 `./plain-json-object` 的 `plain`;副本是寻常对象 `{}`,同 `structuredClone`)·
8
+ * `Map`(键与值都拷)· `Set` · `Date`(按时间值新建)· `RegExp`(`new RegExp(source, flags)`,`lastIndex` 归零)。这四种按**内部槽**认(见下),原型被换掉
9
+ * (含换成 `null`、座位因此读成朴素)的也照这四种拷。
10
+ * 数组拷它的各个下标(可枚举与否都拷,同内核的数组读法 —— 不可枚举的**数据**下标进副本;下标是访问器的,可枚举与否都拒);其余容器拷自有的**可枚举串键**数据属性,照原序;不可枚举的自有属性(数据或访问器)不进副本、
11
+ * 访问器也不被调(同 `Object.keys` / 展开 / `structuredClone`;冻结助手装在 Set / Map 上的只读修改方法就是这一类,所以副本是普通的、能 `add` / `set` 的集合)。
12
+ * 原型不是数据:副本的原型是本 realm 的内建原型(`Object.prototype` / `Array.prototype` / …),与源共享原型这件事不算共享可变状态。
13
+ * 数组的 `length` 与 RegExp 的 `lastIndex` 是语言规定的不可配置属性,副本里照样可写、不可配置。
14
+ * · **原始值**(含 symbol、bigint、`undefined`)原样交回。
15
+ * · **别名**:同一只源对象在图里出现几次,副本里就是同一只新对象出现几次;**环**照拷(副本里同样成环),不死循环;实现是迭代的,深度只受内存限制。
16
+ * · **拒**(`TypeError`,句子是「`mutableCopyOf: <路径> <它是什么>; only plain data is copied …`」,路径从根 `value` 起:`.key` / `["键"]` / `[下标]` /
17
+ * `.get(<Map 键>)` / `.keys()[i]` / `.values()[i]`;外来的键名经 `./caller-text-echo` 有界回显):
18
+ * 函数 · zod schema · 其余对象(类实例 —— 继承上面四种或 `Array` 的除外,见「已知的边」—— 与别的 realm 认不出的对象)·
19
+ * 可枚举的访问器属性(getter / setter —— **getter 从不被调**;数组的访问器下标可枚举与否都拒)·
20
+ * 自有 symbol 键(副本拷不了它,不静默丢)· 数组上挂的非下标键 · 检视就抛的对象(已撤销的 Proxy 等,全包那一句「检视不了」)。
21
+ * 对「带 schema / 函数的导出」(如 `DOMAIN_SCHEMAS`)整只拒 —— 那不是数据表。
22
+ * · 原值一个字节不动:只读描述符、不写源对象;也从不 `[[Get]]` 源对象的成员(读法走内核 `./own-key-read`:一次列成员、每个成员一份描述符,值只从描述符取)。
23
+ *
24
+ * 认 `Map` / `Set` / `Date` / `RegExp` 用的是本 realm 内建的**品牌检查**,以源对象为接收者调:`Map` / `Set` 是模块加载时取的 `has`、`Date` 是加载时取的 `getTime`、
25
+ * `RegExp` 是 `RegExp.prototype` 上的 `source` 与各旗的读取器(读取器取不成加载时的一份,调用时从内建原型上读)。不读源对象自己的成员、不调它的任何代码,
26
+ * 另一 realm 造的这四种也认得出。新建副本用的构造器、填 Map / Set 用的 `forEach` / `set` / `add` 同样是加载时取的。Map / Set 先经内建 `forEach` 拍一份条目快照
27
+ * (拍的时候不检视任何成员),再逐条检视、拷贝 —— 快照拍下之后,检视成员时跑到的 Proxy 陷阱改了源集合,副本也只含快照里的条目,遍历有终点。
28
+ * 快照在**填这只集合时**才拍:排在它自有的可枚举属性之后(那些属性的值先被检视),也排在工作队列里先于它的容器之后;在那之前跑到的 Proxy 陷阱对源集合的修改会进副本。
29
+ * **信任边界**:本 realm 的内建(全局构造器、内建原型上的读取器)在模块加载之后被人替换,不在这只口的防护范围内(包里只有安全轴的朴素数组判据做这一层)。
30
+ * **已知的边**:继承这四种的类的实例按基类拷(子类身份与它原型上的方法不进副本);`Array.isArray` 答真的值 —— 继承 `Array` 的类的实例、包着数组的 Proxy —— 座位读成数组,
31
+ * 拷成普通数组、不拒(子类身份与原型方法同样不进副本);Proxy 的陷阱在检视时照样被调(语言里认不出一只 Proxy),它说了什么副本就是什么。
32
+ *
33
+ * 返回型 {@link MutableCopy}:逐层去掉 `readonly`(`ReadonlyMap` ⇒ `Map`、`ReadonlySet` ⇒ `Set`、只读数组 / 元组 ⇒ 可写数组 / 元组);函数与 schema 位的型原样(运行期那里抛)。
34
+ * 型按**声明的键**映射:声明里有、运行期却是不可枚举的键,型里仍在、副本里没有(型说不出可枚举性)。
35
+ * 纯函数、pure/browser-safe。
36
+ */
37
+ import type { z } from "zod";
38
+ /** `T` 的可改形:逐层去掉 `readonly`。`any` / `unknown`、原始值、函数、zod schema(运行期这两种抛)、`RegExp`、`Date` 原样;`ReadonlyMap` / `ReadonlySet` ⇒ `Map` / `Set`;数组、元组与对象逐键映射(可选性保留)。 */
39
+ export type MutableCopy<T> = unknown extends T ? T : MutableCopyOfKnown<T>;
40
+ type MutableCopyOfKnown<T> = T extends string | number | boolean | bigint | symbol | null | undefined ? T : T extends ((...args: never[]) => unknown) | z.core.$ZodType ? T : T extends RegExp ? RegExp : T extends Date ? Date : T extends ReadonlyMap<infer K, infer V> ? Map<MutableCopy<K>, MutableCopy<V>> : T extends ReadonlySet<infer M> ? Set<MutableCopy<M>> : {
41
+ -readonly [P in keyof T]: MutableCopy<T[P]>;
42
+ };
43
+ /**
44
+ * 取一份可改的深副本:纯数据逐层新建(任何一层都不冻,原值不动),别名保别名、环照拷;不是纯数据的地方抛 `TypeError` 点出路径(规则全文见本模块头注)。
45
+ * 用途:包根导出的闭集都是深冻结的,要在它的基础上改出一份自己的(排序、加一行、改一格)时调它,例:`const rules = mutableCopyOf(EXTENSION_NAMESPACES); rules.models?.push(…)`。
46
+ */
47
+ export declare function mutableCopyOf<T>(value: T): MutableCopy<T>;
48
+ export {};
@@ -0,0 +1,229 @@
1
+ import { echoCallerText } from "./caller-text-echo.js";
2
+ import { UNINSPECTABLE, containerView, dataDescriptor, inspect, isAccessorDescriptor, readDeclaredKey } from "./own-key-read.js";
3
+ import { jsonShapeOf } from "./plain-json-object.js";
4
+ /** 本 realm 的内建:构造器与方法加载时取一次(之后有人改写 `Map.prototype.has` / 全局 `Date` 之类,这里调的仍是加载时那一份);RegExp 的读取器在调用时从加载时取的内建原型上读、以源对象为接收者调。 */
5
+ const MAP = Map;
6
+ const SET = Set;
7
+ const DATE = Date;
8
+ const REGEXP = RegExp;
9
+ const REGEXP_PROTOTYPE = RegExp.prototype;
10
+ const MAP_HAS = Map.prototype.has;
11
+ const SET_HAS = Set.prototype.has;
12
+ const MAP_FOR_EACH = Map.prototype.forEach;
13
+ const SET_FOR_EACH = Set.prototype.forEach;
14
+ const MAP_SET = Map.prototype.set;
15
+ const SET_ADD = Set.prototype.add;
16
+ const DATE_GET_TIME = Date.prototype.getTime;
17
+ /** RegExp 的旗:`RegExp.prototype` 上每只旗的读取器(读正则自己的内部槽,不读实例成员)与它的字母,按 `flags` 的规范次序。 */
18
+ const REGEXP_FLAGS = [
19
+ ["hasIndices", "d"],
20
+ ["global", "g"],
21
+ ["ignoreCase", "i"],
22
+ ["multiline", "m"],
23
+ ["dotAll", "s"],
24
+ ["unicode", "u"],
25
+ ["unicodeSets", "v"],
26
+ ["sticky", "y"],
27
+ ];
28
+ const ROOT = { parent: undefined, segment: "value" };
29
+ const step = (parent, segment) => ({ parent, segment });
30
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
31
+ const keySegment = (key) => (IDENTIFIER.test(key) ? `.${echoCallerText(key)}` : `[${JSON.stringify(echoCallerText(key))}]`);
32
+ /** Map 的一个键在路径里的写法:原始值照写(串带引号、有界回显),对象键没有字面写法 ⇒ 交 `undefined`(路径改用 `.values()[i]`)。 */
33
+ const mapKeyText = (key) => {
34
+ if (typeof key === "string")
35
+ return JSON.stringify(echoCallerText(key));
36
+ if (typeof key === "symbol")
37
+ return echoCallerText(String(key));
38
+ if (typeof key === "bigint")
39
+ return `${String(key)}n`;
40
+ if (key === null || key === undefined || typeof key === "number" || typeof key === "boolean")
41
+ return String(key);
42
+ return undefined; // 对象 / 函数键:没有字面写法
43
+ };
44
+ function pathText(at) {
45
+ let text = "";
46
+ for (let cur = at; cur !== undefined; cur = cur.parent)
47
+ text = cur.segment + text;
48
+ return text;
49
+ }
50
+ function refusal(at, what) {
51
+ return new TypeError(`mutableCopyOf: ${pathText(at)} ${what}; only plain data is copied — arrays, plain objects, Map, Set, Date, RegExp and primitives`);
52
+ }
53
+ /** 品牌检查 + 读数:是这一种 ⇒ 读数;不是(内建读取器 / 方法对它抛)⇒ `undefined`。只调加载时取的内建,以源对象为接收者;不读源对象自己的成员。 */
54
+ function branded(v) {
55
+ if (inspect(() => Reflect.apply(MAP_HAS, v, [undefined])).ok)
56
+ return { kind: "map" }; // 内建 `has` 先认内部槽:不是 Map ⇒ 抛
57
+ if (inspect(() => Reflect.apply(SET_HAS, v, [undefined])).ok)
58
+ return { kind: "set" };
59
+ const time = inspect(() => Reflect.apply(DATE_GET_TIME, v, []));
60
+ if (time.ok)
61
+ return { kind: "date", time: time.value };
62
+ const regexp = inspect(() => {
63
+ const source = Reflect.get(REGEXP_PROTOTYPE, "source", v);
64
+ let flags = "";
65
+ for (const [getter, letter] of REGEXP_FLAGS)
66
+ if (Reflect.get(REGEXP_PROTOTYPE, getter, v) === true)
67
+ flags += letter;
68
+ return { source, flags };
69
+ });
70
+ if (regexp.ok)
71
+ return { kind: "regexp", source: regexp.value.source, flags: regexp.value.flags };
72
+ return undefined;
73
+ }
74
+ /** 一个值是什么:原始值(原样交回)或一只要拷的容器;都不是 ⇒ 抛 {@link refusal}。形状只问座位。 */
75
+ function classify(v, at) {
76
+ const shape = jsonShapeOf(v);
77
+ switch (shape) {
78
+ case "null":
79
+ case "primitive":
80
+ return { leaf: true };
81
+ case "array":
82
+ return { kind: "array" };
83
+ case "plain":
84
+ return branded(v) ?? { kind: "object" }; // 原型换成 null 的 Map / Set / Date / RegExp 座位读成朴素:先按内部槽认,认不出才是朴素对象
85
+ case "uninspectable":
86
+ throw refusal(at, `is ${UNINSPECTABLE}`);
87
+ case "non_plain_object": {
88
+ if (typeof v === "function")
89
+ throw refusal(at, "is a function");
90
+ const object = v;
91
+ const container = branded(object);
92
+ if (container !== undefined)
93
+ return container;
94
+ const internals = readDeclaredKey(object, "_zod").presence; // zod 4 的实例自带(不可枚举的)`_zod`:只看在不在场,不取值、不调 getter
95
+ switch (internals) {
96
+ case "own":
97
+ case "hidden":
98
+ throw refusal(at, "is a zod schema");
99
+ case "unreadable":
100
+ throw refusal(at, `is ${UNINSPECTABLE}`);
101
+ case "inherited":
102
+ case "absent":
103
+ throw refusal(at, "is an object of another kind (a class instance, or an object this realm does not recognise)");
104
+ default: {
105
+ const unhandled = internals;
106
+ throw new Error(`mutableCopyOf: unhandled presence ${String(unhandled)}`);
107
+ }
108
+ }
109
+ }
110
+ default: {
111
+ const unhandled = shape;
112
+ throw new Error(`mutableCopyOf: unhandled shape ${String(unhandled)}`);
113
+ }
114
+ }
115
+ }
116
+ /** 新建一只空副本(内容随后由工作表填)。 */
117
+ function emptyCopy(c) {
118
+ switch (c.kind) {
119
+ case "array":
120
+ return [];
121
+ case "object":
122
+ return {};
123
+ case "map":
124
+ return new MAP();
125
+ case "set":
126
+ return new SET();
127
+ case "date":
128
+ return new DATE(c.time);
129
+ case "regexp":
130
+ return new REGEXP(c.source, c.flags);
131
+ default: {
132
+ const unhandled = c;
133
+ throw new Error(`mutableCopyOf: unhandled container ${String(unhandled.kind)}`);
134
+ }
135
+ }
136
+ }
137
+ /**
138
+ * 取一份可改的深副本:纯数据逐层新建(任何一层都不冻,原值不动),别名保别名、环照拷;不是纯数据的地方抛 `TypeError` 点出路径(规则全文见本模块头注)。
139
+ * 用途:包根导出的闭集都是深冻结的,要在它的基础上改出一份自己的(排序、加一行、改一格)时调它,例:`const rules = mutableCopyOf(EXTENSION_NAMESPACES); rules.models?.push(…)`。
140
+ */
141
+ export function mutableCopyOf(value) {
142
+ const copies = new MAP();
143
+ const queue = { head: undefined, tail: undefined };
144
+ /** 一个值 ⇒ 它的副本:原始值原样;见过的源容器 ⇒ 同一份副本;新容器 ⇒ 先建空副本登记(别名与环由此成立),内容进工作队列。 */
145
+ const copyOf = (node, at) => {
146
+ const known = copies.get(node);
147
+ if (known !== undefined)
148
+ return known;
149
+ const c = classify(node, at);
150
+ if ("leaf" in c)
151
+ return node;
152
+ const source = node;
153
+ const copy = emptyCopy(c);
154
+ copies.set(source, copy);
155
+ const item = { source, copy, container: c, at, next: undefined };
156
+ if (queue.tail === undefined)
157
+ queue.head = item;
158
+ else
159
+ queue.tail.next = item;
160
+ queue.tail = item;
161
+ return copy;
162
+ };
163
+ const root = copyOf(value, ROOT);
164
+ for (let w = queue.head; w !== undefined; w = w.next)
165
+ fill(w, copyOf);
166
+ return root;
167
+ }
168
+ /** 填一只副本:先拷它自有的可枚举串键数据属性(数组即下标),再拷 Map 的条目 / Set 的成员。 */
169
+ function fill(w, copyOf) {
170
+ const isArray = w.container.kind === "array";
171
+ const read = inspect(() => containerView(w.source, isArray, "wide"));
172
+ if (!read.ok)
173
+ throw refusal(w.at, `is ${read.sentence}`);
174
+ const view = read.value;
175
+ if (view.foreign)
176
+ throw refusal(w.at, isArray ? "has an own property that is not an array element (a named or symbol-keyed property)" : "has a symbol-keyed own property");
177
+ if (isArray) {
178
+ const length = view.length;
179
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || length > 2 ** 32 - 1)
180
+ throw refusal(w.at, `is ${UNINSPECTABLE}`);
181
+ w.copy.length = length;
182
+ }
183
+ for (const [key, d] of view.members) {
184
+ const at = step(w.at, isArray ? `[${key}]` : keySegment(key));
185
+ if (isAccessorDescriptor(d))
186
+ throw refusal(at, "is an accessor property (getter / setter — it is never called)");
187
+ Object.defineProperty(w.copy, key, dataDescriptor(copyOf(d.value, at)));
188
+ }
189
+ const c = w.container;
190
+ let i = 0;
191
+ switch (c.kind) {
192
+ case "map": {
193
+ // 先拍快照:内建 `forEach` 直接读源 Map 的内部槽(不走源对象自己的 `Symbol.iterator` / 方法),回调只往私有的快照里放、不检视任何成员;
194
+ // 之后逐条检视时跑到的 Proxy 陷阱即使改了源 Map,也改不到快照 —— 遍历有终点,副本只含快照里的条目(上面拷自有属性时跑到的陷阱在快照之前,它们的修改会进快照)
195
+ const snapshot = new MAP();
196
+ Reflect.apply(MAP_FOR_EACH, w.source, [(value, key) => Reflect.apply(MAP_SET, snapshot, [key, value])]);
197
+ Reflect.apply(MAP_FOR_EACH, snapshot, [
198
+ (value, key) => {
199
+ const keyText = mapKeyText(key);
200
+ const keyCopy = copyOf(key, step(w.at, `.keys()[${i}]`));
201
+ const valueCopy = copyOf(value, step(w.at, keyText === undefined ? `.values()[${i}]` : `.get(${keyText})`));
202
+ Reflect.apply(MAP_SET, w.copy, [keyCopy, valueCopy]);
203
+ i += 1;
204
+ },
205
+ ]);
206
+ return;
207
+ }
208
+ case "set": {
209
+ const snapshot = new SET(); // 同 Map:先拍快照,再逐个检视
210
+ Reflect.apply(SET_FOR_EACH, w.source, [(member) => Reflect.apply(SET_ADD, snapshot, [member])]);
211
+ Reflect.apply(SET_FOR_EACH, snapshot, [
212
+ (member) => {
213
+ Reflect.apply(SET_ADD, w.copy, [copyOf(member, step(w.at, `.values()[${i}]`))]);
214
+ i += 1;
215
+ },
216
+ ]);
217
+ return;
218
+ }
219
+ case "array":
220
+ case "object":
221
+ case "date":
222
+ case "regexp":
223
+ return;
224
+ default: {
225
+ const unhandled = c;
226
+ throw new Error(`mutableCopyOf: unhandled container ${String(unhandled.kind)}`);
227
+ }
228
+ }
229
+ }
@@ -101,6 +101,14 @@ export declare const SETTINGS_UNITS: {
101
101
  readonly reader: "engine";
102
102
  readonly sources: readonly ["userSettings", "projectSettings", "localSettings", "flagSettings", "policySettings", "foreignProjectSettings"];
103
103
  };
104
+ readonly autoCompactEnabled: {
105
+ readonly path: readonly ["autoCompactEnabled"];
106
+ readonly category: "autoCompaction";
107
+ readonly reads: "whole";
108
+ readonly reading: "boolean";
109
+ readonly reader: "engine";
110
+ readonly sources: readonly ["userSettings", "projectSettings", "localSettings", "flagSettings", "policySettings", "foreignProjectSettings"];
111
+ };
104
112
  };
105
113
  export type SettingsUnitName = keyof typeof SETTINGS_UNITS;
106
114
  /** The comparator of one unit — or, for a `members` unit, of one DECLARED member of it: `whole` ⇒ the category's `tighten`;
@@ -5,9 +5,10 @@
5
5
  * Every resolver of a settings file (the shell reads it for each of its sources; a profile loader is a second projection) and every
6
6
  * writer of one reads THIS table instead of keeping a key→category map, a value judge or a reader list of its own for these units.
7
7
  * Unit names: the shell's established ten, then `semaUiLanguage` — the UI-language key, named by its key and placed by its declaration
8
- * (`UI_LANGUAGE_SETTING` in `./ui-language`: the row's `path`, `category` and `sources` are read from there, not written twice) — and
9
- * `autoMemoryEnabled`, the auto-memory switch, mapped to its `autoMemory` member row. The two permission-mode kill-switches map to
10
- * their own `killSwitches` member rows (the table has no managed-only floor for them).
8
+ * (`UI_LANGUAGE_SETTING` in `./ui-language`: the row's `path`, `category` and `sources` are read from there, not written twice) —
9
+ * `autoMemoryEnabled`, the auto-memory switch, mapped to its `autoMemory` member row, and `autoCompactEnabled`, the auto-compaction
10
+ * switch, mapped whole to `autoCompaction`. The two permission-mode kill-switches map to their own `killSwitches` member rows (the
11
+ * table has no managed-only floor for them).
11
12
  *
12
13
  * Who reads a unit (`reader`, on every row; the closed set {@link SETTINGS_UNIT_READERS}):
13
14
  * · `shell` — the value changes only the host's own interface and never reaches the engine, wherever the engine runs — so a writer
@@ -78,7 +79,7 @@
78
79
  * the contract cannot tell what it was meant to forbid, and the strictest answer is the only one that cannot be looser than what the author meant.
79
80
  * The package enforces nothing here (the surfaces are the consumers'); what it pins is that both inputs exist for every such member and that every
80
81
  * out-of-domain value reads `unreadable` without throwing. Not covered, and not settled here: the `whole` units (`permissionMode`, `additionalDirectories`,
81
- * `hooks`, `env`, `model`, `outputStyle`, `semaUiLanguage`) have no direction column; whether "unreadable = absent" closes for them depends on the order of the
82
+ * `hooks`, `env`, `model`, `outputStyle`, `semaUiLanguage`, `autoCompactEnabled`) have no direction column; whether "unreadable = absent" closes for them depends on the order of the
82
83
  * unit's own value domain, which is a design question of its own.
83
84
  * The env DOCUMENT's literal grammar (boolean words, csv + empty-set sentinel, a "≤ 0 means off" cap) is not here: it belongs to
84
85
  * the engine's env catalog, whose one implementation is the server's.
@@ -107,6 +108,7 @@ export const SETTINGS_UNITS = deepFreeze({
107
108
  // the key, its category and the one source that carries it are the declaration's (`UI_LANGUAGE_SETTING`); the computed key keeps the literal type
108
109
  [UI_LANGUAGE_SETTING.key]: { path: [UI_LANGUAGE_SETTING.key], category: UI_LANGUAGE_SETTING.category, reads: "whole", reading: "uiLanguage", reader: "shell", sources: [UI_LANGUAGE_SETTING.source] },
109
110
  autoMemoryEnabled: { path: ["autoMemoryEnabled"], category: "autoMemory", reads: "member", member: "autoMemoryEnabled", reading: "boolean", reader: "engine", sources: SETTINGS_SOURCES },
111
+ autoCompactEnabled: { path: ["autoCompactEnabled"], category: "autoCompaction", reads: "whole", reading: "boolean", reader: "engine", sources: SETTINGS_SOURCES },
110
112
  });
111
113
  /** The one place a unit + optional member resolves to what is being asked about — the row and its comparator. Fail-closed
112
114
  * and loud on every misaddressing: an unknown unit (own-property lookup — `"__proto__"` is unknown, not Object.prototype),
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Acceptance bounds the server applies to the request-face tighten-only seats: read-deny patterns
3
+ * (stars per path segment, stars across the whole list, and entries in the whole list) and entries
4
+ * per seat for the other tighten-only seats.
5
+ *
6
+ * These bounds are an acceptance policy for an untrusted writer; they do not correspond to an
7
+ * engine cost. Pure data, zero imports, browser-safe.
8
+ */
9
+ /** Maximum number of `*` wildcards accepted within a single path segment of a read-deny pattern. */
10
+ export declare const MAX_READ_DENY_STARS_PER_SEGMENT = 2;
11
+ /** Maximum total number of `*` wildcards accepted across all read-deny patterns in the list. */
12
+ export declare const MAX_READ_DENY_STARS_TOTAL = 16;
13
+ /** Maximum number of entries accepted per request-face tighten-only seat other than the read-deny list. */
14
+ export declare const MAX_TIGHTEN_ONLY_SEAT_ENTRIES = 1000;
15
+ /** Maximum number of entries accepted in the request-face read-deny pattern list. */
16
+ export declare const MAX_READ_DENY_ENTRIES = 32;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Acceptance bounds the server applies to the request-face tighten-only seats: read-deny patterns
3
+ * (stars per path segment, stars across the whole list, and entries in the whole list) and entries
4
+ * per seat for the other tighten-only seats.
5
+ *
6
+ * These bounds are an acceptance policy for an untrusted writer; they do not correspond to an
7
+ * engine cost. Pure data, zero imports, browser-safe.
8
+ */
9
+ /** Maximum number of `*` wildcards accepted within a single path segment of a read-deny pattern. */
10
+ export const MAX_READ_DENY_STARS_PER_SEGMENT = 2;
11
+ /** Maximum total number of `*` wildcards accepted across all read-deny patterns in the list. */
12
+ export const MAX_READ_DENY_STARS_TOTAL = 16;
13
+ /** Maximum number of entries accepted per request-face tighten-only seat other than the read-deny list. */
14
+ export const MAX_TIGHTEN_ONLY_SEAT_ENTRIES = 1000;
15
+ /** Maximum number of entries accepted in the request-face read-deny pattern list. */
16
+ export const MAX_READ_DENY_ENTRIES = 32;