@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,129 @@
1
+ import type { CompatibilityVector, ComponentOutcome, SourceFingerprint } from '@kirkchinese/harness-forge-core';
2
+ /** One installed component identity. */
3
+ export interface InstalledComponentRecord {
4
+ readonly kind: 'skill' | 'command' | 'mcp' | 'hooks' | 'agent' | 'code' | 'ui' | 'settings' | 'other';
5
+ readonly name: string;
6
+ readonly path?: string;
7
+ }
8
+ /** One runtime mount outcome recorded for diagnostics. */
9
+ export interface MountRecord {
10
+ readonly kind: 'mcp' | 'hooks' | 'agent' | 'code';
11
+ readonly name: string;
12
+ /** A hooks part's events. */
13
+ readonly events?: readonly string[];
14
+ readonly status: 'mounted' | 'failed';
15
+ /** Why it failed: the failing signals' details, else the mount's message. */
16
+ readonly error?: string;
17
+ }
18
+ /** The harness install a migrated plugin follows: its updates move the plugin, its removal stops it. */
19
+ export interface HarnessInstallRecord {
20
+ readonly harness: string;
21
+ /** What the harness knows it by across updates (`HarnessInstall.key`). */
22
+ readonly key: string;
23
+ /** Learnt from the folder's layout, for a ledger written before installs carried their key: not yet seen listed. */
24
+ readonly inferred?: true;
25
+ /** Migrated while switched off in the harness, by the person's choice: switching it off there does not stop it. */
26
+ readonly enabled?: false;
27
+ }
28
+ /**
29
+ * Why a followed plugin is no longer one its harness runs: `uninstalled` (the harness lists it no more),
30
+ * `switched-off` (it is off there), `never-installed` (migrated by an earlier Harness Forge from a folder the harness
31
+ * never installed: a marketplace offer, a cached version), `misread` (an earlier Harness Forge read the harness's
32
+ * install as another harness's plugin). Its parts stay off until the person removes it or keeps it as their own.
33
+ */
34
+ export declare const DETACHED_REASONS: readonly ["uninstalled", "switched-off", "never-installed", "misread"];
35
+ export type DetachedReason = typeof DETACHED_REASONS[number];
36
+ /** A followed plugin its harness no longer runs. */
37
+ export interface DetachedRecord {
38
+ readonly reason: DetachedReason;
39
+ readonly at: string;
40
+ }
41
+ /** The last time the harness updated a followed plugin: Harness Forge moved it to the new folder. */
42
+ export interface HarnessUpdateRecord {
43
+ readonly from?: string;
44
+ readonly to?: string;
45
+ readonly at: string;
46
+ }
47
+ /** One installed foreign plugin. */
48
+ export interface InstalledPluginRecord {
49
+ readonly id: string;
50
+ readonly source: string;
51
+ readonly name: string;
52
+ /** The plugin's own name where `name` has a suffix telling it from another of the same name. */
53
+ readonly displayName?: string;
54
+ readonly root: string;
55
+ readonly version?: string;
56
+ readonly license?: string;
57
+ readonly installedAt: string;
58
+ readonly planId?: string;
59
+ readonly fingerprint?: SourceFingerprint;
60
+ readonly components: readonly InstalledComponentRecord[];
61
+ /** Skill roots registered for this plugin; used for exact removal. */
62
+ readonly skillRoots?: readonly string[];
63
+ /** Runtime mount results, retained so the workbench can explain failures. */
64
+ readonly mounts?: readonly MountRecord[];
65
+ /** Current honest vector; recomputed from outcomes, not copied from scan. */
66
+ readonly compat?: CompatibilityVector;
67
+ readonly outcomes?: readonly ComponentOutcome[];
68
+ /** Receipt ids in application order; the files live beside the ledger. */
69
+ readonly receipts?: readonly string[];
70
+ /** Components the person switched off: never mounted until switched on again. */
71
+ readonly disabled?: readonly string[];
72
+ /** The harness install it follows; absent for a plugin no harness installed (a folder, the person's own assets). */
73
+ readonly harnessInstall?: HarnessInstallRecord;
74
+ /** Set while its harness no longer runs it: nothing of it is mounted. */
75
+ readonly detached?: DetachedRecord;
76
+ readonly harnessUpdate?: HarnessUpdateRecord;
77
+ /** When the person kept it as their own copy: it follows no harness any more, and is never matched to one again. */
78
+ readonly keptAt?: string;
79
+ }
80
+ /** The complete ledger document. */
81
+ export interface CompatState {
82
+ readonly schemaVersion: 2;
83
+ readonly plugins: readonly InstalledPluginRecord[];
84
+ }
85
+ /** Resolve the Harness home without importing a DSH runtime package. */
86
+ export declare function resolveDshHome(env?: NodeJS.ProcessEnv): string;
87
+ /** Default ledger path. A launched profile keeps its own ledger; a bare
88
+ * composition falls back to the shared Harness Forge directory. */
89
+ export declare function defaultStatePath(env?: NodeJS.ProcessEnv, profile?: {
90
+ readonly dir?: string;
91
+ readonly name?: string;
92
+ }): string;
93
+ /** Whether a file operation failed in a way it may outlive. */
94
+ export declare function isTransient(error: unknown): boolean;
95
+ /**
96
+ * Run a file operation again while it fails transiently, for up to `forMs`. DSH itself can exhaust the process's
97
+ * file handles for seconds (it opens every session's cached projection at once); the waits must not block, since
98
+ * the handles are released by DSH's own callbacks.
99
+ */
100
+ export declare function retryFile<T>(operation: () => T, forMs?: number): Promise<T>;
101
+ /** The ledger schema this Harness Forge reads and writes. */
102
+ export declare const STATE_SCHEMA_VERSION = 2;
103
+ /** A ledger as read: what can be used of it, and what reading it cost. */
104
+ export interface LoadedState {
105
+ readonly state: CompatState;
106
+ /** The file as it was, kept beside it before anything of it was dropped or repaired; never overwritten. */
107
+ readonly backup?: string;
108
+ /** What could not be read (a record, or the whole file), each with why. */
109
+ readonly rejected: readonly string[];
110
+ /** Records read with a field defaulted or dropped, by id. */
111
+ readonly repaired: readonly string[];
112
+ /** The ledger was written by a newer Harness Forge: it is used as nothing and nothing may be written over it. */
113
+ readonly readOnly?: string;
114
+ }
115
+ /**
116
+ * Read the ledger. A missing ledger is empty; one that cannot be read throws (an empty answer would be persisted
117
+ * over the real one); one that is not JSON is kept beside it as `state.json.corrupt-<time>` and a new one starts.
118
+ * Before anything else of it is dropped or repaired, the file is kept as `state.json.unreadable-<time>`: records
119
+ * missing a field that can be defaulted or derived are repaired, records without what identifies a plugin are
120
+ * rejected, their valid peers kept. A ledger of a newer schema is refused whole, read-only.
121
+ */
122
+ export declare function loadState(path?: string): LoadedState;
123
+ /** The usable part of the ledger (see {@link loadState}). */
124
+ export declare function readState(path?: string): CompatState;
125
+ /** Persist the ledger atomically. */
126
+ export declare function writeState(state: CompatState, path?: string): void;
127
+ /** Directory holding receipts beside the ledger. */
128
+ export declare function receiptsDirectory(statePath?: string): string;
129
+ export type { CompatibilityVector, ComponentOutcome };
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Durable per-profile ledger. It records only what Harness Forge wrote or
3
+ * mounted; the foreign source stays read-only. Receipts live next to it and
4
+ * are referenced by id, never embedded wholesale.
5
+ * @module @kirkchinese/harness-forge
6
+ */
7
+ import { constants, copyFileSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
8
+ import { homedir } from 'node:os';
9
+ import { dirname, join } from 'node:path';
10
+ import { pluginId } from '@kirkchinese/harness-forge-core';
11
+ /**
12
+ * Why a followed plugin is no longer one its harness runs: `uninstalled` (the harness lists it no more),
13
+ * `switched-off` (it is off there), `never-installed` (migrated by an earlier Harness Forge from a folder the harness
14
+ * never installed: a marketplace offer, a cached version), `misread` (an earlier Harness Forge read the harness's
15
+ * install as another harness's plugin). Its parts stay off until the person removes it or keeps it as their own.
16
+ */
17
+ export const DETACHED_REASONS = ['uninstalled', 'switched-off', 'never-installed', 'misread'];
18
+ const EMPTY = { schemaVersion: 2, plugins: [] };
19
+ /** Resolve the Harness home without importing a DSH runtime package. */
20
+ export function resolveDshHome(env = process.env) {
21
+ const configured = env.DSH_HOME?.trim();
22
+ if (configured !== undefined && configured.length > 0) {
23
+ if (configured === '~')
24
+ return homedir();
25
+ if (configured.startsWith('~/') || configured.startsWith('~\\'))
26
+ return join(homedir(), configured.slice(2));
27
+ return configured;
28
+ }
29
+ return join(homedir(), '.dsh');
30
+ }
31
+ /** Default ledger path. A launched profile keeps its own ledger; a bare
32
+ * composition falls back to the shared Harness Forge directory. */
33
+ export function defaultStatePath(env = process.env, profile) {
34
+ if (profile?.dir !== undefined && profile.dir.length > 0) {
35
+ return join(profile.dir, '.harness-forge', 'state.json');
36
+ }
37
+ if (profile?.name !== undefined && profile.name.length > 0) {
38
+ return join(resolveDshHome(env), 'harness-forge', 'profiles', profile.name, 'state.json');
39
+ }
40
+ return join(resolveDshHome(env), 'harness-forge', 'state.json');
41
+ }
42
+ /** Errors a file operation may outlive: the process out of handles, the file briefly locked (a scanner, a sync). */
43
+ const TRANSIENT = new Set(['EMFILE', 'ENFILE', 'EBUSY', 'EAGAIN', 'EPERM', 'EACCES']);
44
+ /** Whether a file operation failed in a way it may outlive. */
45
+ export function isTransient(error) {
46
+ const code = error?.code;
47
+ return typeof code === 'string' && TRANSIENT.has(code);
48
+ }
49
+ /**
50
+ * Run a file operation again while it fails transiently, for up to `forMs`. DSH itself can exhaust the process's
51
+ * file handles for seconds (it opens every session's cached projection at once); the waits must not block, since
52
+ * the handles are released by DSH's own callbacks.
53
+ */
54
+ export async function retryFile(operation, forMs = 30_000) {
55
+ const deadline = Date.now() + forMs;
56
+ for (;;) {
57
+ try {
58
+ return operation();
59
+ }
60
+ catch (error) {
61
+ if (!isTransient(error) || Date.now() > deadline)
62
+ throw error;
63
+ await new Promise(resolve => setTimeout(resolve, 100));
64
+ }
65
+ }
66
+ }
67
+ /** The ledger schema this Harness Forge reads and writes. */
68
+ export const STATE_SCHEMA_VERSION = 2;
69
+ /**
70
+ * Read the ledger. A missing ledger is empty; one that cannot be read throws (an empty answer would be persisted
71
+ * over the real one); one that is not JSON is kept beside it as `state.json.corrupt-<time>` and a new one starts.
72
+ * Before anything else of it is dropped or repaired, the file is kept as `state.json.unreadable-<time>`: records
73
+ * missing a field that can be defaulted or derived are repaired, records without what identifies a plugin are
74
+ * rejected, their valid peers kept. A ledger of a newer schema is refused whole, read-only.
75
+ */
76
+ export function loadState(path = defaultStatePath()) {
77
+ let text;
78
+ try {
79
+ text = readFileSync(path, 'utf8');
80
+ }
81
+ catch (error) {
82
+ if (error.code === 'ENOENT')
83
+ return { state: EMPTY, rejected: [], repaired: [] };
84
+ throw error;
85
+ }
86
+ let value;
87
+ try {
88
+ value = JSON.parse(text);
89
+ }
90
+ catch {
91
+ return { state: EMPTY, backup: keepCopy(path, 'corrupt'), rejected: ['the ledger is not JSON'], repaired: [] };
92
+ }
93
+ const lost = (why) => ({ state: EMPTY, backup: keepCopy(path, 'unreadable'), rejected: [why], repaired: [] });
94
+ if (!isPlainRecord(value))
95
+ return lost('the ledger is not a JSON object');
96
+ const version = value['schemaVersion'];
97
+ if (typeof version === 'number' && Number.isInteger(version) && version > STATE_SCHEMA_VERSION) {
98
+ return {
99
+ state: EMPTY,
100
+ rejected: [],
101
+ repaired: [],
102
+ readOnly: `${path} was written by a newer Harness Forge (ledger schema ${String(version)}; this one reads ${String(STATE_SCHEMA_VERSION)}): upgrade Harness Forge. Nothing is restored from it and nothing is written over it`,
103
+ };
104
+ }
105
+ if (version !== 1 && version !== 2)
106
+ return lost(`the ledger has an unknown schemaVersion ${JSON.stringify(version) ?? 'undefined'}`);
107
+ if (!Array.isArray(value['plugins']))
108
+ return lost('the ledger\'s "plugins" is not a list');
109
+ const plugins = [];
110
+ const rejected = [];
111
+ const repaired = [];
112
+ const installedAt = fileTime(path);
113
+ for (const [index, raw] of value['plugins'].entries()) {
114
+ const read = version === 2 ? readRecord(raw, installedAt) : readLegacyRecord(raw, installedAt);
115
+ if (typeof read === 'string') {
116
+ rejected.push(`record ${String(index)}: ${read}`);
117
+ continue;
118
+ }
119
+ plugins.push(read.record);
120
+ if (read.repaired)
121
+ repaired.push(read.record.id);
122
+ }
123
+ // A v1 ledger is migrated (its trust is not carried over): the v1 file is kept as it was.
124
+ const lossy = rejected.length > 0 || repaired.length > 0 || version === 1;
125
+ return { state: { schemaVersion: STATE_SCHEMA_VERSION, plugins }, ...(lossy ? { backup: keepCopy(path, 'unreadable') } : {}), rejected, repaired };
126
+ }
127
+ /** The usable part of the ledger (see {@link loadState}). */
128
+ export function readState(path = defaultStatePath()) {
129
+ return loadState(path).state;
130
+ }
131
+ /** Keep the ledger as it is now beside it, under a name no other copy has. */
132
+ function keepCopy(path, kind) {
133
+ const stamp = `${path}.${kind}-${String(Date.now())}`;
134
+ for (let attempt = 0;; attempt++) {
135
+ const target = attempt === 0 ? stamp : `${stamp}-${String(attempt)}`;
136
+ try {
137
+ copyFileSync(path, target, constants.COPYFILE_EXCL);
138
+ return target;
139
+ }
140
+ catch (error) {
141
+ if (error.code !== 'EEXIST')
142
+ throw error;
143
+ }
144
+ }
145
+ }
146
+ /** When the ledger was last written: a record missing its install time was installed no later. */
147
+ function fileTime(path) {
148
+ try {
149
+ return statSync(path).mtime.toISOString();
150
+ }
151
+ catch {
152
+ return new Date().toISOString();
153
+ }
154
+ }
155
+ /** Persist the ledger atomically. */
156
+ export function writeState(state, path = defaultStatePath()) {
157
+ mkdirSync(dirname(path), { recursive: true });
158
+ const temporary = `${path}.tmp`;
159
+ writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
160
+ renameSync(temporary, path);
161
+ }
162
+ /** Directory holding receipts beside the ledger. */
163
+ export function receiptsDirectory(statePath = defaultStatePath()) {
164
+ return join(dirname(statePath), 'receipts');
165
+ }
166
+ function isPlainRecord(value) {
167
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
168
+ }
169
+ /** What identifies a plugin: its source and root, and its id or name (each derivable from the other). */
170
+ function identity(raw) {
171
+ const source = raw['source'];
172
+ const root = raw['root'];
173
+ if (typeof source !== 'string' || source.length === 0)
174
+ return 'it has no source';
175
+ if (typeof root !== 'string' || root.length === 0)
176
+ return 'it has no root folder';
177
+ const id = typeof raw['id'] === 'string' && raw['id'].length > 0 ? raw['id'] : undefined;
178
+ const name = typeof raw['name'] === 'string' && raw['name'].length > 0 ? raw['name'] : id?.startsWith(`${source}:`) === true ? id.slice(source.length + 1) : undefined;
179
+ if (name === undefined)
180
+ return 'it has neither a name nor an id of its source';
181
+ return { id: id ?? pluginId(source, name), source, name, root };
182
+ }
183
+ /** A v2 record, repaired where a field can be defaulted, or why it cannot be read. */
184
+ function readRecord(raw, installedAt) {
185
+ if (!isPlainRecord(raw))
186
+ return 'it is not an object';
187
+ const base = identity(raw);
188
+ if (typeof base === 'string')
189
+ return base;
190
+ const copy = { ...raw, ...base };
191
+ // Old v2 ledgers may still carry a trust object; it is no longer state, and dropping it loses nothing.
192
+ delete copy['trust'];
193
+ let repaired = base.id !== raw['id'] || base.name !== raw['name'];
194
+ const drop = (key) => {
195
+ if (key in copy) {
196
+ delete copy[key];
197
+ repaired = true;
198
+ }
199
+ };
200
+ if (typeof copy['installedAt'] !== 'string') {
201
+ copy['installedAt'] = installedAt;
202
+ repaired = true;
203
+ }
204
+ const components = Array.isArray(copy['components']) ? copy['components'].filter(isComponent) : [];
205
+ if (!Array.isArray(copy['components']) || components.length !== copy['components'].length)
206
+ repaired = true;
207
+ copy['components'] = components;
208
+ for (const key of ['displayName', 'version', 'license', 'planId', 'keptAt'])
209
+ if (key in copy && typeof copy[key] !== 'string')
210
+ drop(key);
211
+ if ('harnessInstall' in copy && !isHarnessInstall(copy['harnessInstall']))
212
+ drop('harnessInstall');
213
+ if ('detached' in copy && !(isPlainRecord(copy['detached']) && DETACHED_REASONS.includes(copy['detached']['reason']) && typeof copy['detached']['at'] === 'string'))
214
+ drop('detached');
215
+ if ('harnessUpdate' in copy && !(isPlainRecord(copy['harnessUpdate']) && typeof copy['harnessUpdate']['at'] === 'string'))
216
+ drop('harnessUpdate');
217
+ for (const key of ['fingerprint', 'compat'])
218
+ if (key in copy && !isPlainRecord(copy[key]))
219
+ drop(key);
220
+ for (const key of ['mounts', 'outcomes']) {
221
+ if (!(key in copy))
222
+ continue;
223
+ if (!Array.isArray(copy[key]))
224
+ drop(key);
225
+ else if (!copy[key].every(isPlainRecord)) {
226
+ copy[key] = copy[key].filter(isPlainRecord);
227
+ repaired = true;
228
+ }
229
+ }
230
+ for (const key of ['skillRoots', 'receipts', 'disabled']) {
231
+ if (!(key in copy))
232
+ continue;
233
+ if (!Array.isArray(copy[key]))
234
+ drop(key);
235
+ else if (!copy[key].every(item => typeof item === 'string')) {
236
+ copy[key] = copy[key].filter(item => typeof item === 'string');
237
+ repaired = true;
238
+ }
239
+ }
240
+ return { record: copy, repaired };
241
+ }
242
+ /** A v1 record as v2: its identity, version, license, install time, components and skill roots. */
243
+ function readLegacyRecord(raw, installedAt) {
244
+ if (!isPlainRecord(raw))
245
+ return 'it is not an object';
246
+ const base = identity(raw);
247
+ if (typeof base === 'string')
248
+ return base;
249
+ const components = Array.isArray(raw['components']) ? raw['components'].filter(isComponent) : [];
250
+ const record = {
251
+ ...base,
252
+ ...(typeof raw['version'] === 'string' ? { version: raw['version'] } : {}),
253
+ ...(typeof raw['license'] === 'string' ? { license: raw['license'] } : {}),
254
+ installedAt: typeof raw['installedAt'] === 'string' ? raw['installedAt'] : installedAt,
255
+ components,
256
+ ...(Array.isArray(raw['skillRoots']) ? { skillRoots: raw['skillRoots'].filter((root) => typeof root === 'string') } : {}),
257
+ receipts: [],
258
+ };
259
+ return { record, repaired: typeof raw['installedAt'] !== 'string' || !Array.isArray(raw['components']) || components.length !== raw['components'].length };
260
+ }
261
+ function isHarnessInstall(value) {
262
+ return isPlainRecord(value) && typeof value['harness'] === 'string' && typeof value['key'] === 'string';
263
+ }
264
+ function isComponent(value) {
265
+ return isPlainRecord(value) && typeof value['kind'] === 'string' && typeof value['name'] === 'string';
266
+ }
@@ -0,0 +1,48 @@
1
+ import { type TrustSource } from '@kirkchinese/harness-forge-core';
2
+ /** The outcome message of a project part held back until the workspace is trusted. */
3
+ export declare const WAITING_FOR_TRUST = "waiting for you to trust this workspace";
4
+ /** The outcome message of a project `.mcp.json` server Claude Code has not approved (and Harness Forge was not asked to trust). */
5
+ export declare const WAITING_FOR_APPROVAL = "waiting for approval: approve it in Claude Code, or trust this workspace in Harness Forge";
6
+ /** Why a project's command or skill runs no shell line: the reason its rendering shows. */
7
+ export declare function untrustedShell(workspace: string): string;
8
+ /** Whether the workspace of a directory is trusted now, as commands and skills ask when they render. */
9
+ export type TrustCheck = (dir: string) => {
10
+ readonly trusted: boolean;
11
+ readonly workspace: string;
12
+ };
13
+ /** A workspace's trust as the workbench shows it. */
14
+ export interface WorkspaceTrustState {
15
+ readonly workspace: string;
16
+ readonly trusted: boolean;
17
+ /** Where the trust comes from; empty when untrusted. */
18
+ readonly sources: readonly TrustSource[];
19
+ /** The person chose "Not now" for this workspace: its banner stays hidden. */
20
+ readonly dismissed: boolean;
21
+ }
22
+ /** A workspace Harness Forge has a decision on, for the Trust settings list. */
23
+ export interface TrustRecord extends WorkspaceTrustState {
24
+ readonly trustedAt?: string;
25
+ readonly dismissedAt?: string;
26
+ }
27
+ /** The per-profile store of workspaces trusted in Harness Forge. */
28
+ export declare class WorkspaceTrust {
29
+ private readonly home;
30
+ private readonly path;
31
+ private readonly listeners;
32
+ constructor(statePath: string, home?: string);
33
+ private read;
34
+ private write;
35
+ /** The trust of the workspace that holds `cwd`. */
36
+ state(cwd: string): WorkspaceTrustState;
37
+ /** The workspaces Harness Forge holds a decision on (trusted here, or dismissed), most recent first. */
38
+ list(): TrustRecord[];
39
+ /**
40
+ * Trust (or stop trusting) the workspace that holds `cwd` in Harness Forge; trust kept by Claude Code or Codex stays theirs.
41
+ * Trusting ends a dismissal; revoking leaves the workspace undecided again.
42
+ */
43
+ set(cwd: string, trusted: boolean): WorkspaceTrustState;
44
+ /** Hide (or show again) the trust banner of the workspace that holds `cwd`; this trusts nothing. */
45
+ dismiss(cwd: string, dismissed: boolean): WorkspaceTrustState;
46
+ /** Hear each change made here. */
47
+ onChange(listener: (workspace: string, trusted: boolean) => void): () => void;
48
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Workspace trust: whether a project's parts that run code or reach the
3
+ * network may run in DSH. A workspace is trusted when the person accepted
4
+ * Claude Code's trust dialog for it, Codex marks it trusted, or they trusted
5
+ * it in Harness Forge. Harness Forge's own grants live in `trust.json` beside
6
+ * the ledger (per DSH profile), never in the profile's DSH configuration.
7
+ * See `@kirkchinese/harness-forge-core` `trust.ts` for the rules.
8
+ * @module @kirkchinese/harness-forge
9
+ */
10
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
11
+ import { homedir } from 'node:os';
12
+ import { dirname, join, resolve } from 'node:path';
13
+ import { claudeCodeTrusts, codexTrusts, trustKeys, workspaceRootOf } from '@kirkchinese/harness-forge-core';
14
+ /** The outcome message of a project part held back until the workspace is trusted. */
15
+ export const WAITING_FOR_TRUST = 'waiting for you to trust this workspace';
16
+ /** The outcome message of a project `.mcp.json` server Claude Code has not approved (and Harness Forge was not asked to trust). */
17
+ export const WAITING_FOR_APPROVAL = 'waiting for approval: approve it in Claude Code, or trust this workspace in Harness Forge';
18
+ /** Why a project's command or skill runs no shell line: the reason its rendering shows. */
19
+ export function untrustedShell(workspace) {
20
+ return `the workspace ${workspace} is not trusted (trust it in Harness Forge → Migrated)`;
21
+ }
22
+ /** The per-profile store of workspaces trusted in Harness Forge. */
23
+ export class WorkspaceTrust {
24
+ home;
25
+ path;
26
+ listeners = new Set();
27
+ constructor(statePath, home = homedir()) {
28
+ this.home = home;
29
+ this.path = join(dirname(statePath), 'trust.json');
30
+ }
31
+ read() {
32
+ try {
33
+ const raw = JSON.parse(readFileSync(this.path, 'utf8'));
34
+ if (typeof raw === 'object' && raw !== null && typeof raw.workspaces === 'object' && raw.workspaces !== null)
35
+ return raw;
36
+ }
37
+ catch {
38
+ // Absent or unreadable: nothing is trusted here.
39
+ }
40
+ return { schemaVersion: 1, workspaces: {}, dismissed: {} };
41
+ }
42
+ write(workspaces, dismissed) {
43
+ mkdirSync(dirname(this.path), { recursive: true });
44
+ const temporary = `${this.path}.tmp`;
45
+ writeFileSync(temporary, `${JSON.stringify({ schemaVersion: 1, workspaces, dismissed }, null, 2)}\n`, 'utf8');
46
+ renameSync(temporary, this.path);
47
+ }
48
+ /** The trust of the workspace that holds `cwd`. */
49
+ state(cwd) {
50
+ const workspace = workspaceRootOf(resolve(cwd));
51
+ const granted = this.read().workspaces;
52
+ const sources = [];
53
+ if (claudeCodeTrusts(workspace, this.home))
54
+ sources.push('claude-code');
55
+ if (codexTrusts(workspace, this.home))
56
+ sources.push('codex');
57
+ if (trustKeys(workspace, this.home).some(key => granted[key] !== undefined))
58
+ sources.push('forge');
59
+ return { workspace, trusted: sources.length > 0, sources, dismissed: this.read().dismissed?.[workspace] !== undefined };
60
+ }
61
+ /** The workspaces Harness Forge holds a decision on (trusted here, or dismissed), most recent first. */
62
+ list() {
63
+ const stored = this.read();
64
+ const roots = new Set([...Object.keys(stored.workspaces), ...Object.keys(stored.dismissed ?? {})]);
65
+ return [...roots].map((root) => {
66
+ const trustedAt = stored.workspaces[root]?.trustedAt;
67
+ const dismissedAt = stored.dismissed?.[root]?.dismissedAt;
68
+ return { ...this.state(root), workspace: root, ...(trustedAt !== undefined ? { trustedAt } : {}), ...(dismissedAt !== undefined ? { dismissedAt } : {}) };
69
+ }).sort((left, right) => (right.trustedAt ?? right.dismissedAt ?? '').localeCompare(left.trustedAt ?? left.dismissedAt ?? ''));
70
+ }
71
+ /**
72
+ * Trust (or stop trusting) the workspace that holds `cwd` in Harness Forge; trust kept by Claude Code or Codex stays theirs.
73
+ * Trusting ends a dismissal; revoking leaves the workspace undecided again.
74
+ */
75
+ set(cwd, trusted) {
76
+ const workspace = workspaceRootOf(resolve(cwd));
77
+ const current = this.read();
78
+ const workspaces = { ...current.workspaces };
79
+ const dismissed = { ...current.dismissed };
80
+ delete dismissed[workspace];
81
+ if (trusted)
82
+ workspaces[workspace] = { trustedAt: new Date().toISOString() };
83
+ else
84
+ delete workspaces[workspace];
85
+ this.write(workspaces, dismissed);
86
+ for (const listener of [...this.listeners])
87
+ listener(workspace, trusted);
88
+ return this.state(workspace);
89
+ }
90
+ /** Hide (or show again) the trust banner of the workspace that holds `cwd`; this trusts nothing. */
91
+ dismiss(cwd, dismissed) {
92
+ const workspace = workspaceRootOf(resolve(cwd));
93
+ const current = this.read();
94
+ const marks = { ...current.dismissed };
95
+ if (dismissed)
96
+ marks[workspace] = { dismissedAt: new Date().toISOString() };
97
+ else
98
+ delete marks[workspace];
99
+ this.write(current.workspaces, marks);
100
+ return this.state(workspace);
101
+ }
102
+ /** Hear each change made here. */
103
+ onChange(listener) {
104
+ this.listeners.add(listener);
105
+ return () => { this.listeners.delete(listener); };
106
+ }
107
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The turn lifecycle of invoked skills and commands, which every row's
3
+ * frontmatter effects share: a user's message ends the previous turn's
4
+ * grants and starts the queued command's, a typed `/skill` line runs on the
5
+ * skill's route from its turn's first step, and a route ends with its turn.
6
+ * The `harness-forge` row listens for these.
7
+ * @module @kirkchinese/harness-forge
8
+ */
9
+ import type { Context } from '@deepseek-ai/cordis';
10
+ import type { Disposer } from './contract.js';
11
+ import type { HarnessForge } from './service.js';
12
+ /** Listen for the turn lifecycle. Returns the disposers, one per listener. */
13
+ export declare function turnListeners(ctx: Context, forge: HarnessForge): Array<[string, () => Disposer | undefined]>;
@@ -0,0 +1,56 @@
1
+ import { interceptCommands } from '../dsh/commands.js';
2
+ import { dshService, onDsh } from '../dsh/host.js';
3
+ /** Listen for the turn lifecycle. Returns the disposers, one per listener. */
4
+ export function turnListeners(ctx, forge) {
5
+ const invocations = forge.invocations;
6
+ return [
7
+ ['turn start', () => onDsh(ctx, 'agent/pre-step', (async (payload, next) => {
8
+ const { agent, messages, signal } = payload;
9
+ // A forked skill's agent keeps its grants for its whole run; only a user's message ends a turn's.
10
+ if ((agent.session.header.delegationDepth ?? 0) === 0 && messages.some(message => message.source?.kind === 'user')) {
11
+ const sessionId = agent.session.header.id;
12
+ invocations.clear(sessionId);
13
+ // A command's frontmatter belongs to the turn its submitted prompt starts.
14
+ for (const spec of invocations.takeQueued(sessionId))
15
+ await invocations.activate(agent, spec, signal);
16
+ }
17
+ return next();
18
+ }), { prepend: true, owner: 'harness-forge' })],
19
+ ['turn end', () => onDsh(ctx, 'session/event', ((session, event) => {
20
+ const id = session.header?.id ?? session.id;
21
+ if (id === undefined)
22
+ return;
23
+ if (event.type === 'turn/start')
24
+ invocations.turnStarted(id);
25
+ else if (event.type === 'turn/end')
26
+ invocations.turnEnded(id);
27
+ }), { owner: 'harness-forge' })],
28
+ // A typed `/skill` line runs on the skill's route from its turn's first step (DSH 0.2.2 fixes a step's route
29
+ // before agent/pre-step, where the skill is otherwise activated); the route ends with that turn.
30
+ ['typed skills', () => {
31
+ const commands = dshService(ctx, 'commands');
32
+ if (commands === undefined)
33
+ return undefined;
34
+ return interceptCommands(commands, async (args, next) => {
35
+ const [agent, line, , signal] = args;
36
+ const name = /^\/([^\s]+)/u.exec(String(line ?? '').trim())?.[1];
37
+ const spec = name === undefined ? undefined : invocations.skill(name);
38
+ if (spec === undefined || agent === undefined)
39
+ return next();
40
+ await invocations.preselect(agent, spec, signal ?? new AbortController().signal).catch(() => undefined);
41
+ // A line that fails or is refused starts no turn: the route it selected is put back now, not after an unrelated turn.
42
+ let execution;
43
+ try {
44
+ execution = await next();
45
+ }
46
+ catch (error) {
47
+ invocations.release(agent.session.header.id);
48
+ throw error;
49
+ }
50
+ if (execution?.result?.kind !== 'success')
51
+ invocations.release(agent.session.header.id);
52
+ return execution;
53
+ });
54
+ }],
55
+ ];
56
+ }