dsh-taskbridge 0.0.0-stage → 1.3.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.
Files changed (74) hide show
  1. package/CHANGELOG.md +754 -0
  2. package/LICENSE +21 -0
  3. package/README.md +624 -3
  4. package/bin/dsh-delegate-codex-agent.js +115 -0
  5. package/bin/dsh-delegate-control.d.ts +90 -0
  6. package/bin/dsh-delegate-control.js +450 -0
  7. package/bin/dsh-delegate-mcp.d.ts +121 -0
  8. package/bin/dsh-delegate-mcp.js +273 -0
  9. package/codex/dsh-delegate.toml +245 -0
  10. package/cordis.patch.yml +6 -0
  11. package/docs/INTRODUCTION.md +15 -0
  12. package/docs/INTRODUCTION.zh.md +32 -0
  13. package/docs/auth-contract.md +138 -0
  14. package/docs/claude-code.md +31 -0
  15. package/docs/codex-integration.md +922 -0
  16. package/docs/contracts-stage-b.md +443 -0
  17. package/docs/conversation-placement.md +293 -0
  18. package/docs/plugin-market.md +30 -0
  19. package/docs/redaction-contract.md +127 -0
  20. package/docs/runtime-compatibility.md +220 -0
  21. package/docs/silent-wait.md +191 -0
  22. package/docs/taskbridge-upgrade.md +28 -0
  23. package/docs/taskdispatch-upgrade.md +25 -0
  24. package/docs/worker-permissions.md +347 -0
  25. package/docs/workspace-contract.md +538 -0
  26. package/icon.svg +1 -0
  27. package/lib/client.d.ts +118 -0
  28. package/lib/client.js +3232 -0
  29. package/locale/en.json +7 -0
  30. package/locale/zh.json +7 -0
  31. package/package.json +135 -4
  32. package/src/auth/fence.js +361 -0
  33. package/src/auth/grants.js +789 -0
  34. package/src/client/api.js +2322 -0
  35. package/src/client/index.jsx +2333 -0
  36. package/src/client/styles.js +251 -0
  37. package/src/codex/installer.js +3260 -0
  38. package/src/codex/seam.js +429 -0
  39. package/src/codex/toml.js +784 -0
  40. package/src/config/defaults.js +164 -0
  41. package/src/config/redact.js +184 -0
  42. package/src/config/settings.js +629 -0
  43. package/src/config/store.js +186 -0
  44. package/src/config/validate.js +763 -0
  45. package/src/credentials/seam.js +202 -0
  46. package/src/http/execution-plane.js +454 -0
  47. package/src/http/respond.js +175 -0
  48. package/src/http/user-plane.js +1122 -0
  49. package/src/index.d.ts +332 -0
  50. package/src/index.js +657 -0
  51. package/src/jobs/activity.js +1008 -0
  52. package/src/jobs/engine.js +3609 -0
  53. package/src/jobs/history.js +1467 -0
  54. package/src/mcp/server.js +1820 -0
  55. package/src/mcp/wait.js +536 -0
  56. package/src/model/connectivity.js +371 -0
  57. package/src/model/discovery.js +582 -0
  58. package/src/model/native-catalog.js +68 -0
  59. package/src/model/openai-adapter.js +671 -0
  60. package/src/model/probe.js +264 -0
  61. package/src/model/providers.js +756 -0
  62. package/src/model/routing.js +321 -0
  63. package/src/review/preset.js +868 -0
  64. package/src/review/prompts.js +126 -0
  65. package/src/review/reviewer.js +933 -0
  66. package/src/runtime/agent-runner.js +1738 -0
  67. package/src/runtime/endpoint-discovery.js +118 -0
  68. package/src/runtime/permissions.js +1429 -0
  69. package/src/runtime/sandbox.js +358 -0
  70. package/src/runtime/session-placement.js +1103 -0
  71. package/src/workspace/audit.js +775 -0
  72. package/src/workspace/locks.js +167 -0
  73. package/src/workspace/preflight.js +424 -0
  74. package/src/workspace/worktrees.js +613 -0
