@kirkchinese/harness-forge 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +4 -0
  2. package/docs/DETAIL.zh.md +47 -0
  3. package/lib/agents/presets.d.ts +7 -0
  4. package/lib/agents/presets.js +11 -1
  5. package/lib/agents/profiles.js +3 -2
  6. package/lib/agents/row.js +3 -1
  7. package/lib/client/paths.d.ts +12 -0
  8. package/lib/client/paths.js +68 -0
  9. package/lib/client/typert.d.ts +12 -1
  10. package/lib/client/typert.js +54 -6
  11. package/lib/client.js +1593 -270
  12. package/lib/commands/row.js +1 -1
  13. package/lib/context/instructions.js +5 -5
  14. package/lib/dsh/host.d.ts +3 -0
  15. package/lib/dsh/host.js +3 -0
  16. package/lib/forge/contract.d.ts +42 -2
  17. package/lib/forge/contract.js +3 -1
  18. package/lib/forge/follow.d.ts +30 -0
  19. package/lib/forge/follow.js +73 -0
  20. package/lib/forge/ledger.d.ts +70 -7
  21. package/lib/forge/ledger.js +314 -42
  22. package/lib/forge/projects.d.ts +5 -2
  23. package/lib/forge/projects.js +23 -16
  24. package/lib/forge/remote/archive.d.ts +65 -0
  25. package/lib/forge/remote/archive.js +565 -0
  26. package/lib/forge/remote/code-parts.d.ts +18 -0
  27. package/lib/forge/remote/code-parts.js +76 -0
  28. package/lib/forge/remote/fetch.d.ts +265 -0
  29. package/lib/forge/remote/fetch.js +1133 -0
  30. package/lib/forge/remote/service.d.ts +256 -0
  31. package/lib/forge/remote/service.js +868 -0
  32. package/lib/forge/service.d.ts +19 -9
  33. package/lib/forge/service.js +47 -31
  34. package/lib/forge/settings.d.ts +5 -3
  35. package/lib/forge/settings.js +11 -4
  36. package/lib/forge/state.d.ts +60 -0
  37. package/lib/forge/state.js +174 -58
  38. package/lib/hooks/broker/engine.js +2 -8
  39. package/lib/hooks/broker/session-events.d.ts +5 -0
  40. package/lib/hooks/broker/session-events.js +12 -3
  41. package/lib/hooks/broker/types.d.ts +7 -5
  42. package/lib/hooks/condition.d.ts +78 -2
  43. package/lib/hooks/condition.js +494 -73
  44. package/lib/hooks/config.d.ts +1 -1
  45. package/lib/hooks/config.js +4 -0
  46. package/lib/hooks/glob.d.ts +41 -0
  47. package/lib/hooks/glob.js +114 -0
  48. package/lib/hooks/permissions.d.ts +8 -3
  49. package/lib/hooks/permissions.js +119 -26
  50. package/lib/hooks/powershell-aliases.d.ts +19 -0
  51. package/lib/hooks/powershell-aliases.js +58 -0
  52. package/lib/hooks/process.d.ts +17 -0
  53. package/lib/hooks/process.js +156 -1
  54. package/lib/hooks/row.js +2 -0
  55. package/lib/hooks/runner.d.ts +17 -4
  56. package/lib/hooks/runner.js +42 -13
  57. package/lib/hooks/shell-commands.d.ts +10 -1
  58. package/lib/hooks/shell-commands.js +74 -10
  59. package/lib/hooks/shell.d.ts +3 -2
  60. package/lib/hooks/shell.js +5 -2
  61. package/lib/hooks/vocabulary.js +3 -1
  62. package/lib/mcp/catalog.d.ts +5 -2
  63. package/lib/mcp/catalog.js +18 -10
  64. package/lib/mcp/mount.d.ts +40 -2
  65. package/lib/mcp/mount.js +131 -31
  66. package/lib/mcp/policy.d.ts +42 -0
  67. package/lib/mcp/policy.js +43 -0
  68. package/lib/mcp/remote.js +5 -15
  69. package/lib/mcp/row.js +111 -17
  70. package/lib/mods/loader.js +4 -0
  71. package/lib/mods/service/turns.d.ts +8 -7
  72. package/lib/mods/service/turns.js +10 -35
  73. package/lib/opencode/bun.js +14 -2
  74. package/lib/opencode/row.d.ts +14 -1
  75. package/lib/opencode/row.js +38 -20
  76. package/lib/opencode/runtime/server.js +2 -1
  77. package/lib/porting/adapter-paths.d.ts +13 -0
  78. package/lib/porting/adapter-paths.js +120 -0
  79. package/lib/porting/port-gap.d.ts +10 -4
  80. package/lib/porting/port-gap.js +43 -7
  81. package/lib/porting/prompt.js +9 -7
  82. package/lib/porting/row.js +7 -5
  83. package/lib/porting/verify-port.d.ts +3 -10
  84. package/lib/porting/verify-port.js +12 -34
  85. package/lib/sessions/chat-import.d.ts +48 -0
  86. package/lib/sessions/chat-import.js +44 -0
  87. package/lib/sessions/claude.d.ts +16 -10
  88. package/lib/sessions/claude.js +76 -55
  89. package/lib/sessions/codex-discover.d.ts +34 -0
  90. package/lib/sessions/codex-discover.js +205 -0
  91. package/lib/sessions/codex-meta.d.ts +63 -0
  92. package/lib/sessions/codex-meta.js +148 -0
  93. package/lib/sessions/codex-text.d.ts +9 -0
  94. package/lib/sessions/codex-text.js +44 -0
  95. package/lib/sessions/codex.d.ts +34 -22
  96. package/lib/sessions/codex.js +150 -183
  97. package/lib/sessions/opencode.d.ts +15 -9
  98. package/lib/sessions/opencode.js +77 -58
  99. package/lib/sessions/persist.d.ts +162 -0
  100. package/lib/sessions/persist.js +377 -0
  101. package/lib/sessions/row.d.ts +2 -1
  102. package/lib/sessions/row.js +75 -9
  103. package/lib/sessions/turns.d.ts +31 -0
  104. package/lib/sessions/turns.js +63 -0
  105. package/lib/sessions/zstd.d.ts +15 -0
  106. package/lib/sessions/zstd.js +152 -0
  107. package/lib/shared/render.d.ts +30 -1
  108. package/lib/shared/render.js +813 -48
  109. package/lib/skills/provider.d.ts +2 -0
  110. package/lib/skills/provider.js +8 -2
  111. package/lib/skills/row.js +1 -1
  112. package/lib/workbench/adapter-coverage.d.ts +20 -2
  113. package/lib/workbench/adapter-coverage.js +46 -7
  114. package/lib/workbench/overview.d.ts +77 -27
  115. package/lib/workbench/overview.js +99 -12
  116. package/lib/workbench/remote.d.ts +64 -21
  117. package/lib/workbench/remote.js +181 -42
  118. package/lib/workbench/settings.d.ts +5 -1
  119. package/lib/workbench/settings.js +6 -2
  120. package/lib/workbench/workbench.d.ts +34 -4
  121. package/lib/workbench/workbench.js +147 -46
  122. package/locale/zh.json +2 -1
  123. package/package.json +3 -2
  124. package/lib/forge/marketplace-install.d.ts +0 -3
  125. package/lib/forge/marketplace-install.js +0 -64
