@kirkchinese/harness-forge 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +4 -0
  2. package/docs/DETAIL.zh.md +47 -0
  3. package/lib/agents/presets.d.ts +7 -0
  4. package/lib/agents/presets.js +11 -1
  5. package/lib/agents/profiles.js +3 -2
  6. package/lib/agents/row.js +3 -1
  7. package/lib/client/paths.d.ts +12 -0
  8. package/lib/client/paths.js +68 -0
  9. package/lib/client/typert.d.ts +12 -1
  10. package/lib/client/typert.js +54 -6
  11. package/lib/client.js +1593 -270
  12. package/lib/commands/row.js +1 -1
  13. package/lib/context/instructions.js +5 -5
  14. package/lib/dsh/host.d.ts +3 -0
  15. package/lib/dsh/host.js +3 -0
  16. package/lib/forge/contract.d.ts +42 -2
  17. package/lib/forge/contract.js +3 -1
  18. package/lib/forge/follow.d.ts +30 -0
  19. package/lib/forge/follow.js +73 -0
  20. package/lib/forge/ledger.d.ts +70 -7
  21. package/lib/forge/ledger.js +314 -42
  22. package/lib/forge/projects.d.ts +5 -2
  23. package/lib/forge/projects.js +23 -16
  24. package/lib/forge/remote/archive.d.ts +65 -0
  25. package/lib/forge/remote/archive.js +565 -0
  26. package/lib/forge/remote/code-parts.d.ts +18 -0
  27. package/lib/forge/remote/code-parts.js +76 -0
  28. package/lib/forge/remote/fetch.d.ts +265 -0
  29. package/lib/forge/remote/fetch.js +1133 -0
  30. package/lib/forge/remote/service.d.ts +256 -0
  31. package/lib/forge/remote/service.js +868 -0
  32. package/lib/forge/service.d.ts +19 -9
  33. package/lib/forge/service.js +47 -31
  34. package/lib/forge/settings.d.ts +5 -3
  35. package/lib/forge/settings.js +11 -4
  36. package/lib/forge/state.d.ts +60 -0
  37. package/lib/forge/state.js +174 -58
  38. package/lib/hooks/broker/engine.js +2 -8
  39. package/lib/hooks/broker/session-events.d.ts +5 -0
  40. package/lib/hooks/broker/session-events.js +12 -3
  41. package/lib/hooks/broker/types.d.ts +7 -5
  42. package/lib/hooks/condition.d.ts +78 -2
  43. package/lib/hooks/condition.js +494 -73
  44. package/lib/hooks/config.d.ts +1 -1
  45. package/lib/hooks/config.js +4 -0
  46. package/lib/hooks/glob.d.ts +41 -0
  47. package/lib/hooks/glob.js +114 -0
  48. package/lib/hooks/permissions.d.ts +8 -3
  49. package/lib/hooks/permissions.js +119 -26
  50. package/lib/hooks/powershell-aliases.d.ts +19 -0
  51. package/lib/hooks/powershell-aliases.js +58 -0
  52. package/lib/hooks/process.d.ts +17 -0
  53. package/lib/hooks/process.js +156 -1
  54. package/lib/hooks/row.js +2 -0
  55. package/lib/hooks/runner.d.ts +17 -4
  56. package/lib/hooks/runner.js +42 -13
  57. package/lib/hooks/shell-commands.d.ts +10 -1
  58. package/lib/hooks/shell-commands.js +74 -10
  59. package/lib/hooks/shell.d.ts +3 -2
  60. package/lib/hooks/shell.js +5 -2
  61. package/lib/hooks/vocabulary.js +3 -1
  62. package/lib/mcp/catalog.d.ts +5 -2
  63. package/lib/mcp/catalog.js +18 -10
  64. package/lib/mcp/mount.d.ts +40 -2
  65. package/lib/mcp/mount.js +131 -31
  66. package/lib/mcp/policy.d.ts +42 -0
  67. package/lib/mcp/policy.js +43 -0
  68. package/lib/mcp/remote.js +5 -15
  69. package/lib/mcp/row.js +111 -17
  70. package/lib/mods/loader.js +4 -0
  71. package/lib/mods/service/turns.d.ts +8 -7
  72. package/lib/mods/service/turns.js +10 -35
  73. package/lib/opencode/bun.js +14 -2
  74. package/lib/opencode/row.d.ts +14 -1
  75. package/lib/opencode/row.js +38 -20
  76. package/lib/opencode/runtime/server.js +2 -1
  77. package/lib/porting/adapter-paths.d.ts +13 -0
  78. package/lib/porting/adapter-paths.js +120 -0
  79. package/lib/porting/port-gap.d.ts +10 -4
  80. package/lib/porting/port-gap.js +43 -7
  81. package/lib/porting/prompt.js +9 -7
  82. package/lib/porting/row.js +7 -5
  83. package/lib/porting/verify-port.d.ts +3 -10
  84. package/lib/porting/verify-port.js +12 -34
  85. package/lib/sessions/chat-import.d.ts +48 -0
  86. package/lib/sessions/chat-import.js +44 -0
  87. package/lib/sessions/claude.d.ts +16 -10
  88. package/lib/sessions/claude.js +76 -55
  89. package/lib/sessions/codex-discover.d.ts +34 -0
  90. package/lib/sessions/codex-discover.js +205 -0
  91. package/lib/sessions/codex-meta.d.ts +63 -0
  92. package/lib/sessions/codex-meta.js +148 -0
  93. package/lib/sessions/codex-text.d.ts +9 -0
  94. package/lib/sessions/codex-text.js +44 -0
  95. package/lib/sessions/codex.d.ts +34 -22
  96. package/lib/sessions/codex.js +150 -183
  97. package/lib/sessions/opencode.d.ts +15 -9
  98. package/lib/sessions/opencode.js +77 -58
  99. package/lib/sessions/persist.d.ts +162 -0
  100. package/lib/sessions/persist.js +377 -0
  101. package/lib/sessions/row.d.ts +2 -1
  102. package/lib/sessions/row.js +75 -9
  103. package/lib/sessions/turns.d.ts +31 -0
  104. package/lib/sessions/turns.js +63 -0
  105. package/lib/sessions/zstd.d.ts +15 -0
  106. package/lib/sessions/zstd.js +152 -0
  107. package/lib/shared/render.d.ts +30 -1
  108. package/lib/shared/render.js +813 -48
  109. package/lib/skills/provider.d.ts +2 -0
  110. package/lib/skills/provider.js +8 -2
  111. package/lib/skills/row.js +1 -1
  112. package/lib/workbench/adapter-coverage.d.ts +20 -2
  113. package/lib/workbench/adapter-coverage.js +46 -7
  114. package/lib/workbench/overview.d.ts +77 -27
  115. package/lib/workbench/overview.js +99 -12
  116. package/lib/workbench/remote.d.ts +64 -21
  117. package/lib/workbench/remote.js +181 -42
  118. package/lib/workbench/settings.d.ts +5 -1
  119. package/lib/workbench/settings.js +6 -2
  120. package/lib/workbench/workbench.d.ts +34 -4
  121. package/lib/workbench/workbench.js +147 -46
  122. package/locale/zh.json +2 -1
  123. package/package.json +3 -2
  124. package/lib/forge/marketplace-install.d.ts +0 -3
  125. package/lib/forge/marketplace-install.js +0 -64
