dsh-boost 0.0.0-stage → 0.1.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.
- package/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.en.md +476 -0
- package/README.md +408 -2
- package/cordis.patch.yml +40 -0
- package/dist/admission/fixed-cost.d.ts +23 -0
- package/dist/admission/fixed-cost.js +61 -0
- package/dist/admission/fixed-cost.js.map +1 -0
- package/dist/admission/ledger.d.ts +113 -0
- package/dist/admission/ledger.js +176 -0
- package/dist/admission/ledger.js.map +1 -0
- package/dist/admission/retrieval.d.ts +65 -0
- package/dist/admission/retrieval.js +162 -0
- package/dist/admission/retrieval.js.map +1 -0
- package/dist/admission/usage.d.ts +75 -0
- package/dist/admission/usage.js +124 -0
- package/dist/admission/usage.js.map +1 -0
- package/dist/config.d.ts +43 -0
- package/dist/config.js +103 -0
- package/dist/config.js.map +1 -0
- package/dist/gate/binding.d.ts +113 -0
- package/dist/gate/binding.js +297 -0
- package/dist/gate/binding.js.map +1 -0
- package/dist/gate/decide.d.ts +82 -0
- package/dist/gate/decide.js +163 -0
- package/dist/gate/decide.js.map +1 -0
- package/dist/gate/guard.d.ts +69 -0
- package/dist/gate/guard.js +195 -0
- package/dist/gate/guard.js.map +1 -0
- package/dist/gate/invalidate.d.ts +112 -0
- package/dist/gate/invalidate.js +111 -0
- package/dist/gate/invalidate.js.map +1 -0
- package/dist/gate/plan.d.ts +86 -0
- package/dist/gate/plan.js +222 -0
- package/dist/gate/plan.js.map +1 -0
- package/dist/hooks/clock.d.ts +68 -0
- package/dist/hooks/clock.js +82 -0
- package/dist/hooks/clock.js.map +1 -0
- package/dist/hooks/execute.d.ts +79 -0
- package/dist/hooks/execute.js +128 -0
- package/dist/hooks/execute.js.map +1 -0
- package/dist/hooks/llm-stream.d.ts +276 -0
- package/dist/hooks/llm-stream.js +1008 -0
- package/dist/hooks/llm-stream.js.map +1 -0
- package/dist/hooks/pending.d.ts +89 -0
- package/dist/hooks/pending.js +115 -0
- package/dist/hooks/pending.js.map +1 -0
- package/dist/hooks/post-execute.d.ts +247 -0
- package/dist/hooks/post-execute.js +1776 -0
- package/dist/hooks/post-execute.js.map +1 -0
- package/dist/hooks/session-state.d.ts +158 -0
- package/dist/hooks/session-state.js +168 -0
- package/dist/hooks/session-state.js.map +1 -0
- package/dist/hooks/synthesize.d.ts +74 -0
- package/dist/hooks/synthesize.js +100 -0
- package/dist/hooks/synthesize.js.map +1 -0
- package/dist/host/loader.d.ts +23 -0
- package/dist/host/loader.js +31 -0
- package/dist/host/loader.js.map +1 -0
- package/dist/host/platform.d.ts +18 -0
- package/dist/host/platform.js +19 -0
- package/dist/host/platform.js.map +1 -0
- package/dist/host/root.d.ts +18 -0
- package/dist/host/root.js +43 -0
- package/dist/host/root.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +866 -0
- package/dist/index.js.map +1 -0
- package/dist/projection/apply.d.ts +174 -0
- package/dist/projection/apply.js +137 -0
- package/dist/projection/apply.js.map +1 -0
- package/dist/projection/canonicalise.d.ts +43 -0
- package/dist/projection/canonicalise.js +43 -0
- package/dist/projection/canonicalise.js.map +1 -0
- package/dist/projection/counters.d.ts +65 -0
- package/dist/projection/counters.js +88 -0
- package/dist/projection/counters.js.map +1 -0
- package/dist/projection/truncate.d.ts +47 -0
- package/dist/projection/truncate.js +57 -0
- package/dist/projection/truncate.js.map +1 -0
- package/dist/prompt/protocol.d.ts +45 -0
- package/dist/prompt/protocol.js +56 -0
- package/dist/prompt/protocol.js.map +1 -0
- package/dist/receipts/store.d.ts +198 -0
- package/dist/receipts/store.js +734 -0
- package/dist/receipts/store.js.map +1 -0
- package/dist/scope/doc.d.ts +117 -0
- package/dist/scope/doc.js +158 -0
- package/dist/scope/doc.js.map +1 -0
- package/dist/scope/resolve.d.ts +91 -0
- package/dist/scope/resolve.js +146 -0
- package/dist/scope/resolve.js.map +1 -0
- package/dist/scope/store.d.ts +135 -0
- package/dist/scope/store.js +573 -0
- package/dist/scope/store.js.map +1 -0
- package/dist/selector/jev.d.ts +93 -0
- package/dist/selector/jev.js +171 -0
- package/dist/selector/jev.js.map +1 -0
- package/dist/tools/boost.d.ts +367 -0
- package/dist/tools/boost.js +768 -0
- package/dist/tools/boost.js.map +1 -0
- package/dist/tools/family.d.ts +26 -0
- package/dist/tools/family.js +26 -0
- package/dist/tools/family.js.map +1 -0
- package/dist/types.d.ts +113 -0
- package/dist/types.js +21 -0
- package/dist/types.js.map +1 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +75 -4
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persistent scope store: one small JSON document that says where the plugin is
|
|
3
|
+
* active, plus the per-agent judgement cache the synchronous prompt provider
|
|
4
|
+
* reads.
|
|
5
|
+
*
|
|
6
|
+
* `scope.json` is read on every tool call and written only by the `boost`
|
|
7
|
+
* control tool. Reads never throw: a missing file is the clean default
|
|
8
|
+
* (revision 0, no code — a fresh install has simply configured nothing yet),
|
|
9
|
+
* while an unreadable, corrupt or newer-versioned file means "nobody sees the
|
|
10
|
+
* plugin" (`DEFAULT_SCOPE`) plus a stable code for the receipt/status channel.
|
|
11
|
+
* A failed read never touches the file. Writes are compare-and-swap: the caller
|
|
12
|
+
* passes the revision it last saw, the store locks, verifies that revision,
|
|
13
|
+
* mutates, bumps it, and renames a temporary file over `scope.json`. The rename
|
|
14
|
+
* makes a crash leave either the old or the new document, never a half-written
|
|
15
|
+
* one. The revision check makes a lost update require the narrow stale-lock
|
|
16
|
+
* reclaim race documented at `acquireLock`; it cannot silently corrupt or merge
|
|
17
|
+
* a document.
|
|
18
|
+
*
|
|
19
|
+
* ## Sync/async boundary
|
|
20
|
+
*
|
|
21
|
+
* The read path is async (`stat` + `readFile`), because it is called on the
|
|
22
|
+
* hot step path of a live agent and must not block the event loop. The write
|
|
23
|
+
* path is async only while acquiring the lock: everything inside the lock —
|
|
24
|
+
* the disk read, the mutation, the atomic write — is synchronous, so no other
|
|
25
|
+
* writer can interleave between the revision check and the write.
|
|
26
|
+
*
|
|
27
|
+
* ## Cache
|
|
28
|
+
*
|
|
29
|
+
* The cache stores the last validated parse next to the exact bytes and mtime
|
|
30
|
+
* it was parsed from. A read reuses that parse only when both the mtime and the
|
|
31
|
+
* exact bytes match. Byte identity implies the parsed `revision` is unchanged
|
|
32
|
+
* (the invariant design §5.5 asks for), and it is strictly safer than an
|
|
33
|
+
* mtime+revision key: an external edit that preserves both would otherwise be
|
|
34
|
+
* served from the old parse. The cache therefore avoids re-parsing the same
|
|
35
|
+
* bytes, not the read itself — the revision check requires reading
|
|
36
|
+
* `scope.json`. Cache hits keep the cached document object internally and
|
|
37
|
+
* every returned document is a deep copy, so a caller mutating a result cannot
|
|
38
|
+
* poison the cache.
|
|
39
|
+
*
|
|
40
|
+
* The judgement cache is intentionally per agent key (the session id). A
|
|
41
|
+
* single global value would leak one workspace's visibility into every other
|
|
42
|
+
* agent (design §5.5). `remember` is the only writer; `forget` is called from
|
|
43
|
+
* the plugin's `session/disposed` handler so a long-lived process does not keep
|
|
44
|
+
* one entry per session forever.
|
|
45
|
+
*
|
|
46
|
+
* @module dsh-boost/scope/store
|
|
47
|
+
*/
|
|
48
|
+
import { randomUUID } from 'node:crypto';
|
|
49
|
+
import { closeSync, fsyncSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
50
|
+
import { mkdir, open, readFile, stat, unlink } from 'node:fs/promises';
|
|
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, parseScope, parseVersionOneScope, } from './doc.js';
|
|
53
|
+
const SCOPE_FILE = 'scope.json';
|
|
54
|
+
const LOCK_FILE = 'scope.lock';
|
|
55
|
+
/** A lock older than this is a reclaim candidate when its pid is dead (or unrecorded). */
|
|
56
|
+
const LOCK_STALE_MS = 60_000;
|
|
57
|
+
/**
|
|
58
|
+
* After this much time a lock is taken over even when its recorded pid is alive.
|
|
59
|
+
*
|
|
60
|
+
* `startedAt` (not `mtime`) is the age source when present. The write section
|
|
61
|
+
* inside the lock is synchronous and tiny, so a ten-minute hold means a crashed
|
|
62
|
+
* writer whose pid the OS reused; without this bound such a lock wedges every
|
|
63
|
+
* `boost scope` write until it is deleted by hand. Ten times the dead-pid
|
|
64
|
+
* timeout keeps a genuinely slow writer safe.
|
|
65
|
+
*/
|
|
66
|
+
const LOCK_TAKEOVER_MS = 10 * LOCK_STALE_MS;
|
|
67
|
+
/** Largest value `process.kill` accepts as a pid (signed 32-bit). */
|
|
68
|
+
const MAX_PID = 2_147_483_647;
|
|
69
|
+
/** Stable code logged when a live-pid lock is reclaimed on age alone. */
|
|
70
|
+
export const ERR_SCOPE_LOCK_TAKEOVER = 'ERR_SCOPE_LOCK_TAKEOVER';
|
|
71
|
+
/** Per-process identity in the lock file: distinguishes a reused pid from this boot. */
|
|
72
|
+
const BOOT_NONCE = randomUUID();
|
|
73
|
+
/** A write-path failure: the stable code is on `.code` and in the message. */
|
|
74
|
+
function scopeError(code, detail) {
|
|
75
|
+
return Object.assign(new Error(`${code}: ${detail}`), { code });
|
|
76
|
+
}
|
|
77
|
+
/** The stable cancellation error; the file has not been touched yet. */
|
|
78
|
+
function abortedError() {
|
|
79
|
+
return scopeError(ERR_SCOPE_ABORTED, 'the scope write was cancelled');
|
|
80
|
+
}
|
|
81
|
+
/** Stop before the next side effect when the caller has cancelled. */
|
|
82
|
+
function checkAbort(signal) {
|
|
83
|
+
if (signal?.aborted === true)
|
|
84
|
+
throw abortedError();
|
|
85
|
+
}
|
|
86
|
+
/** The errno string of a Node filesystem error, if it has one. */
|
|
87
|
+
function errorCode(error) {
|
|
88
|
+
return typeof error === 'object' && error !== null && 'code' in error
|
|
89
|
+
? error.code
|
|
90
|
+
: undefined;
|
|
91
|
+
}
|
|
92
|
+
/** A human-readable detail for a wrapped error. */
|
|
93
|
+
function messageOf(error) {
|
|
94
|
+
return error instanceof Error ? error.message : String(error);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Liveness probe for lock reclamation.
|
|
98
|
+
*
|
|
99
|
+
* `EPERM` means the process exists but belongs to another user, so it counts as
|
|
100
|
+
* alive; only `ESRCH` proves the recorded writer is gone. Any other outcome is
|
|
101
|
+
* treated as alive too: reclamation must never evict a writer on a guess.
|
|
102
|
+
* `readLockPid` bounds the pid to the range `process.kill` accepts, so the
|
|
103
|
+
* impossible-pid `ERR_INVALID_ARG_TYPE` path is never reached.
|
|
104
|
+
*/
|
|
105
|
+
function isProcessAlive(pid) {
|
|
106
|
+
try {
|
|
107
|
+
process.kill(pid, 0);
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
return errorCode(error) !== 'ESRCH';
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** A deep copy: cached and returned documents never share mutable state. */
|
|
115
|
+
function cloneDoc(doc) {
|
|
116
|
+
return structuredClone(doc);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Classify a failed disk read.
|
|
120
|
+
*
|
|
121
|
+
* `ENOENT` is the clean default: the document does not exist yet, so nobody
|
|
122
|
+
* has been configured in and there is nothing to report. Every other failure
|
|
123
|
+
* (permissions, I/O, a directory where a file is expected) is a genuine
|
|
124
|
+
* degraded read and keeps `ERR_SCOPE_READ_FAILED`.
|
|
125
|
+
*/
|
|
126
|
+
function readFailed(error) {
|
|
127
|
+
if (errorCode(error) === 'ENOENT') {
|
|
128
|
+
return { ok: false, missing: true, doc: cloneDoc(DEFAULT_SCOPE) };
|
|
129
|
+
}
|
|
130
|
+
return {
|
|
131
|
+
ok: false,
|
|
132
|
+
missing: false,
|
|
133
|
+
doc: cloneDoc(DEFAULT_SCOPE),
|
|
134
|
+
code: ERR_SCOPE_READ_FAILED,
|
|
135
|
+
cause: error,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/** Decode one already-read `scope.json`; JSON errors are parse failures too. */
|
|
139
|
+
function decode(text, mtimeMs) {
|
|
140
|
+
let raw;
|
|
141
|
+
try {
|
|
142
|
+
raw = JSON.parse(text);
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
return {
|
|
146
|
+
ok: false,
|
|
147
|
+
doc: cloneDoc(DEFAULT_SCOPE),
|
|
148
|
+
code: ERR_SCOPE_PARSE_FAILED,
|
|
149
|
+
missing: false,
|
|
150
|
+
cause: error,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
const parsed = parseScope(raw);
|
|
154
|
+
if (parsed.code !== undefined) {
|
|
155
|
+
// A v1 document is read-only-degraded, but the explicit upgrade rewrites
|
|
156
|
+
// its recognised fields rather than resetting them to DEFAULT_SCOPE
|
|
157
|
+
// (review row 38). `parseVersionOneScope` is deliberately not applied to
|
|
158
|
+
// the read path.
|
|
159
|
+
const upgrade = parseVersionOneScope(raw);
|
|
160
|
+
return {
|
|
161
|
+
ok: false,
|
|
162
|
+
doc: parsed.doc,
|
|
163
|
+
code: parsed.code,
|
|
164
|
+
missing: false,
|
|
165
|
+
...(upgrade === undefined ? {} : { upgrade }),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
return { ok: true, doc: parsed.doc, mtimeMs, text };
|
|
169
|
+
}
|
|
170
|
+
export class ScopeStore {
|
|
171
|
+
dir;
|
|
172
|
+
file;
|
|
173
|
+
lockFile;
|
|
174
|
+
lockStaleMs;
|
|
175
|
+
lockTakeoverMs;
|
|
176
|
+
now;
|
|
177
|
+
warn;
|
|
178
|
+
cached;
|
|
179
|
+
lockOwner;
|
|
180
|
+
judgements = new Map();
|
|
181
|
+
constructor(dir, options = {}) {
|
|
182
|
+
this.dir = dir;
|
|
183
|
+
this.file = join(dir, SCOPE_FILE);
|
|
184
|
+
this.lockFile = join(dir, LOCK_FILE);
|
|
185
|
+
this.lockStaleMs = options.lockStaleMs ?? LOCK_STALE_MS;
|
|
186
|
+
this.lockTakeoverMs = options.lockTakeoverMs ?? LOCK_TAKEOVER_MS;
|
|
187
|
+
this.now = options.now ?? Date.now;
|
|
188
|
+
this.warn = options.warn ?? ((message) => process.emitWarning(message));
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Read the current document. Never throws and never writes: every stat,
|
|
192
|
+
* read, JSON or shape failure comes back as a fresh `DEFAULT_SCOPE` plus
|
|
193
|
+
* `degraded: 'scope-degraded'` and the stable code.
|
|
194
|
+
*/
|
|
195
|
+
async read() {
|
|
196
|
+
const result = await this.readDisk();
|
|
197
|
+
if (!result.ok) {
|
|
198
|
+
// Ruling 1: a degraded document is never a cache entry. The next call
|
|
199
|
+
// must retry the disk instead of serving the strict default forever.
|
|
200
|
+
this.cached = undefined;
|
|
201
|
+
// A missing file is the clean default (revision 0, no degraded code);
|
|
202
|
+
// a genuine failure keeps its stable code.
|
|
203
|
+
if (result.missing)
|
|
204
|
+
return { doc: cloneDoc(result.doc) };
|
|
205
|
+
return { doc: cloneDoc(result.doc), degraded: 'scope-degraded', code: result.code };
|
|
206
|
+
}
|
|
207
|
+
// On a cache hit `result.doc` is the cached object (identical bytes);
|
|
208
|
+
// either way the caller gets a copy, so a mutation cannot poison it.
|
|
209
|
+
this.cached = { mtimeMs: result.mtimeMs, text: result.text, doc: result.doc };
|
|
210
|
+
return { doc: cloneDoc(result.doc) };
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Compare-and-swap write. Returns the new document (revision `baseRevision + 1`,
|
|
214
|
+
* `updatedAt` now) and leaves it cached.
|
|
215
|
+
*
|
|
216
|
+
* A missing file is a first write: the base is `DEFAULT_SCOPE` at revision 0,
|
|
217
|
+
* so it succeeds only when the caller passes 0. A corrupt or version 1 file
|
|
218
|
+
* is also based on the strict default, which is how `boost scope set`
|
|
219
|
+
* explicitly upgrades a version 1 document. A **future** version (a numeric
|
|
220
|
+
* version greater than 2) is refused with `ERR_SCOPE_FUTURE_VERSION` before
|
|
221
|
+
* the mutation: the newer field set cannot be represented here, so rewriting
|
|
222
|
+
* it would silently drop configuration. An existing file that cannot be read
|
|
223
|
+
* at all is `ERR_SCOPE_READ_FAILED` — never overwritten blindly.
|
|
224
|
+
*/
|
|
225
|
+
async write(mutate, baseRevision, options = {}) {
|
|
226
|
+
const signal = options.signal;
|
|
227
|
+
checkAbort(signal);
|
|
228
|
+
await this.ensureDirectory();
|
|
229
|
+
checkAbort(signal);
|
|
230
|
+
await this.acquireLock(signal);
|
|
231
|
+
try {
|
|
232
|
+
checkAbort(signal);
|
|
233
|
+
const current = this.readDiskSync();
|
|
234
|
+
checkAbort(signal);
|
|
235
|
+
let base;
|
|
236
|
+
if (current.ok) {
|
|
237
|
+
base = current.doc;
|
|
238
|
+
}
|
|
239
|
+
else if (current.missing) {
|
|
240
|
+
// A first write starts from the strict default at revision 0.
|
|
241
|
+
base = current.doc;
|
|
242
|
+
}
|
|
243
|
+
else {
|
|
244
|
+
if (current.code === ERR_SCOPE_FUTURE_VERSION) {
|
|
245
|
+
throw scopeError(ERR_SCOPE_FUTURE_VERSION, `refusing to rewrite ${this.file}: it declares a newer scope version`);
|
|
246
|
+
}
|
|
247
|
+
if (current.code === ERR_SCOPE_READ_FAILED) {
|
|
248
|
+
const detail = current.cause === undefined ? 'unknown read error' : messageOf(current.cause);
|
|
249
|
+
throw scopeError(ERR_SCOPE_READ_FAILED, `cannot read ${this.file}: ${detail}`);
|
|
250
|
+
}
|
|
251
|
+
// A v1 file was read as DEFAULT_SCOPE at revision 0, but its recognised
|
|
252
|
+
// fields are the user's configuration: base the upgrade on those so a
|
|
253
|
+
// partial `scope-set` cannot silently drop `global`/`workspaceIds`.
|
|
254
|
+
base = current.upgrade ?? current.doc;
|
|
255
|
+
}
|
|
256
|
+
if (base.revision !== baseRevision) {
|
|
257
|
+
throw scopeError(ERR_SCOPE_REVISION_CONFLICT, `base revision ${baseRevision} does not match ${base.revision}`);
|
|
258
|
+
}
|
|
259
|
+
const doc = {
|
|
260
|
+
...mutate(base),
|
|
261
|
+
revision: baseRevision + 1,
|
|
262
|
+
updatedAt: new Date().toISOString(),
|
|
263
|
+
};
|
|
264
|
+
checkAbort(signal);
|
|
265
|
+
let written;
|
|
266
|
+
try {
|
|
267
|
+
written = this.writeAtomic(doc);
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
// Serialization and disk failures are storage failures too; rule 8
|
|
271
|
+
// requires a stable code on every error the write path raises.
|
|
272
|
+
throw scopeError(ERR_SCOPE_READ_FAILED, `cannot write ${this.file}: ${messageOf(error)}`);
|
|
273
|
+
}
|
|
274
|
+
// Clone before caching: `doc` may still share arrays with an object the
|
|
275
|
+
// caller (or `mutate`) holds, and the cache must never alias those.
|
|
276
|
+
this.cached = { mtimeMs: written.mtimeMs, text: written.text, doc: cloneDoc(doc) };
|
|
277
|
+
return cloneDoc(doc);
|
|
278
|
+
}
|
|
279
|
+
finally {
|
|
280
|
+
this.releaseLock();
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
/** Cache one agent's visibility judgement; the only writer of this cache. */
|
|
284
|
+
remember(key, visible) {
|
|
285
|
+
this.judgements.set(key, visible);
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Drop one session's cached judgement on session disposal.
|
|
289
|
+
*
|
|
290
|
+
* The judgement map is per session and otherwise lives as long as the plugin;
|
|
291
|
+
* without this a process that served many sessions would retain one boolean
|
|
292
|
+
* (and its string key) per session forever.
|
|
293
|
+
*/
|
|
294
|
+
forget(key) {
|
|
295
|
+
this.judgements.delete(key);
|
|
296
|
+
}
|
|
297
|
+
/** Synchronous per-agent lookup: a miss is `fallback`, and fail-closed is `false`. */
|
|
298
|
+
judgement(key, fallback) {
|
|
299
|
+
return this.judgements.get(key) ?? fallback ?? false;
|
|
300
|
+
}
|
|
301
|
+
/** Async read path: stat + read + decode, all failures degraded. */
|
|
302
|
+
async readDisk() {
|
|
303
|
+
try {
|
|
304
|
+
const stats = await stat(this.file);
|
|
305
|
+
const text = await readFile(this.file, 'utf8');
|
|
306
|
+
return this.decodeFromCache(text, stats.mtimeMs);
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
return readFailed(error);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Reuse the previous parse only when the exact bytes and mtime were already
|
|
314
|
+
* parsed. Byte identity is a stronger key than mtime+revision: an external
|
|
315
|
+
* edit that keeps both cannot be served from the old parse.
|
|
316
|
+
*/
|
|
317
|
+
decodeFromCache(text, mtimeMs) {
|
|
318
|
+
const cached = this.cached;
|
|
319
|
+
if (cached !== undefined && cached.mtimeMs === mtimeMs && cached.text === text) {
|
|
320
|
+
return { ok: true, doc: cached.doc, mtimeMs, text };
|
|
321
|
+
}
|
|
322
|
+
return decode(text, mtimeMs);
|
|
323
|
+
}
|
|
324
|
+
/** Sync read path, used only inside the write lock (see the module comment). */
|
|
325
|
+
readDiskSync() {
|
|
326
|
+
try {
|
|
327
|
+
const stats = statSync(this.file);
|
|
328
|
+
const text = readFileSync(this.file, 'utf8');
|
|
329
|
+
return decode(text, stats.mtimeMs);
|
|
330
|
+
}
|
|
331
|
+
catch (error) {
|
|
332
|
+
return readFailed(error);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
/** The write path must be able to create `<root>/boost` on a fresh install. */
|
|
336
|
+
async ensureDirectory() {
|
|
337
|
+
try {
|
|
338
|
+
await mkdir(this.dir, { recursive: true });
|
|
339
|
+
}
|
|
340
|
+
catch (error) {
|
|
341
|
+
throw scopeError(ERR_SCOPE_READ_FAILED, `cannot create ${this.dir}: ${messageOf(error)}`);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Take the write lock, reclaiming a stale lock at most once.
|
|
346
|
+
*
|
|
347
|
+
* Two independent staleness rules:
|
|
348
|
+
*
|
|
349
|
+
* 1. dead-owner reclaim — older than `lockStaleMs` **and** the recorded pid is
|
|
350
|
+
* dead (or unrecorded/unparseable/out of pid range);
|
|
351
|
+
* 2. bounded takeover — the lock's `startedAt` (falling back to mtime) is
|
|
352
|
+
* older than `lockTakeoverMs`, **even when its pid is alive**. A pid is
|
|
353
|
+
* reused after a crash, so rule 1 alone can leave `scope.lock` held for the
|
|
354
|
+
* whole process lifetime in a container. The hold window is one small
|
|
355
|
+
* synchronous write, so a lock this old is a crashed writer.
|
|
356
|
+
*
|
|
357
|
+
* The takeover re-reads the lock immediately before unlinking and refuses if
|
|
358
|
+
* its bytes or mtime changed, which narrows the cross-process race. Two
|
|
359
|
+
* writers can still judge the same lock stale; `releaseLock` only removes a
|
|
360
|
+
* lock whose content it wrote, and the CAS revision check still refuses to
|
|
361
|
+
* merge divergent writes, so the residual race cannot corrupt the document.
|
|
362
|
+
*
|
|
363
|
+
* When that first read finds **no** lock there is nothing to compare against,
|
|
364
|
+
* so the reclaim is refused with `ERR_SCOPE_LOCKED`. `createLock` already saw
|
|
365
|
+
* the file exist; a lock created between that failure and the read is
|
|
366
|
+
* indistinguishable from one a live writer still owns, and unlinking it
|
|
367
|
+
* would lose that writer's update. Refusing is safe (the caller retries) and
|
|
368
|
+
* the alternative is the one case the changed-lock guard cannot cover.
|
|
369
|
+
*/
|
|
370
|
+
async acquireLock(signal) {
|
|
371
|
+
checkAbort(signal);
|
|
372
|
+
if (await this.createLock()) {
|
|
373
|
+
// `createLock` is the one await that can leave a lock behind; an abort
|
|
374
|
+
// observed after it returns must release it, not strand it.
|
|
375
|
+
if (signal?.aborted === true) {
|
|
376
|
+
this.releaseLock();
|
|
377
|
+
throw abortedError();
|
|
378
|
+
}
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
checkAbort(signal);
|
|
382
|
+
const first = this.readLock();
|
|
383
|
+
const decision = this.classifyLock(first);
|
|
384
|
+
if (decision === 'held') {
|
|
385
|
+
throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} is held by another writer`);
|
|
386
|
+
}
|
|
387
|
+
if (decision === 'missing') {
|
|
388
|
+
throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} existed for createLock but vanished before it could be inspected; another writer may hold it now`);
|
|
389
|
+
}
|
|
390
|
+
if (decision === 'takeover') {
|
|
391
|
+
this.warn(`${ERR_SCOPE_LOCK_TAKEOVER}: taking over ${this.lockFile} from pid ${first?.pid ?? 'unknown'} after ${Math.round(this.ageOf(first) / 1000)}s; the recording process may have crashed and its pid been reused`);
|
|
392
|
+
}
|
|
393
|
+
// Re-read before the unlink: a writer that replaced the lock between the
|
|
394
|
+
// decision and here must not be evicted on a stale observation.
|
|
395
|
+
const again = this.readLock();
|
|
396
|
+
if (again !== undefined && first !== undefined) {
|
|
397
|
+
if (again.text !== first.text || again.mtimeMs !== first.mtimeMs) {
|
|
398
|
+
throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} changed while being reclaimed`);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
try {
|
|
402
|
+
unlinkSync(this.lockFile);
|
|
403
|
+
}
|
|
404
|
+
catch (error) {
|
|
405
|
+
if (errorCode(error) !== 'ENOENT') {
|
|
406
|
+
throw scopeError(ERR_SCOPE_LOCKED, `cannot reclaim ${this.lockFile}: ${messageOf(error)}`);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
if (!(await this.createLock())) {
|
|
410
|
+
throw scopeError(ERR_SCOPE_LOCKED, `${this.lockFile} is held by another writer`);
|
|
411
|
+
}
|
|
412
|
+
if (signal?.aborted === true) {
|
|
413
|
+
this.releaseLock();
|
|
414
|
+
throw abortedError();
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
/** `open(lock, 'wx')`; false means another writer holds it. */
|
|
418
|
+
async createLock() {
|
|
419
|
+
let handle;
|
|
420
|
+
try {
|
|
421
|
+
handle = await open(this.lockFile, 'wx');
|
|
422
|
+
}
|
|
423
|
+
catch (error) {
|
|
424
|
+
if (errorCode(error) === 'EEXIST')
|
|
425
|
+
return false;
|
|
426
|
+
throw scopeError(ERR_SCOPE_LOCKED, `cannot create ${this.lockFile}: ${messageOf(error)}`);
|
|
427
|
+
}
|
|
428
|
+
const content = JSON.stringify({
|
|
429
|
+
pid: process.pid,
|
|
430
|
+
startedAt: this.now(),
|
|
431
|
+
nonce: BOOT_NONCE,
|
|
432
|
+
});
|
|
433
|
+
let failure;
|
|
434
|
+
try {
|
|
435
|
+
await handle.writeFile(content);
|
|
436
|
+
}
|
|
437
|
+
catch (error) {
|
|
438
|
+
failure = error;
|
|
439
|
+
}
|
|
440
|
+
finally {
|
|
441
|
+
await handle.close().catch(() => { });
|
|
442
|
+
}
|
|
443
|
+
if (failure !== undefined) {
|
|
444
|
+
// A lock without owner data would block for the stale timeout; remove
|
|
445
|
+
// what we created.
|
|
446
|
+
await unlink(this.lockFile).catch(() => { });
|
|
447
|
+
throw scopeError(ERR_SCOPE_LOCKED, `cannot write ${this.lockFile}: ${messageOf(failure)}`);
|
|
448
|
+
}
|
|
449
|
+
this.lockOwner = content;
|
|
450
|
+
return true;
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* One read of the lock: bytes, mtime and the owner fields they record.
|
|
454
|
+
*
|
|
455
|
+
* `undefined` means absent (the `EEXIST` raced a release): the caller may
|
|
456
|
+
* retry the create. An unreadable-but-present lock is returned with the mtime
|
|
457
|
+
* and no owner fields, so it becomes reclaimable only after the dead-pid
|
|
458
|
+
* timeout — never immediately, because an unreadable live lock must not be
|
|
459
|
+
* evicted on a guess.
|
|
460
|
+
*/
|
|
461
|
+
readLock() {
|
|
462
|
+
let mtimeMs;
|
|
463
|
+
try {
|
|
464
|
+
mtimeMs = statSync(this.lockFile).mtimeMs;
|
|
465
|
+
}
|
|
466
|
+
catch {
|
|
467
|
+
return undefined;
|
|
468
|
+
}
|
|
469
|
+
let text;
|
|
470
|
+
try {
|
|
471
|
+
text = readFileSync(this.lockFile, 'utf8');
|
|
472
|
+
}
|
|
473
|
+
catch {
|
|
474
|
+
return { text: '', mtimeMs };
|
|
475
|
+
}
|
|
476
|
+
let parsed;
|
|
477
|
+
try {
|
|
478
|
+
parsed = JSON.parse(text);
|
|
479
|
+
}
|
|
480
|
+
catch {
|
|
481
|
+
return { text, mtimeMs };
|
|
482
|
+
}
|
|
483
|
+
const record = typeof parsed === 'object' && parsed !== null ? parsed : {};
|
|
484
|
+
const pid = record.pid;
|
|
485
|
+
const startedAt = record.startedAt;
|
|
486
|
+
return {
|
|
487
|
+
text,
|
|
488
|
+
mtimeMs,
|
|
489
|
+
...(typeof pid === 'number' && Number.isInteger(pid) && pid > 0 && pid <= MAX_PID ? { pid } : {}),
|
|
490
|
+
...(typeof startedAt === 'number' && Number.isFinite(startedAt) && startedAt > 0 && startedAt <= this.now()
|
|
491
|
+
? { startedAt }
|
|
492
|
+
: {}),
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
/** Age from `startedAt` when it is usable, otherwise from the file's mtime. */
|
|
496
|
+
ageOf(lock) {
|
|
497
|
+
if (lock === undefined)
|
|
498
|
+
return 0;
|
|
499
|
+
return Math.max(0, this.now() - (lock.startedAt ?? lock.mtimeMs));
|
|
500
|
+
}
|
|
501
|
+
/** Whether the lock is reclaimable, and whether that decision needs a warning. */
|
|
502
|
+
classifyLock(lock) {
|
|
503
|
+
if (lock === undefined)
|
|
504
|
+
return 'missing';
|
|
505
|
+
const age = this.ageOf(lock);
|
|
506
|
+
if (age <= this.lockStaleMs)
|
|
507
|
+
return 'held';
|
|
508
|
+
if (age >= this.lockTakeoverMs)
|
|
509
|
+
return 'takeover';
|
|
510
|
+
return lock.pid === undefined || !isProcessAlive(lock.pid) ? 'dead' : 'held';
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Remove the lock only if it still contains exactly what this acquisition
|
|
514
|
+
* wrote. An unconditional unlink would delete a replacement lock another
|
|
515
|
+
* writer created after a stale-reclaim race. Every error is swallowed:
|
|
516
|
+
* cleanup must never mask the causal error (rule 8), and a lock left behind
|
|
517
|
+
* is reclaimable after 60 s while a masked conflict is not diagnosable.
|
|
518
|
+
*/
|
|
519
|
+
releaseLock() {
|
|
520
|
+
const owner = this.lockOwner;
|
|
521
|
+
this.lockOwner = undefined;
|
|
522
|
+
if (owner === undefined)
|
|
523
|
+
return;
|
|
524
|
+
try {
|
|
525
|
+
if (readFileSync(this.lockFile, 'utf8') === owner)
|
|
526
|
+
unlinkSync(this.lockFile);
|
|
527
|
+
}
|
|
528
|
+
catch {
|
|
529
|
+
// See the method comment: cleanup never rethrows.
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Serialize `doc` into a temporary file, fsync it, and rename it over
|
|
534
|
+
* `scope.json`. Returns the stored file's mtime and the exact text written
|
|
535
|
+
* (for the cache). A failed write removes the temporary file; the caller's
|
|
536
|
+
* `finally` removes the lock.
|
|
537
|
+
*/
|
|
538
|
+
writeAtomic(doc) {
|
|
539
|
+
const tempFile = join(this.dir, `.${SCOPE_FILE}.${process.pid}.${randomUUID()}.tmp`);
|
|
540
|
+
const text = `${JSON.stringify(doc)}\n`;
|
|
541
|
+
let fd;
|
|
542
|
+
try {
|
|
543
|
+
fd = openSync(tempFile, 'w');
|
|
544
|
+
writeFileSync(fd, text);
|
|
545
|
+
fsyncSync(fd);
|
|
546
|
+
closeSync(fd);
|
|
547
|
+
fd = undefined;
|
|
548
|
+
// Stat before the rename: if this fails nothing has touched `scope.json`,
|
|
549
|
+
// and the mtime of the inode is what `read()` will observe afterwards.
|
|
550
|
+
const mtimeMs = statSync(tempFile).mtimeMs;
|
|
551
|
+
renameSync(tempFile, this.file);
|
|
552
|
+
return { mtimeMs, text };
|
|
553
|
+
}
|
|
554
|
+
catch (error) {
|
|
555
|
+
if (fd !== undefined) {
|
|
556
|
+
try {
|
|
557
|
+
closeSync(fd);
|
|
558
|
+
}
|
|
559
|
+
catch {
|
|
560
|
+
// Already closed or never opened; the unlink below is what matters.
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
try {
|
|
564
|
+
unlinkSync(tempFile);
|
|
565
|
+
}
|
|
566
|
+
catch {
|
|
567
|
+
// Best effort: the temporary file may not exist if openSync failed.
|
|
568
|
+
}
|
|
569
|
+
throw error;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
//# sourceMappingURL=store.js.map
|
|
@@ -0,0 +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,2BAA2B,EAC3B,UAAU,EACV,oBAAoB,GACrB,MAAM,UAAU,CAAA;AAGjB,MAAM,UAAU,GAAG,YAAY,CAAA;AAC/B,MAAM,SAAS,GAAG,YAAY,CAAA;AAC9B,0FAA0F;AAC1F,MAAM,aAAa,GAAG,MAAM,CAAA;AAC5B;;;;;;;;GAQG;AACH,MAAM,gBAAgB,GAAG,EAAE,GAAG,aAAa,CAAA;AAC3C,qEAAqE;AACrE,MAAM,OAAO,GAAG,aAAa,CAAA;AAC7B,yEAAyE;AACzE,MAAM,CAAC,MAAM,uBAAuB,GA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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 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 corrupt or version 1 file\n * is also based on the strict default, which is how `boost scope set`\n * explicitly upgrades a version 1 document. A **future** version (a numeric\n * version greater than 2) is refused with `ERR_SCOPE_FUTURE_VERSION` before\n * the mutation: the newer field set cannot be represented here, so rewriting\n * it would silently drop configuration. An existing file that cannot be read\n * at all is `ERR_SCOPE_READ_FAILED` — never overwritten blindly.\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 // 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 ?? current.doc\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"]}
|