@@ -10,13 +10,14 @@ import { randomUUID } from 'node:crypto';
10
10
  import { existsSync } from 'node:fs';
11
11
  import { homedir } from 'node:os';
12
12
  import { dirname, resolve } from 'node:path';
13
- import { assess, dialects, fingerprintPlugin, HarnessError, planPlugin, scanRoot, shortHash, } from '@kirkchinese/harness-forge-core';
13
+ import { assess, dialects, fingerprintPlugin, HarnessError, dialectOf, harnessInstalls, planPlugin, scanRoot, shortHash, } from '@kirkchinese/harness-forge-core';
14
14
  import { pluginDataDir } from '../mcp/mount.js';
15
15
  import { writeReceipt, readReceipt } from './receipts.js';
16
16
  import { messageOf } from '../shared/util.js';
17
17
  import { mountKindOf, ROW_OF_KIND } from './contract.js';
18
18
  import { LiveMounts } from './live-mounts.js';
19
- import { isTransient, readState, receiptsDirectory, retryFile, writeState, } from './state.js';
19
+ import { followingChanges, followingOf, newHarnessInstall, withHarnessInstall } from './follow.js';
20
+ import { isTransient, loadState, receiptsDirectory, retryFile, writeState, } from './state.js';
20
21
  /** Observations kept per component: the newest per signal, bounded. */
21
22
  const MAX_OBSERVATIONS = 96;
22
23
  const PERSIST_DELAY_MS = 500;
