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,629 @@
1
+ // Settings service: the one authority on validated configuration and on the
2
+ // effective snapshot a job runs under.
3
+ //
4
+ // Three layers compose here - global, project, per-job - and they compose in a
5
+ // fixed order with no implicit source beneath them. A missing provider is a
6
+ // refusal, never a substitution of a harness default, so an operator can always
7
+ // tell which model spent their tokens.
8
+ //
9
+ // Concurrency contract of SettingsService:
10
+ //
11
+ // * Every read-modify-validate-save cycle runs entirely inside one serial
12
+ // queue, so two concurrent edits to different blocks both survive. Reading
13
+ // a field before entering the queue and replacing a whole snapshot
14
+ // afterwards is exactly the lost-update bug this queue removes.
15
+ // * The queue is recuperative: a rejected operation settles the tail to a
16
+ // resolved promise, so the next operation still runs.
17
+ // * Reads do not queue. They serve the cached immutable snapshot, which is
18
+ // only replaced after a durable write, so a reader sees the old or the new
19
+ // document, never a partial one. Concurrent first reads share one load.
20
+ // * A queued operation must never call another queued mutator (that would
21
+ // wait behind itself and never settle). Operations inside the queue use
22
+ // `snapshot()` and `persistWithinQueue()`.
23
+ // * Every snapshot handed out (read, resolution of a mutator, hook argument)
24
+ // is deep-frozen, so an external caller cannot mutate service state.
25
+
26
+ import { SETTINGS_FILE, SCHEMA_VERSION, defaultSettings } from './defaults.js';
27
+ import { JsonDocument, deepFreeze } from './store.js';
28
+ import {
29
+ ConfigError,
30
+ canonicalProjectKey,
31
+ validateConversationSettings,
32
+ validateJobOverrides,
33
+ validateMonitoringSettings,
34
+ validateProjectOverride,
35
+ validateProviderProfile,
36
+ validateReviewSettings,
37
+ validateSelection,
38
+ validateSettings,
39
+ validateWorkerSettings,
40
+ } from './validate.js';
41
+
42
+ /**
43
+ * The conversation policy every run follows, frozen into each task snapshot.
44
+ *
45
+ * One sentence, in the task record, so a finished task can explain itself without
46
+ * the reader consulting a setting: a new submission is a new conversation, and a
47
+ * follow-up continues the thread named by `continueFromTaskId`.
48
+ */
49
+ export const CONVERSATION_POLICY = 'per-task';
50
+
51
+ /**
52
+ * Canonical key for one project path.
53
+ *
54
+ * The single source of truth is `canonicalProjectKey` in `validate.js`: the key
55
+ * persisted with a project override and the key used to look one up must be the
56
+ * same value produced by the same function, otherwise `C:/Work/Proj/`,
57
+ * `c:\work\proj` and `C:\Work\Proj` become three keys of which only one applies.
58
+ * @param {string} projectPath - absolute project path.
59
+ * @returns {{ key: string, display: string }} canonical lookup key and normalized display form.
60
+ */
61
+ export function projectKey(projectPath) {
62
+ return canonicalProjectKey(projectPath);
63
+ }
64
+
65
+ /**
66
+ * Index of canonical project key -> override block for one `projectOverrides`
67
+ * map.
68
+ *
69
+ * Validated documents already store canonical display keys, but a document
70
+ * written by an older build may hold a non-canonical spelling, so every key is
71
+ * canonicalized on the way into the index. Validation refuses two spellings of
72
+ * one project, so at most one block can land on a key. The cache is keyed by the
73
+ * (frozen) map itself, so it cannot go stale.
74
+ */
75
+ const PROJECT_INDEX = new WeakMap();
76
+
77
+ function projectOverrideIndex(projectOverrides) {
78
+ if (projectOverrides === null || typeof projectOverrides !== 'object') return new Map();
79
+ const cached = PROJECT_INDEX.get(projectOverrides);
80
+ if (cached !== undefined) return cached;
81
+ const index = new Map();
82
+ for (const [projectPath, block] of Object.entries(projectOverrides)) {
83
+ let key = projectPath;
84
+ try {
85
+ key = canonicalProjectKey(projectPath, 'projectOverrides key').key;
86
+ } catch {
87
+ // Unreachable for a validated document; keeping the raw key means a
88
+ // lookup still works instead of throwing from a read path.
89
+ }
90
+ index.set(key, block);
91
+ }
92
+ PROJECT_INDEX.set(projectOverrides, index);
93
+ return index;
94
+ }
95
+
96
+ /**
97
+ * Compose the effective execution snapshot for one job.
98
+ *
99
+ * Precedence, highest first: per-job override, project override, global
100
+ * settings. Every field in the result is either explicitly configured or a
101
+ * documented constant default; nothing reads an ambient harness default. The
102
+ * returned object is deep-frozen and is the value a job records as its immutable
103
+ * effective configuration.
104
+ * @param {object} settings - validated settings.
105
+ * @param {object} options - `projectPath` and `overrides`.
106
+ * @returns {object} frozen effective snapshot with its provenance.
107
+ */
108
+ export function resolveEffectiveConfig(settings, { projectPath = null, overrides = {} } = {}) {
109
+ const applied = [];
110
+ let worker = { ...settings.worker };
111
+ let review = { ...settings.review };
112
+ const canonical = projectPath === null || projectPath === undefined ? null : projectKey(projectPath);
113
+
114
+ if (canonical !== null) {
115
+ const projectBlock = projectOverrideIndex(settings.projectOverrides ?? {}).get(canonical.key);
116
+ if (projectBlock !== undefined) {
117
+ if (projectBlock.worker !== undefined) {
118
+ worker = mergeWorker(worker, projectBlock.worker);
119
+ applied.push('project:worker');
120
+ }
121
+ if (projectBlock.review !== undefined) {
122
+ review = { ...projectBlock.review };
123
+ applied.push('project:review');
124
+ }
125
+ }
126
+ }
127
+
128
+ const normalizedOverrides = validateJobOverrides(overrides, settings.providers);
129
+ if (Object.keys(normalizedOverrides).length > 0) {
130
+ worker = mergeWorker(worker, normalizedOverrides);
131
+ applied.push('job:worker');
132
+ }
133
+
134
+ // The three-layer merge is complete; re-validate the composed triple so a
135
+ // project block cannot leave a provider/model pair that global settings once
136
+ // made legal and a later edit invalidated.
137
+ const selection = validateSelection(worker, settings.providers, 'effective.worker');
138
+ const effectiveReview = review.enabled
139
+ ? { ...review, ...pluckSelection(validateSelection(review, settings.providers, 'effective.review')) }
140
+ : { enabled: false, providerId: null, model: null, reasoningEffort: null };
141
+
142
+ return deepFreeze({
143
+ schemaVersion: SCHEMA_VERSION,
144
+ worker: {
145
+ providerId: selection.providerId,
146
+ model: selection.model,
147
+ reasoningEffort: selection.reasoningEffort,
148
+ timeoutSeconds: worker.timeoutSeconds,
149
+ maxParallelism: worker.maxParallelism,
150
+ isolation: worker.isolation,
151
+ // Explicit placeholder for the native provider route. In this stage the
152
+ // route id is the profile id; the wire protocol and endpoint stay
153
+ // server-side facts resolved at call time. The later routing step freezes
154
+ // its decision against this field rather than re-deriving it.
155
+ providerRoute: selection.providerId,
156
+ },
157
+ review: {
158
+ enabled: effectiveReview.enabled === true,
159
+ providerId: effectiveReview.providerId ?? null,
160
+ model: effectiveReview.model ?? null,
161
+ reasoningEffort: effectiveReview.reasoningEffort ?? null,
162
+ providerRoute: effectiveReview.providerId ?? null,
163
+ },
164
+ // What this task does with its DSH conversation is NOT a settings fact any
165
+ // more: it is decided per submission by `continueFromTaskId`. The frozen
166
+ // snapshot therefore carries the rule rather than a stored mode, so a task
167
+ // record states what the plugin will do instead of echoing a retired setting.
168
+ conversation: { policy: CONVERSATION_POLICY },
169
+ // The silence thresholds this task runs under, FROZEN at admission. They are
170
+ // global-only (no project or per-job layer): an operator edits them rarely, and
171
+ // a per-job override would let one submission ask to be watched on a different
172
+ // clock than the alert thresholds the operator actually set. Freezing them here
173
+ // is what makes an edit during a live run apply to the NEXT task instead of
174
+ // silently retiming one already in flight.
175
+ monitoring: {
176
+ selfCheckSeconds: settings.monitoring.selfCheckSeconds,
177
+ attentionSeconds: settings.monitoring.attentionSeconds,
178
+ },
179
+ provenance: {
180
+ // Canonical, not the caller's spelling: a recorded snapshot must compare
181
+ // equal to the key its override is stored under.
182
+ projectPath: canonical === null ? null : canonical.display,
183
+ projectKey: canonical === null ? null : canonical.key,
184
+ applied,
185
+ },
186
+ });
187
+ }
188
+
189
+ function mergeWorker(base, patch) {
190
+ const next = { ...base };
191
+ for (const key of ['providerId', 'model', 'reasoningEffort', 'timeoutSeconds', 'isolation', 'maxParallelism']) {
192
+ if (patch[key] !== undefined) next[key] = patch[key];
193
+ }
194
+ return next;
195
+ }
196
+
197
+ function pluckSelection(selection) {
198
+ return { providerId: selection.providerId, model: selection.model, reasoningEffort: selection.reasoningEffort };
199
+ }
200
+
201
+ /**
202
+ * Project one preset without any field that could carry a secret.
203
+ * @param {object} preset - validated preset.
204
+ * @returns {object} projection.
205
+ */
206
+ function publicPreset(preset) {
207
+ return {
208
+ id: preset.id,
209
+ name: preset.name,
210
+ worker: preset.worker === null ? null : { ...preset.worker },
211
+ review: preset.review === null ? null : { ...preset.review },
212
+ };
213
+ }
214
+
215
+ /**
216
+ * Public, secret-free projection of settings for a settings surface or export.
217
+ *
218
+ * This is also the export shape: a preset holds only provider ids and
219
+ * worker/review blocks, so exporting presets exports no endpoint and no
220
+ * credential. A credential *reference* is included because it is a name, not a
221
+ * value; the value never enters this document.
222
+ * @param {object} settings - validated settings.
223
+ * @returns {object} deep-frozen projection containing no credential value at all.
224
+ */
225
+ export function publicSettings(settings) {
226
+ const presets = Array.isArray(settings.presets) ? settings.presets : [];
227
+ return deepFreeze({
228
+ schemaVersion: settings.schemaVersion,
229
+ delegationEnabled: settings.delegationEnabled === true,
230
+ providers: settings.providers.map((provider) => ({
231
+ id: provider.id,
232
+ name: provider.name,
233
+ source: provider.source ?? 'native',
234
+ ...(provider.source === 'native' ? {} : {
235
+ protocol: provider.protocol,
236
+ baseUrl: provider.baseUrl,
237
+ credentialRef: provider.credentialRef,
238
+ }),
239
+ models: provider.models.map((model) => ({ ...model, efforts: [...model.efforts] })),
240
+ })),
241
+ worker: { ...settings.worker },
242
+ review: { ...settings.review },
243
+ authorization: { ...settings.authorization },
244
+ // Included so a settings surface (and an export/import round-trip) sees the
245
+ // actual thresholds a new task will freeze. They are plain bounded integers,
246
+ // never a secret.
247
+ monitoring: { ...validateMonitoringSettings(settings.monitoring) },
248
+ projectOverrides: structuredClone(settings.projectOverrides ?? {}),
249
+ presets: presets.map(publicPreset),
250
+ // Kept in the export for compatibility with documents and clients that read
251
+ // it, but no longer a choice: the value is the retired directory-level mode and
252
+ // is inert. A restored configuration therefore cannot reintroduce implicit
253
+ // conversation reuse.
254
+ conversation: { ...validateConversationSettings(settings.conversation) },
255
+ });
256
+ }
257
+
258
+ /**
259
+ * Export envelope for settings.
260
+ *
261
+ * Deliberately identical to {@link publicSettings}: one projection, one place
262
+ * where a field could leak, one test surface. Nonsecret presets are included.
263
+ * @param {object} settings - validated settings.
264
+ * @returns {object} deep-frozen export document.
265
+ */
266
+ export function exportSettings(settings) {
267
+ return publicSettings(settings);
268
+ }
269
+
270
+ /** Refusal codes surfaced by the settings service. */
271
+ export const SETTINGS_CODES = Object.freeze({
272
+ invalid: 'SETTINGS_INVALID',
273
+ noProviders: 'SETTINGS_NO_PROVIDERS',
274
+ // The document was persisted but the post-commit notification hook failed.
275
+ // The write stands; see `details.persisted`.
276
+ changedHookFailed: 'SETTINGS_CHANGED_HOOK_FAILED',
277
+ });
278
+
279
+ /**
280
+ * Settings service owning the validated document and its persistence.
281
+ */
282
+ export class SettingsService {
283
+ /**
284
+ * @param {string} dataDir - plugin data directory.
285
+ * @param {object} [options] - lifecycle hooks.
286
+ * @param {(next: object, previous: object) => Promise<void> | void} [options.beforeCommit] -
287
+ * awaited after validation and before the durable write; throwing aborts the
288
+ * write, so the store and the cached snapshot keep the previous document.
289
+ * @param {(next: object, previous: object) => Promise<void> | void} [options.onChanged] -
290
+ * awaited after a successful durable write; the write stands even when it
291
+ * throws (see docs/config-contract.md).
292
+ */
293
+ constructor(dataDir, { beforeCommit, onChanged } = {}) {
294
+ for (const [name, hook] of [['beforeCommit', beforeCommit], ['onChanged', onChanged]]) {
295
+ if (hook !== undefined && hook !== null && typeof hook !== 'function') {
296
+ throw new TypeError(`SettingsService: ${name} must be a function when provided`);
297
+ }
298
+ }
299
+ this.document = new JsonDocument(dataDir, SETTINGS_FILE, {
300
+ schemaVersion: SCHEMA_VERSION,
301
+ initial: defaultSettings,
302
+ });
303
+ this.beforeCommit = beforeCommit ?? null;
304
+ this.onChanged = onChanged ?? null;
305
+ /** @type {object | null} last known validated, deep-frozen snapshot. */
306
+ this.cached = null;
307
+ /** @type {Promise<object> | null} in-flight first read, shared by concurrent readers. */
308
+ this.loading = null;
309
+ /** @type {Promise<void>} tail of the serial mutation queue. */
310
+ this.queue = Promise.resolve();
311
+ }
312
+
313
+ /**
314
+ * Read validated settings, refusing an unusable stored document loudly.
315
+ * A fresh install (absent file) yields the documented empty defaults whose
316
+ * selection fields are null; selection is validated only when a job is opened.
317
+ * Concurrent callers share one physical read and one validation pass.
318
+ * @returns {Promise<object>} validated settings, deep-frozen.
319
+ */
320
+ async read() {
321
+ if (this.cached !== null) return this.cached;
322
+ if (this.loading === null) {
323
+ this.loading = this.snapshot().finally(() => { this.loading = null; });
324
+ }
325
+ return await this.loading;
326
+ }
327
+
328
+ /**
329
+ * Load and validate the document without queuing.
330
+ *
331
+ * Safe to call from inside a queued operation: it never waits on the queue
332
+ * tail, so it cannot self-lock.
333
+ * @returns {Promise<object>} validated snapshot, deep-frozen.
334
+ */
335
+ async snapshot() {
336
+ if (this.cached !== null) return this.cached;
337
+ const raw = await this.document.load();
338
+ this.cached = deepFreeze(validateSettings(raw));
339
+ return this.cached;
340
+ }
341
+
342
+ /**
343
+ * Replace the stored document after full validation.
344
+ * @param {unknown} candidate - candidate settings document.
345
+ * @returns {Promise<object>} committed settings.
346
+ */
347
+ async replace(candidate) {
348
+ return await this.serialize(async () => {
349
+ const previous = await this.snapshot();
350
+ return await this.persistWithinQueue(candidate, previous);
351
+ });
352
+ }
353
+
354
+ /**
355
+ * Replace ordinary configuration while preserving the separately controlled
356
+ * delegation switch. The read and write share the same queue as switch edits,
357
+ * so a slow settings save cannot undo a concurrent disable.
358
+ * @param {unknown} candidate - settings-shaped object.
359
+ * @returns {Promise<object>} committed settings.
360
+ */
361
+ async replaceConfiguration(candidate) {
362
+ return await this.serialize(async () => {
363
+ const previous = await this.snapshot();
364
+ const next = candidate !== null && typeof candidate === 'object' && !Array.isArray(candidate)
365
+ ? { ...candidate, delegationEnabled: previous.delegationEnabled }
366
+ : candidate;
367
+ return await this.persistWithinQueue(next, previous);
368
+ });
369
+ }
370
+
371
+ /**
372
+ * Add or replace one provider profile.
373
+ * @param {unknown} candidate - candidate provider.
374
+ * @returns {Promise<object>} committed settings.
375
+ */
376
+ async upsertProvider(candidate) {
377
+ // Shape validation is pure, so it happens before the turn is queued; the
378
+ // read that depends on current state happens inside it.
379
+ const profile = validateProviderProfile(candidate);
380
+ return await this.serialize(async () => {
381
+ const previous = await this.snapshot();
382
+ const providers = previous.providers.filter((entry) => entry.id !== profile.id);
383
+ providers.push(profile);
384
+ return await this.persistWithinQueue({ ...previous, providers }, previous);
385
+ });
386
+ }
387
+
388
+ /**
389
+ * Remove one provider profile. A provider still referenced by worker or
390
+ * review settings is refused: silently dropping the reference would leave
391
+ * delegation pointing at nothing.
392
+ * @param {string} providerId - provider to remove.
393
+ * @returns {Promise<object>} committed settings.
394
+ */
395
+ async removeProvider(providerId) {
396
+ return await this.serialize(async () => {
397
+ const previous = await this.snapshot();
398
+ const providers = previous.providers.filter((entry) => entry.id !== providerId);
399
+ if (previous.worker.providerId === providerId) {
400
+ throw new ConfigError('PROVIDER_IN_USE', 'the worker settings select this provider', { providerId, role: 'worker' });
401
+ }
402
+ if (previous.review.enabled && previous.review.providerId === providerId) {
403
+ throw new ConfigError('PROVIDER_IN_USE', 'the additional review selects this provider', { providerId, role: 'review' });
404
+ }
405
+ for (const [projectPath, block] of Object.entries(previous.projectOverrides)) {
406
+ if (block?.worker?.providerId === providerId || block?.review?.providerId === providerId) {
407
+ throw new ConfigError('PROVIDER_IN_USE', 'a project override selects this provider', { providerId, projectPath });
408
+ }
409
+ }
410
+ if (providers.length === 0) {
411
+ // No provider is left: keeping a selection or a project override would
412
+ // leave a document that cannot run. Presets are combinations of a
413
+ // provider triple, so they go with it.
414
+ return await this.persistWithinQueue({
415
+ ...previous,
416
+ providers,
417
+ worker: defaultSettings().worker,
418
+ review: defaultSettings().review,
419
+ projectOverrides: {},
420
+ presets: [],
421
+ }, previous);
422
+ }
423
+ return await this.persistWithinQueue({ ...previous, providers }, previous);
424
+ });
425
+ }
426
+
427
+ /**
428
+ * Replace the worker execution settings block.
429
+ * @param {unknown} candidate - candidate worker block.
430
+ * @returns {Promise<object>} committed settings.
431
+ */
432
+ async setWorker(candidate) {
433
+ return await this.serialize(async () => {
434
+ const previous = await this.snapshot();
435
+ const worker = validateWorkerSettings(candidate, previous.providers);
436
+ return await this.persistWithinQueue({ ...previous, worker }, previous);
437
+ });
438
+ }
439
+
440
+ /**
441
+ * Refuse to write a conversation block from a settings edit.
442
+ *
443
+ * The directory-level conversation mode has been removed, so there is no longer
444
+ * an operator control for it and no legitimate caller for this mutator. It is
445
+ * kept as a stated refusal rather than deleted so an older client that still
446
+ * posts the block gets an explanation instead of a silent no-op — the failure
447
+ * mode where a page believes it saved a mode that governs runs.
448
+ * @param {unknown} _candidate - ignored.
449
+ * @returns {Promise<never>} never resolves.
450
+ * @throws {ConfigError} always, with `code: CONVERSATION_MODE_REMOVED`.
451
+ */
452
+ async setConversation(_candidate) {
453
+ throw new ConfigError(
454
+ 'CONVERSATION_MODE_REMOVED',
455
+ 'the directory-level conversation mode has been removed; new submissions always start a new DSH conversation, '
456
+ + 'and a follow-up continues the thread named by continueFromTaskId',
457
+ { field: 'conversation.mode', replacement: 'continueFromTaskId' },
458
+ );
459
+ }
460
+
461
+ /**
462
+ * Replace the additional-review block. Enabling review requires a complete,
463
+ * independently valid provider/model/effort triple.
464
+ * @param {unknown} candidate - candidate review block.
465
+ * @returns {Promise<object>} committed settings.
466
+ */
467
+ async setReview(candidate) {
468
+ return await this.serialize(async () => {
469
+ const previous = await this.snapshot();
470
+ const review = validateReviewSettings(candidate, previous.providers);
471
+ return await this.persistWithinQueue({ ...previous, review }, previous);
472
+ });
473
+ }
474
+
475
+ /**
476
+ * Replace or clear one project override.
477
+ *
478
+ * The path is canonicalized before use, and every stored key that canonicalizes
479
+ * to the same project is replaced or removed, so an override written under an
480
+ * older spelling is still reachable - and clearable - through any spelling.
481
+ * @param {string} projectPath - absolute project path.
482
+ * @param {unknown} block - project block, or null to clear.
483
+ * @returns {Promise<object>} committed settings.
484
+ */
485
+ async setProjectOverride(projectPath, block) {
486
+ const { key, display } = projectKey(projectPath);
487
+ return await this.serialize(async () => {
488
+ const previous = await this.snapshot();
489
+ const projectOverrides = {};
490
+ for (const [storedPath, storedBlock] of Object.entries(previous.projectOverrides)) {
491
+ let storedKey = storedPath;
492
+ try {
493
+ storedKey = projectKey(storedPath).key;
494
+ } catch {
495
+ // Unreachable for a validated document; keep the entry visible instead
496
+ // of failing an unrelated edit.
497
+ }
498
+ if (storedKey !== key) projectOverrides[storedPath] = storedBlock;
499
+ }
500
+ if (block !== null && block !== undefined) {
501
+ projectOverrides[display] = validateProjectOverride(block, previous.providers);
502
+ }
503
+ return await this.persistWithinQueue({ ...previous, projectOverrides }, previous);
504
+ });
505
+ }
506
+
507
+ /**
508
+ * Set the single delegation switch through the same serialized write path as
509
+ * every other setting mutation.
510
+ * @param {boolean} enabled - whether the local MCP surface may submit work.
511
+ * @returns {Promise<object>} committed settings.
512
+ */
513
+ async setDelegationEnabled(enabled) {
514
+ if (typeof enabled !== 'boolean') {
515
+ throw new ConfigError('SETTINGS_INVALID', 'delegationEnabled must be a boolean', { field: 'delegationEnabled' });
516
+ }
517
+ return await this.serialize(async () => {
518
+ const previous = await this.snapshot();
519
+ return await this.persistWithinQueue({ ...previous, delegationEnabled: enabled }, previous);
520
+ });
521
+ }
522
+
523
+ /** Replace legacy grant TTL values when reading an older client document. */
524
+ async setAuthorization(candidate) {
525
+ return await this.serialize(async () => {
526
+ const previous = await this.snapshot();
527
+ return await this.persistWithinQueue({ ...previous, authorization: candidate }, previous);
528
+ });
529
+ }
530
+
531
+ /**
532
+ * Replace the activity-monitoring block.
533
+ *
534
+ * This is the mutator a later authenticated UI endpoint calls; it is the only
535
+ * write path for these two thresholds, so the bounds and the ordering rule live
536
+ * in exactly one place ({@link validateMonitoringSettings}) and no caller can
537
+ * persist a pair the monitor would refuse to run.
538
+ *
539
+ * The write goes through the same serialized queue as every other settings
540
+ * mutation, so it cannot lose a concurrent edit and a fresh task admitted after
541
+ * it freezes the new values. A task already running keeps the snapshot it froze.
542
+ * @param {unknown} candidate - `{ selfCheckSeconds, attentionSeconds }`.
543
+ * @returns {Promise<object>} committed settings.
544
+ */
545
+ async setMonitoring(candidate) {
546
+ // Shape validation is pure, so it happens before the turn is queued.
547
+ const monitoring = validateMonitoringSettings(candidate);
548
+ return await this.serialize(async () => {
549
+ const previous = await this.snapshot();
550
+ return await this.persistWithinQueue({ ...previous, monitoring }, previous);
551
+ });
552
+ }
553
+
554
+ /**
555
+ * Validate and commit a whole settings-shaped document.
556
+ *
557
+ * Unlike the block mutators this accepts an entire document, which is the path
558
+ * an import or an export round-trip uses. It queues like every other write; it
559
+ * exists as a named entry point rather than as a second write path.
560
+ * @param {object} candidate - settings-shaped object.
561
+ * @returns {Promise<object>} committed settings.
562
+ */
563
+ async replaceValidated(candidate) {
564
+ return await this.replace(candidate);
565
+ }
566
+
567
+ /**
568
+ * Run one operation after every operation queued before it.
569
+ *
570
+ * The tail is settled in both outcomes: a rejected operation does not poison
571
+ * the queue for the rest of the process. The caller awaits the operation's own
572
+ * promise, so a failure stays with the caller who caused it.
573
+ * @param {() => Promise<object>} operation - queued operation.
574
+ * @returns {Promise<object>} the operation's result.
575
+ */
576
+ serialize(operation) {
577
+ const run = this.queue.then(() => operation());
578
+ this.queue = run.then(() => undefined, () => undefined);
579
+ return run;
580
+ }
581
+
582
+ /**
583
+ * Validate, notify, persist and notify again - only ever called from inside
584
+ * {@link SettingsService#serialize}.
585
+ *
586
+ * Order and failure semantics:
587
+ * 1. `beforeCommit(next, previous)` is awaited. A throw aborts here: nothing
588
+ * is written and `cached` still holds `previous`.
589
+ * 2. the durable write happens. A throw leaves the store and `cached` on the
590
+ * previous document.
591
+ * 3. `cached` becomes the persisted snapshot.
592
+ * 4. `onChanged(next, previous)` is awaited. A throw does not roll back the
593
+ * write; it surfaces as SETTINGS_CHANGED_HOOK_FAILED with
594
+ * `details.persisted = true` so a caller can tell the two cases apart.
595
+ * @param {unknown} candidate - unvalidated next document.
596
+ * @param {object} previous - validated previous snapshot.
597
+ * @returns {Promise<object>} committed settings.
598
+ */
599
+ async persistWithinQueue(candidate, previous) {
600
+ const next = deepFreeze(validateSettings(candidate));
601
+
602
+ if (this.beforeCommit !== null) {
603
+ // A throw here is a refusal: no write, no cache change. The hook is what
604
+ // pre-registers a provider with the native registry, and a provider that
605
+ // could not be registered must not be persisted.
606
+ await this.beforeCommit(next, previous);
607
+ }
608
+
609
+ const persisted = await this.document.commit(() => structuredClone(next));
610
+ this.cached = persisted;
611
+
612
+ if (this.onChanged !== null) {
613
+ try {
614
+ await this.onChanged(persisted, previous);
615
+ } catch (error) {
616
+ throw new ConfigError(
617
+ SETTINGS_CODES.changedHookFailed,
618
+ 'the settings document was persisted but the change notification failed',
619
+ {
620
+ persisted: true,
621
+ cause: typeof error?.code === 'string' ? error.code : null,
622
+ detail: typeof error?.message === 'string' ? error.message.slice(0, 300) : null,
623
+ },
624
+ );
625
+ }
626
+ }
627
+ return persisted;
628
+ }
629
+ }