dsh-boost 0.1.4 → 0.2.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"doc.js","sourceRoot":"","sources":["../../src/scope/doc.ts"],"names":[],"mappings":"AAoCA,iFAAiF;AACjF,MAAM,CAAC,MAAM,yBAAyB,GAAG,2BAA2B,CAAA;AAEpE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,0BAA0B,CAAA;AAElE,sEAAsE;AACtE,MAAM,CAAC,MAAM,sBAAsB,GAAG,wBAAwB,CAAA;AAE9D,oEAAoE;AACpE,MAAM,CAAC,MAAM,qBAAqB,GAAG,uBAAuB,CAAA;AAE5D,iEAAiE;AACjE,MAAM,CAAC,MAAM,2BAA2B,GAAG,6BAA6B,CAAA;AAExE,kEAAkE;AAClE,MAAM,CAAC,MAAM,gBAAgB,GAAG,kBAAkB,CAAA;AAElD;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,mBAAmB,CAAA;AAiCpD;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAa;IACrC,OAAO,EAAE,CAAC;IACV,QAAQ,EAAE,CAAC;IACX,IAAI,EAAE,UAAU;IAChB,YAAY,EAAE,EAAE;IAChB,MAAM,EAAE,IAAI;IACZ,UAAU,EAAE,QAAQ;CACrB,CAAA;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,GAGX;IACH;QACE,IAAI,EAAE,sBAAsB;QAC5B,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC;KAChF;IACD;QACE,IAAI,EAAE,wBAAwB;QAC9B,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;YACf,MAAM,OAAO,GAAI,GAA6B,CAAC,OAAO,CAAA;YACtD,OAAO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,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAChF,IAAI,EAAE,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC;QAC5B,YAAY,EAAE,iBAAiB,CAAC,MAAM,CAAC,YAAY,CAAC;QACpD,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC;QAClC,UAAU,EAAE,eAAe,CAAC,MAAM,CAAC,UAAU,CAAC;KAC/C,CAAA;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,GAAa,EAAE,WAA+B;IACtE,IAAI,WAAW,KAAK,SAAS;QAAE,OAAO,KAAK,CAAA;IAC3C,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,CAAC,YAAY,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAA;AACxE,CAAC","sourcesContent":["/**\n * Scope document model: where the plugin is allowed to act.\n *\n * `scope.json` is the single source of truth for the exposure surface (design\n * §5.5). This module only parses an already-read value; it never touches the\n * filesystem. Task 9's store owns reading, locking and writing.\n *\n * The input is the JSON-decoded value `JSON.parse` produces for `scope.json`,\n * not an arbitrary host object: exotic in-memory shapes (throwing getters,\n * inherited fields) are outside the contract and are not defended against.\n *\n * Parsing is fail-closed in three ordered stages. **Type delimitation runs\n * before the version checks**: a non-object, `null` or an array is a parse\n * failure even when it carries a `version` property. Then a numeric `version`\n * greater than `2` is a **future version**: it is a valid document written by a\n * newer plugin, so reads degrade but writes must never rewrite it (the field\n * set may be newer than this parser knows). Finally anything whose `version` is\n * not exactly `2` — version 1, a missing or non-numeric version — is an\n * **unknown version**; a version 1 document is the one upgradeable case, and\n * the command decides when to upgrade it.\n *\n * A matching stage rejects immediately, and no failure returns a partial\n * document: every failure comes back as a fresh deep copy of `DEFAULT_SCOPE`,\n * the strictest exposure (`selected + []`), so a malformed or newer-versioned\n * file degrades to \"nobody sees it\" rather than crashing the agent.\n *\n * Individual fields are guarded on the strict side too: an unknown `mode` is\n * `'selected'`, a non-array `workspaceIds` is `[]`, non-string members are\n * dropped, a non-boolean `shadow` is `true`, an unknown `projection` is\n * `'shadow'`, and a non-finite `revision` is `0`. `updatedAt` is never\n * validated beyond being a string.\n *\n * @module dsh-boost/scope/doc\n */\nimport type { ProjectionMode } from '../projection/apply.js'\n\n/** Stable rejection code: the file names a version this parser does not know. */\nexport const ERR_SCOPE_UNKNOWN_VERSION = 'ERR_SCOPE_UNKNOWN_VERSION'\n\n/**\n * Stable rejection code: the file's version is a number newer than this parser\n * (version 3+). Reads degrade like any other failure, but the document is\n * **read-only**: it may carry fields and workspace ids this parser would prune,\n * so writing it back would silently lose the user's configuration.\n */\nexport const ERR_SCOPE_FUTURE_VERSION = 'ERR_SCOPE_FUTURE_VERSION'\n\n/** Stable rejection code: the file is not a scope document at all. */\nexport const ERR_SCOPE_PARSE_FAILED = 'ERR_SCOPE_PARSE_FAILED'\n\n/** Stable rejection code: the file exists but could not be read. */\nexport const ERR_SCOPE_READ_FAILED = 'ERR_SCOPE_READ_FAILED'\n\n/** Stable rejection code: the write's base revision is stale. */\nexport const ERR_SCOPE_REVISION_CONFLICT = 'ERR_SCOPE_REVISION_CONFLICT'\n\n/** Stable rejection code: another writer holds the scope lock. */\nexport const ERR_SCOPE_LOCKED = 'ERR_SCOPE_LOCKED'\n\n/**\n * Stable rejection code: the write was cancelled through its `AbortSignal`.\n *\n * Checked at every await boundary of the write path. A cancellation is not a\n * storage failure — the file is left exactly as it was — so the caller can\n * report it without implying the scope is damaged.\n */\nexport const ERR_SCOPE_ABORTED = 'ERR_SCOPE_ABORTED'\n\n/** Every stable scope failure code (design §5.5 plus the future-version split). */\nexport type ScopeCode =\n | typeof ERR_SCOPE_UNKNOWN_VERSION\n | typeof ERR_SCOPE_FUTURE_VERSION\n | typeof ERR_SCOPE_PARSE_FAILED\n | typeof ERR_SCOPE_READ_FAILED\n | typeof ERR_SCOPE_REVISION_CONFLICT\n | typeof ERR_SCOPE_LOCKED\n | typeof ERR_SCOPE_ABORTED\n\n/** The subset `parseScope` itself can return. */\ntype ParseCode =\n | typeof ERR_SCOPE_UNKNOWN_VERSION\n | typeof ERR_SCOPE_FUTURE_VERSION\n | typeof ERR_SCOPE_PARSE_FAILED\n\n/** A parsed `scope.json` document, version 2 (design §5.5). */\nexport interface ScopeDoc {\n version: 2\n /** Incremented by the store on every successful write. */\n revision: number\n /** Last write time, when the store recorded one; never validated further. */\n updatedAt?: string\n mode: 'selected' | 'global'\n workspaceIds: string[]\n /** Shadow accounting switch (`boost shadow` with a boolean body). */\n shadow: boolean\n /** Projection shape: off, accounting only, or real replacement. */\n projection: ProjectionMode\n}\n\n/**\n * The strictest exposure and the fallback for every failure: nobody sees the\n * plugin until the user opts in.\n */\nexport const DEFAULT_SCOPE: ScopeDoc = {\n version: 2,\n revision: 0,\n mode: 'selected',\n workspaceIds: [],\n shadow: true,\n projection: 'shadow',\n}\n\n/**\n * Type delimitation and version classification, in the order the cases must be\n * checked.\n *\n * The first entry rejects everything that is not a plain object (including\n * `null` and arrays, whatever extra properties they carry). The second marks a\n * numeric version greater than 2 as a future version; it must run **before**\n * the catch-all third entry, which treats every remaining non-2 version\n * (version 1, missing, non-numeric) as unknown. A matching entry ends parsing\n * before the remaining fields are read.\n */\nconst DELIMITERS: ReadonlyArray<{\n readonly code: ParseCode\n readonly matches: (raw: unknown) => boolean\n}> = [\n {\n code: ERR_SCOPE_PARSE_FAILED,\n matches: (raw) => raw === null || typeof raw !== 'object' || Array.isArray(raw),\n },\n {\n code: ERR_SCOPE_FUTURE_VERSION,\n matches: (raw) => {\n const version = (raw as { version?: unknown }).version\n return typeof version === 'number' && version > 2\n },\n },\n {\n code: ERR_SCOPE_UNKNOWN_VERSION,\n matches: (raw) => (raw as { version?: unknown }).version !== 2,\n },\n]\n\n/** A failed parse: always a fresh copy of the strictest document. */\nfunction rejected(code: ParseCode): { doc: ScopeDoc; code: ParseCode } {\n return { doc: structuredClone(DEFAULT_SCOPE), code }\n}\n\n/** Strict side for `mode`: anything but the two literals means `selected`. */\nfunction parseMode(raw: unknown): ScopeDoc['mode'] {\n return raw === 'selected' || raw === 'global' ? raw : 'selected'\n}\n\n/** Strict side for `workspaceIds`: a non-array is empty, non-strings dropped. */\nfunction parseWorkspaceIds(raw: unknown): string[] {\n return Array.isArray(raw) ? raw.filter((id): id is string => typeof id === 'string') : []\n}\n\n/** Strict side for `revision`: anything but a finite number is the initial revision. */\nfunction parseRevision(raw: unknown): number {\n return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0\n}\n\n/** Strict side for `shadow`: a non-boolean keeps shadow accounting on. */\nfunction parseShadow(raw: unknown): boolean {\n return typeof raw === 'boolean' ? raw : true\n}\n\n/** Strict side for `projection`: anything else falls back to shadow accounting. */\nfunction parseProjection(raw: unknown): ProjectionMode {\n return raw === 'off' || raw === 'shadow' || raw === 'on' ? raw : 'shadow'\n}\n\n/**\n * Read one `scope.json` value, as produced by `JSON.parse`.\n *\n * A value whose type or version is wrong is rejected with a stable code and a\n * deep copy of `DEFAULT_SCOPE`; a version 2 object yields a complete document\n * built from its fields, with every malformed field degraded to its strict\n * value.\n */\nexport function parseScope(raw: unknown): {\n doc: ScopeDoc\n code?: 'ERR_SCOPE_UNKNOWN_VERSION' | 'ERR_SCOPE_FUTURE_VERSION' | 'ERR_SCOPE_PARSE_FAILED'\n} {\n const rejection = DELIMITERS.find((delimiter) => delimiter.matches(raw))\n if (rejection) return rejected(rejection.code)\n\n const source = raw as Record<string, unknown>\n return {\n doc: {\n version: 2,\n revision: parseRevision(source.revision),\n ...(typeof source.updatedAt === 'string' ? { updatedAt: source.updatedAt } : {}),\n mode: parseMode(source.mode),\n workspaceIds: parseWorkspaceIds(source.workspaceIds),\n shadow: parseShadow(source.shadow),\n projection: parseProjection(source.projection),\n },\n }\n}\n\n/**\n * The upgrade base for a version 1 document.\n *\n * Reading a v1 file still degrades to {@link DEFAULT_SCOPE} and reports\n * {@link ERR_SCOPE_UNKNOWN_VERSION} (design §5.5 rule 3: unknown versions are\n * read-only). Only the explicit `scope-set` upgrade may rewrite it, and this\n * function answers \"what did the user's v1 file actually say\" for that one\n * write: `version` becomes 2 and `revision` starts at the degraded read's 0,\n * while every recognised field keeps its value (strict side for malformed\n * ones). Never use this on the read path — a v1 document is not a valid v2\n * document and must keep presenting as invisible until upgraded.\n *\n * `undefined` for anything that is not a plain object with `version === 1`,\n * including v2, future versions, missing versions and non-objects.\n */\nexport function parseVersionOneScope(raw: unknown): ScopeDoc | undefined {\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined\n if ((raw as { version?: unknown }).version !== 1) return undefined\n const source = raw as Record<string, unknown>\n return {\n version: 2,\n revision: 0,\n ...(typeof source.updatedAt === 'string' ? { updatedAt: source.updatedAt } : {}),\n mode: parseMode(source.mode),\n workspaceIds: parseWorkspaceIds(source.workspaceIds),\n shadow: parseShadow(source.shadow),\n projection: parseProjection(source.projection),\n }\n}\n\n/**\n * Whether the plugin may act for an agent in `workspaceId`.\n *\n * An agent with no workspace has the global view, and the plugin never injects\n * into the global view (design §5.5), so `undefined` is always invisible.\n * `mode: 'global'` widens to any *defined* workspace id, not to `undefined`.\n */\nexport function isVisible(doc: ScopeDoc, workspaceId: string | undefined): boolean {\n if (workspaceId === undefined) return false\n return doc.mode === 'global' || doc.workspaceIds.includes(workspaceId)\n}\n"]}
1
+ {"version":3,"file":"doc.js","sourceRoot":"","sources":["../../src/scope/doc.ts"],"names":[],"mappings":"AAoCA,iFAAiF;AACjF,MAAM,CAAC,MAAM,yBAAyB,GAAG,2BAA2B,CAAA;AAEpE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,0BAA0B,CAAA;AAElE,sEAAsE;AACtE,MAAM,CAAC,MAAM,sBAAsB,GAAG,wBAAwB,CAAA;AAE9D,oEAAoE;AACpE,MAAM,CAAC,MAAM,qBAAqB,GAAG,uBAAuB,CAA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AS,CAAC,GAAa,EAAE,WAA+B;IACtE,IAAI,WAAW,KAAK,SAAS;QAAE,OAAO,KAAK,CAAA;IAC3C,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,CAAC,YAAY,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAA;AACxE,CAAC","sourcesContent":["/**\n * Scope document model: where the plugin is allowed to act.\n *\n * `scope.json` is the single source of truth for the exposure surface (design\n * §5.5). This module only parses an already-read value; it never touches the\n * filesystem. Task 9's store owns reading, locking and writing.\n *\n * The input is the JSON-decoded value `JSON.parse` produces for `scope.json`,\n * not an arbitrary host object: exotic in-memory shapes (throwing getters,\n * inherited fields) are outside the contract and are not defended against.\n *\n * Parsing is fail-closed in three ordered stages. **Type delimitation runs\n * before the version checks**: a non-object, `null` or an array is a parse\n * failure even when it carries a `version` property. Then a numeric `version`\n * greater than `2` is a **future version**: it is a valid document written by a\n * newer plugin, so reads degrade but writes must never rewrite it (the field\n * set may be newer than this parser knows). Finally anything whose `version` is\n * not exactly `2` — version 1, a missing or non-numeric version — is an\n * **unknown version**; a version 1 document is the one upgradeable case, and\n * the command decides when to upgrade it.\n *\n * A matching stage rejects immediately, and no failure returns a partial\n * document: every failure comes back as a fresh deep copy of `DEFAULT_SCOPE`,\n * the strictest exposure (`selected + []`), so a malformed or newer-versioned\n * file degrades to \"nobody sees it\" rather than crashing the agent.\n *\n * Individual fields are guarded on the strict side too: an unknown `mode` is\n * `'selected'`, a non-array `workspaceIds` is `[]`, non-string members are\n * dropped, a non-boolean `shadow` is `true`, an unknown `projection` is\n * `'shadow'`, and a non-finite `revision` is `0`. `updatedAt` is never\n * validated beyond being a string.\n *\n * @module dsh-boost/scope/doc\n */\nimport type { ProjectionMode } from '../projection/apply.js'\n\n/** Stable rejection code: the file names a version this parser does not know. */\nexport const ERR_SCOPE_UNKNOWN_VERSION = 'ERR_SCOPE_UNKNOWN_VERSION'\n\n/**\n * Stable rejection code: the file's version is a number newer than this parser\n * (version 3+). Reads degrade like any other failure, but the document is\n * **read-only**: it may carry fields and workspace ids this parser would prune,\n * so writing it back would silently lose the user's configuration.\n */\nexport const ERR_SCOPE_FUTURE_VERSION = 'ERR_SCOPE_FUTURE_VERSION'\n\n/** Stable rejection code: the file is not a scope document at all. */\nexport const ERR_SCOPE_PARSE_FAILED = 'ERR_SCOPE_PARSE_FAILED'\n\n/** Stable rejection code: the file exists but could not be read. */\nexport const ERR_SCOPE_READ_FAILED = 'ERR_SCOPE_READ_FAILED'\n\n/**\n * Stable rejection code: the document could not be written.\n *\n * Distinct from `ERR_SCOPE_READ_FAILED` on purpose: the caller still holds a\n * valid baseline, so \"re-read\" is the wrong advice and would throw away a\n * draft that is perfectly good.\n */\nexport const ERR_SCOPE_WRITE_FAILED = 'ERR_SCOPE_WRITE_FAILED'\n\n/** Stable rejection code: the write's base revision is stale. */\nexport const ERR_SCOPE_REVISION_CONFLICT = 'ERR_SCOPE_REVISION_CONFLICT'\n\n/** Stable rejection code: another writer holds the scope lock. */\nexport const ERR_SCOPE_LOCKED = 'ERR_SCOPE_LOCKED'\n\n/**\n * Stable rejection code: the write was cancelled through its `AbortSignal`.\n *\n * Checked at every await boundary of the write path. A cancellation is not a\n * storage failure — the file is left exactly as it was — so the caller can\n * report it without implying the scope is damaged.\n */\nexport const ERR_SCOPE_ABORTED = 'ERR_SCOPE_ABORTED'\n\n/** Every stable scope failure code (design §5.5 plus the future-version split). */\nexport type ScopeCode =\n | typeof ERR_SCOPE_UNKNOWN_VERSION\n | typeof ERR_SCOPE_FUTURE_VERSION\n | typeof ERR_SCOPE_PARSE_FAILED\n | typeof ERR_SCOPE_READ_FAILED\n | typeof ERR_SCOPE_WRITE_FAILED\n | typeof ERR_SCOPE_REVISION_CONFLICT\n | typeof ERR_SCOPE_LOCKED\n | typeof ERR_SCOPE_ABORTED\n\n/** The subset `parseScope` itself can return. */\ntype ParseCode =\n | typeof ERR_SCOPE_UNKNOWN_VERSION\n | typeof ERR_SCOPE_FUTURE_VERSION\n | typeof ERR_SCOPE_PARSE_FAILED\n\n/** A parsed `scope.json` document, version 2 (design §5.5). */\nexport interface ScopeDoc {\n version: 2\n /** Incremented by the store on every successful write. */\n revision: number\n /** Last write time, when the store recorded one; never validated further. */\n updatedAt?: string\n mode: 'selected' | 'global'\n workspaceIds: string[]\n /** Shadow accounting switch (`boost shadow` with a boolean body). */\n shadow: boolean\n /** Projection shape: off, accounting only, or real replacement. */\n projection: ProjectionMode\n}\n\n/**\n * The strictest exposure and the fallback for every failure: nobody sees the\n * plugin until the user opts in.\n */\nexport const DEFAULT_SCOPE: ScopeDoc = {\n version: 2,\n revision: 0,\n mode: 'selected',\n workspaceIds: [],\n shadow: true,\n projection: 'shadow',\n}\n\n/**\n * Type delimitation and version classification, in the order the cases must be\n * checked.\n *\n * The first entry rejects everything that is not a plain object (including\n * `null` and arrays, whatever extra properties they carry). The second marks a\n * numeric version greater than 2 as a future version; it must run **before**\n * the catch-all third entry, which treats every remaining non-2 version\n * (version 1, missing, non-numeric) as unknown. A matching entry ends parsing\n * before the remaining fields are read.\n */\nconst DELIMITERS: ReadonlyArray<{\n readonly code: ParseCode\n readonly matches: (raw: unknown) => boolean\n}> = [\n {\n code: ERR_SCOPE_PARSE_FAILED,\n matches: (raw) => raw === null || typeof raw !== 'object' || Array.isArray(raw),\n },\n {\n code: ERR_SCOPE_FUTURE_VERSION,\n matches: (raw) => {\n const version = (raw as { version?: unknown }).version\n return typeof version === 'number' && version > 2\n },\n },\n {\n code: ERR_SCOPE_UNKNOWN_VERSION,\n matches: (raw) => (raw as { version?: unknown }).version !== 2,\n },\n]\n\n/** A failed parse: always a fresh copy of the strictest document. */\nfunction rejected(code: ParseCode): { doc: ScopeDoc; code: ParseCode } {\n return { doc: structuredClone(DEFAULT_SCOPE), code }\n}\n\n/** Strict side for `mode`: anything but the two literals means `selected`. */\nfunction parseMode(raw: unknown): ScopeDoc['mode'] {\n return raw === 'selected' || raw === 'global' ? raw : 'selected'\n}\n\n/** Strict side for `workspaceIds`: a non-array is empty, non-strings dropped. */\nfunction parseWorkspaceIds(raw: unknown): string[] {\n return Array.isArray(raw) ? raw.filter((id): id is string => typeof id === 'string') : []\n}\n\n/** Strict side for `revision`: anything but a finite number is the initial revision. */\nfunction parseRevision(raw: unknown): number {\n return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0\n}\n\n/** Strict side for `shadow`: a non-boolean keeps shadow accounting on. */\nfunction parseShadow(raw: unknown): boolean {\n return typeof raw === 'boolean' ? raw : true\n}\n\n/** Strict side for `projection`: anything else falls back to shadow accounting. */\nfunction parseProjection(raw: unknown): ProjectionMode {\n return raw === 'off' || raw === 'shadow' || raw === 'on' ? raw : 'shadow'\n}\n\n/**\n * Read one `scope.json` value, as produced by `JSON.parse`.\n *\n * A value whose type or version is wrong is rejected with a stable code and a\n * deep copy of `DEFAULT_SCOPE`; a version 2 object yields a complete document\n * built from its fields, with every malformed field degraded to its strict\n * value.\n */\nexport function parseScope(raw: unknown): {\n doc: ScopeDoc\n code?: 'ERR_SCOPE_UNKNOWN_VERSION' | 'ERR_SCOPE_FUTURE_VERSION' | 'ERR_SCOPE_PARSE_FAILED'\n} {\n const rejection = DELIMITERS.find((delimiter) => delimiter.matches(raw))\n if (rejection) return rejected(rejection.code)\n\n const source = raw as Record<string, unknown>\n return {\n doc: {\n version: 2,\n revision: parseRevision(source.revision),\n ...(typeof source.updatedAt === 'string' ? { updatedAt: source.updatedAt } : {}),\n mode: parseMode(source.mode),\n workspaceIds: parseWorkspaceIds(source.workspaceIds),\n shadow: parseShadow(source.shadow),\n projection: parseProjection(source.projection),\n },\n }\n}\n\n/**\n * The upgrade base for a version 1 document.\n *\n * Reading a v1 file still degrades to {@link DEFAULT_SCOPE} and reports\n * {@link ERR_SCOPE_UNKNOWN_VERSION} (design §5.5 rule 3: unknown versions are\n * read-only). Only the explicit `scope-set` upgrade may rewrite it, and this\n * function answers \"what did the user's v1 file actually say\" for that one\n * write: `version` becomes 2 and `revision` starts at the degraded read's 0,\n * while every recognised field keeps its value (strict side for malformed\n * ones). Never use this on the read path — a v1 document is not a valid v2\n * document and must keep presenting as invisible until upgraded.\n *\n * `undefined` for anything that is not a plain object with `version === 1`,\n * including v2, future versions, missing versions and non-objects.\n */\nexport function parseVersionOneScope(raw: unknown): ScopeDoc | undefined {\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined\n if ((raw as { version?: unknown }).version !== 1) return undefined\n const source = raw as Record<string, unknown>\n return {\n version: 2,\n revision: 0,\n ...(typeof source.updatedAt === 'string' ? { updatedAt: source.updatedAt } : {}),\n mode: parseMode(source.mode),\n workspaceIds: parseWorkspaceIds(source.workspaceIds),\n shadow: parseShadow(source.shadow),\n projection: parseProjection(source.projection),\n }\n}\n\n/**\n * Whether the plugin may act for an agent in `workspaceId`.\n *\n * An agent with no workspace has the global view, and the plugin never injects\n * into the global view (design §5.5), so `undefined` is always invisible.\n * `mode: 'global'` widens to any *defined* workspace id, not to `undefined`.\n */\nexport function isVisible(doc: ScopeDoc, workspaceId: string | undefined): boolean {\n if (workspaceId === undefined) return false\n return doc.mode === 'global' || doc.workspaceIds.includes(workspaceId)\n}\n"]}
@@ -49,7 +49,7 @@ import { randomUUID } from 'node:crypto';
49
49
  import { closeSync, fsyncSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
50
50
  import { mkdir, open, readFile, stat, unlink } from 'node:fs/promises';
51
51
  import { join } from 'node:path';
52
- import { DEFAULT_SCOPE, ERR_SCOPE_ABORTED, ERR_SCOPE_FUTURE_VERSION, ERR_SCOPE_LOCKED, ERR_SCOPE_PARSE_FAILED, ERR_SCOPE_READ_FAILED, ERR_SCOPE_REVISION_CONFLICT, ERR_SCOPE_UNKNOWN_VERSION, parseScope, parseVersionOneScope, } from './doc.js';
52
+ import { DEFAULT_SCOPE, ERR_SCOPE_ABORTED, ERR_SCOPE_FUTURE_VERSION, ERR_SCOPE_LOCKED, ERR_SCOPE_PARSE_FAILED, ERR_SCOPE_READ_FAILED, ERR_SCOPE_WRITE_FAILED, ERR_SCOPE_REVISION_CONFLICT, ERR_SCOPE_UNKNOWN_VERSION, parseScope, parseVersionOneScope, } from './doc.js';
53
53
  const SCOPE_FILE = 'scope.json';
54
54
  const LOCK_FILE = 'scope.lock';
55
55
  /** A lock older than this is a reclaim candidate when its pid is dead (or unrecorded). */
@@ -282,9 +282,10 @@ export class ScopeStore {
282
282
  written = this.writeAtomic(doc);
283
283
  }
284
284
  catch (error) {
285
- // Serialization and disk failures are storage failures too; rule 8
286
- // requires a stable code on every error the write path raises.
287
- throw scopeError(ERR_SCOPE_READ_FAILED, `cannot write ${this.file}: ${messageOf(error)}`);
285
+ // A write failure is not a read failure: the caller still knows its
286
+ // baseline, and telling it to re-read would discard a draft that is
287
+ // perfectly good. Rule 8 requires a stable code on every error.
288
+ throw scopeError(ERR_SCOPE_WRITE_FAILED, `cannot write ${this.file}: ${messageOf(error)}`);
288
289
  }
289
290
  // Clone before caching: `doc` may still share arrays with an object the
290
291
  // caller (or `mutate`) holds, and the cache must never alias those.
@@ -1 +1 @@
1
- {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/scope/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EACL,SAAS,EACT,SAAS,EACT,QAAQ,EACR,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,aAAa,GACd,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAEtE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,wBAAwB,EACxB,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,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,CAAC,CAAA;QAC9E,CAAC;QAAC,MAAM,CAAC;YACP,kDAAkD;QACpD,CAAC;IACH,CAAC;IAED;;;;;OAKG;IACK,WAAW,CAAC,GAAa;QAC/B,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,UAAU,IAAI,OAAO,CAAC,GAAG,IAAI,UAAU,EAAE,MAAM,CAAC,CAAA;QACpF,MAAM,IAAI,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAA;QACvC,IAAI,EAAsB,CAAA;QAC1B,IAAI,CAAC;YACH,EAAE,GAAG,QAAQ,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;YAC5B,aAAa,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;YACvB,SAAS,CAAC,EAAE,CAAC,CAAA;YACb,SAAS,CAAC,EAAE,CAAC,CAAA;YACb,EAAE,GAAG,SAAS,CAAA;YACd,0EAA0E;YAC1E,uEAAuE;YACvE,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAA;YAC1C,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,CAAA;YAC/B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;QAC1B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,EAAE,KAAK,SAAS,EAAE,CAAC;gBACrB,IAAI,CAAC;oBACH,SAAS,CAAC,EAAE,CAAC,CAAA;gBACf,CAAC;gBAAC,MAAM,CAAC;oBACP,oEAAoE;gBACtE,CAAC;YACH,CAAC;YACD,IAAI,CAAC;gBACH,UAAU,CAAC,QAAQ,CAAC,CAAA;YACtB,CAAC;YAAC,MAAM,CAAC;gBACP,oEAAoE;YACtE,CAAC;YACD,MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Persistent scope store: one small JSON document that says where the plugin is\n * active, plus the per-agent judgement cache the synchronous prompt provider\n * reads.\n *\n * `scope.json` is read on every tool call and written only by the `boost`\n * control tool. Reads never throw: a missing file is the clean default\n * (revision 0, no code — a fresh install has simply configured nothing yet),\n * while an unreadable, corrupt or newer-versioned file means \"nobody sees the\n * plugin\" (`DEFAULT_SCOPE`) plus a stable code for the receipt/status channel.\n * A failed read never touches the file. Writes are compare-and-swap: the caller\n * passes the revision it last saw, the store locks, verifies that revision,\n * mutates, bumps it, and renames a temporary file over `scope.json`. The rename\n * makes a crash leave either the old or the new document, never a half-written\n * one. The revision check makes a lost update require the narrow stale-lock\n * reclaim race documented at `acquireLock`; it cannot silently corrupt or merge\n * a document.\n *\n * ## Sync/async boundary\n *\n * The read path is async (`stat` + `readFile`), because it is called on the\n * hot step path of a live agent and must not block the event loop. The write\n * path is async only while acquiring the lock: everything inside the lock —\n * the disk read, the mutation, the atomic write — is synchronous, so no other\n * writer can interleave between the revision check and the write.\n *\n * ## Cache\n *\n * The cache stores the last validated parse next to the exact bytes and mtime\n * it was parsed from. A read reuses that parse only when both the mtime and the\n * exact bytes match. Byte identity implies the parsed `revision` is unchanged\n * (the invariant design §5.5 asks for), and it is strictly safer than an\n * mtime+revision key: an external edit that preserves both would otherwise be\n * served from the old parse. The cache therefore avoids re-parsing the same\n * bytes, not the read itself — the revision check requires reading\n * `scope.json`. Cache hits keep the cached document object internally and\n * every returned document is a deep copy, so a caller mutating a result cannot\n * poison the cache.\n *\n * The judgement cache is intentionally per agent key (the session id). A\n * single global value would leak one workspace's visibility into every other\n * agent (design §5.5). `remember` is the only writer; `forget` is called from\n * the plugin's `session/disposed` handler so a long-lived process does not keep\n * one entry per session forever.\n *\n * @module dsh-boost/scope/store\n */\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n fsyncSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { mkdir, open, readFile, stat, unlink } from 'node:fs/promises'\nimport type { FileHandle } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport {\n DEFAULT_SCOPE,\n ERR_SCOPE_ABORTED,\n ERR_SCOPE_FUTURE_VERSION,\n ERR_SCOPE_LOCKED,\n ERR_SCOPE_PARSE_FAILED,\n ERR_SCOPE_READ_FAILED,\n ERR_SCOPE_REVISION_CONFLICT,\n ERR_SCOPE_UNKNOWN_VERSION,\n parseScope,\n parseVersionOneScope,\n} from './doc.js'\nimport type { ScopeCode, ScopeDoc } from './doc.js'\n\nconst SCOPE_FILE = 'scope.json'\nconst LOCK_FILE = 'scope.lock'\n/** A lock older than this is a reclaim candidate when its pid is dead (or unrecorded). */\nconst LOCK_STALE_MS = 60_000\n/**\n * After this much time a lock is taken over even when its recorded pid is alive.\n *\n * `startedAt` (not `mtime`) is the age source when present. The write section\n * inside the lock is synchronous and tiny, so a ten-minute hold means a crashed\n * writer whose pid the OS reused; without this bound such a lock wedges every\n * `boost scope` write until it is deleted by hand. Ten times the dead-pid\n * timeout keeps a genuinely slow writer safe.\n */\nconst LOCK_TAKEOVER_MS = 10 * LOCK_STALE_MS\n/** Largest value `process.kill` accepts as a pid (signed 32-bit). */\nconst MAX_PID = 2_147_483_647\n/** Stable code logged when a live-pid lock is reclaimed on age alone. */\nexport const ERR_SCOPE_LOCK_TAKEOVER = 'ERR_SCOPE_LOCK_TAKEOVER'\n/** Per-process identity in the lock file: distinguishes a reused pid from this boot. */\nconst BOOT_NONCE = randomUUID()\n\n/**\n * One disk read.\n *\n * A missing file is its own arm, not a failure: it still carries the strict\n * default to serve, but no code and no degraded flag, because \"nothing has\n * been configured yet\" is the clean state a fresh install starts in. Both read\n * paths and the write path use `missing` to tell a first write from an I/O\n * error; only genuine failures carry a stable `code` and `cause`.\n */\ntype DiskRead =\n | { ok: true; doc: ScopeDoc; mtimeMs: number; text: string }\n | { ok: false; missing: true; doc: ScopeDoc }\n | {\n ok: false\n missing: false\n doc: ScopeDoc\n code: ScopeCode\n cause?: unknown\n /** The v1 field values an explicit upgrade must carry (see `parseVersionOneScope`). */\n upgrade?: ScopeDoc\n }\n\n/** A write-path failure: the stable code is on `.code` and in the message. */\nfunction scopeError(code: ScopeCode, detail: string): Error & { code: ScopeCode } {\n return Object.assign(new Error(`${code}: ${detail}`), { code })\n}\n\n/** The stable cancellation error; the file has not been touched yet. */\nfunction abortedError(): Error & { code: ScopeCode } {\n return scopeError(ERR_SCOPE_ABORTED, 'the scope write was cancelled')\n}\n\n/** Stop before the next side effect when the caller has cancelled. */\nfunction checkAbort(signal: AbortSignal | undefined): void {\n if (signal?.aborted === true) throw abortedError()\n}\n\n/** The errno string of a Node filesystem error, if it has one. */\nfunction errorCode(error: unknown): string | undefined {\n return typeof error === 'object' && error !== null && 'code' in error\n ? (error as NodeJS.ErrnoException).code\n : undefined\n}\n\n/** A human-readable detail for a wrapped error. */\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * Liveness probe for lock reclamation.\n *\n * `EPERM` means the process exists but belongs to another user, so it counts as\n * alive; only `ESRCH` proves the recorded writer is gone. Any other outcome is\n * treated as alive too: reclamation must never evict a writer on a guess.\n * `readLockPid` bounds the pid to the range `process.kill` accepts, so the\n * impossible-pid `ERR_INVALID_ARG_TYPE` path is never reached.\n */\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n return errorCode(error) !== 'ESRCH'\n }\n}\n\n/** A deep copy: cached and returned documents never share mutable state. */\nfunction cloneDoc(doc: ScopeDoc): ScopeDoc {\n return structuredClone(doc)\n}\n\n/**\n * Classify a failed disk read.\n *\n * `ENOENT` is the clean default: the document does not exist yet, so nobody\n * has been configured in and there is nothing to report. Every other failure\n * (permissions, I/O, a directory where a file is expected) is a genuine\n * degraded read and keeps `ERR_SCOPE_READ_FAILED`.\n */\nfunction readFailed(error: unknown): DiskRead {\n if (errorCode(error) === 'ENOENT') {\n return { ok: false, missing: true, doc: cloneDoc(DEFAULT_SCOPE) }\n }\n return {\n ok: false,\n missing: false,\n doc: cloneDoc(DEFAULT_SCOPE),\n code: ERR_SCOPE_READ_FAILED,\n cause: error,\n }\n}\n\n/** Decode one already-read `scope.json`; JSON errors are parse failures too. */\nfunction decode(text: string, mtimeMs: number): DiskRead {\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n return {\n ok: false,\n doc: cloneDoc(DEFAULT_SCOPE),\n code: ERR_SCOPE_PARSE_FAILED,\n missing: false,\n cause: error,\n }\n }\n const parsed = parseScope(raw)\n if (parsed.code !== undefined) {\n // A v1 document is read-only-degraded, but the explicit upgrade rewrites\n // its recognised fields rather than resetting them to DEFAULT_SCOPE\n // (review row 38). `parseVersionOneScope` is deliberately not applied to\n // the read path.\n const upgrade = parseVersionOneScope(raw)\n return {\n ok: false,\n doc: parsed.doc,\n code: parsed.code,\n missing: false,\n ...(upgrade === undefined ? {} : { upgrade }),\n }\n }\n return { ok: true, doc: parsed.doc, mtimeMs, text }\n}\n\n/** Test seam and operator hook for the lock's time-based takeover. */\nexport interface ScopeStoreOptions {\n /** Age after which a live-pid lock is ignored (defaults to ten dead-pid timeouts). */\n lockTakeoverMs?: number\n /** Age after which a dead-pid lock is reclaimable (defaults to 60 s). */\n lockStaleMs?: number\n /** Clock, injectable so tests do not sleep. */\n now?: () => number\n /** Sink for the takeover warning; defaults to a process warning. */\n warn?: (message: string) => void\n}\n\nexport class ScopeStore {\n private readonly file: string\n private readonly lockFile: string\n private readonly lockStaleMs: number\n private readonly lockTakeoverMs: number\n private readonly now: () => number\n private readonly warn: (message: string) => void\n private cached?: { mtimeMs: number; text: string; doc: ScopeDoc }\n private lockOwner?: string\n private readonly judgements = new Map<string, boolean>()\n\n constructor(private readonly dir: string, options: ScopeStoreOptions = {}) {\n this.file = join(dir, SCOPE_FILE)\n this.lockFile = join(dir, LOCK_FILE)\n this.lockStaleMs = options.lockStaleMs ?? LOCK_STALE_MS\n this.lockTakeoverMs = options.lockTakeoverMs ?? LOCK_TAKEOVER_MS\n this.now = options.now ?? Date.now\n this.warn = options.warn ?? ((message: string) => process.emitWarning(message))\n }\n\n /**\n * Read the current document. Never throws and never writes: every stat,\n * read, JSON or shape failure comes back as a fresh `DEFAULT_SCOPE` plus\n * `degraded: 'scope-degraded'` and the stable code.\n */\n async read(): Promise<{ doc: ScopeDoc; degraded?: 'scope-degraded'; code?: ScopeCode }> {\n const result = await this.readDisk()\n if (!result.ok) {\n // Ruling 1: a degraded document is never a cache entry. The next call\n // must retry the disk instead of serving the strict default forever.\n this.cached = undefined\n // A missing file is the clean default (revision 0, no degraded code);\n // a genuine failure keeps its stable code.\n if (result.missing) return { doc: cloneDoc(result.doc) }\n return { doc: cloneDoc(result.doc), degraded: 'scope-degraded', code: result.code }\n }\n\n // On a cache hit `result.doc` is the cached object (identical bytes);\n // either way the caller gets a copy, so a mutation cannot poison it.\n this.cached = { mtimeMs: result.mtimeMs, text: result.text, doc: result.doc }\n return { doc: cloneDoc(result.doc) }\n }\n\n /**\n * Compare-and-swap write. Returns the new document (revision `baseRevision + 1`,\n * `updatedAt` now) and leaves it cached.\n *\n * A missing file is a first write: the base is `DEFAULT_SCOPE` at revision 0,\n * so it succeeds only when the caller passes 0. A version 1 file is based on\n * the fields it actually carries, which is how `boost scope set` explicitly\n * upgrades it. Every other present-but-unusable document is refused before\n * the mutation: a **future** version (a numeric version greater than 2) with\n * `ERR_SCOPE_FUTURE_VERSION`, a non-document with\n * `ERR_SCOPE_PARSE_FAILED`, a missing or non-numeric version with\n * `ERR_SCOPE_UNKNOWN_VERSION`, and an unreadable file with\n * `ERR_SCOPE_READ_FAILED`. Each refusal leaves the file byte-identical.\n */\n async write(\n mutate: (doc: ScopeDoc) => ScopeDoc,\n baseRevision: number,\n options: { signal?: AbortSignal } = {},\n ): Promise<ScopeDoc> {\n const signal = options.signal\n checkAbort(signal)\n await this.ensureDirectory()\n checkAbort(signal)\n await this.acquireLock(signal)\n try {\n checkAbort(signal)\n const current = this.readDiskSync()\n checkAbort(signal)\n let base: ScopeDoc\n if (current.ok) {\n base = current.doc\n } else if (current.missing) {\n // A first write starts from the strict default at revision 0.\n base = current.doc\n } else {\n if (current.code === ERR_SCOPE_FUTURE_VERSION) {\n throw scopeError(\n ERR_SCOPE_FUTURE_VERSION,\n `refusing to rewrite ${this.file}: it declares a newer scope version`,\n )\n }\n if (current.code === ERR_SCOPE_READ_FAILED) {\n const detail = current.cause === undefined ? 'unknown read error' : messageOf(current.cause)\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot read ${this.file}: ${detail}`)\n }\n // Both remaining codes mean the bytes are present but unusable. Key on\n // the code, not on this branch: only a v1 document (whose `upgrade`\n // `decode` supplied) has recognised fields worth preserving, and only\n // its documented `scope-set` upgrade may rewrite the file. A parse\n // failure has no fields at all, and a missing or non-numeric version is\n // equally unrepresentable; basing a write on DEFAULT_SCOPE for either\n // would silently replace the user's document, which `docs/RELEASE.md`\n // promises not to do (\"写拒绝\" / \"写不盲改\").\n if (current.code === ERR_SCOPE_PARSE_FAILED) {\n throw scopeError(\n ERR_SCOPE_PARSE_FAILED,\n `refusing to rewrite ${this.file}: it is not a scope document`,\n )\n }\n if (current.upgrade === undefined) {\n throw scopeError(\n ERR_SCOPE_UNKNOWN_VERSION,\n `refusing to rewrite ${this.file}: it declares an unknown scope version`,\n )\n }\n // A v1 file was read as DEFAULT_SCOPE at revision 0, but its recognised\n // fields are the user's configuration: base the upgrade on those so a\n // partial `scope-set` cannot silently drop `global`/`workspaceIds`.\n base = current.upgrade\n }\n if (base.revision !== baseRevision) {\n throw scopeError(\n ERR_SCOPE_REVISION_CONFLICT,\n `base revision ${baseRevision} does not match ${base.revision}`,\n )\n }\n\n const doc: ScopeDoc = {\n ...mutate(base),\n revision: baseRevision + 1,\n updatedAt: new Date().toISOString(),\n }\n checkAbort(signal)\n let written: { mtimeMs: number; text: string }\n try {\n written = this.writeAtomic(doc)\n } catch (error) {\n // Serialization and disk failures are storage failures too; rule 8\n // requires a stable code on every error the write path raises.\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot write ${this.file}: ${messageOf(error)}`)\n }\n // Clone before caching: `doc` may still share arrays with an object the\n // caller (or `mutate`) holds, and the cache must never alias those.\n this.cached = { mtimeMs: written.mtimeMs, text: written.text, doc: cloneDoc(doc) }\n return cloneDoc(doc)\n } finally {\n this.releaseLock()\n }\n }\n\n /** Cache one agent's visibility judgement; the only writer of this cache. */\n remember(key: string, visible: boolean): void {\n this.judgements.set(key, visible)\n }\n\n /**\n * Drop one session's cached judgement on session disposal.\n *\n * The judgement map is per session and otherwise lives as long as the plugin;\n * without this a process that served many sessions would retain one boolean\n * (and its string key) per session forever.\n */\n forget(key: string): void {\n this.judgements.delete(key)\n }\n\n /** Synchronous per-agent lookup: a miss is `fallback`, and fail-closed is `false`. */\n judgement(key: string, fallback?: boolean): boolean {\n return this.judgements.get(key) ?? fallback ?? false\n }\n\n /** Async read path: stat + read + decode, all failures degraded. */\n private async readDisk(): Promise<DiskRead> {\n try {\n const stats = await stat(this.file)\n const text = await readFile(this.file, 'utf8')\n return this.decodeFromCache(text, stats.mtimeMs)\n } catch (error) {\n return readFailed(error)\n }\n }\n\n /**\n * Reuse the previous parse only when the exact bytes and mtime were already\n * parsed. Byte identity is a stronger key than mtime+revision: an external\n * edit that keeps both cannot be served from the old parse.\n */\n private decodeFromCache(text: string, mtimeMs: number): DiskRead {\n const cached = this.cached\n if (cached !== undefined && cached.mtimeMs === mtimeMs && cached.text === text) {\n return { ok: true, doc: cached.doc, mtimeMs, text }\n }\n return decode(text, mtimeMs)\n }\n\n /** Sync read path, used only inside the write lock (see the module comment). */\n private readDiskSync(): DiskRead {\n try {\n const stats = statSync(this.file)\n const text = readFileSync(this.file, 'utf8')\n return decode(text, stats.mtimeMs)\n } catch (error) {\n return readFailed(error)\n }\n }\n\n /** The write path must be able to create `<root>/boost` on a fresh install. */\n private async ensureDirectory(): Promise<void> {\n try {\n await mkdir(this.dir, { recursive: true })\n } catch (error) {\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot create ${this.dir}: ${messageOf(error)}`)\n }\n }\n\n /**\n * Take the write lock, reclaiming a stale lock at most once.\n *\n * Two independent staleness rules:\n *\n * 1. dead-owner reclaim — older than `lockStaleMs` **and** the recorded pid is\n * dead (or unrecorded/unparseable/out of pid range);\n * 2. bounded takeover — the lock's `startedAt` (falling back to mtime) is\n * older than `lockTakeoverMs`, **even when its pid is alive**. A pid is\n * reused after a crash, so rule 1 alone can leave `scope.lock` held for the\n * whole process lifetime in a container. The hold window is one small\n * synchronous write, so a lock this old is a crashed writer.\n *\n * The takeover re-reads the lock immediately before unlinking and refuses if\n * its bytes or mtime changed, which narrows the cross-process race. Two\n * writers can still judge the same lock stale; `releaseLock` only removes a\n * lock whose content it wrote, and the CAS revision check still refuses to\n * merge divergent writes, so the residual race cannot corrupt the document.\n *\n * When that first read finds **no** lock there is nothing to compare against,\n * so the reclaim is refused with `ERR_SCOPE_LOCKED`. `createLock` already saw\n * the file exist; a lock created between that failure and the read is\n * indistinguishable from one a live writer still owns, and unlinking it\n * would lose that writer's update. Refusing is safe (the caller retries) and\n * the alternative is the one case the changed-lock guard cannot cover.\n */\n private async acquireLock(signal?: AbortSignal): Promise<void> {\n checkAbort(signal)\n if (await this.createLock()) {\n // `createLock` is the one await that can leave a lock behind; an abort\n // observed after it returns must release it, not strand it.\n if (signal?.aborted === true) {\n this.releaseLock()\n throw abortedError()\n }\n return\n }\n checkAbort(signal)\n const first = this.readLock()\n const decision = this.classifyLock(first)\n if (decision === 'held') {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} is held by another writer`)\n }\n if (decision === 'missing') {\n throw scopeError(\n ERR_SCOPE_LOCKED,\n `${this.lockFile} existed for createLock but vanished before it could be inspected; another writer may hold it now`,\n )\n }\n if (decision === 'takeover') {\n this.warn(\n `${ERR_SCOPE_LOCK_TAKEOVER}: taking over ${this.lockFile} from pid ${\n first?.pid ?? 'unknown'\n } after ${Math.round(this.ageOf(first) / 1000)}s; the recording process may have crashed and its pid been reused`,\n )\n }\n\n // Re-read before the unlink: a writer that replaced the lock between the\n // decision and here must not be evicted on a stale observation.\n const again = this.readLock()\n if (again !== undefined && first !== undefined) {\n if (again.text !== first.text || again.mtimeMs !== first.mtimeMs) {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} changed while being reclaimed`)\n }\n }\n try {\n unlinkSync(this.lockFile)\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') {\n throw scopeError(ERR_SCOPE_LOCKED, `cannot reclaim ${this.lockFile}: ${messageOf(error)}`)\n }\n }\n if (!(await this.createLock())) {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} is held by another writer`)\n }\n if (signal?.aborted === true) {\n this.releaseLock()\n throw abortedError()\n }\n }\n\n /** `open(lock, 'wx')`; false means another writer holds it. */\n private async createLock(): Promise<boolean> {\n let handle: FileHandle\n try {\n handle = await open(this.lockFile, 'wx')\n } catch (error) {\n if (errorCode(error) === 'EEXIST') return false\n throw scopeError(ERR_SCOPE_LOCKED, `cannot create ${this.lockFile}: ${messageOf(error)}`)\n }\n\n const content = JSON.stringify({\n pid: process.pid,\n startedAt: this.now(),\n nonce: BOOT_NONCE,\n })\n let failure: unknown\n try {\n await handle.writeFile(content)\n } catch (error) {\n failure = error\n } finally {\n await handle.close().catch(() => {})\n }\n if (failure !== undefined) {\n // A lock without owner data would block for the stale timeout; remove\n // what we created.\n await unlink(this.lockFile).catch(() => {})\n throw scopeError(ERR_SCOPE_LOCKED, `cannot write ${this.lockFile}: ${messageOf(failure)}`)\n }\n this.lockOwner = content\n return true\n }\n\n /**\n * One read of the lock: bytes, mtime and the owner fields they record.\n *\n * `undefined` means absent (the `EEXIST` raced a release): the caller may\n * retry the create. An unreadable-but-present lock is returned with the mtime\n * and no owner fields, so it becomes reclaimable only after the dead-pid\n * timeout — never immediately, because an unreadable live lock must not be\n * evicted on a guess.\n */\n private readLock(): { text: string; mtimeMs: number; pid?: number; startedAt?: number } | undefined {\n let mtimeMs: number\n try {\n mtimeMs = statSync(this.lockFile).mtimeMs\n } catch {\n return undefined\n }\n let text: string\n try {\n text = readFileSync(this.lockFile, 'utf8')\n } catch {\n return { text: '', mtimeMs }\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return { text, mtimeMs }\n }\n const record = typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {}\n const pid = record.pid\n const startedAt = record.startedAt\n return {\n text,\n mtimeMs,\n ...(typeof pid === 'number' && Number.isInteger(pid) && pid > 0 && pid <= MAX_PID ? { pid } : {}),\n ...(typeof startedAt === 'number' && Number.isFinite(startedAt) && startedAt > 0 && startedAt <= this.now()\n ? { startedAt }\n : {}),\n }\n }\n\n /** Age from `startedAt` when it is usable, otherwise from the file's mtime. */\n private ageOf(lock: { mtimeMs: number; startedAt?: number } | undefined): number {\n if (lock === undefined) return 0\n return Math.max(0, this.now() - (lock.startedAt ?? lock.mtimeMs))\n }\n\n /** Whether the lock is reclaimable, and whether that decision needs a warning. */\n private classifyLock(\n lock: { mtimeMs: number; pid?: number; startedAt?: number } | undefined,\n ): 'held' | 'dead' | 'takeover' | 'missing' {\n if (lock === undefined) return 'missing'\n const age = this.ageOf(lock)\n if (age <= this.lockStaleMs) return 'held'\n if (age >= this.lockTakeoverMs) return 'takeover'\n return lock.pid === undefined || !isProcessAlive(lock.pid) ? 'dead' : 'held'\n }\n\n /**\n * Remove the lock only if it still contains exactly what this acquisition\n * wrote. An unconditional unlink would delete a replacement lock another\n * writer created after a stale-reclaim race. Every error is swallowed:\n * cleanup must never mask the causal error (rule 8), and a lock left behind\n * is reclaimable after 60 s while a masked conflict is not diagnosable.\n */\n private releaseLock(): void {\n const owner = this.lockOwner\n this.lockOwner = undefined\n if (owner === undefined) return\n try {\n if (readFileSync(this.lockFile, 'utf8') === owner) unlinkSync(this.lockFile)\n } catch {\n // See the method comment: cleanup never rethrows.\n }\n }\n\n /**\n * Serialize `doc` into a temporary file, fsync it, and rename it over\n * `scope.json`. Returns the stored file's mtime and the exact text written\n * (for the cache). A failed write removes the temporary file; the caller's\n * `finally` removes the lock.\n */\n private writeAtomic(doc: ScopeDoc): { mtimeMs: number; text: string } {\n const tempFile = join(this.dir, `.${SCOPE_FILE}.${process.pid}.${randomUUID()}.tmp`)\n const text = `${JSON.stringify(doc)}\\n`\n let fd: number | undefined\n try {\n fd = openSync(tempFile, 'w')\n writeFileSync(fd, text)\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n // Stat before the rename: if this fails nothing has touched `scope.json`,\n // and the mtime of the inode is what `read()` will observe afterwards.\n const mtimeMs = statSync(tempFile).mtimeMs\n renameSync(tempFile, this.file)\n return { mtimeMs, text }\n } catch (error) {\n if (fd !== undefined) {\n try {\n closeSync(fd)\n } catch {\n // Already closed or never opened; the unlink below is what matters.\n }\n }\n try {\n unlinkSync(tempFile)\n } catch {\n // Best effort: the temporary file may not exist if openSync failed.\n }\n throw error\n }\n }\n}\n"]}
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/scope/store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EACL,SAAS,EACT,SAAS,EACT,QAAQ,EACR,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,aAAa,GACd,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAEtE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,wBAAwB,EACxB,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,sBAAsB,EACtB,2BAA2B,EAC3B,yBAAyB,EACzB,UAAU,EACV,oBAAoB,GACrB,MAAM,UAAU,CAAA;AAGjB,MAAM,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H,CAAC;IAED;;;;;OAKG;IACK,WAAW,CAAC,GAAa;QAC/B,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,UAAU,IAAI,OAAO,CAAC,GAAG,IAAI,UAAU,EAAE,MAAM,CAAC,CAAA;QACpF,MAAM,IAAI,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAA;QACvC,IAAI,EAAsB,CAAA;QAC1B,IAAI,CAAC;YACH,EAAE,GAAG,QAAQ,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;YAC5B,aAAa,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;YACvB,SAAS,CAAC,EAAE,CAAC,CAAA;YACb,SAAS,CAAC,EAAE,CAAC,CAAA;YACb,EAAE,GAAG,SAAS,CAAA;YACd,0EAA0E;YAC1E,uEAAuE;YACvE,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAA;YAC1C,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,CAAA;YAC/B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAA;QAC1B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,EAAE,KAAK,SAAS,EAAE,CAAC;gBACrB,IAAI,CAAC;oBACH,SAAS,CAAC,EAAE,CAAC,CAAA;gBACf,CAAC;gBAAC,MAAM,CAAC;oBACP,oEAAoE;gBACtE,CAAC;YACH,CAAC;YACD,IAAI,CAAC;gBACH,UAAU,CAAC,QAAQ,CAAC,CAAA;YACtB,CAAC;YAAC,MAAM,CAAC;gBACP,oEAAoE;YACtE,CAAC;YACD,MAAM,KAAK,CAAA;QACb,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Persistent scope store: one small JSON document that says where the plugin is\n * active, plus the per-agent judgement cache the synchronous prompt provider\n * reads.\n *\n * `scope.json` is read on every tool call and written only by the `boost`\n * control tool. Reads never throw: a missing file is the clean default\n * (revision 0, no code — a fresh install has simply configured nothing yet),\n * while an unreadable, corrupt or newer-versioned file means \"nobody sees the\n * plugin\" (`DEFAULT_SCOPE`) plus a stable code for the receipt/status channel.\n * A failed read never touches the file. Writes are compare-and-swap: the caller\n * passes the revision it last saw, the store locks, verifies that revision,\n * mutates, bumps it, and renames a temporary file over `scope.json`. The rename\n * makes a crash leave either the old or the new document, never a half-written\n * one. The revision check makes a lost update require the narrow stale-lock\n * reclaim race documented at `acquireLock`; it cannot silently corrupt or merge\n * a document.\n *\n * ## Sync/async boundary\n *\n * The read path is async (`stat` + `readFile`), because it is called on the\n * hot step path of a live agent and must not block the event loop. The write\n * path is async only while acquiring the lock: everything inside the lock —\n * the disk read, the mutation, the atomic write — is synchronous, so no other\n * writer can interleave between the revision check and the write.\n *\n * ## Cache\n *\n * The cache stores the last validated parse next to the exact bytes and mtime\n * it was parsed from. A read reuses that parse only when both the mtime and the\n * exact bytes match. Byte identity implies the parsed `revision` is unchanged\n * (the invariant design §5.5 asks for), and it is strictly safer than an\n * mtime+revision key: an external edit that preserves both would otherwise be\n * served from the old parse. The cache therefore avoids re-parsing the same\n * bytes, not the read itself — the revision check requires reading\n * `scope.json`. Cache hits keep the cached document object internally and\n * every returned document is a deep copy, so a caller mutating a result cannot\n * poison the cache.\n *\n * The judgement cache is intentionally per agent key (the session id). A\n * single global value would leak one workspace's visibility into every other\n * agent (design §5.5). `remember` is the only writer; `forget` is called from\n * the plugin's `session/disposed` handler so a long-lived process does not keep\n * one entry per session forever.\n *\n * @module dsh-boost/scope/store\n */\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n fsyncSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { mkdir, open, readFile, stat, unlink } from 'node:fs/promises'\nimport type { FileHandle } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport {\n DEFAULT_SCOPE,\n ERR_SCOPE_ABORTED,\n ERR_SCOPE_FUTURE_VERSION,\n ERR_SCOPE_LOCKED,\n ERR_SCOPE_PARSE_FAILED,\n ERR_SCOPE_READ_FAILED,\n ERR_SCOPE_WRITE_FAILED,\n ERR_SCOPE_REVISION_CONFLICT,\n ERR_SCOPE_UNKNOWN_VERSION,\n parseScope,\n parseVersionOneScope,\n} from './doc.js'\nimport type { ScopeCode, ScopeDoc } from './doc.js'\n\nconst SCOPE_FILE = 'scope.json'\nconst LOCK_FILE = 'scope.lock'\n/** A lock older than this is a reclaim candidate when its pid is dead (or unrecorded). */\nconst LOCK_STALE_MS = 60_000\n/**\n * After this much time a lock is taken over even when its recorded pid is alive.\n *\n * `startedAt` (not `mtime`) is the age source when present. The write section\n * inside the lock is synchronous and tiny, so a ten-minute hold means a crashed\n * writer whose pid the OS reused; without this bound such a lock wedges every\n * `boost scope` write until it is deleted by hand. Ten times the dead-pid\n * timeout keeps a genuinely slow writer safe.\n */\nconst LOCK_TAKEOVER_MS = 10 * LOCK_STALE_MS\n/** Largest value `process.kill` accepts as a pid (signed 32-bit). */\nconst MAX_PID = 2_147_483_647\n/** Stable code logged when a live-pid lock is reclaimed on age alone. */\nexport const ERR_SCOPE_LOCK_TAKEOVER = 'ERR_SCOPE_LOCK_TAKEOVER'\n/** Per-process identity in the lock file: distinguishes a reused pid from this boot. */\nconst BOOT_NONCE = randomUUID()\n\n/**\n * One disk read.\n *\n * A missing file is its own arm, not a failure: it still carries the strict\n * default to serve, but no code and no degraded flag, because \"nothing has\n * been configured yet\" is the clean state a fresh install starts in. Both read\n * paths and the write path use `missing` to tell a first write from an I/O\n * error; only genuine failures carry a stable `code` and `cause`.\n */\ntype DiskRead =\n | { ok: true; doc: ScopeDoc; mtimeMs: number; text: string }\n | { ok: false; missing: true; doc: ScopeDoc }\n | {\n ok: false\n missing: false\n doc: ScopeDoc\n code: ScopeCode\n cause?: unknown\n /** The v1 field values an explicit upgrade must carry (see `parseVersionOneScope`). */\n upgrade?: ScopeDoc\n }\n\n/** A write-path failure: the stable code is on `.code` and in the message. */\nfunction scopeError(code: ScopeCode, detail: string): Error & { code: ScopeCode } {\n return Object.assign(new Error(`${code}: ${detail}`), { code })\n}\n\n/** The stable cancellation error; the file has not been touched yet. */\nfunction abortedError(): Error & { code: ScopeCode } {\n return scopeError(ERR_SCOPE_ABORTED, 'the scope write was cancelled')\n}\n\n/** Stop before the next side effect when the caller has cancelled. */\nfunction checkAbort(signal: AbortSignal | undefined): void {\n if (signal?.aborted === true) throw abortedError()\n}\n\n/** The errno string of a Node filesystem error, if it has one. */\nfunction errorCode(error: unknown): string | undefined {\n return typeof error === 'object' && error !== null && 'code' in error\n ? (error as NodeJS.ErrnoException).code\n : undefined\n}\n\n/** A human-readable detail for a wrapped error. */\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * Liveness probe for lock reclamation.\n *\n * `EPERM` means the process exists but belongs to another user, so it counts as\n * alive; only `ESRCH` proves the recorded writer is gone. Any other outcome is\n * treated as alive too: reclamation must never evict a writer on a guess.\n * `readLockPid` bounds the pid to the range `process.kill` accepts, so the\n * impossible-pid `ERR_INVALID_ARG_TYPE` path is never reached.\n */\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n return errorCode(error) !== 'ESRCH'\n }\n}\n\n/** A deep copy: cached and returned documents never share mutable state. */\nfunction cloneDoc(doc: ScopeDoc): ScopeDoc {\n return structuredClone(doc)\n}\n\n/**\n * Classify a failed disk read.\n *\n * `ENOENT` is the clean default: the document does not exist yet, so nobody\n * has been configured in and there is nothing to report. Every other failure\n * (permissions, I/O, a directory where a file is expected) is a genuine\n * degraded read and keeps `ERR_SCOPE_READ_FAILED`.\n */\nfunction readFailed(error: unknown): DiskRead {\n if (errorCode(error) === 'ENOENT') {\n return { ok: false, missing: true, doc: cloneDoc(DEFAULT_SCOPE) }\n }\n return {\n ok: false,\n missing: false,\n doc: cloneDoc(DEFAULT_SCOPE),\n code: ERR_SCOPE_READ_FAILED,\n cause: error,\n }\n}\n\n/** Decode one already-read `scope.json`; JSON errors are parse failures too. */\nfunction decode(text: string, mtimeMs: number): DiskRead {\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n return {\n ok: false,\n doc: cloneDoc(DEFAULT_SCOPE),\n code: ERR_SCOPE_PARSE_FAILED,\n missing: false,\n cause: error,\n }\n }\n const parsed = parseScope(raw)\n if (parsed.code !== undefined) {\n // A v1 document is read-only-degraded, but the explicit upgrade rewrites\n // its recognised fields rather than resetting them to DEFAULT_SCOPE\n // (review row 38). `parseVersionOneScope` is deliberately not applied to\n // the read path.\n const upgrade = parseVersionOneScope(raw)\n return {\n ok: false,\n doc: parsed.doc,\n code: parsed.code,\n missing: false,\n ...(upgrade === undefined ? {} : { upgrade }),\n }\n }\n return { ok: true, doc: parsed.doc, mtimeMs, text }\n}\n\n/** Test seam and operator hook for the lock's time-based takeover. */\nexport interface ScopeStoreOptions {\n /** Age after which a live-pid lock is ignored (defaults to ten dead-pid timeouts). */\n lockTakeoverMs?: number\n /** Age after which a dead-pid lock is reclaimable (defaults to 60 s). */\n lockStaleMs?: number\n /** Clock, injectable so tests do not sleep. */\n now?: () => number\n /** Sink for the takeover warning; defaults to a process warning. */\n warn?: (message: string) => void\n}\n\nexport class ScopeStore {\n private readonly file: string\n private readonly lockFile: string\n private readonly lockStaleMs: number\n private readonly lockTakeoverMs: number\n private readonly now: () => number\n private readonly warn: (message: string) => void\n private cached?: { mtimeMs: number; text: string; doc: ScopeDoc }\n private lockOwner?: string\n private readonly judgements = new Map<string, boolean>()\n\n constructor(private readonly dir: string, options: ScopeStoreOptions = {}) {\n this.file = join(dir, SCOPE_FILE)\n this.lockFile = join(dir, LOCK_FILE)\n this.lockStaleMs = options.lockStaleMs ?? LOCK_STALE_MS\n this.lockTakeoverMs = options.lockTakeoverMs ?? LOCK_TAKEOVER_MS\n this.now = options.now ?? Date.now\n this.warn = options.warn ?? ((message: string) => process.emitWarning(message))\n }\n\n /**\n * Read the current document. Never throws and never writes: every stat,\n * read, JSON or shape failure comes back as a fresh `DEFAULT_SCOPE` plus\n * `degraded: 'scope-degraded'` and the stable code.\n */\n async read(): Promise<{ doc: ScopeDoc; degraded?: 'scope-degraded'; code?: ScopeCode }> {\n const result = await this.readDisk()\n if (!result.ok) {\n // Ruling 1: a degraded document is never a cache entry. The next call\n // must retry the disk instead of serving the strict default forever.\n this.cached = undefined\n // A missing file is the clean default (revision 0, no degraded code);\n // a genuine failure keeps its stable code.\n if (result.missing) return { doc: cloneDoc(result.doc) }\n return { doc: cloneDoc(result.doc), degraded: 'scope-degraded', code: result.code }\n }\n\n // On a cache hit `result.doc` is the cached object (identical bytes);\n // either way the caller gets a copy, so a mutation cannot poison it.\n this.cached = { mtimeMs: result.mtimeMs, text: result.text, doc: result.doc }\n return { doc: cloneDoc(result.doc) }\n }\n\n /**\n * Compare-and-swap write. Returns the new document (revision `baseRevision + 1`,\n * `updatedAt` now) and leaves it cached.\n *\n * A missing file is a first write: the base is `DEFAULT_SCOPE` at revision 0,\n * so it succeeds only when the caller passes 0. A version 1 file is based on\n * the fields it actually carries, which is how `boost scope set` explicitly\n * upgrades it. Every other present-but-unusable document is refused before\n * the mutation: a **future** version (a numeric version greater than 2) with\n * `ERR_SCOPE_FUTURE_VERSION`, a non-document with\n * `ERR_SCOPE_PARSE_FAILED`, a missing or non-numeric version with\n * `ERR_SCOPE_UNKNOWN_VERSION`, and an unreadable file with\n * `ERR_SCOPE_READ_FAILED`. Each refusal leaves the file byte-identical.\n */\n async write(\n mutate: (doc: ScopeDoc) => ScopeDoc,\n baseRevision: number,\n options: { signal?: AbortSignal } = {},\n ): Promise<ScopeDoc> {\n const signal = options.signal\n checkAbort(signal)\n await this.ensureDirectory()\n checkAbort(signal)\n await this.acquireLock(signal)\n try {\n checkAbort(signal)\n const current = this.readDiskSync()\n checkAbort(signal)\n let base: ScopeDoc\n if (current.ok) {\n base = current.doc\n } else if (current.missing) {\n // A first write starts from the strict default at revision 0.\n base = current.doc\n } else {\n if (current.code === ERR_SCOPE_FUTURE_VERSION) {\n throw scopeError(\n ERR_SCOPE_FUTURE_VERSION,\n `refusing to rewrite ${this.file}: it declares a newer scope version`,\n )\n }\n if (current.code === ERR_SCOPE_READ_FAILED) {\n const detail = current.cause === undefined ? 'unknown read error' : messageOf(current.cause)\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot read ${this.file}: ${detail}`)\n }\n // Both remaining codes mean the bytes are present but unusable. Key on\n // the code, not on this branch: only a v1 document (whose `upgrade`\n // `decode` supplied) has recognised fields worth preserving, and only\n // its documented `scope-set` upgrade may rewrite the file. A parse\n // failure has no fields at all, and a missing or non-numeric version is\n // equally unrepresentable; basing a write on DEFAULT_SCOPE for either\n // would silently replace the user's document, which `docs/RELEASE.md`\n // promises not to do (\"写拒绝\" / \"写不盲改\").\n if (current.code === ERR_SCOPE_PARSE_FAILED) {\n throw scopeError(\n ERR_SCOPE_PARSE_FAILED,\n `refusing to rewrite ${this.file}: it is not a scope document`,\n )\n }\n if (current.upgrade === undefined) {\n throw scopeError(\n ERR_SCOPE_UNKNOWN_VERSION,\n `refusing to rewrite ${this.file}: it declares an unknown scope version`,\n )\n }\n // A v1 file was read as DEFAULT_SCOPE at revision 0, but its recognised\n // fields are the user's configuration: base the upgrade on those so a\n // partial `scope-set` cannot silently drop `global`/`workspaceIds`.\n base = current.upgrade\n }\n if (base.revision !== baseRevision) {\n throw scopeError(\n ERR_SCOPE_REVISION_CONFLICT,\n `base revision ${baseRevision} does not match ${base.revision}`,\n )\n }\n\n const doc: ScopeDoc = {\n ...mutate(base),\n revision: baseRevision + 1,\n updatedAt: new Date().toISOString(),\n }\n checkAbort(signal)\n let written: { mtimeMs: number; text: string }\n try {\n written = this.writeAtomic(doc)\n } catch (error) {\n // A write failure is not a read failure: the caller still knows its\n // baseline, and telling it to re-read would discard a draft that is\n // perfectly good. Rule 8 requires a stable code on every error.\n throw scopeError(ERR_SCOPE_WRITE_FAILED, `cannot write ${this.file}: ${messageOf(error)}`)\n }\n // Clone before caching: `doc` may still share arrays with an object the\n // caller (or `mutate`) holds, and the cache must never alias those.\n this.cached = { mtimeMs: written.mtimeMs, text: written.text, doc: cloneDoc(doc) }\n return cloneDoc(doc)\n } finally {\n this.releaseLock()\n }\n }\n\n /** Cache one agent's visibility judgement; the only writer of this cache. */\n remember(key: string, visible: boolean): void {\n this.judgements.set(key, visible)\n }\n\n /**\n * Drop one session's cached judgement on session disposal.\n *\n * The judgement map is per session and otherwise lives as long as the plugin;\n * without this a process that served many sessions would retain one boolean\n * (and its string key) per session forever.\n */\n forget(key: string): void {\n this.judgements.delete(key)\n }\n\n /** Synchronous per-agent lookup: a miss is `fallback`, and fail-closed is `false`. */\n judgement(key: string, fallback?: boolean): boolean {\n return this.judgements.get(key) ?? fallback ?? false\n }\n\n /** Async read path: stat + read + decode, all failures degraded. */\n private async readDisk(): Promise<DiskRead> {\n try {\n const stats = await stat(this.file)\n const text = await readFile(this.file, 'utf8')\n return this.decodeFromCache(text, stats.mtimeMs)\n } catch (error) {\n return readFailed(error)\n }\n }\n\n /**\n * Reuse the previous parse only when the exact bytes and mtime were already\n * parsed. Byte identity is a stronger key than mtime+revision: an external\n * edit that keeps both cannot be served from the old parse.\n */\n private decodeFromCache(text: string, mtimeMs: number): DiskRead {\n const cached = this.cached\n if (cached !== undefined && cached.mtimeMs === mtimeMs && cached.text === text) {\n return { ok: true, doc: cached.doc, mtimeMs, text }\n }\n return decode(text, mtimeMs)\n }\n\n /** Sync read path, used only inside the write lock (see the module comment). */\n private readDiskSync(): DiskRead {\n try {\n const stats = statSync(this.file)\n const text = readFileSync(this.file, 'utf8')\n return decode(text, stats.mtimeMs)\n } catch (error) {\n return readFailed(error)\n }\n }\n\n /** The write path must be able to create `<root>/boost` on a fresh install. */\n private async ensureDirectory(): Promise<void> {\n try {\n await mkdir(this.dir, { recursive: true })\n } catch (error) {\n throw scopeError(ERR_SCOPE_READ_FAILED, `cannot create ${this.dir}: ${messageOf(error)}`)\n }\n }\n\n /**\n * Take the write lock, reclaiming a stale lock at most once.\n *\n * Two independent staleness rules:\n *\n * 1. dead-owner reclaim — older than `lockStaleMs` **and** the recorded pid is\n * dead (or unrecorded/unparseable/out of pid range);\n * 2. bounded takeover — the lock's `startedAt` (falling back to mtime) is\n * older than `lockTakeoverMs`, **even when its pid is alive**. A pid is\n * reused after a crash, so rule 1 alone can leave `scope.lock` held for the\n * whole process lifetime in a container. The hold window is one small\n * synchronous write, so a lock this old is a crashed writer.\n *\n * The takeover re-reads the lock immediately before unlinking and refuses if\n * its bytes or mtime changed, which narrows the cross-process race. Two\n * writers can still judge the same lock stale; `releaseLock` only removes a\n * lock whose content it wrote, and the CAS revision check still refuses to\n * merge divergent writes, so the residual race cannot corrupt the document.\n *\n * When that first read finds **no** lock there is nothing to compare against,\n * so the reclaim is refused with `ERR_SCOPE_LOCKED`. `createLock` already saw\n * the file exist; a lock created between that failure and the read is\n * indistinguishable from one a live writer still owns, and unlinking it\n * would lose that writer's update. Refusing is safe (the caller retries) and\n * the alternative is the one case the changed-lock guard cannot cover.\n */\n private async acquireLock(signal?: AbortSignal): Promise<void> {\n checkAbort(signal)\n if (await this.createLock()) {\n // `createLock` is the one await that can leave a lock behind; an abort\n // observed after it returns must release it, not strand it.\n if (signal?.aborted === true) {\n this.releaseLock()\n throw abortedError()\n }\n return\n }\n checkAbort(signal)\n const first = this.readLock()\n const decision = this.classifyLock(first)\n if (decision === 'held') {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} is held by another writer`)\n }\n if (decision === 'missing') {\n throw scopeError(\n ERR_SCOPE_LOCKED,\n `${this.lockFile} existed for createLock but vanished before it could be inspected; another writer may hold it now`,\n )\n }\n if (decision === 'takeover') {\n this.warn(\n `${ERR_SCOPE_LOCK_TAKEOVER}: taking over ${this.lockFile} from pid ${\n first?.pid ?? 'unknown'\n } after ${Math.round(this.ageOf(first) / 1000)}s; the recording process may have crashed and its pid been reused`,\n )\n }\n\n // Re-read before the unlink: a writer that replaced the lock between the\n // decision and here must not be evicted on a stale observation.\n const again = this.readLock()\n if (again !== undefined && first !== undefined) {\n if (again.text !== first.text || again.mtimeMs !== first.mtimeMs) {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} changed while being reclaimed`)\n }\n }\n try {\n unlinkSync(this.lockFile)\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') {\n throw scopeError(ERR_SCOPE_LOCKED, `cannot reclaim ${this.lockFile}: ${messageOf(error)}`)\n }\n }\n if (!(await this.createLock())) {\n throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} is held by another writer`)\n }\n if (signal?.aborted === true) {\n this.releaseLock()\n throw abortedError()\n }\n }\n\n /** `open(lock, 'wx')`; false means another writer holds it. */\n private async createLock(): Promise<boolean> {\n let handle: FileHandle\n try {\n handle = await open(this.lockFile, 'wx')\n } catch (error) {\n if (errorCode(error) === 'EEXIST') return false\n throw scopeError(ERR_SCOPE_LOCKED, `cannot create ${this.lockFile}: ${messageOf(error)}`)\n }\n\n const content = JSON.stringify({\n pid: process.pid,\n startedAt: this.now(),\n nonce: BOOT_NONCE,\n })\n let failure: unknown\n try {\n await handle.writeFile(content)\n } catch (error) {\n failure = error\n } finally {\n await handle.close().catch(() => {})\n }\n if (failure !== undefined) {\n // A lock without owner data would block for the stale timeout; remove\n // what we created.\n await unlink(this.lockFile).catch(() => {})\n throw scopeError(ERR_SCOPE_LOCKED, `cannot write ${this.lockFile}: ${messageOf(failure)}`)\n }\n this.lockOwner = content\n return true\n }\n\n /**\n * One read of the lock: bytes, mtime and the owner fields they record.\n *\n * `undefined` means absent (the `EEXIST` raced a release): the caller may\n * retry the create. An unreadable-but-present lock is returned with the mtime\n * and no owner fields, so it becomes reclaimable only after the dead-pid\n * timeout — never immediately, because an unreadable live lock must not be\n * evicted on a guess.\n */\n private readLock(): { text: string; mtimeMs: number; pid?: number; startedAt?: number } | undefined {\n let mtimeMs: number\n try {\n mtimeMs = statSync(this.lockFile).mtimeMs\n } catch {\n return undefined\n }\n let text: string\n try {\n text = readFileSync(this.lockFile, 'utf8')\n } catch {\n return { text: '', mtimeMs }\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return { text, mtimeMs }\n }\n const record = typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {}\n const pid = record.pid\n const startedAt = record.startedAt\n return {\n text,\n mtimeMs,\n ...(typeof pid === 'number' && Number.isInteger(pid) && pid > 0 && pid <= MAX_PID ? { pid } : {}),\n ...(typeof startedAt === 'number' && Number.isFinite(startedAt) && startedAt > 0 && startedAt <= this.now()\n ? { startedAt }\n : {}),\n }\n }\n\n /** Age from `startedAt` when it is usable, otherwise from the file's mtime. */\n private ageOf(lock: { mtimeMs: number; startedAt?: number } | undefined): number {\n if (lock === undefined) return 0\n return Math.max(0, this.now() - (lock.startedAt ?? lock.mtimeMs))\n }\n\n /** Whether the lock is reclaimable, and whether that decision needs a warning. */\n private classifyLock(\n lock: { mtimeMs: number; pid?: number; startedAt?: number } | undefined,\n ): 'held' | 'dead' | 'takeover' | 'missing' {\n if (lock === undefined) return 'missing'\n const age = this.ageOf(lock)\n if (age <= this.lockStaleMs) return 'held'\n if (age >= this.lockTakeoverMs) return 'takeover'\n return lock.pid === undefined || !isProcessAlive(lock.pid) ? 'dead' : 'held'\n }\n\n /**\n * Remove the lock only if it still contains exactly what this acquisition\n * wrote. An unconditional unlink would delete a replacement lock another\n * writer created after a stale-reclaim race. Every error is swallowed:\n * cleanup must never mask the causal error (rule 8), and a lock left behind\n * is reclaimable after 60 s while a masked conflict is not diagnosable.\n */\n private releaseLock(): void {\n const owner = this.lockOwner\n this.lockOwner = undefined\n if (owner === undefined) return\n try {\n if (readFileSync(this.lockFile, 'utf8') === owner) unlinkSync(this.lockFile)\n } catch {\n // See the method comment: cleanup never rethrows.\n }\n }\n\n /**\n * Serialize `doc` into a temporary file, fsync it, and rename it over\n * `scope.json`. Returns the stored file's mtime and the exact text written\n * (for the cache). A failed write removes the temporary file; the caller's\n * `finally` removes the lock.\n */\n private writeAtomic(doc: ScopeDoc): { mtimeMs: number; text: string } {\n const tempFile = join(this.dir, `.${SCOPE_FILE}.${process.pid}.${randomUUID()}.tmp`)\n const text = `${JSON.stringify(doc)}\\n`\n let fd: number | undefined\n try {\n fd = openSync(tempFile, 'w')\n writeFileSync(fd, text)\n fsyncSync(fd)\n closeSync(fd)\n fd = undefined\n // Stat before the rename: if this fails nothing has touched `scope.json`,\n // and the mtime of the inode is what `read()` will observe afterwards.\n const mtimeMs = statSync(tempFile).mtimeMs\n renameSync(tempFile, this.file)\n return { mtimeMs, text }\n } catch (error) {\n if (fd !== undefined) {\n try {\n closeSync(fd)\n } catch {\n // Already closed or never opened; the unlink below is what matters.\n }\n }\n try {\n unlinkSync(tempFile)\n } catch {\n // Best effort: the temporary file may not exist if openSync failed.\n }\n throw error\n }\n }\n}\n"]}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The path this plugin's HTTP surface owns, shared by both halves.
3
+ *
4
+ * One constant rather than a copy in each half: the page and the route are
5
+ * built separately, and a rename that reached only one of them would leave a
6
+ * page that loads and then silently 404s.
7
+ */
8
+ export const HTTP_API_PREFIX = '/dsh-boost/api';
9
+ //# sourceMappingURL=api-prefix.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-prefix.js","sourceRoot":"","sources":["../../src/shared/api-prefix.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,gBAAgB,CAAA","sourcesContent":["/**\n * The path this plugin's HTTP surface owns, shared by both halves.\n *\n * One constant rather than a copy in each half: the page and the route are\n * built separately, and a rename that reached only one of them would leave a\n * page that loads and then silently 404s.\n */\nexport const HTTP_API_PREFIX = '/dsh-boost/api'\n"]}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The wire contract between the route and the page, in one place.
3
+ *
4
+ * Both halves are built separately and neither can import the other's runtime,
5
+ * so the shape they agree on lives here. A field renamed on one side and not
6
+ * the other is a silent `undefined` at runtime — the page renders "未测量" and
7
+ * nobody notices — which is why the types are shared rather than restated.
8
+ */
9
+ export {};
10
+ //# sourceMappingURL=api-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-types.js","sourceRoot":"","sources":["../../src/shared/api-types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG","sourcesContent":["/**\n * The wire contract between the route and the page, in one place.\n *\n * Both halves are built separately and neither can import the other's runtime,\n * so the shape they agree on lives here. A field renamed on one side and not\n * the other is a silent `undefined` at runtime — the page renders \"未测量\" and\n * nobody notices — which is why the types are shared rather than restated.\n */\n\n/** A workspace as the route reports it. */\nexport interface WorkspaceEntry {\n id: string\n path: string\n}\n\n/**\n * The workspace list, or the reason there is none.\n *\n * `available: false` is NOT an empty list: the page disables saving on it and\n * says the list could not be read. Rendering an empty list instead would read\n * as \"you have no workspaces\", which is a different, wrong statement.\n */\nexport type WorkspaceListing =\n | { available: true; entries: WorkspaceEntry[] }\n | { available: false; code: string }\n\n/** The JSON body `GET /dsh-boost/api/state` returns. */\nexport interface StatePayload {\n status: unknown\n scope: unknown\n workspaces: WorkspaceListing\n config: unknown\n}\n"]}
@@ -5,11 +5,19 @@ import { ERR_SCOPE_ABORTED, ERR_SCOPE_FUTURE_VERSION, ERR_SCOPE_LOCKED, ERR_SCOP
5
5
  /** Stable failure code: `cmd` names no subcommand this tool implements. */
6
6
  const ERR_BOOST_UNKNOWN_CMD = 'ERR_BOOST_UNKNOWN_CMD';
7
7
  /** Stable failure code: a required argument (`baseRevision`) is missing or malformed. */
8
- const ERR_BOOST_INVALID_ARGS = 'ERR_BOOST_INVALID_ARGS';
8
+ export const ERR_BOOST_INVALID_ARGS = 'ERR_BOOST_INVALID_ARGS';
9
9
  /** Stable failure code: `body` is not a valid, writable scope patch. */
10
- const ERR_BOOST_INVALID_BODY = 'ERR_BOOST_INVALID_BODY';
10
+ export const ERR_BOOST_INVALID_BODY = 'ERR_BOOST_INVALID_BODY';
11
11
  /** Stable failure code: an unexpected internal failure, so the tool still answers. */
12
- const ERR_BOOST_INTERNAL = 'ERR_BOOST_INTERNAL';
12
+ export const ERR_BOOST_INTERNAL = 'ERR_BOOST_INTERNAL';
13
+ /**
14
+ * Load-time log code: the settings page's data route could not be mounted.
15
+ *
16
+ * Log-only, like `ERR_BOOST_PARTIAL_MOUNT`: the plugin keeps working, the page
17
+ * just has no data source. Emitted from the mount path itself, so it appears in
18
+ * the host log rather than in `boost status`.
19
+ */
20
+ export const ERR_BOOST_HTTP_MOUNT_FAILED = 'ERR_BOOST_HTTP_MOUNT_FAILED';
13
21
  /** Every scope failure code, for passing the store's codes through unchanged. */
14
22
  const SCOPE_CODES = new Set([
15
23
  ERR_SCOPE_UNKNOWN_VERSION,