@@ -39,6 +40,12 @@ export function failedToSwitchOff(componentId, reason) {
39
40
  export function failedToCleanUp(componentId, reason) {
40
41
  return { componentId, status: 'failed', level: 'L0', evidence: 'runtime', message: `failed to clean up after a failed install: ${reason}` };
41
42
  }
43
+ /** What an outcome's message says when the plugin's harness no longer runs it (see `follow.ts`). */
44
+ export const NOT_FOLLOWED = 'not run: its harness no longer runs this plugin';
45
+ /** The outcome of a component of a detached plugin: off until the person removes or keeps the plugin. */
46
+ export function notFollowed(componentId) {
47
+ return { componentId, status: 'inactive', level: 'L0', evidence: 'source', message: NOT_FOLLOWED };
48
+ }
42
49
  function skipped(componentId, message) {
43
50
  return { componentId, status: 'skipped', level: 'L0', evidence: 'source', message };
44
51
  }
@@ -58,10 +65,16 @@ export class Ledger {
58
65
  disposed = false;
59
66
  queue = Promise.resolve();
60
67
  persistTimer;
61
- /** Why the ledger could not be read at startup; while set, it is never written. */
62
- unreadLedger;
68
+ /** Records being applied (restored at startup, or followed to their harness's change) and how many are done. */
69
+ progress = { done: 0, total: 0 };
70
+ /** The last unreadable-record problem reported per harness, so each is said once, not at every page load. */
71
+ unreadReported = new Map();
72
+ /** The follow pass queued and not yet run: another request joins it instead of queueing its own. */
73
+ following;
74
+ /** Why the ledger may not be written (unreadable at startup, or a newer Harness Forge's); while set, it never is. */
75
+ writeRefusal;
63
76
  constructor(ctx, statePath, dataRoot,
64
- /** Where a withdrawal that failed is recorded (the shared service's faults). */
77
+ /** Where a withdrawal that failed, or a ledger read only in part, is recorded (the shared service's faults). */
65
78
  fault) {
66
79
  this.ctx = ctx;
67
80
  this.statePath = statePath;
@@ -77,7 +90,7 @@ export class Ledger {
77
90
  if (this.mounters.has(kind))
78
91
  throw new HarnessError('internal', `a mounter for ${kind} is already registered`);
79
92
  this.mounters.set(kind, mounter);
80
- this.reapply();
93
+ this.reapply(kind);
81
94
  return () => {
82
95
  if (this.mounters.get(kind) !== mounter)
83
96
  return;
@@ -88,9 +101,11 @@ export class Ledger {
88
101
  }
89
102
  /**
90
103
  * Re-apply installed plans; only actions without a live registration run.
91
- * Called when a mounter appears.
104
+ * Called when a mounter appears: with its kind, only that kind's actions
105
+ * mount, so a part that failed (a server that cannot start) is tried again
106
+ * when its own row comes back, not once for every row that starts at boot.
92
107
  */
93
- reapply() {
108
+ reapply(kind) {
94
109
  if (this.disposed)
95
110
  return;
96
111
  void this.exclusive(async () => {
@@ -100,7 +115,7 @@ export class Ledger {
100
115
  if (install.plan === undefined)
101
116
  continue;
102
117
  try {
103
- await this.applyNow(install.plan);
118
+ await this.applyNow(install.plan, kind);
104
119
  }
105
120
  catch {
106
121
  // The ledger keeps the previous outcome; the next re-apply runs again.
@@ -195,44 +210,83 @@ export class Ledger {
195
210
  return run;
196
211
  }
197
212
  async restoreNow() {
198
- let state;
213
+ let loaded;
199
214
  try {
200
- state = await retryFile(() => readState(this.statePath));
215
+ loaded = await retryFile(() => loadState(this.statePath));
201
216
  }
202
217
  catch (error) {
203
218
  // Writing now would replace the ledger with what is live: nothing. Every write is refused until it is read.
204
- this.unreadLedger = messageOf(error);
219
+ this.writeRefusal = {
220
+ message: `the ledger could not be read at startup (${messageOf(error)}); nothing is written over it`,
221
+ suggestion: 'Fix or move aside .harness-forge/state.json, then restart DSH.',
222
+ };
205
223
  throw error;
206
224
  }
207
- this.unreadLedger = undefined;
208
- for (const record of state.plugins) {
209
- if (this.live.has(record.id))
210
- continue;
211
- if (!existsSync(record.root)) {
212
- this.keepUnrestored(record, `source directory is missing: ${record.root}`);
213
- continue;
214
- }
225
+ if (loaded.readOnly !== undefined) {
226
+ // A newer Harness Forge's ledger: never downgraded, never overwritten.
227
+ this.writeRefusal = { message: loaded.readOnly, suggestion: 'Upgrade Harness Forge, then restart DSH.' };
228
+ this.faultOf(new Error(loaded.readOnly));
229
+ return;
230
+ }
231
+ this.writeRefusal = undefined;
232
+ if (loaded.rejected.length > 0) {
233
+ this.faultOf(new Error(`part of the ledger could not be read and was left out: ${loaded.rejected.join('; ')}. The file as it was is kept at ${loaded.backup ?? this.statePath}`));
234
+ }
235
+ const state = loaded.state;
236
+ const current = this.readHarnesses();
237
+ this.begin(state.plugins.length);
238
+ for (const stored of state.plugins) {
215
239
  try {
216
- const plan = this.planNow(record.root, record.source);
217
- if (record.fingerprint !== undefined && plan.fingerprint.digest !== record.fingerprint.digest) {
218
- // The source changed while DSH was closed; apply its current content.
219
- this.live.set(record.id, { record, mounts: new LiveMounts(this.faultOf), outcomes: new Map() });
220
- }
221
- else {
222
- this.live.set(record.id, {
223
- record,
224
- mounts: new LiveMounts(this.faultOf),
225
- outcomes: new Map((record.outcomes ?? []).map(outcome => [outcome.componentId, outcome])),
226
- });
227
- }
228
- await this.applyNow(plan);
240
+ if (!this.live.has(stored.id))
241
+ await this.restoreRecord(withHarnessInstall(stored, current, homedir()), current);
229
242
  }
230
- catch (error) {
231
- this.keepUnrestored(record, messageOf(error));
243
+ finally {
244
+ this.step();
232
245
  }
233
246
  }
234
247
  this.persist();
235
248
  }
249
+ /** Restore one record, following its harness: to the folder of a new version, or detached when no longer run. */
250
+ async restoreRecord(stored, current) {
251
+ const following = followingOf(stored, current);
252
+ if (following.kind === 'detached' || (following.kind === 'none' && stored.detached !== undefined)) {
253
+ this.keepDetached(stored, following.kind === 'detached' ? following.reason : stored.detached.reason);
254
+ return;
255
+ }
256
+ const { detached: _attached, ...record } = following.kind === 'none' ? stored : { ...stored, harnessInstall: following.identity };
257
+ if (following.kind === 'moved') {
258
+ this.live.set(record.id, { record, mounts: new LiveMounts(this.faultOf), outcomes: new Map() });
259
+ try {
260
+ await this.moveNow(record.id, following.root);
261
+ }
262
+ catch {
263
+ // The move could not apply: the plugin was restored from its old folder, or kept with why it was not.
264
+ }
265
+ return;
266
+ }
267
+ if (!existsSync(record.root)) {
268
+ this.keepUnrestored(record, `source directory is missing: ${record.root}`);
269
+ return;
270
+ }
271
+ try {
272
+ const plan = this.planNow(record.root, record.source);
273
+ if (record.fingerprint !== undefined && plan.fingerprint.digest !== record.fingerprint.digest) {
274
+ // The source changed while DSH was closed; apply its current content.
275
+ this.live.set(record.id, { record, mounts: new LiveMounts(this.faultOf), outcomes: new Map() });
276
+ }
277
+ else {
278
+ this.live.set(record.id, {
279
+ record,
280
+ mounts: new LiveMounts(this.faultOf),
281
+ outcomes: new Map((record.outcomes ?? []).map(outcome => [outcome.componentId, outcome])),
282
+ });
283
+ }
284
+ await this.applyNow(plan);
285
+ }
286
+ catch (error) {
287
+ this.keepUnrestored(record, messageOf(error));
288
+ }
289
+ }
236
290
  /** Keep a record that could not be restored visible, with the reason. */
237
291
  keepUnrestored(record, reason) {
238
292
  const outcomes = (record.outcomes ?? []).map(outcome => ({ ...outcome, status: 'failed', message: `not restored: ${reason}` }));
@@ -242,6 +296,165 @@ export class Ledger {
242
296
  outcomes: new Map(outcomes.map(outcome => [outcome.componentId, outcome])),
243
297
  });
244
298
  }
299
+ /** Keep a record its harness no longer runs listed, nothing of it mounted. */
300
+ keepDetached(record, reason, stillLive = []) {
301
+ const detached = record.detached?.reason === reason ? record.detached : { reason, at: new Date().toISOString() };
302
+ const ids = new Set([...(record.outcomes ?? []).map(outcome => outcome.componentId), ...this.live.get(record.id)?.plan?.actions.flatMap(action => action.componentId ?? []) ?? []]);
303
+ const stuck = new Map(stillLive.map(outcome => [outcome.componentId, outcome]));
304
+ const outcomes = [...ids].map(id => stuck.get(id) ?? notFollowed(id));
305
+ const mounts = this.live.get(record.id)?.mounts ?? new LiveMounts(this.faultOf);
306
+ this.live.set(record.id, {
307
+ record: { ...record, detached, outcomes, mounts: [], skillRoots: [] },
308
+ mounts,
309
+ outcomes: new Map(outcomes.map(outcome => [outcome.componentId, outcome])),
310
+ });
311
+ }
312
+ /** Detach a live plugin its harness no longer runs: its registrations are withdrawn, the record kept. */
313
+ async detachNow(id, reason) {
314
+ const install = this.live.get(id);
315
+ if (install === undefined)
316
+ return;
317
+ const { failed } = await install.mounts.release();
318
+ for (const mounter of this.mounters.values())
319
+ await mounter.settle?.(GLOBAL_SCOPE).catch(() => undefined);
320
+ // A registration that could not be withdrawn stays shown as such: following again retries nothing, removing does.
321
+ this.keepDetached(install.record, reason, failed.map(({ mount, reason: why }) => failedToSwitchOff(mount.componentId, why)));
322
+ }
323
+ /**
324
+ * Move a followed plugin to the folder its harness now runs (an update), as Get plugins' Update moves a fetched
325
+ * one (see {@link rerootNow}): the parts the person switched off stay off, and the move is noted on the record.
326
+ */
327
+ async moveNow(id, root) {
328
+ const before = this.live.get(id)?.record;
329
+ if (before === undefined)
330
+ return;
331
+ await this.rerootNow(id, root, before.source);
332
+ const install = this.live.get(id);
333
+ if (install === undefined)
334
+ return;
335
+ install.record = { ...install.record, harnessUpdate: { ...(before.version !== undefined ? { from: before.version } : {}), ...(install.record.version !== undefined ? { to: install.record.version } : {}), at: new Date().toISOString() } };
336
+ this.persist();
337
+ }
338
+ /**
339
+ * Follow every harness's changes since the last pass (see `follow.ts`). Queued behind the ledger's other work;
340
+ * nothing is queued when no record needs anything, and a pass already waiting is joined. Settles when it has run.
341
+ */
342
+ follow() {
343
+ if (this.disposed)
344
+ return Promise.resolve();
345
+ if (this.following !== undefined)
346
+ return this.following;
347
+ const current = this.readHarnesses();
348
+ const pending = [...this.live.values()].filter(install => install.unrecorded !== true && followingChanges(install.record, followingOf(install.record, current))).map(install => install.record.id);
349
+ if (pending.length === 0)
350
+ return Promise.resolve();
351
+ this.begin(pending.length);
352
+ const run = this.exclusive(async () => {
353
+ this.following = undefined;
354
+ // Read again: the harness may have changed while the pass waited.
355
+ const now = this.readHarnesses();
356
+ for (const id of pending) {
357
+ try {
358
+ if (!this.disposed)
359
+ await this.followOne(id, now);
360
+ }
361
+ catch (error) {
362
+ this.faultOf(error);
363
+ }
364
+ finally {
365
+ this.step();
366
+ }
367
+ }
368
+ this.persist();
369
+ });
370
+ this.following = run.catch(() => undefined);
371
+ return this.following;
372
+ }
373
+ /**
374
+ * What every harness has installed now. A harness whose record could not be read in full, while plugins migrated
375
+ * from it follow it, is reported once per distinct problem: nothing of those plugins changes until it reads whole.
376
+ */
377
+ readHarnesses() {
378
+ const current = harnessInstalls(homedir());
379
+ const followed = new Set([...this.live.values()].flatMap(install => install.record.harnessInstall?.harness ?? []));
380
+ for (const harness of new Set([...this.unreadReported.keys(), ...current.uncertain])) {
381
+ const problems = current.unread.filter(item => item.harness === harness).map(item => item.message);
382
+ const said = problems.join('; ');
383
+ if (problems.length === 0)
384
+ this.unreadReported.delete(harness);
385
+ else if (this.unreadReported.get(harness) !== said && followed.has(harness)) {
386
+ this.unreadReported.set(harness, said);
387
+ const label = dialectOf(harness)?.label ?? harness;
388
+ this.faultOf(new Error(`couldn't read ${label}'s plugin list (${said}); nothing changed for the plugins migrated from ${label}, and it is read again at the next load`));
389
+ }
390
+ }
391
+ return current;
392
+ }
393
+ /** Follow one live plugin's harness install. */
394
+ async followOne(id, current) {
395
+ const install = this.live.get(id);
396
+ if (install === undefined || install.unrecorded === true)
397
+ return;
398
+ const following = followingOf(install.record, current);
399
+ if (!followingChanges(install.record, following))
400
+ return;
401
+ if (following.kind === 'detached')
402
+ return this.detachNow(id, following.reason);
403
+ if (following.kind === 'none')
404
+ return;
405
+ const { detached, ...record } = install.record;
406
+ install.record = { ...record, harnessInstall: following.identity };
407
+ if (following.kind === 'moved')
408
+ return this.moveNow(id, following.root);
409
+ // Running again where it was (installed again, switched on again): its parts mount as at install.
410
+ if (detached === undefined)
411
+ return;
412
+ try {
413
+ await this.applyNow(this.planNow(record.root, record.source));
414
+ }
415
+ catch (error) {
416
+ this.keepUnrestored(install.record, messageOf(error));
417
+ throw error;
418
+ }
419
+ }
420
+ /**
421
+ * Keep a plugin its harness no longer runs as the person's own copy, in the folder it is in: it follows no harness
422
+ * any more and its parts mount again.
423
+ */
424
+ async keepNow(id) {
425
+ this.assertAlive();
426
+ const install = this.live.get(id);
427
+ if (install === undefined)
428
+ throw new HarnessError('not-installed', `no installed plugin ${id}`);
429
+ if (install.record.detached === undefined)
430
+ throw new HarnessError('internal', `${id} is still run by its harness; there is nothing to keep`);
431
+ if (!existsSync(install.record.root)) {
432
+ throw new HarnessError('manifest-not-found', `the plugin's folder is gone: ${install.record.root}`, { suggestion: 'Remove it, or install it again in its harness.' });
433
+ }
434
+ const previous = install.record;
435
+ const { detached: _detached, harnessInstall: _followed, ...record } = previous;
436
+ install.record = { ...record, keptAt: new Date().toISOString() };
437
+ install.outcomes.clear();
438
+ try {
439
+ return await this.applyNow(this.planNow(record.root, record.source));
440
+ }
441
+ catch (error) {
442
+ this.keepDetached(previous, previous.detached.reason);
443
+ throw error;
444
+ }
445
+ }
446
+ /** How far applying records has got, while any are still being applied. */
447
+ applying() {
448
+ return this.progress.total === 0 ? undefined : { ...this.progress };
449
+ }
450
+ begin(count) {
451
+ this.progress.total += count;
452
+ }
453
+ step() {
454
+ this.progress.done++;
455
+ if (this.progress.done >= this.progress.total)
456
+ this.progress = { done: 0, total: 0 };
457
+ }
245
458
  planNow(root, source) {
246
459
  const plugin = this.scanRoot(resolve(root), source);
247
460
  // A manifest that does not parse means the plugin is not what its author wrote: nothing of it is installed.
@@ -253,7 +466,11 @@ export class Ledger {
253
466
  this.plans.set(plan.id, plan);
254
467
  return plan;
255
468
  }
256
- async applyNow(plan) {
469
+ /**
470
+ * Apply a plan: every action without a live registration mounts.
471
+ * @param only - mount only this kind's actions; the others keep their outcome.
472
+ */
473
+ async applyNow(plan, only) {
257
474
  this.assertAlive();
258
475
  const plugin = this.scanRoot(plan.root, plan.source);
259
476
  const fingerprint = fingerprintPlugin(plugin);
@@ -266,6 +483,9 @@ export class Ledger {
266
483
  if (this.live.get(plan.pluginId)?.unrecorded === true)
267
484
  await this.teardown(plan.pluginId);
268
485
  const existing = this.live.get(plan.pluginId);
486
+ if (existing?.record.detached !== undefined) {
487
+ throw new HarnessError('not-installed', `${plan.pluginId} is no longer run by its harness: nothing of it mounts until it is kept or removed`, { suggestion: 'Keep it as your own copy, or remove it.' });
488
+ }
269
489
  const components = new Map(plugin.components.map(component => [component.id, component]));
270
490
  const outcomes = new Map(existing?.outcomes ?? []);
271
491
  const mounts = existing?.mounts ?? new LiveMounts(this.faultOf);
@@ -307,6 +527,10 @@ export class Ledger {
307
527
  continue;
308
528
  }
309
529
  const mounter = this.mounters.get(kind);
530
+ if (only !== undefined && kind !== only && mounter !== undefined && prior !== undefined) {
531
+ receiptActions.push({ actionId: action.id, kind: action.kind, name: action.name, status: 'skipped' });
532
+ continue;
533
+ }
310
534
  if (mounter === undefined) {
311
535
  outcomes.set(component.id, inactive(component.id, kind));
312
536
  receiptActions.push({ actionId: action.id, kind: action.kind, name: action.name, status: 'skipped' });
@@ -505,6 +729,41 @@ export class Ledger {
505
729
  this.persist();
506
730
  return true;
507
731
  }
732
+ /**
733
+ * Move an installed plugin to a new copy of its source (an update fetched
734
+ * into a directory of its own): its registrations are withdrawn and the new
735
+ * copy applied under the same id, keeping the parts the person switched off,
736
+ * its install time and its receipts. When the new copy does not apply, the
737
+ * old one is applied again and the failure is thrown.
738
+ */
739
+ async rerootNow(id, root, source) {
740
+ this.assertAlive();
741
+ const install = this.live.get(id);
742
+ if (install === undefined)
743
+ throw new HarnessError('not-installed', `no installed plugin ${id}`);
744
+ const previous = install.record;
745
+ if (!await this.teardown(id))
746
+ throw new HarnessError('not-installed', `no installed plugin ${id}`);
747
+ const holder = (record) => ({ record, mounts: new LiveMounts(this.faultOf), outcomes: new Map() });
748
+ this.live.set(id, holder({ ...previous, root: resolve(root), source: source ?? previous.source }));
749
+ try {
750
+ const plan = this.planNow(root, source ?? previous.source);
751
+ if (plan.pluginId !== id)
752
+ throw new HarnessError('manifest-invalid', `the new copy is a different plugin (${plan.pluginId}, not ${id})`, { suggestion: 'Remove the plugin and install the new one.' });
753
+ return await this.applyNow(plan);
754
+ }
755
+ catch (error) {
756
+ this.live.set(id, holder(previous));
757
+ try {
758
+ await this.applyNow(this.planNow(previous.root, previous.source));
759
+ }
760
+ catch {
761
+ this.keepUnrestored(previous, messageOf(error));
762
+ }
763
+ this.persist();
764
+ throw error;
765
+ }
766
+ }
508
767
  /** Release one installation without deciding whether the ledger survives. */
509
768
  async teardown(id) {
510
769
  const install = this.live.get(id);
@@ -560,7 +819,7 @@ export class Ledger {
560
819
  return plugin;
561
820
  const name = `${plugin.name}-${shortHash(resolve(root).toLowerCase(), 6)}`;
562
821
  const renamed = scanRoot(root, plugin.source, { name });
563
- return { ...renamed, warnings: [...renamed.warnings, { code: 'name-conflict', message: `a plugin named ${plugin.name} is already installed from ${holder.record.root}; this one is installed as ${name}` }] };
822
+ return { ...renamed, displayName: plugin.displayName ?? plugin.name, warnings: [...renamed.warnings, { code: 'name-conflict', message: `a plugin named ${plugin.name} is already installed from ${holder.record.root}; this one is installed as ${name}` }] };
564
823
  }
565
824
  buildRecord(plugin, plan, existing, outcomes, commandNames, receiptId) {
566
825
  const components = plugin.components.map(component => ({
@@ -576,6 +835,7 @@ export class Ledger {
576
835
  id: plugin.id,
577
836
  source: plugin.source,
578
837
  name: plugin.name,
838
+ ...(plugin.displayName !== undefined ? { displayName: plugin.displayName } : {}),
579
839
  root: plugin.root,
580
840
  ...(plugin.version !== undefined ? { version: plugin.version } : {}),
581
841
  ...(plugin.license !== undefined ? { license: plugin.license } : {}),
@@ -589,8 +849,18 @@ export class Ledger {
589
849
  outcomes: [...outcomes.values()],
590
850
  receipts: [...(existing?.record.receipts ?? []), receiptId],
591
851
  ...(existing?.record.disabled !== undefined && existing.record.disabled.length > 0 ? { disabled: existing.record.disabled } : {}),
852
+ ...this.followed(plugin, existing),
592
853
  };
593
854
  }
855
+ /** What a record follows: kept from its earlier record, else the harness install it was migrated from, if any. */
856
+ followed(plugin, existing) {
857
+ if (existing !== undefined) {
858
+ const { harnessInstall, harnessUpdate, keptAt } = existing.record;
859
+ return { ...(harnessInstall !== undefined ? { harnessInstall } : {}), ...(harnessUpdate !== undefined ? { harnessUpdate } : {}), ...(keptAt !== undefined ? { keptAt } : {}) };
860
+ }
861
+ const harnessInstall = newHarnessInstall(plugin.root, plugin.displayName ?? plugin.name, plugin.source, harnessInstalls(homedir()), homedir());
862
+ return harnessInstall === undefined ? {} : { harnessInstall };
863
+ }
594
864
  report(result) {
595
865
  const components = new Map(result.plugin.components.map(component => [component.id, component]));
596
866
  const mcp = [];
@@ -657,10 +927,8 @@ export class Ledger {
657
927
  }
658
928
  }
659
929
  writeLedger() {
660
- if (this.unreadLedger !== undefined) {
661
- throw new HarnessError('internal', `the ledger could not be read at startup (${this.unreadLedger}); nothing is written over it`, {
662
- suggestion: 'Fix or move aside .harness-forge/state.json, then restart DSH.',
663
- });
930
+ if (this.writeRefusal !== undefined) {
931
+ throw new HarnessError('internal', this.writeRefusal.message, { suggestion: this.writeRefusal.suggestion });
664
932
  }
665
933
  const state = { schemaVersion: 2, plugins: [...this.live.values()].filter(install => install.unrecorded !== true).map(install => install.record) };
666
934
  writeState(state, this.statePath);
@@ -722,11 +990,15 @@ export function mountsFor(plugin, outcomes) {
722
990
  continue;
723
991
  if (outcome.status === 'skipped' || outcome.status === 'inactive')
724
992
  continue;
993
+ // A run-time failure is in the failing observations; `message` then only names the mount.
994
+ const failing = (outcome.observations ?? []).filter(observation => !observation.ok).map(observation => (observation.detail !== undefined ? `${observation.signal}: ${observation.detail}` : observation.signal));
995
+ const error = failing.length > 0 ? failing.join('; ') : outcome.message;
725
996
  mounts.push({
726
997
  kind: component.kind === 'agent' ? 'agent' : component.kind === 'code' ? 'code' : component.kind === 'mcp' ? 'mcp' : 'hooks',
727
998
  name: component.name,
999
+ ...(component.kind === 'hooks' ? { events: component.events } : {}),
728
1000
  status: outcome.status === 'failed' ? 'failed' : 'mounted',
729
- ...(outcome.status === 'failed' && outcome.message !== undefined ? { error: outcome.message } : {}),
1001
+ ...(outcome.status === 'failed' && error !== undefined ? { error } : {}),
730
1002
  });
731
1003
  }
732
1004
  return mounts;
@@ -45,7 +45,7 @@ export declare class ProjectAssets {
45
45
  private readonly mounts;
46
46
  /** Each session's mounts, once its first mount finished. */
47
47
  private readonly settled;
48
- /** Mounts of ended sessions whose withdrawal failed: kept, and withdrawn again on the next release or at dispose. */
48
+ /** Mounts of ended sessions whose withdrawal failed: kept, and withdrawn again on every trust change, release and at dispose. */
49
49
  private readonly retained;
50
50
  /** Mounting, reconciling and releasing run one at a time, in the order they were asked for. */
51
51
  private chain;
@@ -83,12 +83,15 @@ export declare class ProjectAssets {
83
83
  private mountAll;
84
84
  /**
85
85
  * Trust changed for a workspace: mount what now may run in its open
86
- * sessions, and withdraw what no longer may (trust revoked).
86
+ * sessions, and withdraw what no longer may (trust revoked). Ended
87
+ * sessions' parts whose withdrawal failed are withdrawn again, never mounted.
87
88
  */
88
89
  private reconcile;
89
90
  /** Mount the given parts of a session's project assets that may run; the others wait. */
90
91
  private mountParts;
91
92
  /** Withdraw a session's project assets. */
92
93
  release(sessionId: string): Promise<void>;
94
+ /** Withdraw an ended session's mounts; those whose withdrawal fails are retained, to be tried again. */
95
+ private withdrawEnded;
93
96
  dispose(): Promise<void>;
94
97
  }
@@ -19,7 +19,7 @@ function gate(component, plugin, cwd, trust) {
19
19
  if (component.kind === 'mcp' && plugin.source === 'claude-code' && component.metadata?.['scope'] === 'project') {
20
20
  const approval = claudeMcpApproval(component.name, trust.workspace, cwd, true, homedir());
21
21
  if (approval === 'disabled')
22
- return { componentId: component.id, status: 'skipped', level: 'L0', evidence: 'source', message: 'disabled in Claude Code (disabledMcpjsonServers)' };
22
+ return { componentId: component.id, status: 'skipped', level: 'L0', evidence: 'source', message: 'disabled in Claude Code (disabledMcpjsonServers)', skippedBy: 'disabled-in-claude-code' };
23
23
  if (approval === 'pending' && !trust.sources.includes('forge'))
24
24
  return waiting(WAITING_FOR_APPROVAL);
25
25
  }
@@ -52,7 +52,7 @@ export class ProjectAssets {
52
52
  mounts = new Map();
53
53
  /** Each session's mounts, once its first mount finished. */
54
54
  settled = new Map();
55
- /** Mounts of ended sessions whose withdrawal failed: kept, and withdrawn again on the next release or at dispose. */
55
+ /** Mounts of ended sessions whose withdrawal failed: kept, and withdrawn again on every trust change, release and at dispose. */
56
56
  retained = new Map();
57
57
  /** Mounting, reconciling and releasing run one at a time, in the order they were asked for. */
58
58
  chain = Promise.resolve();
@@ -150,10 +150,13 @@ export class ProjectAssets {
150
150
  }
151
151
  /**
152
152
  * Trust changed for a workspace: mount what now may run in its open
153
- * sessions, and withdraw what no longer may (trust revoked).
153
+ * sessions, and withdraw what no longer may (trust revoked). Ended
154
+ * sessions' parts whose withdrawal failed are withdrawn again, never mounted.
154
155
  */
155
156
  async reconcile(workspace) {
156
157
  // Runs in the chain: every session mounted before it has settled, and those after read the new trust themselves.
158
+ for (const [sessionId, mounts] of [...this.retained])
159
+ await this.withdrawEnded(sessionId, mounts);
157
160
  for (const mount of [...this.settled.values()].flat()) {
158
161
  if (!isInside(workspace, mount.workspace) && mount.unsettled.size === 0)
159
162
  continue;
@@ -313,21 +316,25 @@ export class ProjectAssets {
313
316
  await this.serial(async () => {
314
317
  const mounts = this.settled.get(sessionId) ?? this.retained.get(sessionId) ?? [];
315
318
  this.settled.delete(sessionId);
316
- const left = [];
317
- for (const mount of mounts)
318
- if ((await mount.live.release()).failed.length > 0)
319
- left.push(mount);
320
- if (left.length > 0) {
321
- this.retained.set(sessionId, left);
322
- return;
323
- }
324
- this.retained.delete(sessionId);
325
- if (mounts.length === 0)
326
- return;
327
- for (const mounter of this.ledger.mounters.values())
328
- await mounter.release?.({ sessionId }).catch((error) => this.fault?.(error));
319
+ await this.withdrawEnded(sessionId, mounts);
329
320
  });
330
321
  }
322
+ /** Withdraw an ended session's mounts; those whose withdrawal fails are retained, to be tried again. */
323
+ async withdrawEnded(sessionId, mounts) {
324
+ const left = [];
325
+ for (const mount of mounts)
326
+ if ((await mount.live.release()).failed.length > 0)
327
+ left.push(mount);
328
+ if (left.length > 0) {
329
+ this.retained.set(sessionId, left);
330
+ return;
331
+ }
332
+ this.retained.delete(sessionId);
333
+ if (mounts.length === 0)
334
+ return;
335
+ for (const mounter of this.ledger.mounters.values())
336
+ await mounter.release?.({ sessionId }).catch((error) => this.fault?.(error));
337
+ }
331
338
  async dispose() {
332
339
  this.stopTrust();
333
340
  for (const id of new Set([...this.mounts.keys(), ...this.retained.keys()]))
@@ -0,0 +1,65 @@
1
+ /** Bounds on what one unpack or copy may write. */
2
+ export interface TreeLimits {
3
+ /** Total bytes of file content. */
4
+ readonly maxBytes: number;
5
+ /** Files, directories and links together (for a tar, every header record). */
6
+ readonly maxEntries: number;
7
+ }
8
+ /** Claude Code's bounds on a plugin copied into its cache: 256 MiB, 20,000 entries. */
9
+ export declare const PLUGIN_LIMITS: TreeLimits;
10
+ /** A whole repository unpacked to read its marketplace: larger, since only part of it is a plugin. */
11
+ export declare const REPOSITORY_LIMITS: TreeLimits;
12
+ /** Options of an unpack. */
13
+ export interface UnpackOptions {
14
+ readonly limits?: TreeLimits;
15
+ /** Aborting stops the unpack with the signal's reason. */
16
+ readonly signal?: AbortSignal;
17
+ }
18
+ /**
19
+ * How a destination is told apart from others: in Unicode NFC (macOS treats
20
+ * other normalizations of a name as the same file), and case-insensitively
21
+ * where the file system is (macOS, Windows).
22
+ */
23
+ export declare function destinationKey(path: string, platform?: NodeJS.Platform): string;
24
+ /**
25
+ * Unpack a `.tar.gz` into `dest` (which must not exist yet or be empty).
26
+ * @returns the commit SHA a `git archive` tarball records (GitHub's pax `comment`), when there is one.
27
+ */
28
+ export declare function extractTarGz(archive: Buffer, dest: string, options?: UnpackOptions & {
29
+ readonly strip?: number;
30
+ }): Promise<{
31
+ commit?: string;
32
+ }>;
33
+ /** Unpack a zip into `dest`: stored and deflated members, without ZIP64. */
34
+ export declare function extractZip(archive: Buffer, dest: string, options?: UnpackOptions): Promise<void>;
35
+ /**
36
+ * Copy a plugin directory to `dest`, leaving out `.git` and every link (a
37
+ * link is not followed, so nothing outside the checkout is read). The
38
+ * directory itself must be a real directory inside `boundary`, reached through
39
+ * no link, and so must every directory under it when it is read. Returns the
40
+ * links and anything else that is not a regular file (a FIFO, a device) left
41
+ * out. Used for every source, a folder on this computer included, so what is
42
+ * shown and installed is this copy.
43
+ *
44
+ * A parent directory replaced by a link between a directory's real-path check
45
+ * and the open of a file in it is not caught: that takes a process running
46
+ * now, on this computer, with write access to the user's own folders, which
47
+ * could as well change the plugin's files before they are listed.
48
+ */
49
+ export declare function copyTree(source: string, dest: string, boundary?: string, limits?: TreeLimits): string[];
50
+ /**
51
+ * A SHA-256 over a directory or file as installed: every path (sorted), its
52
+ * type, whether it is executable, a file's bytes and a link's target. Equal
53
+ * digests are the same files; what a confirmation showed is bound to one.
54
+ */
55
+ export declare function treeDigest(path: string): string;
56
+ /** Refuse a checkout directory whose manifests (or the folders holding them) are links. */
57
+ export declare function refuseLinkedManifests(dir: string): void;
58
+ /** Bytes and entries under a directory (`.git` included), stopping once past the limits. */
59
+ export declare function treeSize(directory: string, limits: TreeLimits): {
60
+ bytes: number;
61
+ entries: number;
62
+ over: boolean;
63
+ };
64
+ /** The single top-level directory of an unpacked zip ("the plugin root may be at the top of the zip or one directory down"). */
65
+ export declare function zipRoot(directory: string): string;