@kirkchinese/harness-forge 0.0.0-stage → 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 (279) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +46 -2
  3. package/assets/icon.svg +12 -0
  4. package/cordis.patch.yml +28 -0
  5. package/docs/DETAIL.zh.md +47 -0
  6. package/lib/agents/presets.d.ts +98 -0
  7. package/lib/agents/presets.js +292 -0
  8. package/lib/agents/profiles.d.ts +58 -0
  9. package/lib/agents/profiles.js +279 -0
  10. package/lib/agents/row.d.ts +17 -0
  11. package/lib/agents/row.js +148 -0
  12. package/lib/client/paths.d.ts +12 -0
  13. package/lib/client/paths.js +68 -0
  14. package/lib/client/styles.d.ts +8 -0
  15. package/lib/client/styles.js +89 -0
  16. package/lib/client/typert.d.ts +25 -0
  17. package/lib/client/typert.js +158 -0
  18. package/lib/client.js +23823 -0
  19. package/lib/commands/definition.d.ts +40 -0
  20. package/lib/commands/definition.js +113 -0
  21. package/lib/commands/output-styles.d.ts +42 -0
  22. package/lib/commands/output-styles.js +152 -0
  23. package/lib/commands/row.d.ts +9 -0
  24. package/lib/commands/row.js +157 -0
  25. package/lib/context/instructions.d.ts +32 -0
  26. package/lib/context/instructions.js +88 -0
  27. package/lib/context/row.d.ts +16 -0
  28. package/lib/context/row.js +17 -0
  29. package/lib/dsh/commands.d.ts +30 -0
  30. package/lib/dsh/commands.js +61 -0
  31. package/lib/dsh/host.d.ts +110 -0
  32. package/lib/dsh/host.js +217 -0
  33. package/lib/dsh/model-route.d.ts +21 -0
  34. package/lib/dsh/model-route.js +37 -0
  35. package/lib/dsh/session-records.d.ts +78 -0
  36. package/lib/dsh/session-records.js +36 -0
  37. package/lib/dsh/subagents.d.ts +46 -0
  38. package/lib/dsh/subagents.js +14 -0
  39. package/lib/forge/contract.d.ts +271 -0
  40. package/lib/forge/contract.js +45 -0
  41. package/lib/forge/follow.d.ts +30 -0
  42. package/lib/forge/follow.js +73 -0
  43. package/lib/forge/ledger.d.ts +206 -0
  44. package/lib/forge/ledger.js +1005 -0
  45. package/lib/forge/live-mounts.d.ts +45 -0
  46. package/lib/forge/live-mounts.js +78 -0
  47. package/lib/forge/npm.d.ts +31 -0
  48. package/lib/forge/npm.js +60 -0
  49. package/lib/forge/projects.d.ts +97 -0
  50. package/lib/forge/projects.js +343 -0
  51. package/lib/forge/receipts.d.ts +5 -0
  52. package/lib/forge/receipts.js +31 -0
  53. package/lib/forge/remote/archive.d.ts +65 -0
  54. package/lib/forge/remote/archive.js +565 -0
  55. package/lib/forge/remote/code-parts.d.ts +18 -0
  56. package/lib/forge/remote/code-parts.js +76 -0
  57. package/lib/forge/remote/fetch.d.ts +265 -0
  58. package/lib/forge/remote/fetch.js +1133 -0
  59. package/lib/forge/remote/service.d.ts +256 -0
  60. package/lib/forge/remote/service.js +868 -0
  61. package/lib/forge/row.d.ts +32 -0
  62. package/lib/forge/row.js +59 -0
  63. package/lib/forge/service.d.ts +115 -0
  64. package/lib/forge/service.js +290 -0
  65. package/lib/forge/settings.d.ts +43 -0
  66. package/lib/forge/settings.js +122 -0
  67. package/lib/forge/state.d.ts +129 -0
  68. package/lib/forge/state.js +266 -0
  69. package/lib/forge/trust.d.ts +48 -0
  70. package/lib/forge/trust.js +107 -0
  71. package/lib/forge/turns.d.ts +13 -0
  72. package/lib/forge/turns.js +56 -0
  73. package/lib/hooks/broker/engine.d.ts +112 -0
  74. package/lib/hooks/broker/engine.js +722 -0
  75. package/lib/hooks/broker/helpers.d.ts +10 -0
  76. package/lib/hooks/broker/helpers.js +22 -0
  77. package/lib/hooks/broker/lifecycle.d.ts +65 -0
  78. package/lib/hooks/broker/lifecycle.js +342 -0
  79. package/lib/hooks/broker/session-events.d.ts +27 -0
  80. package/lib/hooks/broker/session-events.js +205 -0
  81. package/lib/hooks/broker/tools.d.ts +52 -0
  82. package/lib/hooks/broker/tools.js +424 -0
  83. package/lib/hooks/broker/types.d.ts +264 -0
  84. package/lib/hooks/broker/types.js +1 -0
  85. package/lib/hooks/broker.d.ts +80 -0
  86. package/lib/hooks/broker.js +95 -0
  87. package/lib/hooks/codex-user.d.ts +5 -0
  88. package/lib/hooks/codex-user.js +109 -0
  89. package/lib/hooks/condition.d.ts +87 -0
  90. package/lib/hooks/condition.js +602 -0
  91. package/lib/hooks/config.d.ts +85 -0
  92. package/lib/hooks/config.js +154 -0
  93. package/lib/hooks/glob.d.ts +41 -0
  94. package/lib/hooks/glob.js +114 -0
  95. package/lib/hooks/matcher.d.ts +20 -0
  96. package/lib/hooks/matcher.js +39 -0
  97. package/lib/hooks/notice.d.ts +17 -0
  98. package/lib/hooks/notice.js +39 -0
  99. package/lib/hooks/output.d.ts +56 -0
  100. package/lib/hooks/output.js +214 -0
  101. package/lib/hooks/permissions.d.ts +19 -0
  102. package/lib/hooks/permissions.js +202 -0
  103. package/lib/hooks/powershell-aliases.d.ts +19 -0
  104. package/lib/hooks/powershell-aliases.js +58 -0
  105. package/lib/hooks/process.d.ts +64 -0
  106. package/lib/hooks/process.js +289 -0
  107. package/lib/hooks/row.d.ts +17 -0
  108. package/lib/hooks/row.js +96 -0
  109. package/lib/hooks/runner.d.ts +98 -0
  110. package/lib/hooks/runner.js +322 -0
  111. package/lib/hooks/shell-commands.d.ts +28 -0
  112. package/lib/hooks/shell-commands.js +241 -0
  113. package/lib/hooks/shell.d.ts +44 -0
  114. package/lib/hooks/shell.js +129 -0
  115. package/lib/hooks/transcript.d.ts +28 -0
  116. package/lib/hooks/transcript.js +141 -0
  117. package/lib/hooks/vocabulary.d.ts +57 -0
  118. package/lib/hooks/vocabulary.js +366 -0
  119. package/lib/index.d.ts +31 -0
  120. package/lib/index.js +287 -0
  121. package/lib/mcp/auth.d.ts +35 -0
  122. package/lib/mcp/auth.js +178 -0
  123. package/lib/mcp/catalog.d.ts +39 -0
  124. package/lib/mcp/catalog.js +69 -0
  125. package/lib/mcp/mount.d.ts +113 -0
  126. package/lib/mcp/mount.js +317 -0
  127. package/lib/mcp/policy.d.ts +42 -0
  128. package/lib/mcp/policy.js +43 -0
  129. package/lib/mcp/remote.d.ts +45 -0
  130. package/lib/mcp/remote.js +133 -0
  131. package/lib/mcp/row.d.ts +9 -0
  132. package/lib/mcp/row.js +225 -0
  133. package/lib/mods/bundler.d.ts +38 -0
  134. package/lib/mods/bundler.js +157 -0
  135. package/lib/mods/chain.d.ts +103 -0
  136. package/lib/mods/chain.js +436 -0
  137. package/lib/mods/claude.d.ts +27 -0
  138. package/lib/mods/claude.js +56 -0
  139. package/lib/mods/engine.d.ts +160 -0
  140. package/lib/mods/engine.js +701 -0
  141. package/lib/mods/expect.d.ts +8 -0
  142. package/lib/mods/expect.js +248 -0
  143. package/lib/mods/host.d.ts +105 -0
  144. package/lib/mods/host.js +462 -0
  145. package/lib/mods/loader.d.ts +53 -0
  146. package/lib/mods/loader.js +231 -0
  147. package/lib/mods/ops.d.ts +13 -0
  148. package/lib/mods/ops.js +117 -0
  149. package/lib/mods/row.d.ts +9 -0
  150. package/lib/mods/row.js +77 -0
  151. package/lib/mods/runtime.d.ts +60 -0
  152. package/lib/mods/runtime.js +133 -0
  153. package/lib/mods/service/commands.d.ts +17 -0
  154. package/lib/mods/service/commands.js +121 -0
  155. package/lib/mods/service/drawings.d.ts +36 -0
  156. package/lib/mods/service/drawings.js +64 -0
  157. package/lib/mods/service/sessions.d.ts +63 -0
  158. package/lib/mods/service/sessions.js +345 -0
  159. package/lib/mods/service/tools.d.ts +32 -0
  160. package/lib/mods/service/tools.js +253 -0
  161. package/lib/mods/service/turns.d.ts +33 -0
  162. package/lib/mods/service/turns.js +136 -0
  163. package/lib/mods/service/types.d.ts +151 -0
  164. package/lib/mods/service/types.js +1 -0
  165. package/lib/mods/service.d.ts +72 -0
  166. package/lib/mods/service.js +104 -0
  167. package/lib/mods/surfaces.d.ts +93 -0
  168. package/lib/mods/surfaces.js +309 -0
  169. package/lib/mods/values.d.ts +30 -0
  170. package/lib/mods/values.js +95 -0
  171. package/lib/opencode/bun.d.ts +40 -0
  172. package/lib/opencode/bun.js +168 -0
  173. package/lib/opencode/convert.d.ts +53 -0
  174. package/lib/opencode/convert.js +255 -0
  175. package/lib/opencode/row.d.ts +22 -0
  176. package/lib/opencode/row.js +104 -0
  177. package/lib/opencode/runtime/core.d.ts +74 -0
  178. package/lib/opencode/runtime/core.js +249 -0
  179. package/lib/opencode/runtime/events.d.ts +80 -0
  180. package/lib/opencode/runtime/events.js +281 -0
  181. package/lib/opencode/runtime/mount.d.ts +27 -0
  182. package/lib/opencode/runtime/mount.js +283 -0
  183. package/lib/opencode/runtime/server.d.ts +27 -0
  184. package/lib/opencode/runtime/server.js +354 -0
  185. package/lib/opencode/runtime/types.d.ts +109 -0
  186. package/lib/opencode/runtime/types.js +1 -0
  187. package/lib/opencode/runtime.d.ts +55 -0
  188. package/lib/opencode/runtime.js +79 -0
  189. package/lib/porting/adapter-paths.d.ts +13 -0
  190. package/lib/porting/adapter-paths.js +120 -0
  191. package/lib/porting/port-gap.d.ts +36 -0
  192. package/lib/porting/port-gap.js +158 -0
  193. package/lib/porting/port-sessions.d.ts +41 -0
  194. package/lib/porting/port-sessions.js +98 -0
  195. package/lib/porting/prompt.d.ts +23 -0
  196. package/lib/porting/prompt.js +51 -0
  197. package/lib/porting/row.d.ts +16 -0
  198. package/lib/porting/row.js +27 -0
  199. package/lib/porting/verify-port.d.ts +46 -0
  200. package/lib/porting/verify-port.js +82 -0
  201. package/lib/presets/fs-search.d.ts +25 -0
  202. package/lib/presets/fs-search.js +17 -0
  203. package/lib/presets/tool-filter.d.ts +35 -0
  204. package/lib/presets/tool-filter.js +91 -0
  205. package/lib/sessions/chat-import.d.ts +48 -0
  206. package/lib/sessions/chat-import.js +44 -0
  207. package/lib/sessions/claude.d.ts +35 -0
  208. package/lib/sessions/claude.js +104 -0
  209. package/lib/sessions/codex-discover.d.ts +34 -0
  210. package/lib/sessions/codex-discover.js +205 -0
  211. package/lib/sessions/codex-meta.d.ts +63 -0
  212. package/lib/sessions/codex-meta.js +148 -0
  213. package/lib/sessions/codex-text.d.ts +9 -0
  214. package/lib/sessions/codex-text.js +44 -0
  215. package/lib/sessions/codex.d.ts +42 -0
  216. package/lib/sessions/codex.js +270 -0
  217. package/lib/sessions/opencode.d.ts +38 -0
  218. package/lib/sessions/opencode.js +339 -0
  219. package/lib/sessions/persist.d.ts +162 -0
  220. package/lib/sessions/persist.js +377 -0
  221. package/lib/sessions/row.d.ts +15 -0
  222. package/lib/sessions/row.js +101 -0
  223. package/lib/sessions/turns.d.ts +31 -0
  224. package/lib/sessions/turns.js +63 -0
  225. package/lib/sessions/zstd.d.ts +15 -0
  226. package/lib/sessions/zstd.js +152 -0
  227. package/lib/shared/invocation.d.ts +169 -0
  228. package/lib/shared/invocation.js +325 -0
  229. package/lib/shared/render.d.ts +101 -0
  230. package/lib/shared/render.js +1353 -0
  231. package/lib/shared/util.d.ts +21 -0
  232. package/lib/shared/util.js +32 -0
  233. package/lib/skills/bundled.d.ts +3 -0
  234. package/lib/skills/bundled.js +42 -0
  235. package/lib/skills/provider.d.ts +74 -0
  236. package/lib/skills/provider.js +346 -0
  237. package/lib/skills/row.d.ts +22 -0
  238. package/lib/skills/row.js +204 -0
  239. package/lib/workbench/adapter-coverage.d.ts +65 -0
  240. package/lib/workbench/adapter-coverage.js +141 -0
  241. package/lib/workbench/model-tools.d.ts +10 -0
  242. package/lib/workbench/model-tools.js +122 -0
  243. package/lib/workbench/overview.d.ts +153 -0
  244. package/lib/workbench/overview.js +246 -0
  245. package/lib/workbench/remote.d.ts +161 -0
  246. package/lib/workbench/remote.js +561 -0
  247. package/lib/workbench/row.d.ts +15 -0
  248. package/lib/workbench/row.js +16 -0
  249. package/lib/workbench/settings.d.ts +19 -0
  250. package/lib/workbench/settings.js +60 -0
  251. package/lib/workbench/workbench.d.ts +130 -0
  252. package/lib/workbench/workbench.js +361 -0
  253. package/locale/agents/en.json +6 -0
  254. package/locale/agents/zh.json +6 -0
  255. package/locale/commands/en.json +6 -0
  256. package/locale/commands/zh.json +6 -0
  257. package/locale/context/en.json +6 -0
  258. package/locale/context/zh.json +6 -0
  259. package/locale/en.json +6 -0
  260. package/locale/hooks/en.json +6 -0
  261. package/locale/hooks/zh.json +6 -0
  262. package/locale/mcp/en.json +6 -0
  263. package/locale/mcp/zh.json +6 -0
  264. package/locale/mods/en.json +6 -0
  265. package/locale/mods/zh.json +6 -0
  266. package/locale/opencode/en.json +6 -0
  267. package/locale/opencode/zh.json +6 -0
  268. package/locale/porter/en.json +6 -0
  269. package/locale/porter/zh.json +6 -0
  270. package/locale/sessions/en.json +6 -0
  271. package/locale/sessions/zh.json +6 -0
  272. package/locale/skills/en.json +6 -0
  273. package/locale/skills/zh.json +6 -0
  274. package/locale/workbench/en.json +6 -0
  275. package/locale/workbench/zh.json +6 -0
  276. package/locale/zh.json +7 -0
  277. package/package.json +247 -3
  278. package/runtime/opencode-host.mjs +270 -0
  279. package/skills/harness-forge/SKILL.md +47 -0