@@ -1,12 +1,14 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
- import { type ForeignPlugin, type MarketplaceIndex, type Plan } from '@kirkchinese/harness-forge-core';
2
+ import { type ForeignPlugin, type Plan } from '@kirkchinese/harness-forge-core';
3
3
  import { type ForeignShell } from '../hooks/shell.js';
4
4
  import { Invocations } from '../shared/invocation.js';
5
5
  import type { InstalledPluginRecord } from './state.js';
6
6
  import type { Disposer, MountKind, Mounter, RowApis } from './contract.js';
7
- import { Ledger, type ApplyResult, type InstallReport } from './ledger.js';
7
+ import { Ledger, type ApplyProgress, type ApplyResult, type InstallReport } from './ledger.js';
8
8
  import { ProjectAssets } from './projects.js';
9
9
  import { ImportedSettings } from './settings.js';
10
+ import { RemotePlugins } from './remote/service.js';
11
+ import type { FetchDeps, FetchLimits } from './remote/fetch.js';
10
12
  export type { AgentReport, ApplyResult, HookReport, InstallReport, McpReport } from './ledger.js';
11
13
  /** The service name the `harness-forge` row provides. */
12
14
  export declare const FORGE_SERVICE = "harnessForge";
@@ -34,6 +36,8 @@ export declare class HarnessForge {
34
36
  /** Claude Code and Codex project assets per session. */
35
37
  readonly projects: ProjectAssets;
36
38
  readonly ledger: Ledger;
39
+ /** Plugins fetched from the network into `<dataRoot>/remote`. */
40
+ readonly remote: RemotePlugins;
37
41
  private readonly apis;
38
42
  private readonly watchers;
39
43
  private readonly recentFaults;
@@ -42,7 +46,13 @@ export declare class HarnessForge {
42
46
  * @param statePath - the ledger file.
43
47
  * @param dataRoot - profile-local writable directory (shims, OAuth state, mod store).
44
48
  */
45
- constructor(ctx: Context, statePath: string, dataRoot: string);
49
+ /** `remote`: what plugins from the network are fetched with (tests replace git, npm, fetch and the resolver). */
50
+ constructor(ctx: Context, statePath: string, dataRoot: string, options?: {
51
+ readonly remote?: {
52
+ readonly deps?: FetchDeps;
53
+ readonly limits?: FetchLimits;
54
+ };
55
+ });
46
56
  /** A session's working directory, as hooks and commands see it. */
47
57
  directory(agent: unknown, signal: AbortSignal): Promise<string>;
48
58
  /** Register the mounter of one kind of component; see {@link Ledger.registerMounter}. */
@@ -84,16 +94,18 @@ export declare class HarnessForge {
84
94
  apply(plan: Plan): Promise<ApplyResult>;
85
95
  /** Plan and apply one plugin root. */
86
96
  install(root: string, source?: string): Promise<InstallReport>;
87
- /** Read a marketplace index without installing anything. */
88
- scanMarketplace(path: string): MarketplaceIndex;
89
- /** Install one marketplace entry from a local path or git source. */
90
- installMarketplace(path: string, name: string): Promise<InstallReport>;
91
97
  /** Undo the actions of one receipt and remove its live registrations. */
92
98
  undo(receiptId: string): Promise<boolean>;
93
99
  /** Switch one part of an installed plugin off or on again; it stays so across restarts. */
94
100
  setPartEnabled(pluginId: string, componentId: string, enabled: boolean): Promise<boolean>;
95
101
  /** Remove one installation and every registration it owns. */
96
102
  uninstall(id: string): Promise<boolean>;
103
+ /** Keep a plugin its harness no longer runs as the person's own copy: it mounts again and follows no harness. */
104
+ keep(id: string): Promise<ApplyResult>;
105
+ /** Follow the harnesses' updates and removals of migrated plugins; see `follow.ts`. Settles once applied. */
106
+ follow(): Promise<void>;
107
+ /** How far applying the ledger's records has got, while some still are (at startup, after a harness change). */
108
+ applying(): ApplyProgress | undefined;
97
109
  /** Scan one plugin without writing anything. */
98
110
  scan(root: string, source?: string): ForeignPlugin;
99
111
  /** List current installations in stable name order. */
@@ -101,5 +113,3 @@ export declare class HarnessForge {
101
113
  /** Drop every runtime registration without rewriting the durable ledger. */
102
114
  dispose(): Promise<void>;
103
115
  }
104
- /** Infer the dialect of a marketplace index from its manifest location. */
105
- export declare function marketplaceDialect(index: MarketplaceIndex): string;
@@ -7,16 +7,16 @@
7
7
  * @module @kirkchinese/harness-forge
8
8
  */
9
9
  import { join, resolve } from 'node:path';
10
- import { detectSource, dialectOf, HarnessError, readMarketplace, } from '@kirkchinese/harness-forge-core';
10
+ import { detectSource, dialectOf, HarnessError, scanRoot as scanForeignRoot, } from '@kirkchinese/harness-forge-core';
11
11
  import { createForeignShell } from '../hooks/shell.js';
12
12
  import { Invocations } from '../shared/invocation.js';
13
- import { fetchGitSource } from './marketplace-install.js';
14
13
  import { sessionDirectory } from '../dsh/host.js';
15
14
  import { loggerOf, messageOf } from '../shared/util.js';
16
15
  import { Ledger } from './ledger.js';
17
16
  import { ProjectAssets } from './projects.js';
18
17
  import { WorkspaceTrust } from './trust.js';
19
18
  import { ImportedSettings } from './settings.js';
19
+ import { RemotePlugins } from './remote/service.js';
20
20
  /** The service name the `harness-forge` row provides. */
21
21
  export const FORGE_SERVICE = 'harnessForge';
22
22
  const MAX_FAULTS = 50;
@@ -33,6 +33,8 @@ export class HarnessForge {
33
33
  /** Claude Code and Codex project assets per session. */
34
34
  projects;
35
35
  ledger;
36
+ /** Plugins fetched from the network into `<dataRoot>/remote`. */
37
+ remote;
36
38
  apis = new Map();
37
39
  watchers = new Map();
38
40
  recentFaults = [];
@@ -41,15 +43,37 @@ export class HarnessForge {
41
43
  * @param statePath - the ledger file.
42
44
  * @param dataRoot - profile-local writable directory (shims, OAuth state, mod store).
43
45
  */
44
- constructor(ctx, statePath, dataRoot) {
46
+ /** `remote`: what plugins from the network are fetched with (tests replace git, npm, fetch and the resolver). */
47
+ constructor(ctx, statePath, dataRoot, options = {}) {
45
48
  this.ctx = ctx;
46
49
  this.statePath = statePath;
47
50
  this.dataRoot = dataRoot;
48
- this.shell = createForeignShell(process.env, dataRoot);
51
+ this.shell = createForeignShell(process.env, dataRoot, (path) => {
52
+ const message = `could not remove the hook input file ${path}`;
53
+ loggerOf(ctx)?.warn?.(`harness-forge: ${message}`);
54
+ this.fault('hooks', new Error(message));
55
+ });
49
56
  this.invocations = new Invocations(ctx, name => this.lookup('agents')?.presetOf(name), (agent, signal) => sessionDirectory(ctx, agent, signal));
50
57
  this.settings = new ImportedSettings(sessionId => this.invocations.rules(sessionId));
51
58
  this.ledger = new Ledger(ctx, statePath, dataRoot, error => this.fault('ledger', error));
52
59
  this.projects = new ProjectAssets(this.ledger, dataRoot, new WorkspaceTrust(statePath), error => this.fault('projects', error));
60
+ this.remote = new RemotePlugins(join(dataRoot, 'remote'), {
61
+ scan: (root, source, replacing) => {
62
+ // The new copy of an installed plugin keeps its name, which the installed copy otherwise holds.
63
+ if (replacing !== undefined && this.ledger.live.has(replacing)) {
64
+ const plain = scanForeignRoot(root, source);
65
+ if (plain.id === replacing)
66
+ return plain;
67
+ }
68
+ return this.scan(root, source);
69
+ },
70
+ install: async (root, source) => {
71
+ const report = await this.install(root, source);
72
+ return { pluginId: report.plugin.id, report };
73
+ },
74
+ reroot: (pluginId, root, source) => this.ledger.exclusive(() => this.ledger.rerootNow(pluginId, root, source)),
75
+ installed: pluginId => this.ledger.live.has(pluginId),
76
+ }, options.remote?.deps, options.remote?.limits);
53
77
  this.ledger.registerMounter('settings', {
54
78
  mount: async ({ component, scope }) => {
55
79
  if (component.kind !== 'settings')
@@ -202,24 +226,6 @@ export class HarnessForge {
202
226
  const result = await this.ledger.exclusive(() => this.ledger.applyNow(this.ledger.planNow(root, source)));
203
227
  return this.ledger.report(result);
204
228
  }
205
- /** Read a marketplace index without installing anything. */
206
- scanMarketplace(path) {
207
- return readMarketplace(path);
208
- }
209
- /** Install one marketplace entry from a local path or git source. */
210
- async installMarketplace(path, name) {
211
- const index = readMarketplace(path);
212
- const entry = index.entries.find(candidate => candidate.name === name);
213
- if (entry === undefined)
214
- throw new HarnessError('marketplace-failed', `marketplace ${index.name} has no entry "${name}"`);
215
- if (entry.source.kind === 'path' && entry.source.path !== undefined)
216
- return this.install(entry.source.path, marketplaceDialect(index));
217
- if (entry.source.kind === 'git') {
218
- const root = await fetchGitSource(entry.source, join(this.dataRoot, 'marketplace-cache'));
219
- return this.install(root, marketplaceDialect(index));
220
- }
221
- throw new HarnessError('unsupported-source', `entry "${name}" uses ${entry.source.kind}; supported marketplace sources are local path and git`);
222
- }
223
229
  /** Undo the actions of one receipt and remove its live registrations. */
224
230
  undo(receiptId) {
225
231
  return this.ledger.exclusive(() => this.ledger.undoNow(receiptId));
@@ -234,9 +240,28 @@ export class HarnessForge {
234
240
  if (!await this.ledger.teardown(id))
235
241
  return false;
236
242
  this.ledger.persist();
243
+ // A plugin fetched from the network takes its files with it; a failure there leaves the removal done.
244
+ try {
245
+ this.remote.released(id);
246
+ }
247
+ catch (error) {
248
+ this.fault('remote', error);
249
+ }
237
250
  return true;
238
251
  });
239
252
  }
253
+ /** Keep a plugin its harness no longer runs as the person's own copy: it mounts again and follows no harness. */
254
+ keep(id) {
255
+ return this.ledger.exclusive(() => this.ledger.keepNow(id));
256
+ }
257
+ /** Follow the harnesses' updates and removals of migrated plugins; see `follow.ts`. Settles once applied. */
258
+ follow() {
259
+ return this.ledger.follow();
260
+ }
261
+ /** How far applying the ledger's records has got, while some still are (at startup, after a harness change). */
262
+ applying() {
263
+ return this.ledger.applying();
264
+ }
240
265
  /** Scan one plugin without writing anything. */
241
266
  scan(root, source) {
242
267
  return this.ledger.scan(root, source);
@@ -263,12 +288,3 @@ export class HarnessForge {
263
288
  await this.projects.dispose();
264
289
  }
265
290
  }
266
- /** Infer the dialect of a marketplace index from its manifest location. */
267
- export function marketplaceDialect(index) {
268
- const normalized = index.manifestPath.replace(/\\/gu, '/');
269
- if (normalized.includes('/.agents/plugins/'))
270
- return 'codex';
271
- if (normalized.includes('/.claude-plugin/'))
272
- return 'claude-code';
273
- return 'agent-plugins';
274
- }
@@ -1,4 +1,5 @@
1
- import type { PermissionRules, SettingsComponent } from '@kirkchinese/harness-forge-core';
1
+ import { type SettingsComponent } from '@kirkchinese/harness-forge-core';
2
+ import type { PermissionRuleSet } from '../hooks/permissions.js';
2
3
  /** The session facts settings scoping reads. */
3
4
  export interface SessionHeaderLike {
4
5
  readonly id: string;
@@ -32,10 +33,11 @@ export declare class ImportedSettings {
32
33
  env(session?: SessionHeaderLike): Record<string, string>;
33
34
  /**
34
35
  * The Claude-syntax permission rules in effect for a session; deny from any
35
- * scope holds. An invoked skill's `allowed-tools` and `disallowed-tools`
36
+ * scope holds. A rule from a settings file carries where its `/path` file
37
+ * patterns anchor. An invoked skill's `allowed-tools` and `disallowed-tools`
36
38
  * count for the rest of its turn.
37
39
  */
38
- permissionRules(session?: SessionHeaderLike): PermissionRules;
40
+ permissionRules(session?: SessionHeaderLike): PermissionRuleSet;
39
41
  /** `disableAllHooks` from the settings in effect, the most specific scope winning. */
40
42
  hooksDisabled(session?: SessionHeaderLike): boolean;
41
43
  }
@@ -7,6 +7,7 @@
7
7
  * @module @kirkchinese/harness-forge
8
8
  */
9
9
  import { readFileSync } from 'node:fs';
10
+ import { leadsToShare } from '@kirkchinese/harness-forge-core';
10
11
  /** The settings in effect, process-wide and per session. */
11
12
  export class ImportedSettings {
12
13
  turnRules;
@@ -56,6 +57,9 @@ export class ImportedSettings {
56
57
  if (source !== undefined && kind !== source)
57
58
  continue;
58
59
  try {
60
+ // A file on a link to a network share it is not on is unreadable (see `leadsToShare`).
61
+ if (leadsToShare(file))
62
+ continue;
59
63
  deepMerge(merged, JSON.parse(readFileSync(file, 'utf8')));
60
64
  }
61
65
  catch {
@@ -74,7 +78,8 @@ export class ImportedSettings {
74
78
  }
75
79
  /**
76
80
  * The Claude-syntax permission rules in effect for a session; deny from any
77
- * scope holds. An invoked skill's `allowed-tools` and `disallowed-tools`
81
+ * scope holds. A rule from a settings file carries where its `/path` file
82
+ * patterns anchor. An invoked skill's `allowed-tools` and `disallowed-tools`
78
83
  * count for the rest of its turn.
79
84
  */
80
85
  permissionRules(session) {
@@ -82,9 +87,11 @@ export class ImportedSettings {
82
87
  const deny = [];
83
88
  const ask = [];
84
89
  for (const { component } of this.settingsFor(session)) {
85
- allow.push(...component.permissions.allow);
86
- deny.push(...component.permissions.deny);
87
- ask.push(...component.permissions.ask);
90
+ const { ruleRoot } = component;
91
+ const anchored = (rules) => ruleRoot === undefined ? [...rules] : rules.map(rule => ({ rule, root: ruleRoot }));
92
+ allow.push(...anchored(component.permissions.allow));
93
+ deny.push(...anchored(component.permissions.deny));
94
+ ask.push(...anchored(component.permissions.ask));
88
95
  }
89
96
  if (session !== undefined) {
90
97
  const turn = this.turnRules(session.id);
@@ -9,14 +9,48 @@ export interface InstalledComponentRecord {
9
9
  export interface MountRecord {
10
10
  readonly kind: 'mcp' | 'hooks' | 'agent' | 'code';
11
11
  readonly name: string;
12
+ /** A hooks part's events. */
13
+ readonly events?: readonly string[];
12
14
  readonly status: 'mounted' | 'failed';
15
+ /** Why it failed: the failing signals' details, else the mount's message. */
13
16
  readonly error?: string;
14
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
+ }
15
47
  /** One installed foreign plugin. */
16
48
  export interface InstalledPluginRecord {
17
49
  readonly id: string;
18
50
  readonly source: string;
19
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;
20
54
  readonly root: string;
21
55
  readonly version?: string;
22
56
  readonly license?: string;
@@ -35,6 +69,13 @@ export interface InstalledPluginRecord {
35
69
  readonly receipts?: readonly string[];
36
70
  /** Components the person switched off: never mounted until switched on again. */
37
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;
38
79
  }
39
80
  /** The complete ledger document. */
40
81
  export interface CompatState {
@@ -57,10 +98,29 @@ export declare function isTransient(error: unknown): boolean;
57
98
  * the handles are released by DSH's own callbacks.
58
99
  */
59
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
+ }
60
115
  /**
61
116
  * Read the ledger. A missing ledger is empty; one that cannot be read throws (an empty answer would be persisted
62
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.
63
121
  */
122
+ export declare function loadState(path?: string): LoadedState;
123
+ /** The usable part of the ledger (see {@link loadState}). */
64
124
  export declare function readState(path?: string): CompatState;
65
125
  /** Persist the ledger atomically. */
66
126
  export declare function writeState(state: CompatState, path?: string): void;
@@ -4,9 +4,17 @@
4
4
  * are referenced by id, never embedded wholesale.
5
5
  * @module @kirkchinese/harness-forge
6
6
  */
7
- import { copyFileSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
7
+ import { constants, copyFileSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
8
8
  import { homedir } from 'node:os';
9
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'];
10
18
  const EMPTY = { schemaVersion: 2, plugins: [] };
11
19
  /** Resolve the Harness home without importing a DSH runtime package. */
12
20
  export function resolveDshHome(env = process.env) {
@@ -31,7 +39,6 @@ export function defaultStatePath(env = process.env, profile) {
31
39
  }
32
40
  return join(resolveDshHome(env), 'harness-forge', 'state.json');
33
41
  }
34
- /** Read the ledger. A v1 ledger is migrated without trusting execution. */
35
42
  /** Errors a file operation may outlive: the process out of handles, the file briefly locked (a scanner, a sync). */
36
43
  const TRANSIENT = new Set(['EMFILE', 'ENFILE', 'EBUSY', 'EAGAIN', 'EPERM', 'EACCES']);
37
44
  /** Whether a file operation failed in a way it may outlive. */
@@ -57,18 +64,23 @@ export async function retryFile(operation, forMs = 30_000) {
57
64
  }
58
65
  }
59
66
  }
67
+ /** The ledger schema this Harness Forge reads and writes. */
68
+ export const STATE_SCHEMA_VERSION = 2;
60
69
  /**
61
70
  * Read the ledger. A missing ledger is empty; one that cannot be read throws (an empty answer would be persisted
62
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.
63
75
  */
64
- export function readState(path = defaultStatePath()) {
76
+ export function loadState(path = defaultStatePath()) {
65
77
  let text;
66
78
  try {
67
79
  text = readFileSync(path, 'utf8');
68
80
  }
69
81
  catch (error) {
70
82
  if (error.code === 'ENOENT')
71
- return EMPTY;
83
+ return { state: EMPTY, rejected: [], repaired: [] };
72
84
  throw error;
73
85
  }
74
86
  let value;
@@ -76,36 +88,68 @@ export function readState(path = defaultStatePath()) {
76
88
  value = JSON.parse(text);
77
89
  }
78
90
  catch {
79
- copyFileSync(path, `${path}.corrupt-${String(Date.now())}`);
80
- return EMPTY;
81
- }
82
- {
83
- if (typeof value !== 'object' || value === null || Array.isArray(value))
84
- return EMPTY;
85
- const record = value;
86
- if (!Array.isArray(record.plugins))
87
- return EMPTY;
88
- if (record.schemaVersion === 2) {
89
- return { schemaVersion: 2, plugins: record.plugins.filter(isV2Record).map(stripLegacyTrust) };
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;
90
139
  }
91
- if (record.schemaVersion === 1) {
92
- return {
93
- schemaVersion: 2,
94
- plugins: record.plugins.filter(isLegacyRecord).map(legacy => ({
95
- id: legacy.id,
96
- source: legacy.source,
97
- name: legacy.name,
98
- root: legacy.root,
99
- ...(typeof legacy.version === 'string' ? { version: legacy.version } : {}),
100
- ...(typeof legacy.license === 'string' ? { license: legacy.license } : {}),
101
- installedAt: legacy.installedAt,
102
- components: legacy.components.filter(isLegacyComponent),
103
- ...(Array.isArray(legacy.skillRoots) ? { skillRoots: legacy.skillRoots.filter((root) => typeof root === 'string') } : {}),
104
- receipts: [],
105
- })),
106
- };
140
+ catch (error) {
141
+ if (error.code !== 'EEXIST')
142
+ throw error;
107
143
  }
108
- return EMPTY;
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();
109
153
  }
110
154
  }
111
155
  /** Persist the ledger atomically. */
@@ -119,32 +163,104 @@ export function writeState(state, path = defaultStatePath()) {
119
163
  export function receiptsDirectory(statePath = defaultStatePath()) {
120
164
  return join(dirname(statePath), 'receipts');
121
165
  }
122
- function isV2Record(value) {
123
- return isBaseRecord(value);
166
+ function isPlainRecord(value) {
167
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
124
168
  }
125
- /** Old v2 ledgers may still carry a trust object; it is no longer state. */
126
- function stripLegacyTrust(record) {
127
- const copy = { ...record };
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.
128
192
  delete copy['trust'];
129
- return copy;
130
- }
131
- function isLegacyRecord(value) {
132
- return isBaseRecord(value);
133
- }
134
- function isBaseRecord(value) {
135
- if (typeof value !== 'object' || value === null || Array.isArray(value))
136
- return false;
137
- const record = value;
138
- return typeof record['id'] === 'string'
139
- && typeof record['source'] === 'string'
140
- && typeof record['name'] === 'string'
141
- && typeof record['root'] === 'string'
142
- && typeof record['installedAt'] === 'string'
143
- && Array.isArray(record['components']);
144
- }
145
- function isLegacyComponent(value) {
146
- if (typeof value !== 'object' || value === null || Array.isArray(value))
147
- return false;
148
- const component = value;
149
- return typeof component['kind'] === 'string' && typeof component['name'] === 'string';
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';
150
266
  }