@@ -0,0 +1,1467 @@
1
+ // Bounded durable job history.
2
+ //
3
+ // What may be stored is decided by explicit projection, not by whatever the
4
+ // caller happens to hold. `projectView` allow-lists the public fields a job view
5
+ // may contribute; every string passes `redactText`, the whole projection passes
6
+ // `redactDeep`, and the result is fitted to `maxEntryBytes`. Authorization
7
+ // handles (grant id, grant kind), prompts, native agent/session ids and
8
+ // controller state are deliberately absent: a restart cannot resume anything
9
+ // from this file, so nothing in it may look resumable.
10
+ //
11
+ // Two conditions are refusals rather than repairs:
12
+ //
13
+ // * A document that is not valid JSON, or carries an unknown `schemaVersion`, is
14
+ // refused and the file is left exactly as found. Later saves refuse too, so
15
+ // nothing overwrites a document the operator may still want to inspect.
16
+ // * A limit that cannot be met by evicting a terminal record is refused. A live
17
+ // (pending/running) job is never silently dropped.
18
+ //
19
+ // On load, `pending`/`running` records become `interrupted` with
20
+ // `error.code = JOB_INTERRUPTED_RESTART`. They are never resubmitted, and the
21
+ // authorization that once covered them is not restored.
22
+
23
+ import { randomBytes } from 'node:crypto';
24
+ import * as nodeFs from 'node:fs/promises';
25
+ import { dirname, join } from 'node:path';
26
+
27
+ import { redactDeep } from '../config/redact.js';
28
+
29
+ /** Persisted document format version. Unknown versions are refused, never migrated. */
30
+ const SCHEMA_VERSION = 1;
31
+
32
+ /** Document file name inside the plugin data directory. */
33
+ const HISTORY_FILE = 'history.json';
34
+
35
+ /** Default bounds. */
36
+ const DEFAULT_LIMITS = Object.freeze({
37
+ maxEntries: 200,
38
+ maxBytes: 8 * 1024 * 1024,
39
+ maxEntryBytes: 256 * 1024,
40
+ });
41
+
42
+ /** Below this an entry cannot even carry an empty job record. */
43
+ const MIN_ENTRY_BYTES = 4096;
44
+
45
+ /** Room held back for the `truncation` block so fitting never overruns. */
46
+ const FIT_RESERVE = 512;
47
+
48
+ /** Appended to any string this module had to cut. */
49
+ const TRUNCATION_MARK = '… [truncated]';
50
+
51
+ const MAX_PATH_CHARS = 4096;
52
+ const MAX_LABEL_CHARS = 256;
53
+ const MAX_MESSAGE_CHARS = 4096;
54
+ const MAX_DETAIL_STRING_CHARS = 512;
55
+ const MAX_TEXT_CHARS = 64 * 1024;
56
+ const MAX_LIST_ITEMS = 500;
57
+ const MAX_DETAIL_KEYS = 32;
58
+ const MAX_DETAIL_DEPTH = 4;
59
+ const MAX_TRUNCATION_ITEMS = 12;
60
+ const MIN_DOCUMENT_BYTES = 64 * 1024;
61
+ const MAX_SAFE_TIMESTAMP = 8.64e15;
62
+
63
+ /** States this module understands. `interrupted` is produced only by history. */
64
+ const KNOWN_STATES = new Set(['pending', 'running', 'awaiting-host-review', 'failed', 'cancelled', 'interrupted']);
65
+
66
+ /** States that occupy a slot in the running engine and must never be evicted. */
67
+ const LIVE_STATES = new Set(['pending', 'running']);
68
+
69
+ /** Stable refusal codes. Each one means "nothing was written". */
70
+ export const HISTORY_CODES = Object.freeze({
71
+ unreadable: 'HISTORY_UNREADABLE',
72
+ fileTooLarge: 'HISTORY_FILE_TOO_LARGE',
73
+ malformed: 'HISTORY_MALFORMED',
74
+ schemaUnsupported: 'HISTORY_SCHEMA_UNSUPPORTED',
75
+ viewInvalid: 'HISTORY_VIEW_INVALID',
76
+ entryTooLarge: 'HISTORY_ENTRY_TOO_LARGE',
77
+ limitExceeded: 'HISTORY_LIMIT_EXCEEDED',
78
+ writeFailed: 'HISTORY_WRITE_FAILED',
79
+ disposed: 'HISTORY_DISPOSED',
80
+ });
81
+
82
+ /** Windows rename races are transient: retry them briefly before refusing. */
83
+ const WINDOWS_TRANSIENT_RENAME = new Set(['EACCES', 'EBUSY', 'EPERM']);
84
+
85
+ /** Raised for every history refusal. `details` is bounded and secret-free. */
86
+ export class HistoryError extends Error {
87
+ /**
88
+ * @param {string} code - stable machine code.
89
+ * @param {string} message - operator-readable explanation.
90
+ * @param {object} [details] - bounded, non-secret context.
91
+ */
92
+ constructor(code, message, details = {}) {
93
+ super(message);
94
+ this.name = 'HistoryError';
95
+ this.code = code;
96
+ this.details = details;
97
+ }
98
+ }
99
+
100
+ /** Fields that may be long enough to need cutting to fit the entry budget. */
101
+ const TEXT_PATHS = [
102
+ ['diff', 'patchText'],
103
+ ['execution', 'text'],
104
+ ['review', 'text'],
105
+ ['error', 'message'],
106
+ ['execution', 'error'],
107
+ ['review', 'error', 'message'],
108
+ ['reviewRouteError', 'message'],
109
+ ];
110
+
111
+ /** Arrays that may be shrunk when an entry does not fit. */
112
+ const ARRAY_PATHS = [
113
+ ['diff', 'files'],
114
+ ['diff', 'changes'],
115
+ ['diff', 'sensitivePaths'],
116
+ ['baseline', 'preexistingPaths'],
117
+ ['review', 'denials'],
118
+ ['permission', 'evidence'],
119
+ ['permission', 'pending', 'boundsApplied'],
120
+ ['permission', 'pending', 'argumentKeys'],
121
+ ];
122
+
123
+ /** Whole blocks dropped, in order, only when an entry still does not fit. */
124
+ const DROP_PATHS = [
125
+ ['worktree'],
126
+ ['baseline'],
127
+ ['diff', 'changes'],
128
+ ['diff', 'files'],
129
+ ['diff', 'sensitivePaths'],
130
+ ['review', 'denials'],
131
+ ['execution', 'turnEnd'],
132
+ ['review', 'selection'],
133
+ ['effective', 'provenance'],
134
+ ['permission', 'evidence'],
135
+ ];
136
+
137
+ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
138
+
139
+ /**
140
+ * How many settled permission decisions one stored task record keeps.
141
+ *
142
+ * Small on purpose: this is human evidence ("what did the commander decide, and
143
+ * why"), not an audit log, and an unbounded trail would let one noisy run push
144
+ * every other field out of the entry budget.
145
+ */
146
+ const MAX_PERMISSION_EVIDENCE = 8;
147
+
148
+ /**
149
+ * How many distinct activity kinds one stored record keeps counts for.
150
+ *
151
+ * The live classifier owns a closed vocabulary far smaller than this, so the cap
152
+ * only ever bounds a document written by a FUTURE build that learned more kinds —
153
+ * a stored record must never be able to grow with model output, and the count map
154
+ * is the one field keyed by something other than a fixed name.
155
+ */
156
+ const MAX_ACTIVITY_KINDS = 24;
157
+
158
+ /**
159
+ * One bounded, versioned job history document.
160
+ *
161
+ * Writes are serialized through an internal queue and land through a temp file
162
+ * plus rename, so a concurrent save cannot lose an earlier one and a crash leaves
163
+ * either the old or the new complete document. Each method returns detached data:
164
+ * mutating a returned view cannot reach the stored document.
165
+ */
166
+ export class HistoryStore {
167
+ /**
168
+ * @param {string} dataDir - plugin data directory.
169
+ * @param {object} [options] - `maxEntries`, `maxBytes`, `maxEntryBytes`, and an
170
+ * optional test-only `fs` seam (`stat`, `readFile`, `writeFile`, `rename`,
171
+ * `mkdir`, `rm`).
172
+ */
173
+ constructor(dataDir, options = {}) {
174
+ if (typeof dataDir !== 'string' || dataDir.trim() === '') {
175
+ throw new TypeError('HistoryStore needs a data directory');
176
+ }
177
+ const limits = { ...DEFAULT_LIMITS };
178
+ for (const key of Object.keys(DEFAULT_LIMITS)) {
179
+ const value = options[key];
180
+ if (value === undefined) continue;
181
+ if (!Number.isSafeInteger(value) || value <= 0) throw new TypeError(`${key} must be a positive integer`);
182
+ limits[key] = value;
183
+ }
184
+ if (limits.maxEntryBytes < MIN_ENTRY_BYTES) {
185
+ throw new TypeError(`maxEntryBytes must be at least ${MIN_ENTRY_BYTES}`);
186
+ }
187
+ if (limits.maxBytes < limits.maxEntryBytes) {
188
+ throw new TypeError('maxBytes must be at least maxEntryBytes');
189
+ }
190
+
191
+ this.dir = dataDir;
192
+ this.path = join(dataDir, HISTORY_FILE);
193
+ this.maxEntries = limits.maxEntries;
194
+ this.maxBytes = limits.maxBytes;
195
+ this.maxEntryBytes = limits.maxEntryBytes;
196
+ // The document adds a small envelope plus one separator per entry; this read
197
+ // bound leaves room for both and for a hand-edited file.
198
+ this.maxDocumentBytes = Math.max(limits.maxBytes * 2, MIN_DOCUMENT_BYTES);
199
+ this.fs = options.fs ?? nodeFs;
200
+
201
+ this.jobs = null;
202
+ this.loading = null;
203
+ this.refusal = null;
204
+ this.queue = Promise.resolve();
205
+ this.disposed = false;
206
+ }
207
+
208
+ /**
209
+ * Read the stored views, newest first.
210
+ *
211
+ * Idempotent: the first call reads and normalizes, later calls return detached
212
+ * copies of the same data. A missing file is an empty history. A refused
213
+ * document leaves the file untouched and makes every later call refuse alike.
214
+ * @returns {Promise<object[]>} detached, redacted public views, newest first.
215
+ */
216
+ async load() {
217
+ const jobs = await this.ensureLoaded();
218
+ return jobs.slice().reverse().map((job) => structuredClone(job));
219
+ }
220
+
221
+ /**
222
+ * Atomically upsert one public view by `taskId`.
223
+ *
224
+ * The view is projected and bounded before it reaches the document; limits are
225
+ * enforced by evicting the oldest terminal record first. A live view is never
226
+ * evicted, and a limit that cannot be met is refused with nothing written.
227
+ * @param {object} view - public job view.
228
+ * @returns {Promise<object>} detached copy of the stored entry.
229
+ */
230
+ async save(view) {
231
+ if (this.disposed) throw this.disposedError();
232
+ if (this.refusal !== null) this.throwIfRefused();
233
+ const entry = projectView(view, this.maxEntryBytes);
234
+ const run = this.enqueue(async () => {
235
+ this.throwIfRefused();
236
+ const base = await this.ensureLoaded();
237
+ const draft = base.map((job) => structuredClone(job));
238
+ const index = draft.findIndex((job) => job.taskId === entry.taskId);
239
+ if (index >= 0) {
240
+ // A LIVE snapshot may never roll a TERMINAL record back. The engine writes a
241
+ // checkpoint while a task waits for a decision, and that write can land after
242
+ // the run has already finished (or been interrupted at load time). Losing that
243
+ // race must not resurrect a finished task as `running`, so the terminal record
244
+ // wins and the stale checkpoint is discarded instead of stored.
245
+ if (isTerminal(draft[index].state) && !isTerminal(entry.state)) return structuredClone(draft[index]);
246
+ draft[index] = entry;
247
+ } else {
248
+ draft.push(entry);
249
+ }
250
+ draft.sort(compareStored);
251
+ const now = Date.now();
252
+ this.enforceLimits(draft, entry.taskId, now);
253
+ await this.writeDocument(draft, now);
254
+ this.jobs = draft;
255
+ return structuredClone(entry);
256
+ });
257
+ return await run;
258
+ }
259
+
260
+ /**
261
+ * Wait for the in-flight read and every queued write to settle.
262
+ * @returns {Promise<void>} resolves when the document is consistent.
263
+ */
264
+ async flush() {
265
+ if (this.loading !== null) await this.loading.catch(() => undefined);
266
+ await this.queue;
267
+ }
268
+
269
+ /**
270
+ * Flush and refuse every later save.
271
+ * @returns {Promise<void>} resolves after the last queued write lands.
272
+ */
273
+ async dispose() {
274
+ if (this.disposed) return;
275
+ this.disposed = true;
276
+ await this.flush();
277
+ }
278
+
279
+ /**
280
+ * Run one mutation on the write queue. A rejected mutation settles the tail, so
281
+ * one failed write does not poison every later save.
282
+ * @param {() => Promise<object>} work - queued mutation.
283
+ * @returns {Promise<object>} mutation result.
284
+ */
285
+ enqueue(work) {
286
+ const run = this.queue.then(work);
287
+ this.queue = run.then(() => undefined, () => undefined);
288
+ return run;
289
+ }
290
+
291
+ /**
292
+ * Share one physical read between concurrent callers.
293
+ * @returns {Promise<object[]>} stored entries, ascending by creation time.
294
+ */
295
+ async ensureLoaded() {
296
+ if (this.jobs !== null) return this.jobs;
297
+ if (this.refusal !== null) this.throwIfRefused();
298
+ if (this.loading === null) {
299
+ this.loading = this.readOnce().finally(() => { this.loading = null; });
300
+ }
301
+ return await this.loading;
302
+ }
303
+
304
+ /**
305
+ * Perform the single physical read, normalize interrupted jobs, and persist the
306
+ * normalization when the document changed.
307
+ * @returns {Promise<object[]>} stored entries, ascending by creation time.
308
+ */
309
+ async readOnce() {
310
+ let info;
311
+ try {
312
+ info = await this.fs.stat(this.path);
313
+ } catch (error) {
314
+ if (error?.code === 'ENOENT') {
315
+ this.jobs = [];
316
+ return this.jobs;
317
+ }
318
+ throw this.refuse(HISTORY_CODES.unreadable, 'the job history document could not be inspected', {
319
+ cause: typeof error?.code === 'string' ? error.code : 'unknown',
320
+ });
321
+ }
322
+ if (typeof info?.isFile === 'function' && !info.isFile()) {
323
+ throw this.refuse(HISTORY_CODES.unreadable, 'the job history path is not a regular file', {});
324
+ }
325
+ if (Number.isFinite(info?.size) && info.size > this.maxDocumentBytes) {
326
+ throw this.refuse(HISTORY_CODES.fileTooLarge, 'the job history document exceeds the readable bound', {
327
+ bytes: info.size,
328
+ limit: this.maxDocumentBytes,
329
+ });
330
+ }
331
+
332
+ let raw;
333
+ try {
334
+ raw = await this.fs.readFile(this.path, 'utf8');
335
+ } catch (error) {
336
+ throw this.refuse(HISTORY_CODES.unreadable, 'the job history document could not be read', {
337
+ cause: typeof error?.code === 'string' ? error.code : 'unknown',
338
+ });
339
+ }
340
+ if (Buffer.byteLength(raw, 'utf8') > this.maxDocumentBytes) {
341
+ throw this.refuse(HISTORY_CODES.fileTooLarge, 'the job history document exceeds the readable bound', {
342
+ limit: this.maxDocumentBytes,
343
+ });
344
+ }
345
+
346
+ let parsed;
347
+ try {
348
+ parsed = JSON.parse(raw);
349
+ } catch {
350
+ throw this.refuse(HISTORY_CODES.malformed, 'the job history document is not valid JSON', {});
351
+ }
352
+ if (!isPlainObject(parsed)) {
353
+ throw this.refuse(HISTORY_CODES.malformed, 'the job history document is not a JSON object', {});
354
+ }
355
+ if (parsed.schemaVersion !== SCHEMA_VERSION) {
356
+ throw this.refuse(
357
+ HISTORY_CODES.schemaUnsupported,
358
+ 'the job history document uses a schemaVersion this release does not support',
359
+ { schemaVersion: Number.isSafeInteger(parsed.schemaVersion) ? parsed.schemaVersion : 'unknown' },
360
+ );
361
+ }
362
+ if (!Array.isArray(parsed.jobs)) {
363
+ throw this.refuse(HISTORY_CODES.malformed, 'the job history document has no jobs array', {});
364
+ }
365
+
366
+ const stored = parsed.jobs;
367
+ const projected = [];
368
+ for (let index = 0; index < stored.length; index += 1) {
369
+ try {
370
+ projected.push(projectView(stored[index], this.maxEntryBytes));
371
+ } catch (error) {
372
+ // A record that cannot be projected is not repaired by guessing: the whole
373
+ // document is refused, because dropping one record silently loses evidence.
374
+ throw this.refuse(HISTORY_CODES.malformed, 'the job history document contains an unusable job record', {
375
+ index,
376
+ reason: error?.code === HISTORY_CODES.viewInvalid ? 'invalid view' : 'not an object',
377
+ });
378
+ }
379
+ }
380
+
381
+ const now = Date.now();
382
+ const normalized = projected.map((entry) => markInterrupted(entry, now)).sort(compareStored);
383
+
384
+ if (JSON.stringify(stored) !== JSON.stringify(normalized)) {
385
+ // Persist the normalization before claiming it: a later restart must not
386
+ // report the same live jobs again. A failed write is not cached, so a later
387
+ // load retries the read instead of refusing forever.
388
+ await this.writeDocument(normalized, now);
389
+ }
390
+ this.jobs = normalized;
391
+ return this.jobs;
392
+ }
393
+
394
+ /**
395
+ * Replace the document atomically: write a random sibling, then rename over the
396
+ * target. A crash leaves either the old or the new complete document, and a
397
+ * failed write removes its temp file.
398
+ * @param {object[]} jobs - entries, ascending.
399
+ * @param {number} now - update stamp.
400
+ * @returns {Promise<void>} resolves after the rename.
401
+ */
402
+ async writeDocument(jobs, now) {
403
+ const content = `${JSON.stringify({ schemaVersion: SCHEMA_VERSION, updatedAt: now, jobs })}\n`;
404
+ const temp = `${this.path}.${randomBytes(6).toString('hex')}.tmp`;
405
+ try {
406
+ await this.fs.mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
407
+ await this.fs.writeFile(temp, content, { mode: 0o600, flag: 'wx' });
408
+ await renameWithRetry(this.fs, temp, this.path);
409
+ } catch (error) {
410
+ await this.fs.rm(temp, { force: true }).catch(() => undefined);
411
+ throw new HistoryError(HISTORY_CODES.writeFailed, 'the job history document could not be written', {
412
+ cause: typeof error?.code === 'string' ? error.code : 'unknown',
413
+ });
414
+ }
415
+ }
416
+
417
+ /**
418
+ * Enforce `maxEntries` and `maxBytes` on a draft by evicting the oldest terminal
419
+ * record first. The entry just saved is protected, so a save never discards
420
+ * itself silently. Nothing is written when no safe eviction exists.
421
+ * @param {object[]} draft - mutable entry list, ascending.
422
+ * @param {string} protectedId - id of the entry just upserted.
423
+ * @param {number} now - update stamp used for exact byte accounting.
424
+ * @returns {void}
425
+ * @throws {HistoryError} when the bounds cannot be met without dropping a live view.
426
+ */
427
+ enforceLimits(draft, protectedId, now) {
428
+ const slots = draft.map((job) => ({ job, bytes: byteLength(JSON.stringify(job)) }));
429
+ let sum = slots.reduce((total, slot) => total + slot.bytes, 0);
430
+ const envelope = byteLength(JSON.stringify({ schemaVersion: SCHEMA_VERSION, updatedAt: now, jobs: [] }));
431
+ // `jobs: []` contributes two bracket bytes; the real document spends one
432
+ // separator byte between each pair of entries instead.
433
+ const documentBytes = () => envelope - 2 + sum + Math.max(0, slots.length - 1);
434
+
435
+ while (slots.length > this.maxEntries || documentBytes() > this.maxBytes) {
436
+ const chosen = slots
437
+ .map((slot) => slot.job)
438
+ .filter((job) => isTerminal(job.state) && job.taskId !== protectedId)
439
+ .sort(compareOldestFirst)[0] ?? null;
440
+ if (chosen === null) {
441
+ throw new HistoryError(
442
+ HISTORY_CODES.limitExceeded,
443
+ 'the job history bounds cannot be met without dropping a live job',
444
+ { entries: slots.length, limit: this.maxEntries, bytes: documentBytes(), byteLimit: this.maxBytes },
445
+ );
446
+ }
447
+ const index = slots.findIndex((slot) => slot.job === chosen);
448
+ sum -= slots[index].bytes;
449
+ slots.splice(index, 1);
450
+ }
451
+
452
+ draft.length = 0;
453
+ for (const slot of slots) draft.push(slot.job);
454
+ }
455
+
456
+ /**
457
+ * Record a refusal and return it, so the caller can `throw`.
458
+ * @param {string} code - refusal code.
459
+ * @param {string} message - explanation.
460
+ * @param {object} details - bounded, non-secret context.
461
+ * @returns {HistoryError} the refusal.
462
+ */
463
+ refuse(code, message, details) {
464
+ const refusal = this.refusal ?? { code, message, details };
465
+ this.refusal = refusal;
466
+ return new HistoryError(refusal.code, refusal.message, { ...refusal.details });
467
+ }
468
+
469
+ /**
470
+ * Re-throw a cached refusal, if the document was refused earlier.
471
+ * @returns {void}
472
+ * @throws {HistoryError} the original refusal.
473
+ */
474
+ throwIfRefused() {
475
+ if (this.refusal === null) return;
476
+ throw new HistoryError(this.refusal.code, this.refusal.message, { ...this.refusal.details });
477
+ }
478
+
479
+ /** @returns {HistoryError} the refusal used once the store is disposed. */
480
+ disposedError() {
481
+ return new HistoryError(HISTORY_CODES.disposed, 'the job history store has been disposed', {});
482
+ }
483
+ }
484
+
485
+ /**
486
+ * Project one public job view onto the stored field set.
487
+ *
488
+ * Every nested block is rebuilt from an allow-list, so a caller cannot add a
489
+ * field, a credential or a native handle by widening its own object.
490
+ * @param {object} view - public job view.
491
+ * @param {number} maxEntryBytes - per-entry byte budget.
492
+ * @returns {object} bounded, redacted entry.
493
+ */
494
+ function projectView(view, maxEntryBytes) {
495
+ if (!isPlainObject(view)) {
496
+ throw new HistoryError(HISTORY_CODES.viewInvalid, 'a job history view must be an object', {});
497
+ }
498
+ const taskId = typeof view.taskId === 'string' ? view.taskId.trim() : '';
499
+ if (taskId === '' || taskId.length > MAX_LABEL_CHARS) {
500
+ throw new HistoryError(HISTORY_CODES.viewInvalid, 'a job history view needs a bounded taskId', {});
501
+ }
502
+ if (!KNOWN_STATES.has(view.state)) {
503
+ throw new HistoryError(HISTORY_CODES.viewInvalid, 'a job history view needs a known state', {});
504
+ }
505
+
506
+ const ctx = newCutContext(view.truncation, maxEntryBytes);
507
+ const entry = {
508
+ taskId,
509
+ state: view.state,
510
+ phase: label(view.phase),
511
+ createdAt: time(view.createdAt),
512
+ startedAt: time(view.startedAt),
513
+ endedAt: time(view.endedAt),
514
+ sourcePath: path(view.sourcePath, ctx, 'sourcePath'),
515
+ workspacePath: path(view.workspacePath, ctx, 'workspacePath'),
516
+ executionWorkspacePath: path(view.executionWorkspacePath, ctx, 'executionWorkspacePath'),
517
+ isolation: knownValue(view.isolation, ['worktree', 'shared']),
518
+ interruptedFrom: knownValue(view.interruptedFrom, ['pending', 'running']),
519
+ // The connection identity is provenance: which external connection asked for
520
+ // the work. Grant id and grant kind are authorization state and are not
521
+ // stored, so a restart cannot be mistaken for a still-valid grant.
522
+ connectionId: label(view.connectionId),
523
+ effective: effectiveView(view.effective),
524
+ route: selectionView(view.route),
525
+ reviewRoute: selectionView(view.reviewRoute),
526
+ reviewRouteError: errorView(view.reviewRouteError, ctx),
527
+ worktree: worktreeView(view.worktree),
528
+ baseline: baselineView(view.baseline, ctx),
529
+ diff: diffView(view.diff, ctx),
530
+ execution: executionView(view.execution, ctx),
531
+ review: reviewView(view.review, ctx),
532
+ // The per-call permission evidence. Persisted so a restart can show WHY a call
533
+ // was allowed or refused, and so an interrupted wait is visible as history
534
+ // instead of vanishing. Every field is re-projected here from an allow-list and
535
+ // then re-redacted, so a stored record inherits the same masking the live view
536
+ // had — including key-aware masking of anything credential-named.
537
+ permission: permissionView(view.permission, ctx),
538
+ // The bounded progress summary. Stored so a restart can show what the run was
539
+ // doing when it stopped and how much activity it had — and stored through the
540
+ // same allow-list discipline as everything else, so no model text, reasoning,
541
+ // tool argument or diff can enter through it. `waitingOn` is what lets an
542
+ // interrupted record say "it was waiting on a tool call", which is the same
543
+ // fact as `permission.interrupted` for a paused approval but is a different
544
+ // story for an ordinary long-running command.
545
+ activity: activityView(view.activity),
546
+ error: errorView(view.error, ctx),
547
+ cancelledBy: label(view.cancelledBy),
548
+ hostAcceptance: acceptanceView(view.hostAcceptance),
549
+ // A completed job is not an accepted one. This is fixed, never copied.
550
+ selfApproved: false,
551
+ };
552
+
553
+ // A live state is normalized to `interrupted` by `markInterrupted` on the next
554
+ // load, which also closes its outstanding permission request. A terminal record
555
+ // never passes through that path, so its permission block must be closed HERE:
556
+ // the process that could decide the request is gone as soon as this record is
557
+ // durable, and a stored `pending` would otherwise remain apparently decidable
558
+ // forever. Keep the terminal task state untouched; only the request becomes
559
+ // history. `decidedBy: 'restart'` is the existing public vocabulary for this
560
+ // normalization and covers both crash recovery and terminal-record projection.
561
+ if (!LIVE_STATES.has(entry.state)) markPermissionInterrupted(entry);
562
+
563
+ const redacted = redactDeep(entry);
564
+ fitEntry(redacted, ctx);
565
+ // Markers recorded by an earlier projection are carried forward, so fitting an
566
+ // already-fitted entry is a no-op and a reload never rewrites the file.
567
+ const truncation = cutView(ctx);
568
+ if (truncation !== null) redacted.truncation = truncation;
569
+ return redacted;
570
+ }
571
+
572
+ /**
573
+ * Mark a job that was live when the process stopped as history-only
574
+ * `interrupted`. Finished states and their actual metadata are preserved.
575
+ * @param {object} entry - projected entry.
576
+ * @param {number} now - load time, used when the record never recorded an end.
577
+ * @returns {object} the same entry, updated in place.
578
+ */
579
+ function markInterrupted(entry, now) {
580
+ if (!LIVE_STATES.has(entry.state)) return entry;
581
+ entry.interruptedFrom = entry.state;
582
+ entry.state = 'interrupted';
583
+ entry.phase = 'interrupted';
584
+ entry.endedAt = entry.endedAt ?? now;
585
+ entry.error = {
586
+ code: 'JOB_INTERRUPTED_RESTART',
587
+ message: 'the job was still live when the plugin restarted; it was not resubmitted',
588
+ details: { previousState: entry.interruptedFrom },
589
+ };
590
+ // A permission wait that was open when the process stopped is part of the same
591
+ // fact: the request is history only and can never be decided or replayed.
592
+ markPermissionInterrupted(entry);
593
+ // The same for the activity summary: a span that was still open is closed here,
594
+ // so a restart reports "interrupted while a tool was running" instead of an idle
595
+ // duration that keeps growing for a run nobody is watching.
596
+ markActivityInterrupted(entry);
597
+ return entry;
598
+ }
599
+
600
+ /** @returns {object | null} bounded effective-configuration snapshot. */
601
+ function effectiveView(value) {
602
+ if (!isPlainObject(value)) return null;
603
+ const worker = isPlainObject(value.worker) ? value.worker : {};
604
+ const review = isPlainObject(value.review) ? value.review : {};
605
+ const provenance = isPlainObject(value.provenance) ? value.provenance : {};
606
+ return {
607
+ worker: {
608
+ providerId: label(worker.providerId),
609
+ model: label(worker.model),
610
+ reasoningEffort: label(worker.reasoningEffort),
611
+ timeoutSeconds: count(worker.timeoutSeconds),
612
+ maxParallelism: count(worker.maxParallelism),
613
+ isolation: knownValue(worker.isolation, ['worktree', 'shared']),
614
+ },
615
+ review: {
616
+ enabled: review.enabled === true,
617
+ providerId: label(review.providerId),
618
+ model: label(review.model),
619
+ reasoningEffort: label(review.reasoningEffort),
620
+ },
621
+ // The conversation policy the task was frozen with (a rule, not a stored
622
+ // setting) plus, in `value.conversation` below, what the run actually did. No
623
+ // session id is stored here, so history is not a way back into a conversation.
624
+ conversation: isPlainObject(value.conversation)
625
+ ? { policy: label(value.conversation.policy) }
626
+ : null,
627
+ // The silence thresholds this task froze at admission. Stored because they are
628
+ // the only way a stored activity block can be interpreted: "idle for 12 minutes"
629
+ // means something different under a 10-minute attention threshold than under a
630
+ // two-hour one, and the live settings may have changed since.
631
+ monitoring: isPlainObject(value.monitoring)
632
+ ? {
633
+ selfCheckSeconds: count(value.monitoring.selfCheckSeconds),
634
+ attentionSeconds: count(value.monitoring.attentionSeconds),
635
+ }
636
+ : null,
637
+ provenance: {
638
+ projectPath: path(provenance.projectPath),
639
+ projectKey: path(provenance.projectKey),
640
+ applied: stringList(provenance.applied),
641
+ },
642
+ };
643
+ }
644
+
645
+ /** @returns {object | null} bounded model-selection summary. */
646
+ function selectionView(value) {
647
+ if (!isPlainObject(value)) return null;
648
+ return {
649
+ providerId: label(value.providerId),
650
+ providerRoute: label(value.providerRoute),
651
+ model: label(value.model),
652
+ reasoningEffort: label(value.reasoningEffort),
653
+ };
654
+ }
655
+
656
+ /** @returns {object | null} bounded worktree metadata. */
657
+ function worktreeView(value) {
658
+ if (!isPlainObject(value)) return null;
659
+ return {
660
+ taskId: label(value.taskId),
661
+ workspacePath: path(value.workspacePath),
662
+ sourcePath: path(value.sourcePath),
663
+ baseHead: label(value.baseHead),
664
+ isolated: value.isolated === true,
665
+ detached: value.detached === true,
666
+ state: label(value.state),
667
+ createdAt: time(value.createdAt),
668
+ completedAt: time(value.completedAt),
669
+ sourcePreexistingChanges: count(value.sourcePreexistingChanges),
670
+ disposable: value.disposable === true,
671
+ };
672
+ }
673
+
674
+ /** @returns {object | null} bounded audit baseline. */
675
+ function baselineView(value, ctx) {
676
+ if (!isPlainObject(value)) return null;
677
+ return {
678
+ head: label(value.head),
679
+ dirtyBaseline: value.dirtyBaseline === true,
680
+ preexistingChanges: count(value.preexistingChanges),
681
+ preexistingPaths: pathList(value.preexistingPaths, ctx, 'baseline.preexistingPaths'),
682
+ statusTruncated: value.statusTruncated === true,
683
+ statusFormat: label(value.statusFormat),
684
+ capturedAt: time(value.capturedAt),
685
+ };
686
+ }
687
+
688
+ /** @returns {object | null} bounded change evidence. */
689
+ function diffView(value, ctx) {
690
+ if (!isPlainObject(value)) return null;
691
+ const files = [];
692
+ const fileTotal = Array.isArray(value.files) ? value.files.length : 0;
693
+ if (Array.isArray(value.files)) {
694
+ for (const item of value.files.slice(0, MAX_LIST_ITEMS)) {
695
+ if (isPlainObject(item)) {
696
+ files.push({ code: label(item.code), path: path(item.path), from: path(item.from) });
697
+ } else {
698
+ files.push({ code: null, path: path(item), from: null });
699
+ }
700
+ }
701
+ }
702
+ const changes = [];
703
+ if (Array.isArray(value.changes)) {
704
+ for (const item of value.changes.slice(0, MAX_LIST_ITEMS)) {
705
+ if (!isPlainObject(item)) continue;
706
+ changes.push({
707
+ added: count(item.added),
708
+ removed: count(item.removed),
709
+ path: path(item.path),
710
+ from: path(item.from),
711
+ });
712
+ }
713
+ }
714
+ return {
715
+ head: label(value.head),
716
+ baseHead: label(value.baseHead),
717
+ dirtyBaseline: value.dirtyBaseline === true,
718
+ preexistingChanges: count(value.preexistingChanges),
719
+ files,
720
+ fileCount: count(value.fileCount),
721
+ truncatedFiles: value.truncatedFiles === true || fileTotal > files.length,
722
+ changes,
723
+ // Paths stay visible; their content was excluded before the diff ran.
724
+ sensitivePaths: pathList(value.sensitivePaths, ctx, 'diff.sensitivePaths'),
725
+ sensitiveTouchedCount: count(value.sensitiveTouchedCount),
726
+ sensitiveContentWithheld: value.sensitiveContentWithheld !== false,
727
+ patchWithheld: value.patchWithheld === true,
728
+ patchText: text(value.patchText, ctx, 'diff.patchText'),
729
+ patchTruncated: value.patchTruncated === true,
730
+ patchBytes: count(value.patchBytes),
731
+ capturedAt: time(value.capturedAt),
732
+ error: errorView(value.error, ctx),
733
+ };
734
+ }
735
+
736
+ /**
737
+ * @returns {object | null} bounded execution record. Native agent and session ids
738
+ * are dropped: this module stores outcomes, never a way back into a run. The
739
+ * `conversation` block is the exception and is deliberately narrow — it carries
740
+ * the mode that was frozen for the task, whether a conversation was continued,
741
+ * and the Workspace id the run was grouped in. It never carries the session id,
742
+ * so a restart cannot resume a conversation from this file.
743
+ */
744
+ function executionView(value, ctx) {
745
+ if (!isPlainObject(value)) return null;
746
+ return {
747
+ workspacePath: path(value.workspacePath),
748
+ outcome: label(value.outcome),
749
+ text: text(value.text, ctx, 'execution.text'),
750
+ reasoningOnly: value.reasoningOnly === true,
751
+ textTruncated: value.textTruncated === true,
752
+ usage: usageView(value.usage),
753
+ turnEnd: isPlainObject(value.turnEnd) ? { reason: label(value.turnEnd.reason) } : null,
754
+ conversation: conversationView(value.conversation),
755
+ cancelCause: label(value.cancelCause),
756
+ error: typeof value.error === 'string'
757
+ ? text(value.error, ctx, 'execution.error', MAX_MESSAGE_CHARS)
758
+ : errorView(value.error, ctx),
759
+ };
760
+ }
761
+
762
+ /**
763
+ * @returns {object | null} bounded conversation placement. `sessionId` and every
764
+ * other resumable handle is absent on purpose: the durable job history must not be
765
+ * a second way into a conversation. `kind`/`continuedFromTaskId` state whether the
766
+ * run started a new thread or continued the task it named.
767
+ */
768
+ function conversationView(value) {
769
+ if (!isPlainObject(value)) return null;
770
+ return {
771
+ kind: knownValue(value.kind, ['new', 'continuation']),
772
+ continuedFromTaskId: label(value.continuedFromTaskId),
773
+ reused: value.reused === true,
774
+ workspaceId: label(value.workspaceId),
775
+ workspacePath: path(value.workspacePath),
776
+ workspaceCreated: value.workspaceCreated === true,
777
+ sessionCreated: value.sessionCreated === true,
778
+ };
779
+ }
780
+
781
+ /**
782
+ * @returns {object | null} usage counters. Only finite non-negative numbers are
783
+ * kept; `redactDeep` masks any counter-named field that is not one.
784
+ */
785
+ function usageView(value) {
786
+ if (!isPlainObject(value)) return null;
787
+ const out = {};
788
+ for (const key of [
789
+ 'inputTokens', 'outputTokens', 'totalTokens', 'reasoningTokens',
790
+ 'cacheTokens', 'cacheReadTokens', 'cacheWriteTokens',
791
+ ]) {
792
+ if (value[key] === undefined) continue;
793
+ const number = count(value[key]);
794
+ if (number !== null) setOwn(out, key, number);
795
+ }
796
+ return Object.keys(out).length === 0 ? null : out;
797
+ }
798
+
799
+ /** @returns {object | null} bounded additional-review outcome. */
800
+ function reviewView(value, ctx) {
801
+ if (!isPlainObject(value)) return null;
802
+ return {
803
+ state: label(value.state),
804
+ verdict: isPlainObject(value.verdict)
805
+ ? { verdict: label(value.verdict.verdict), reason: text(value.verdict.reason, ctx, 'review.verdict.reason') }
806
+ : null,
807
+ text: text(value.text, ctx, 'review.text'),
808
+ error: errorView(value.error, ctx),
809
+ selection: selectionView(value.selection),
810
+ denials: stringList(value.denials, ctx, 'review.denials'),
811
+ denialsDelivered: count(value.denialsDelivered),
812
+ };
813
+ }
814
+
815
+ /**
816
+ * Bounded projection of one per-call permission request.
817
+ *
818
+ * The allow-list is deliberate and narrow: identifiers, the redacted argument
819
+ * rendering, the completeness facts, the timestamps, and the decision evidence.
820
+ * What is NOT stored: the exact private fingerprint (it binds one live call and is
821
+ * meaningless after a restart, where the call it named is gone), the exact argument
822
+ * text, and the internal timer/signal handles. A restarted record therefore cannot
823
+ * be used to replay or re-authorise anything — it is evidence, not a capability.
824
+ * @param {unknown} value - one pending or settled permission view.
825
+ * @param {object} ctx - cut context.
826
+ * @param {string} field - path prefix for truncation markers.
827
+ * @returns {object | null} bounded copy.
828
+ */
829
+ function permissionEntryView(value, ctx, field) {
830
+ if (!isPlainObject(value)) return null;
831
+ const access = isPlainObject(value.requestedAccess) ? value.requestedAccess : {};
832
+ const verified = isPlainObject(value.verified) ? value.verified : null;
833
+ const grant = isPlainObject(value.grant) ? value.grant : null;
834
+ return {
835
+ requestId: label(value.requestId),
836
+ taskId: label(value.taskId),
837
+ sessionId: label(value.sessionId),
838
+ toolName: label(value.toolName),
839
+ callId: label(value.callId),
840
+ turn: count(value.turn),
841
+ step: count(value.step),
842
+ state: label(value.state),
843
+ // The asker's own claim, still labelled as one.
844
+ reason: label(value.reason),
845
+ reasonSource: label(value.reasonSource),
846
+ requestedAccess: { kind: label(access.kind), mode: label(access.mode) },
847
+ argumentKeys: stringList(value.argumentKeys, ctx, `${field}.argumentKeys`),
848
+ // The redacted, bounded rendering of the real arguments. Already redacted by the
849
+ // bridge; `redactDeep` runs again over the whole entry below, so a stored record
850
+ // is masked twice rather than trusted once.
851
+ arguments: text(value.arguments, ctx, `${field}.arguments`, MAX_DETAIL_STRING_CHARS * 8),
852
+ argumentsRedacted: value.argumentsRedacted === true,
853
+ completeness: label(value.completeness),
854
+ argumentsComplete: value.argumentsComplete === true,
855
+ boundsApplied: stringList(value.boundsApplied, ctx, `${field}.boundsApplied`),
856
+ omitted: isPlainObject(value.omitted)
857
+ ? {
858
+ valueChars: count(value.omitted.valueChars),
859
+ keys: count(value.omitted.keys),
860
+ depth: count(value.omitted.depth),
861
+ items: count(value.omitted.items),
862
+ }
863
+ : null,
864
+ allowBlocked: label(value.allowBlocked),
865
+ createdAt: time(value.createdAt),
866
+ deadlineAt: time(value.deadlineAt),
867
+ decision: label(value.decision),
868
+ decidedAt: time(value.decidedAt),
869
+ decidedBy: label(value.decidedBy),
870
+ decisionReason: label(value.decisionReason),
871
+ outcome: label(value.outcome),
872
+ verified: verified === null
873
+ ? null
874
+ : {
875
+ fingerprintQuoted: verified.fingerprintQuoted === true,
876
+ argumentsComplete: verified.argumentsComplete === true,
877
+ callReread: verified.callReread === true,
878
+ turnOpen: verified.turnOpen === true,
879
+ boundsApplied: stringList(verified.boundsApplied, ctx, `${field}.verified.boundsApplied`),
880
+ },
881
+ grant: grant === null
882
+ ? null
883
+ : {
884
+ kind: label(grant.kind),
885
+ appliesTo: label(grant.appliesTo),
886
+ callId: label(grant.callId),
887
+ reusable: grant.reusable === true,
888
+ },
889
+ standingModeUnchanged: value.standingModeUnchanged === true,
890
+ };
891
+ }
892
+
893
+ /**
894
+ * Bounded projection of a task's whole permission block.
895
+ *
896
+ * The settled trail is stored oldest-last-first and cut to a small bound, because
897
+ * it is evidence an operator reads rather than machine state. `pending` is stored
898
+ * too: after a restart it is what proves the task was WAITING when the process
899
+ * stopped, and it is written with the same allow-list, so it cannot be replayed.
900
+ * @param {unknown} value - task `permission` block.
901
+ * @param {object} ctx - cut context.
902
+ * @returns {object | null} bounded copy.
903
+ */
904
+ function permissionView(value, ctx) {
905
+ if (!isPlainObject(value)) return null;
906
+ const evidence = Array.isArray(value.evidence) ? value.evidence : [];
907
+ const pending = permissionEntryView(value.pending, ctx, 'permission.pending');
908
+ return {
909
+ bridged: value.bridged === true,
910
+ waiting: value.waiting === true,
911
+ pending,
912
+ evidence: evidence
913
+ .slice(-MAX_PERMISSION_EVIDENCE)
914
+ .map((entry, index) => permissionEntryView(entry, ctx, `permission.evidence[${index}]`))
915
+ .filter((entry) => entry !== null),
916
+ pausedExecutionMs: count(value.pausedExecutionMs),
917
+ standingSandboxMode: label(value.standingSandboxMode),
918
+ grantScope: label(value.grantScope),
919
+ };
920
+ }
921
+
922
+ /**
923
+ * Mark a live task's outstanding request as interrupted on load.
924
+ *
925
+ * A request that was pending when the process stopped can never be decided: the
926
+ * bridge, the Agent and the paused native tool call all died with the process, and
927
+ * `markInterrupted` has already made the task non-live. This rewrites only the
928
+ * PENDING record so the stored history says "this wait did not survive", instead of
929
+ * leaving a record a reader could mistake for a still-decidable request.
930
+ * @param {object} entry - projected entry.
931
+ * @returns {object} the same entry.
932
+ */
933
+ function markPermissionInterrupted(entry) {
934
+ const permission = entry?.permission;
935
+ if (!isPlainObject(permission)) return entry;
936
+ const pending = permission.pending;
937
+ if (!isPlainObject(pending)) {
938
+ if (permission.waiting === true) permission.waiting = false;
939
+ return entry;
940
+ }
941
+ // Already normalized to "cannot be decided" (a checkpoint that was written before
942
+ // the terminal record, or a re-load of one): state the interrupt fact as well, so
943
+ // every interrupted record says the same thing regardless of which write produced it.
944
+ if (pending.state !== 'pending') {
945
+ permission.waiting = false;
946
+ permission.interrupted = true;
947
+ return entry;
948
+ }
949
+ pending.state = 'unavailable';
950
+ pending.outcome = 'unavailable';
951
+ pending.decidedBy = 'restart';
952
+ pending.decidedAt = entry.endedAt ?? pending.decidedAt ?? null;
953
+ pending.decisionReason = 'the process stopped while this request was pending; it cannot be decided and was not replayed';
954
+ pending.allowBlocked = 'the process stopped while this request was pending';
955
+ permission.waiting = false;
956
+ permission.interrupted = true;
957
+ return entry;
958
+ }
959
+
960
+ /**
961
+ * Bounded projection of one task's activity summary.
962
+ *
963
+ * Every field is a count, a timestamp or an identifier. The tool name and call id
964
+ * are identifiers the native session log already carries; the argument text and
965
+ * result body are NOT reachable from here because the live summary never holds
966
+ * them. `kinds` is rebuilt from a closed key allow-list rather than copied, so a
967
+ * widened live shape cannot smuggle a new field into the document.
968
+ * @param {unknown} value - task `activity` block.
969
+ * @returns {object | null} bounded copy, or null when the task never ran.
970
+ */
971
+ function activityView(value) {
972
+ if (!isPlainObject(value)) return null;
973
+ const tool = isPlainObject(value.currentTool) ? value.currentTool : null;
974
+ const lastTool = isPlainObject(value.lastTool) ? value.lastTool : null;
975
+ const selfCheck = isPlainObject(value.selfCheck) ? value.selfCheck : null;
976
+ const kinds = {};
977
+ if (isPlainObject(value.kinds)) {
978
+ for (const [key, countValue] of Object.entries(value.kinds).slice(0, MAX_ACTIVITY_KINDS)) {
979
+ const number = count(countValue);
980
+ if (number === null) continue;
981
+ if (key.length === 0 || key.length > MAX_LABEL_CHARS) continue;
982
+ setOwn(kinds, key, number);
983
+ }
984
+ }
985
+ return {
986
+ lastActivityAt: time(value.lastActivityAt),
987
+ // The idle span and what the run was doing during it. `waitingOn: 'tool'` is
988
+ // the one case where a long span is WORK rather than silence, and recording it
989
+ // is what stops a restarted record from describing a build as a stall.
990
+ idleForMs: count(value.idleForMs),
991
+ waitingOn: knownValue(value.waitingOn, ['idle', 'tool']),
992
+ currentTool: tool === null
993
+ ? null
994
+ : {
995
+ name: label(tool.name),
996
+ callId: label(tool.callId),
997
+ startedAt: time(tool.startedAt),
998
+ elapsedMs: count(tool.elapsedMs),
999
+ },
1000
+ lastTool: lastTool === null
1001
+ ? null
1002
+ : { name: label(lastTool.name), durationMs: count(lastTool.durationMs) },
1003
+ events: count(value.events),
1004
+ activityEvents: count(value.activityEvents),
1005
+ toolCallsStarted: count(value.toolCallsStarted),
1006
+ toolCallsFinished: count(value.toolCallsFinished),
1007
+ selfCheckSeconds: count(value.selfCheckSeconds),
1008
+ attentionSeconds: count(value.attentionSeconds),
1009
+ // Present when the elapsed values were frozen at the run's end, so a reader can
1010
+ // tell a final span from one still being measured.
1011
+ finalizedAt: time(value.finalizedAt),
1012
+ selfCheck: selfCheck === null
1013
+ ? null
1014
+ : {
1015
+ episode: count(selfCheck.episode),
1016
+ checkedAt: time(selfCheck.checkedAt),
1017
+ verdict: label(selfCheck.verdict),
1018
+ },
1019
+ // A stored record whose run was interrupted while a tool was in flight keeps the
1020
+ // cut-off call as evidence instead of dropping it.
1021
+ ...(isPlainObject(value.interruptedTool)
1022
+ ? {
1023
+ interruptedTool: {
1024
+ name: label(value.interruptedTool.name),
1025
+ callId: label(value.interruptedTool.callId),
1026
+ startedAt: time(value.interruptedTool.startedAt),
1027
+ elapsedMs: count(value.interruptedTool.elapsedMs),
1028
+ },
1029
+ }
1030
+ : {}),
1031
+ kinds,
1032
+ };
1033
+ }
1034
+
1035
+ /**
1036
+ * Mark a live task's activity summary as belonging to an interrupted run.
1037
+ *
1038
+ * `markInterrupted` already rewrote the state; this makes the silence describe what
1039
+ * it actually was, so a restarted record cannot present a tool that was mid-flight
1040
+ * as "idle for four hours". The span is closed at the recorded end time and the
1041
+ * outstanding tool call is marked cut off rather than deleted — it is evidence that
1042
+ * something was running when the process stopped.
1043
+ * @param {object} entry - projected entry.
1044
+ * @returns {object} the same entry.
1045
+ */
1046
+ function markActivityInterrupted(entry) {
1047
+ const activity = entry?.activity;
1048
+ if (!isPlainObject(activity)) return entry;
1049
+ if (isPlainObject(activity.currentTool)) {
1050
+ activity.interruptedTool = { ...activity.currentTool };
1051
+ }
1052
+ activity.currentTool = null;
1053
+ activity.waitingOn = null;
1054
+ activity.idleForMs = null;
1055
+ activity.interrupted = true;
1056
+ return entry;
1057
+ }
1058
+
1059
+ /**
1060
+ * Bounded error record.
1061
+ * @param {unknown} value - error value.
1062
+ * @param {object} ctx - cut context.
1063
+ * @returns {object | null} bounded error record.
1064
+ */
1065
+ function errorView(value, ctx) {
1066
+ if (value === null || value === undefined) return null;
1067
+ if (typeof value === 'string') {
1068
+ return { code: null, message: text(value, ctx, 'error.message', MAX_MESSAGE_CHARS), details: null };
1069
+ }
1070
+ if (!isPlainObject(value)) return null;
1071
+ return {
1072
+ code: label(value.code),
1073
+ message: text(value.message, ctx, 'error.message', MAX_MESSAGE_CHARS),
1074
+ details: boundedDetails(value.details, ctx, 'error.details', 0),
1075
+ };
1076
+ }
1077
+
1078
+ /** @returns {object | null} bounded host-acceptance record. */
1079
+ function acceptanceView(value) {
1080
+ if (!isPlainObject(value)) return null;
1081
+ return {
1082
+ accepted: value.accepted === true,
1083
+ state: label(value.state),
1084
+ acceptedAt: time(value.acceptedAt),
1085
+ by: label(value.by),
1086
+ note: label(value.note),
1087
+ };
1088
+ }
1089
+
1090
+ /**
1091
+ * Bound an open-ended detail object by shape, not by name: depth, key count and
1092
+ * string size. `redactDeep` still masks every secret-named key inside it.
1093
+ * @param {unknown} value - detail value.
1094
+ * @param {object} ctx - cut context.
1095
+ * @param {string} field - field label for the truncation marker.
1096
+ * @param {number} depth - current depth.
1097
+ * @returns {unknown} bounded copy.
1098
+ */
1099
+ function boundedDetails(value, ctx, field, depth) {
1100
+ if (value === null || value === undefined) return null;
1101
+ if (typeof value === 'string') return text(value, ctx, field, MAX_DETAIL_STRING_CHARS);
1102
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null;
1103
+ if (typeof value === 'boolean') return value;
1104
+ if (depth >= MAX_DETAIL_DEPTH) {
1105
+ ctx.fields.add(field);
1106
+ return null;
1107
+ }
1108
+ if (Array.isArray(value)) {
1109
+ if (value.length > MAX_DETAIL_KEYS) ctx.fields.add(field);
1110
+ return value.slice(0, MAX_DETAIL_KEYS).map((item) => boundedDetails(item, ctx, field, depth + 1));
1111
+ }
1112
+ if (typeof value === 'object') {
1113
+ const out = {};
1114
+ const entries = Object.entries(value);
1115
+ if (entries.length > MAX_DETAIL_KEYS) ctx.fields.add(field);
1116
+ for (const [key, item] of entries.slice(0, MAX_DETAIL_KEYS)) {
1117
+ if (typeof key !== 'string' || FORBIDDEN_KEYS.has(key)) continue;
1118
+ setOwn(out, key, boundedDetails(item, ctx, `${field}.${key}`, depth + 1));
1119
+ }
1120
+ return out;
1121
+ }
1122
+ return null;
1123
+ }
1124
+
1125
+ /**
1126
+ * Fit one entry into `maxEntryBytes`.
1127
+ *
1128
+ * Free text is halved first, then long arrays, then optional blocks; each cut is
1129
+ * recorded, so a consumer can see that evidence was reduced instead of receiving
1130
+ * a silently short record. Only when nothing more can be cut is the entry refused.
1131
+ * @param {object} entry - mutable entry.
1132
+ * @param {object} ctx - cut context.
1133
+ * @returns {void}
1134
+ * @throws {HistoryError} when the entry cannot be bounded.
1135
+ */
1136
+ function fitEntry(entry, ctx) {
1137
+ const budget = ctx.maxEntryBytes - FIT_RESERVE;
1138
+ let size = byteLength(JSON.stringify(entry));
1139
+ for (let guard = 0; guard < 200 && size > budget; guard += 1) {
1140
+ if (!cutLargestText(entry, ctx) && !cutLargestArray(entry, ctx) && !dropBlock(entry, ctx)) break;
1141
+ size = byteLength(JSON.stringify(entry));
1142
+ }
1143
+ if (size > budget) {
1144
+ throw new HistoryError(
1145
+ HISTORY_CODES.entryTooLarge,
1146
+ 'the job history view cannot be bounded to the configured entry budget',
1147
+ { bytes: size, limit: ctx.maxEntryBytes },
1148
+ );
1149
+ }
1150
+ }
1151
+
1152
+ /**
1153
+ * Halve the longest remaining free-text field.
1154
+ * @param {object} entry - mutable entry.
1155
+ * @param {object} ctx - cut context.
1156
+ * @returns {boolean} whether anything was cut.
1157
+ */
1158
+ function cutLargestText(entry, ctx) {
1159
+ let chosen = null;
1160
+ let length = 0;
1161
+ for (const parts of TEXT_PATHS) {
1162
+ const value = getPath(entry, parts);
1163
+ if (typeof value !== 'string' || value === '') continue;
1164
+ if (value.length > length) {
1165
+ chosen = parts;
1166
+ length = value.length;
1167
+ }
1168
+ }
1169
+ if (chosen === null) return false;
1170
+ const current = getPath(entry, chosen);
1171
+ const base = current.endsWith(TRUNCATION_MARK) ? current.slice(0, -TRUNCATION_MARK.length) : current;
1172
+ const limit = Math.floor(base.length / 2);
1173
+ setPath(entry, chosen, `${base.slice(0, limit)}${TRUNCATION_MARK}`);
1174
+ const field = chosen.join('.');
1175
+ ctx.fields.add(field);
1176
+ // Keep the existing evidence flags honest when the patch itself was cut.
1177
+ if (field === 'diff.patchText') entry.diff.patchTruncated = true;
1178
+ return true;
1179
+ }
1180
+
1181
+ /**
1182
+ * Halve the longest remaining list.
1183
+ * @param {object} entry - mutable entry.
1184
+ * @param {object} ctx - cut context.
1185
+ * @returns {boolean} whether anything was cut.
1186
+ */
1187
+ function cutLargestArray(entry, ctx) {
1188
+ let chosen = null;
1189
+ let length = 0;
1190
+ for (const parts of ARRAY_PATHS) {
1191
+ const value = getPath(entry, parts);
1192
+ if (!Array.isArray(value) || value.length === 0) continue;
1193
+ if (value.length > length) {
1194
+ chosen = parts;
1195
+ length = value.length;
1196
+ }
1197
+ }
1198
+ if (chosen === null) return false;
1199
+ const current = getPath(entry, chosen);
1200
+ setPath(entry, chosen, current.slice(0, Math.floor(current.length / 2)));
1201
+ const field = chosen.join('.');
1202
+ ctx.fields.add(field);
1203
+ if (field === 'diff.files') entry.diff.truncatedFiles = true;
1204
+ return true;
1205
+ }
1206
+
1207
+ /**
1208
+ * Drop the first optional block that is still present.
1209
+ * @param {object} entry - mutable entry.
1210
+ * @param {object} ctx - cut context.
1211
+ * @returns {boolean} whether anything was dropped.
1212
+ */
1213
+ function dropBlock(entry, ctx) {
1214
+ for (const parts of DROP_PATHS) {
1215
+ if (!deletePath(entry, parts)) continue;
1216
+ ctx.dropped.add(parts.join('.'));
1217
+ return true;
1218
+ }
1219
+ return false;
1220
+ }
1221
+
1222
+ /** @returns {object} empty cut context seeded with markers a stored entry carried. */
1223
+ function newCutContext(incoming, maxEntryBytes) {
1224
+ const ctx = {
1225
+ fields: new Set(),
1226
+ dropped: new Set(),
1227
+ maxEntryBytes,
1228
+ };
1229
+ if (!isPlainObject(incoming)) return ctx;
1230
+ for (const [key, target] of [['fields', ctx.fields], ['dropped', ctx.dropped]]) {
1231
+ const list = incoming[key];
1232
+ if (!Array.isArray(list)) continue;
1233
+ for (const item of list.slice(0, MAX_TRUNCATION_ITEMS)) {
1234
+ if (typeof item === 'string' && item !== '') target.add(item.slice(0, 120));
1235
+ }
1236
+ }
1237
+ return ctx;
1238
+ }
1239
+
1240
+ /** @returns {object | null} the recorded cuts, bounded and stable. */
1241
+ function cutView(ctx) {
1242
+ const fields = [...ctx.fields].slice(0, MAX_TRUNCATION_ITEMS);
1243
+ const dropped = [...ctx.dropped].slice(0, MAX_TRUNCATION_ITEMS);
1244
+ if (fields.length === 0 && dropped.length === 0) return null;
1245
+ return {
1246
+ fields,
1247
+ dropped,
1248
+ note: 'entry fitted to the job history byte budget',
1249
+ };
1250
+ }
1251
+
1252
+ /**
1253
+ * Read a nested value without trusting any level's prototype.
1254
+ * @param {object} target - root object.
1255
+ * @param {string[]} parts - key path.
1256
+ * @returns {unknown} the value, or undefined.
1257
+ */
1258
+ function getPath(target, parts) {
1259
+ let node = target;
1260
+ for (const part of parts) {
1261
+ if (!isPlainObject(node) || !Object.hasOwn(node, part)) return undefined;
1262
+ node = node[part];
1263
+ }
1264
+ return node;
1265
+ }
1266
+
1267
+ /**
1268
+ * Replace a nested value on an entry this module built itself.
1269
+ * @param {object} target - root object.
1270
+ * @param {string[]} parts - key path.
1271
+ * @param {unknown} value - next value.
1272
+ * @returns {void}
1273
+ */
1274
+ function setPath(target, parts, value) {
1275
+ let node = target;
1276
+ for (let index = 0; index < parts.length - 1; index += 1) {
1277
+ node = node[parts[index]];
1278
+ if (!isPlainObject(node)) return;
1279
+ }
1280
+ node[parts[parts.length - 1]] = value;
1281
+ }
1282
+
1283
+ /**
1284
+ * Remove a nested key from an entry this module built itself.
1285
+ * @param {object} target - root object.
1286
+ * @param {string[]} parts - key path.
1287
+ * @returns {boolean} whether the key existed.
1288
+ */
1289
+ function deletePath(target, parts) {
1290
+ let node = target;
1291
+ for (let index = 0; index < parts.length - 1; index += 1) {
1292
+ node = node[parts[index]];
1293
+ if (!isPlainObject(node)) return false;
1294
+ }
1295
+ const key = parts[parts.length - 1];
1296
+ if (!isPlainObject(node) || !Object.hasOwn(node, key)) return false;
1297
+ delete node[key];
1298
+ return true;
1299
+ }
1300
+
1301
+ /**
1302
+ * Assign an own property without ever reaching a prototype setter.
1303
+ * @param {object} target - object.
1304
+ * @param {string} key - key.
1305
+ * @param {unknown} value - value.
1306
+ * @returns {void}
1307
+ */
1308
+ function setOwn(target, key, value) {
1309
+ Object.defineProperty(target, key, {
1310
+ value,
1311
+ enumerable: true,
1312
+ writable: true,
1313
+ configurable: true,
1314
+ });
1315
+ }
1316
+
1317
+ /** @returns {boolean} true for plain objects (never arrays or class instances' prototypes). */
1318
+ function isPlainObject(value) {
1319
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
1320
+ const proto = Object.getPrototypeOf(value);
1321
+ return proto === Object.prototype || proto === null;
1322
+ }
1323
+
1324
+ /** @returns {string | null} bounded label, or null when absent. */
1325
+ function label(value) {
1326
+ if (typeof value !== 'string' || value === '') return null;
1327
+ return value.slice(0, MAX_LABEL_CHARS);
1328
+ }
1329
+
1330
+ /**
1331
+ * @param {unknown} value - path.
1332
+ * @param {object} [ctx] - cut context; omitted for project-owned paths.
1333
+ * @param {string} [field] - field label used when the path had to be cut.
1334
+ * @returns {string | null} bounded path, or null when absent.
1335
+ */
1336
+ function path(value, ctx = null, field = '') {
1337
+ if (typeof value !== 'string' || value === '') return null;
1338
+ if (value.length <= MAX_PATH_CHARS) return value;
1339
+ if (ctx !== null && field !== '') ctx.fields.add(field);
1340
+ return value.slice(0, MAX_PATH_CHARS);
1341
+ }
1342
+
1343
+ /**
1344
+ * @param {unknown} value - value to read.
1345
+ * @param {string} field - field label for truncation reporting.
1346
+ * @param {number} [cap] - characters kept.
1347
+ * @param {object} [ctx] - cut context; omitted only for non-nested calls.
1348
+ * @returns {string} bounded text.
1349
+ */
1350
+ function text(value, ctx, field, cap = MAX_TEXT_CHARS) {
1351
+ if (typeof value !== 'string' || value === '') return '';
1352
+ if (value.length <= cap) return value;
1353
+ ctx.fields.add(field);
1354
+ return `${value.slice(0, cap)}${TRUNCATION_MARK}`;
1355
+ }
1356
+
1357
+ /**
1358
+ * @param {unknown} value - list value.
1359
+ * @param {object} [ctx] - cut context.
1360
+ * @param {string} [field] - field label when the list had to be cut.
1361
+ * @returns {string[]} bounded string list.
1362
+ */
1363
+ function stringList(value, ctx = null, field = '') {
1364
+ if (!Array.isArray(value)) return [];
1365
+ const kept = value
1366
+ .filter((item) => typeof item === 'string')
1367
+ .slice(0, MAX_LIST_ITEMS)
1368
+ .map((item) => item.slice(0, MAX_MESSAGE_CHARS));
1369
+ if (ctx !== null && field !== '' && value.length > kept.length) ctx.fields.add(field);
1370
+ return kept;
1371
+ }
1372
+
1373
+ /**
1374
+ * @param {unknown} value - path list.
1375
+ * @param {object} ctx - cut context.
1376
+ * @param {string} field - field label.
1377
+ * @returns {string[]} bounded path list.
1378
+ */
1379
+ function pathList(value, ctx, field) {
1380
+ if (!Array.isArray(value)) return [];
1381
+ const kept = value
1382
+ .filter((item) => typeof item === 'string' && item !== '')
1383
+ .slice(0, MAX_LIST_ITEMS)
1384
+ .map((item) => item.slice(0, MAX_PATH_CHARS));
1385
+ if (value.length > kept.length) ctx.fields.add(field);
1386
+ return kept;
1387
+ }
1388
+
1389
+ /** @returns {number | null} finite non-negative integer, or null. */
1390
+ function count(value) {
1391
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return null;
1392
+ return Math.trunc(value);
1393
+ }
1394
+
1395
+ /** @returns {number | null} finite, plausible millisecond timestamp. */
1396
+ function time(value) {
1397
+ if (typeof value !== 'number' || !Number.isFinite(value)) return null;
1398
+ if (value < 0 || value > MAX_SAFE_TIMESTAMP) return null;
1399
+ return Math.trunc(value);
1400
+ }
1401
+
1402
+ /**
1403
+ * @param {unknown} value - candidate.
1404
+ * @param {string[]} allowed - exact permitted values.
1405
+ * @returns {string | null} the value, or null when it is not one of them.
1406
+ */
1407
+ function knownValue(value, allowed) {
1408
+ return typeof value === 'string' && allowed.includes(value) ? value : null;
1409
+ }
1410
+
1411
+ /** @returns {boolean} true when this state must never be evicted by a save. */
1412
+ function isTerminal(state) {
1413
+ return KNOWN_STATES.has(state) && !LIVE_STATES.has(state);
1414
+ }
1415
+
1416
+ /**
1417
+ * Total order used on disk: creation time, then id, so serialization is stable.
1418
+ * @param {object} a - first entry.
1419
+ * @param {object} b - second entry.
1420
+ * @returns {number} sort order.
1421
+ */
1422
+ function compareStored(a, b) {
1423
+ const left = a.createdAt ?? 0;
1424
+ const right = b.createdAt ?? 0;
1425
+ if (left !== right) return left - right;
1426
+ return a.taskId < b.taskId ? -1 : a.taskId > b.taskId ? 1 : 0;
1427
+ }
1428
+
1429
+ /**
1430
+ * Eviction order: oldest end (or creation) first.
1431
+ * @param {object} a - first entry.
1432
+ * @param {object} b - second entry.
1433
+ * @returns {number} sort order.
1434
+ */
1435
+ function compareOldestFirst(a, b) {
1436
+ const left = a.endedAt ?? a.createdAt ?? 0;
1437
+ const right = b.endedAt ?? b.createdAt ?? 0;
1438
+ if (left !== right) return left - right;
1439
+ return compareStored(a, b);
1440
+ }
1441
+
1442
+ /** @returns {number} UTF-8 byte length of a string. */
1443
+ function byteLength(value) {
1444
+ return Buffer.byteLength(value, 'utf8');
1445
+ }
1446
+
1447
+ /**
1448
+ * Rename over the target, retrying the transient Windows sharing errors.
1449
+ * @param {object} fs - filesystem seam.
1450
+ * @param {string} temp - source path.
1451
+ * @param {string} target - destination path.
1452
+ * @returns {Promise<void>} resolves after the rename.
1453
+ */
1454
+ async function renameWithRetry(fs, temp, target) {
1455
+ let delay = 20;
1456
+ for (let attempt = 0; ; attempt += 1) {
1457
+ try {
1458
+ await fs.rename(temp, target);
1459
+ return;
1460
+ } catch (error) {
1461
+ const transient = process.platform === 'win32' && WINDOWS_TRANSIENT_RENAME.has(error?.code ?? '');
1462
+ if (!transient || attempt >= 8) throw error;
1463
+ }
1464
+ await new Promise((resolve) => { setTimeout(resolve, delay); });
1465
+ delay = Math.min(delay * 2, 200);
1466
+ }
1467
+ }