@@ -0,0 +1,1005 @@
1
+ /**
2
+ * The ledger: installing, restoring, undoing and removing plugins, the record
3
+ * that survives restarts, and the mounters each row registers for its kind
4
+ * of component. A component whose row is off waits as `inactive` and mounts
5
+ * as soon as the row's mounter is registered; a row that goes away withdraws
6
+ * its components back to `inactive`.
7
+ * @module @kirkchinese/harness-forge
8
+ */
9
+ import { randomUUID } from 'node:crypto';
10
+ import { existsSync } from 'node:fs';
11
+ import { homedir } from 'node:os';
12
+ import { dirname, resolve } from 'node:path';
13
+ import { assess, dialects, fingerprintPlugin, HarnessError, dialectOf, harnessInstalls, planPlugin, scanRoot, shortHash, } from '@kirkchinese/harness-forge-core';
14
+ import { pluginDataDir } from '../mcp/mount.js';
15
+ import { writeReceipt, readReceipt } from './receipts.js';
16
+ import { messageOf } from '../shared/util.js';
17
+ import { mountKindOf, ROW_OF_KIND } from './contract.js';
18
+ import { LiveMounts } from './live-mounts.js';
19
+ import { followingChanges, followingOf, newHarnessInstall, withHarnessInstall } from './follow.js';
20
+ import { isTransient, loadState, receiptsDirectory, retryFile, writeState, } from './state.js';
21
+ /** Observations kept per component: the newest per signal, bounded. */
22
+ const MAX_OBSERVATIONS = 96;
23
+ const PERSIST_DELAY_MS = 500;
24
+ const GLOBAL_SCOPE = {};
25
+ /** The outcome of a component whose row is off. */
26
+ export function inactive(componentId, kind) {
27
+ return { componentId, status: 'inactive', level: 'L0', evidence: 'source', message: `inactive because the ${ROW_OF_KIND[kind]} row is off` };
28
+ }
29
+ /** What an outcome's message says when the person switched the component off. */
30
+ export const SWITCHED_OFF = 'switched off';
31
+ /** The outcome of a component the person switched off. */
32
+ export function switchedOff(componentId) {
33
+ return { componentId, status: 'inactive', level: 'L0', evidence: 'source', message: SWITCHED_OFF };
34
+ }
35
+ /** The outcome of a component whose withdrawal failed: it stays live, and switching it off again retries. */
36
+ export function failedToSwitchOff(componentId, reason) {
37
+ return { componentId, status: 'failed', level: 'L0', evidence: 'runtime', message: `failed to switch off: ${reason}` };
38
+ }
39
+ /** The outcome of a component a failed install could not withdraw: it stays live until removing the plugin (or installing it again) withdraws it. */
40
+ export function failedToCleanUp(componentId, reason) {
41
+ return { componentId, status: 'failed', level: 'L0', evidence: 'runtime', message: `failed to clean up after a failed install: ${reason}` };
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
+ }
49
+ function skipped(componentId, message) {
50
+ return { componentId, status: 'skipped', level: 'L0', evidence: 'source', message };
51
+ }
52
+ /**
53
+ * The installations: the in-memory registry, plan application, undo and
54
+ * teardown, runtime evidence and the durable ledger, every mutation through
55
+ * one queue.
56
+ */
57
+ export class Ledger {
58
+ ctx;
59
+ statePath;
60
+ dataRoot;
61
+ fault;
62
+ live = new Map();
63
+ plans = new Map();
64
+ mounters = new Map();
65
+ disposed = false;
66
+ queue = Promise.resolve();
67
+ persistTimer;
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;
76
+ constructor(ctx, statePath, dataRoot,
77
+ /** Where a withdrawal that failed, or a ledger read only in part, is recorded (the shared service's faults). */
78
+ fault) {
79
+ this.ctx = ctx;
80
+ this.statePath = statePath;
81
+ this.dataRoot = dataRoot;
82
+ this.fault = fault;
83
+ }
84
+ faultOf = (error) => { this.fault?.(error); };
85
+ /**
86
+ * Register the mounter of one kind: components of that kind waiting as
87
+ * inactive mount now. The disposer withdraws them back to inactive.
88
+ */
89
+ registerMounter(kind, mounter) {
90
+ if (this.mounters.has(kind))
91
+ throw new HarnessError('internal', `a mounter for ${kind} is already registered`);
92
+ this.mounters.set(kind, mounter);
93
+ this.reapply(kind);
94
+ return () => {
95
+ if (this.mounters.get(kind) !== mounter)
96
+ return;
97
+ this.mounters.delete(kind);
98
+ if (!this.disposed)
99
+ void this.exclusive(() => this.withdraw(kind));
100
+ };
101
+ }
102
+ /**
103
+ * Re-apply installed plans; only actions without a live registration run.
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.
107
+ */
108
+ reapply(kind) {
109
+ if (this.disposed)
110
+ return;
111
+ void this.exclusive(async () => {
112
+ if (this.disposed)
113
+ return;
114
+ for (const install of [...this.live.values()]) {
115
+ if (install.plan === undefined)
116
+ continue;
117
+ try {
118
+ await this.applyNow(install.plan, kind);
119
+ }
120
+ catch {
121
+ // The ledger keeps the previous outcome; the next re-apply runs again.
122
+ }
123
+ }
124
+ });
125
+ }
126
+ /**
127
+ * Withdraw every mount of one kind (its row went away): those components
128
+ * wait as inactive. The live registrations say what to withdraw, so a source
129
+ * that no longer scans is withdrawn as well.
130
+ */
131
+ async withdraw(kind) {
132
+ if (this.disposed)
133
+ return;
134
+ let changed = false;
135
+ for (const install of this.live.values()) {
136
+ const components = new Set();
137
+ const { released, failed } = await install.mounts.release(candidate => candidate.kind === kind);
138
+ for (const mount of released)
139
+ components.add(mount.componentId);
140
+ const stuck = new Set(failed.map(failure => failure.mount.componentId));
141
+ // A component of the kind that mounted nothing to withdraw (it failed, say) waits as inactive too.
142
+ const plugin = this.tryScan(install);
143
+ if (plugin !== undefined) {
144
+ const byId = new Map(plugin.components.map(component => [component.id, component]));
145
+ for (const action of install.plan?.actions ?? []) {
146
+ const component = action.componentId === undefined ? undefined : byId.get(action.componentId);
147
+ if (component !== undefined && mountKindOf(action, component) === kind)
148
+ components.add(component.id);
149
+ }
150
+ }
151
+ let touched = false;
152
+ for (const componentId of components) {
153
+ if (install.record.disabled?.includes(componentId) === true || stuck.has(componentId))
154
+ continue;
155
+ install.outcomes.set(componentId, inactive(componentId, kind));
156
+ touched = true;
157
+ }
158
+ for (const { mount, reason } of failed) {
159
+ install.outcomes.set(mount.componentId, failedToSwitchOff(mount.componentId, reason));
160
+ touched = true;
161
+ }
162
+ if (touched) {
163
+ this.refreshRecord(install, plugin);
164
+ changed = true;
165
+ }
166
+ }
167
+ if (changed)
168
+ this.persist();
169
+ }
170
+ /** The plugin as its source scans now, or undefined when it no longer does. */
171
+ tryScan(install) {
172
+ try {
173
+ return this.scanRoot(install.record.root, install.record.source);
174
+ }
175
+ catch {
176
+ return undefined;
177
+ }
178
+ }
179
+ /**
180
+ * The record's derived fields after its outcomes changed. Without the
181
+ * scanned plugin (its source is gone) only the outcomes are updated.
182
+ */
183
+ refreshRecord(install, plugin = this.tryScan(install)) {
184
+ if (plugin === undefined) {
185
+ install.record = { ...install.record, outcomes: [...install.outcomes.values()] };
186
+ return;
187
+ }
188
+ install.record = {
189
+ ...install.record,
190
+ skillRoots: skillRootsOf(plugin, install.outcomes),
191
+ outcomes: [...install.outcomes.values()],
192
+ compat: assess(plugin, [...install.outcomes.values()]),
193
+ mounts: mountsFor(plugin, install.outcomes),
194
+ };
195
+ }
196
+ /** Scan one plugin without writing anything. */
197
+ scan(root, source) {
198
+ return this.scanRoot(resolve(root), source);
199
+ }
200
+ /** List current installations in stable name order. */
201
+ list() {
202
+ return [...this.live.values()].map(install => install.record).sort((a, b) => a.name.localeCompare(b.name, 'en'));
203
+ }
204
+ // ---------------------------------------------------------------------------
205
+ // Queue-owned operations
206
+ // ---------------------------------------------------------------------------
207
+ exclusive(operation) {
208
+ const run = this.queue.then(operation, operation);
209
+ this.queue = run.catch(() => undefined);
210
+ return run;
211
+ }
212
+ async restoreNow() {
213
+ let loaded;
214
+ try {
215
+ loaded = await retryFile(() => loadState(this.statePath));
216
+ }
217
+ catch (error) {
218
+ // Writing now would replace the ledger with what is live: nothing. Every write is refused until it is read.
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
+ };
223
+ throw error;
224
+ }
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) {
239
+ try {
240
+ if (!this.live.has(stored.id))
241
+ await this.restoreRecord(withHarnessInstall(stored, current, homedir()), current);
242
+ }
243
+ finally {
244
+ this.step();
245
+ }
246
+ }
247
+ this.persist();
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
+ }
290
+ /** Keep a record that could not be restored visible, with the reason. */
291
+ keepUnrestored(record, reason) {
292
+ const outcomes = (record.outcomes ?? []).map(outcome => ({ ...outcome, status: 'failed', message: `not restored: ${reason}` }));
293
+ this.live.set(record.id, {
294
+ record: { ...record, outcomes, mounts: [] },
295
+ mounts: new LiveMounts(this.faultOf),
296
+ outcomes: new Map(outcomes.map(outcome => [outcome.componentId, outcome])),
297
+ });
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
+ }
458
+ planNow(root, source) {
459
+ const plugin = this.scanRoot(resolve(root), source);
460
+ // A manifest that does not parse means the plugin is not what its author wrote: nothing of it is installed.
461
+ const invalid = plugin.warnings.find(warning => warning.code === 'manifest-invalid' || warning.code === 'manifest-schema-unknown');
462
+ if (invalid !== undefined) {
463
+ throw new HarnessError('manifest-invalid', `${plugin.root}: ${invalid.message}; the plugin was not imported`, { suggestion: 'Fix the manifest and import it again.' });
464
+ }
465
+ const plan = planPlugin(plugin);
466
+ this.plans.set(plan.id, plan);
467
+ return plan;
468
+ }
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) {
474
+ this.assertAlive();
475
+ const plugin = this.scanRoot(plan.root, plan.source);
476
+ const fingerprint = fingerprintPlugin(plugin);
477
+ if (fingerprint.digest !== plan.fingerprint.digest) {
478
+ throw new HarnessError('fingerprint-mismatch', `source changed since the plan was created: ${plan.root}`, {
479
+ suggestion: 'Scan again and review the new plan.',
480
+ });
481
+ }
482
+ // A failed install left registrations live: they are withdrawn before anything is installed over them.
483
+ if (this.live.get(plan.pluginId)?.unrecorded === true)
484
+ await this.teardown(plan.pluginId);
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
+ }
489
+ const components = new Map(plugin.components.map(component => [component.id, component]));
490
+ const outcomes = new Map(existing?.outcomes ?? []);
491
+ const mounts = existing?.mounts ?? new LiveMounts(this.faultOf);
492
+ /** The actions this apply registered: withdrawn again when the apply cannot be recorded. */
493
+ const added = new Set();
494
+ const disabled = new Set(existing?.record.disabled ?? []);
495
+ const commandNames = new Map();
496
+ for (const component of plugin.components) {
497
+ const prior = outcomes.get(component.id);
498
+ // A mounted command keeps its name across restarts; a failed one carries an error instead.
499
+ if (component.kind === 'command' && (prior?.status === 'mounted' || prior?.status === 'verified') && prior.message !== undefined) {
500
+ commandNames.set(component.id, prior.message);
501
+ }
502
+ }
503
+ const receiptId = randomUUID();
504
+ const startedAt = new Date().toISOString();
505
+ const receiptActions = [];
506
+ const used = new Set();
507
+ for (const action of plan.actions) {
508
+ const component = action.componentId === undefined ? undefined : components.get(action.componentId);
509
+ if (component === undefined) {
510
+ receiptActions.push({ actionId: action.id, kind: action.kind, name: action.name, status: 'failed' });
511
+ continue;
512
+ }
513
+ if (mounts.has(action.id)) {
514
+ receiptActions.push({ actionId: action.id, kind: action.kind, name: action.name, status: 'skipped' });
515
+ continue;
516
+ }
517
+ if (disabled.has(component.id)) {
518
+ outcomes.set(component.id, switchedOff(component.id));
519
+ receiptActions.push({ actionId: action.id, kind: action.kind, name: action.name, status: 'skipped' });
520
+ continue;
521
+ }
522
+ const prior = outcomes.get(component.id);
523
+ const kind = mountKindOf(action, component);
524
+ if (typeof kind !== 'string') {
525
+ outcomes.set(component.id, skipped(component.id, kind.skipped));
526
+ receiptActions.push({ actionId: action.id, kind: action.kind, name: action.name, status: 'skipped' });
527
+ continue;
528
+ }
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
+ }
534
+ if (mounter === undefined) {
535
+ outcomes.set(component.id, inactive(component.id, kind));
536
+ receiptActions.push({ actionId: action.id, kind: action.kind, name: action.name, status: 'skipped' });
537
+ continue;
538
+ }
539
+ used.add(mounter);
540
+ try {
541
+ const applied = await mounter.mount({
542
+ action,
543
+ component,
544
+ plugin,
545
+ dataDir: pluginDataDir(this.dataRoot, plugin.id),
546
+ scope: GLOBAL_SCOPE,
547
+ commandNames,
548
+ takenNames: () => this.allCommandNames(plugin.id),
549
+ });
550
+ if (applied.disposer !== undefined) {
551
+ mounts.add(action.id, { componentId: component.id, kind, dispose: applied.disposer });
552
+ added.add(action.id);
553
+ }
554
+ // Runtime evidence gathered before a restart stays attached to the component.
555
+ outcomes.set(component.id, prior?.observations === undefined || applied.outcome.status === 'skipped'
556
+ ? applied.outcome
557
+ : withObservations(applied.outcome, prior.observations));
558
+ receiptActions.push({
559
+ actionId: action.id,
560
+ kind: action.kind,
561
+ name: action.name,
562
+ status: applied.outcome.status === 'skipped' ? 'skipped' : 'applied',
563
+ ...(applied.outcome.message !== undefined ? { undoToken: applied.outcome.message } : {}),
564
+ });
565
+ }
566
+ catch (error) {
567
+ const info = error instanceof HarnessError ? error.toJSON() : { code: 'runtime-failed', message: messageOf(error) };
568
+ outcomes.set(component.id, { componentId: component.id, status: 'failed', level: 'L0', evidence: 'runtime', message: info.message });
569
+ receiptActions.push({ actionId: action.id, kind: action.kind, name: action.name, status: 'failed', error: info });
570
+ }
571
+ }
572
+ // The delegation tool restarts on each agent change; the next request must see them all.
573
+ for (const mounter of used)
574
+ await mounter.settle?.(GLOBAL_SCOPE).catch(() => undefined);
575
+ let record;
576
+ let receipt;
577
+ let applied;
578
+ try {
579
+ record = this.buildRecord(plugin, plan, existing, outcomes, commandNames, receiptId);
580
+ const receiptComponents = [...outcomes.values()].map(outcome => ({
581
+ componentId: outcome.componentId,
582
+ status: outcome.status,
583
+ level: outcome.level,
584
+ ...(outcome.message !== undefined ? { message: outcome.message } : {}),
585
+ }));
586
+ const failed = receiptActions.some(action => action.status === 'failed');
587
+ applied = receiptActions.some(action => action.status === 'applied');
588
+ receipt = {
589
+ id: receiptId,
590
+ planId: plan.id,
591
+ pluginId: plugin.id,
592
+ root: plugin.root,
593
+ status: failed ? (applied ? 'partial' : 'failed') : 'applied',
594
+ startedAt,
595
+ finishedAt: new Date().toISOString(),
596
+ actions: receiptActions,
597
+ components: receiptComponents,
598
+ achieved: record.compat?.achieved ?? assess(plugin, [...outcomes.values()]).achieved,
599
+ };
600
+ await retryFile(() => writeReceipt(receipt, receiptsDirectory(this.statePath)));
601
+ this.live.set(plugin.id, { record, mounts, outcomes, plan });
602
+ await retryFile(() => this.writeLedger());
603
+ }
604
+ catch (error) {
605
+ // Nothing of this apply is recorded: what it registered is withdrawn, so no live code is left untracked.
606
+ const { failed } = await mounts.release((_mount, actionId) => added.has(actionId));
607
+ for (const mounter of used)
608
+ await mounter.settle?.(GLOBAL_SCOPE).catch(() => undefined);
609
+ if (failed.length > 0) {
610
+ // A registration whose withdrawal failed is never dropped: its install stays listed, with why, and owns it.
611
+ const kept = existing ?? { record: { ...this.buildRecord(plugin, plan, undefined, new Map(), commandNames, receiptId), receipts: [] }, mounts, outcomes: new Map(), unrecorded: true };
612
+ for (const { mount, reason } of failed)
613
+ kept.outcomes.set(mount.componentId, failedToCleanUp(mount.componentId, reason));
614
+ this.refreshRecord(kept, plugin);
615
+ this.live.set(plugin.id, kept);
616
+ }
617
+ else if (existing !== undefined)
618
+ this.live.set(plugin.id, existing);
619
+ else
620
+ this.live.delete(plugin.id);
621
+ throw error;
622
+ }
623
+ return {
624
+ plugin,
625
+ compat: record.compat ?? assess(plugin, [...outcomes.values()]),
626
+ receipt,
627
+ outcomes: [...outcomes.values()],
628
+ alreadyInstalled: existing !== undefined && !applied,
629
+ };
630
+ }
631
+ async undoNow(receiptId) {
632
+ let found;
633
+ for (const install of this.live.values()) {
634
+ if (!install.record.receipts?.includes(receiptId))
635
+ continue;
636
+ const receipt = readReceipt(receiptId, receiptsDirectory(this.statePath));
637
+ if (receipt !== undefined) {
638
+ found = { install, receipt };
639
+ break;
640
+ }
641
+ }
642
+ if (found === undefined)
643
+ return false;
644
+ const { install, receipt } = found;
645
+ const planActions = new Map(install.plan?.actions.map(action => [action.id, action]) ?? []);
646
+ const stuck = [];
647
+ for (const action of receipt.actions) {
648
+ const componentId = planActions.get(action.actionId)?.componentId;
649
+ if (action.status !== 'applied') {
650
+ if (componentId !== undefined && install.outcomes.get(componentId)?.status === 'skipped')
651
+ install.outcomes.delete(componentId);
652
+ continue;
653
+ }
654
+ const { failed } = await install.mounts.release((_mount, actionId) => actionId === action.actionId);
655
+ for (const { mount, reason } of failed) {
656
+ install.outcomes.set(mount.componentId, failedToSwitchOff(mount.componentId, reason));
657
+ stuck.push(`${mount.componentId}: failed to switch off: ${reason}`);
658
+ }
659
+ if (componentId !== undefined && failed.length === 0)
660
+ install.outcomes.delete(componentId);
661
+ }
662
+ if (stuck.length > 0) {
663
+ // The receipt stays applied: undoing it again retries.
664
+ this.refreshRecord(install);
665
+ this.persist();
666
+ throw new HarnessError('runtime-failed', `undo incomplete: ${stuck.join('; ')}`, { suggestion: 'Undo it again to retry.' });
667
+ }
668
+ await retryFile(() => writeReceipt({ ...receipt, status: 'undone', finishedAt: new Date().toISOString() }, receiptsDirectory(this.statePath)));
669
+ if (install.outcomes.size === 0) {
670
+ this.live.delete(install.record.id);
671
+ this.persist();
672
+ return true;
673
+ }
674
+ this.refreshRecord(install);
675
+ install.record = { ...install.record, receipts: install.record.receipts?.filter(id => id !== receiptId) ?? [] };
676
+ this.persist();
677
+ return true;
678
+ }
679
+ /**
680
+ * Switch one component of an installed plugin off (its registrations are
681
+ * released and it stays off across restarts) or on again (it mounts as at
682
+ * install). Returns whether anything changed.
683
+ */
684
+ async setEnabledNow(pluginId, componentId, enabled) {
685
+ this.assertAlive();
686
+ const install = this.live.get(pluginId);
687
+ if (install === undefined)
688
+ throw new HarnessError('not-installed', `no installed plugin ${pluginId}`);
689
+ // Switching off needs no scan: a source that changed or went away is still switched off.
690
+ const known = install.outcomes.has(componentId)
691
+ || install.plan?.actions.some(action => action.componentId === componentId) === true
692
+ || (enabled && this.scanRoot(install.record.root, install.record.source).components.some(candidate => candidate.id === componentId));
693
+ if (!known)
694
+ throw new HarnessError('not-installed', `${pluginId} has no part ${componentId}`);
695
+ const disabled = new Set(install.record.disabled ?? []);
696
+ if (disabled.has(componentId) === !enabled)
697
+ return false;
698
+ if (enabled)
699
+ disabled.delete(componentId);
700
+ else
701
+ disabled.add(componentId);
702
+ install.record = { ...install.record, disabled: [...disabled] };
703
+ if (enabled) {
704
+ install.outcomes.delete(componentId);
705
+ await this.applyNow(install.plan ?? this.planNow(install.record.root, install.record.source));
706
+ return true;
707
+ }
708
+ const settle = new Set();
709
+ const { released, failed } = await install.mounts.release(candidate => candidate.componentId === componentId);
710
+ for (const mount of released) {
711
+ const mounter = this.mounters.get(mount.kind);
712
+ if (mounter !== undefined)
713
+ settle.add(mounter);
714
+ }
715
+ for (const mounter of settle)
716
+ await mounter.settle?.(GLOBAL_SCOPE).catch(() => undefined);
717
+ if (failed.length > 0) {
718
+ // Still live: it is not recorded as off, so switching it off again retries.
719
+ disabled.delete(componentId);
720
+ install.record = { ...install.record, disabled: [...disabled] };
721
+ const outcome = failedToSwitchOff(componentId, failed.map(failure => failure.reason).join('; '));
722
+ install.outcomes.set(componentId, outcome);
723
+ this.refreshRecord(install);
724
+ this.persist();
725
+ throw new HarnessError('runtime-failed', `${componentId}: ${outcome.message ?? ''}`, { suggestion: 'Switch it off again to retry.' });
726
+ }
727
+ install.outcomes.set(componentId, switchedOff(componentId));
728
+ this.refreshRecord(install);
729
+ this.persist();
730
+ return true;
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
+ }
767
+ /** Release one installation without deciding whether the ledger survives. */
768
+ async teardown(id) {
769
+ const install = this.live.get(id);
770
+ if (install === undefined)
771
+ return false;
772
+ const { failed } = await install.mounts.release();
773
+ if (failed.length > 0) {
774
+ // The installation stays, with what is still live shown as failed: removing it again retries.
775
+ const stillLive = install.unrecorded === true ? failedToCleanUp : failedToSwitchOff;
776
+ for (const { mount, reason } of failed)
777
+ install.outcomes.set(mount.componentId, stillLive(mount.componentId, reason));
778
+ this.refreshRecord(install);
779
+ throw new HarnessError('runtime-failed', `${id}: ${failed.map(({ mount }) => `${mount.componentId}: ${install.outcomes.get(mount.componentId)?.message ?? ''}`).join('; ')}`, { suggestion: 'Remove it again to retry.' });
780
+ }
781
+ this.live.delete(id);
782
+ return true;
783
+ }
784
+ // ---------------------------------------------------------------------------
785
+ // Evidence
786
+ // ---------------------------------------------------------------------------
787
+ /** Record one runtime observation; the component's status follows its evidence. */
788
+ observe(componentId, observation) {
789
+ for (const install of this.live.values()) {
790
+ const prior = install.outcomes.get(componentId);
791
+ if (prior === undefined)
792
+ continue;
793
+ const next = 'clear' in observation
794
+ ? withObservations(prior, (prior.observations ?? []).filter(item => item.signal !== observation.clear))
795
+ : withObservations(prior, [...prior.observations ?? [], observation]);
796
+ install.outcomes.set(componentId, next);
797
+ this.refreshRecord(install);
798
+ this.persistSoon();
799
+ return;
800
+ }
801
+ }
802
+ // ---------------------------------------------------------------------------
803
+ // Helpers
804
+ // ---------------------------------------------------------------------------
805
+ scanRoot(root, source) {
806
+ // A harness's user directory (`~/.claude`, `~/.codex`) is the user's own assets, not a plugin.
807
+ for (const dialect of dialects()) {
808
+ if (dialect.user === undefined || resolve(root) !== resolve(dialect.user.root(homedir())) || (source !== undefined && source !== dialect.id))
809
+ continue;
810
+ const user = dialect.user.scan(homedir());
811
+ if (user === undefined)
812
+ throw new HarnessError('manifest-not-found', `${root} ${dialect.user.emptyMessage}`);
813
+ return user;
814
+ }
815
+ const plugin = scanRoot(root, source);
816
+ // Another installed plugin has this name: this one gets a stable suffix from its root, so both are installed.
817
+ const holder = this.live.get(plugin.id);
818
+ if (holder === undefined || samePath(holder.record.root, root))
819
+ return plugin;
820
+ const name = `${plugin.name}-${shortHash(resolve(root).toLowerCase(), 6)}`;
821
+ const renamed = scanRoot(root, plugin.source, { 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}` }] };
823
+ }
824
+ buildRecord(plugin, plan, existing, outcomes, commandNames, receiptId) {
825
+ const components = plugin.components.map(component => ({
826
+ kind: component.kind,
827
+ name: component.kind === 'command'
828
+ ? commandNames.get(component.id) ?? component.name
829
+ : component.kind === 'mcp' || component.kind === 'agent'
830
+ ? outcomes.get(component.id)?.message ?? component.name
831
+ : component.name,
832
+ ...(component.path !== undefined ? { path: component.path } : {}),
833
+ }));
834
+ return {
835
+ id: plugin.id,
836
+ source: plugin.source,
837
+ name: plugin.name,
838
+ ...(plugin.displayName !== undefined ? { displayName: plugin.displayName } : {}),
839
+ root: plugin.root,
840
+ ...(plugin.version !== undefined ? { version: plugin.version } : {}),
841
+ ...(plugin.license !== undefined ? { license: plugin.license } : {}),
842
+ installedAt: existing?.record.installedAt ?? new Date().toISOString(),
843
+ planId: plan.id,
844
+ fingerprint: plan.fingerprint,
845
+ components,
846
+ skillRoots: skillRootsOf(plugin, outcomes),
847
+ mounts: mountsFor(plugin, outcomes),
848
+ compat: assess(plugin, [...outcomes.values()]),
849
+ outcomes: [...outcomes.values()],
850
+ receipts: [...(existing?.record.receipts ?? []), receiptId],
851
+ ...(existing?.record.disabled !== undefined && existing.record.disabled.length > 0 ? { disabled: existing.record.disabled } : {}),
852
+ ...this.followed(plugin, existing),
853
+ };
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
+ }
864
+ report(result) {
865
+ const components = new Map(result.plugin.components.map(component => [component.id, component]));
866
+ const mcp = [];
867
+ const hooks = [];
868
+ const agents = [];
869
+ for (const outcome of result.outcomes) {
870
+ if (outcome.status === 'skipped' || outcome.status === 'inactive')
871
+ continue;
872
+ const component = components.get(outcome.componentId);
873
+ if (component === undefined)
874
+ continue;
875
+ const status = outcome.status === 'failed' ? 'failed' : 'mounted';
876
+ const error = outcome.status === 'failed' && outcome.message !== undefined ? { error: outcome.message } : {};
877
+ if (component.kind === 'mcp')
878
+ mcp.push({ name: outcome.message ?? component.name, status, ...error });
879
+ if (component.kind === 'hooks')
880
+ hooks.push({ name: component.name, dialect: result.plugin.source === 'codex' ? 'codex' : 'claude-code', status, ...error });
881
+ if (component.kind === 'agent')
882
+ agents.push({ name: component.name, presetId: outcome.message ?? '', status, ...error });
883
+ }
884
+ const record = this.live.get(result.plugin.id)?.record;
885
+ return {
886
+ ...result,
887
+ skillRoots: record?.skillRoots ?? [],
888
+ commands: record?.components.filter(component => component.kind === 'command').map(component => component.name) ?? [],
889
+ mcp,
890
+ hooks,
891
+ agents,
892
+ };
893
+ }
894
+ allCommandNames(excludePluginId) {
895
+ const names = new Set();
896
+ for (const [id, install] of this.live) {
897
+ if (id === excludePluginId)
898
+ continue;
899
+ for (const component of install.record.components)
900
+ if (component.kind === 'command')
901
+ names.add(component.name);
902
+ }
903
+ return names;
904
+ }
905
+ assertAlive() {
906
+ if (this.disposed)
907
+ throw new HarnessError('internal', 'Harness Forge service is disposed');
908
+ }
909
+ persistSoon() {
910
+ if (this.persistTimer !== undefined)
911
+ return;
912
+ this.persistTimer = setTimeout(() => {
913
+ this.persistTimer = undefined;
914
+ this.persist();
915
+ }, PERSIST_DELAY_MS);
916
+ this.persistTimer.unref?.();
917
+ }
918
+ /** Write the ledger, or try again shortly when the write fails transiently. */
919
+ persist() {
920
+ try {
921
+ this.writeLedger();
922
+ }
923
+ catch (error) {
924
+ if (!isTransient(error))
925
+ throw error;
926
+ this.persistSoon();
927
+ }
928
+ }
929
+ writeLedger() {
930
+ if (this.writeRefusal !== undefined) {
931
+ throw new HarnessError('internal', this.writeRefusal.message, { suggestion: this.writeRefusal.suggestion });
932
+ }
933
+ const state = { schemaVersion: 2, plugins: [...this.live.values()].filter(install => install.unrecorded !== true).map(install => install.record) };
934
+ writeState(state, this.statePath);
935
+ }
936
+ }
937
+ /** The same directory, whatever the case or separators (Windows paths are case-insensitive). */
938
+ function samePath(a, b) {
939
+ return process.platform === 'win32' ? resolve(a).toLowerCase() === resolve(b).toLowerCase() : resolve(a) === resolve(b);
940
+ }
941
+ /**
942
+ * Attach observations to an outcome: the newest per signal, bounded. A
943
+ * component with any currently failing signal is `failed`; one whose every
944
+ * observed signal succeeded is `verified`. Mount alone stays `mounted`.
945
+ */
946
+ function withObservations(outcome, observations) {
947
+ const latest = new Map();
948
+ for (const observation of observations) {
949
+ latest.delete(observation.signal);
950
+ latest.set(observation.signal, observation);
951
+ }
952
+ const kept = [...latest.values()].slice(-MAX_OBSERVATIONS);
953
+ if (outcome.status === 'skipped' || outcome.status === 'inactive')
954
+ return outcome;
955
+ if (kept.length === 0) {
956
+ const { observations: _dropped, ...rest } = outcome;
957
+ return { ...rest, status: 'mounted', evidence: 'source' };
958
+ }
959
+ // `message` keeps the mount identity (command name, server, preset); the
960
+ // failing observations carry their own details.
961
+ return {
962
+ ...outcome,
963
+ observations: kept,
964
+ status: kept.some(observation => !observation.ok) ? 'failed' : 'verified',
965
+ evidence: 'runtime',
966
+ };
967
+ }
968
+ /** The directory a skill provider root must contain for this skill body. */
969
+ export function skillRootOf(bodyPath) {
970
+ return /[\\/]SKILL\.md$/iu.test(bodyPath) ? dirname(dirname(bodyPath)) : dirname(bodyPath);
971
+ }
972
+ /** The skill roots of a plugin's mounted skills. */
973
+ function skillRootsOf(plugin, outcomes) {
974
+ const roots = new Set();
975
+ for (const component of plugin.components) {
976
+ const status = outcomes.get(component.id)?.status;
977
+ if (component.kind === 'skill' && (status === 'mounted' || status === 'verified'))
978
+ roots.add(skillRootOf(component.bodyPath));
979
+ }
980
+ return [...roots].sort((a, b) => a.localeCompare(b, 'en'));
981
+ }
982
+ /** Project the current component outcomes into the workbench mount list. */
983
+ export function mountsFor(plugin, outcomes) {
984
+ const mounts = [];
985
+ for (const [componentId, outcome] of outcomes) {
986
+ const component = plugin.components.find(candidate => candidate.id === componentId);
987
+ if (component === undefined)
988
+ continue;
989
+ if (component.kind !== 'mcp' && component.kind !== 'hooks' && component.kind !== 'agent' && component.kind !== 'code')
990
+ continue;
991
+ if (outcome.status === 'skipped' || outcome.status === 'inactive')
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;
996
+ mounts.push({
997
+ kind: component.kind === 'agent' ? 'agent' : component.kind === 'code' ? 'code' : component.kind === 'mcp' ? 'mcp' : 'hooks',
998
+ name: component.name,
999
+ ...(component.kind === 'hooks' ? { events: component.events } : {}),
1000
+ status: outcome.status === 'failed' ? 'failed' : 'mounted',
1001
+ ...(outcome.status === 'failed' && error !== undefined ? { error } : {}),
1002
+ });
1003
+ }
1004
+ return mounts;
1005
+ }