@staix/agent-hosts 0.1.0 → 0.3.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.
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  Install an exact version after it is published.
6
6
 
7
7
  ```sh
8
- bun add --exact @staix/agent-hosts@0.1.0
8
+ bun add --exact @staix/agent-hosts@0.3.0
9
9
  ```
10
10
 
11
11
  ## Supported hosts
@@ -13,17 +13,18 @@ bun add --exact @staix/agent-hosts@0.1.0
13
13
  | Host ID | Default MCP files | Format | Verified versions |
14
14
  | --- | --- | --- | --- |
15
15
  | `claude` | user `~/.claude.json` | JSON `mcpServers` | `2.1.332` |
16
- | `codex` | user `~/.codex/config.toml` | TOML `mcp_servers` | `0.165.0` |
16
+ | `codex` | user `~/.codex/config.toml` | TOML `mcp_servers` | `0.165.0`, `0.172.0` |
17
17
  | `kimi` | user `~/.kimi-code/mcp.json` / project `.kimi-code/mcp.json` | JSON `mcpServers` | `2.7.2` |
18
- | `pi` | user `~/.pi/agent/mcp.json` | JSON `mcpServers` | `1.6.0` |
19
- | `qwen` | user `~/.qwen/settings.json` | JSON `mcpServers` | `0.26.1` |
20
- | `jcode` | user `~/.jcode/mcp.json` | JSON `servers` (alias `mcpServers`) | `0.99.1` |
21
- | `opencode` | user `~/.config/opencode/opencode.json` | JSON `mcp` | `1.18.35` |
22
- | `gemini` | user `~/.gemini/settings.json` | JSON `mcpServers` | `0.61.0` |
18
+ | `pi` | user `~/.pi/agent/mcp.json` | JSON `mcpServers` | `1.6.0`, `1.6.1` |
19
+ | `qwen` | user `~/.qwen/settings.json` | JSON `mcpServers` | `0.26.1`, `0.27.1` |
20
+ | `jcode` | user `~/.jcode/mcp.json` | JSON `servers` (alias `mcpServers`) | `0.99.1`, `1.0.3` |
21
+ | `opencode` | user `~/.config/opencode/opencode.json` | JSON `mcp` | `1.18.35`, `1.19.5` |
22
+ | `gemini` | user `~/.gemini/settings.json` | JSON `mcpServers` | `0.61.0`, `0.67.0` |
23
+ | `agy` | project `.agents/mcp_config.json` | JSON `mcpServers` | `1.5.18` |
23
24
 
24
- `HOSTS` records the file scopes, environment overrides, format, entry fields, and verified versions. `HostDefinition.entry` lists the minimum fields read by the host. Extra fields, including `env`, pass through. `CLAUDE_CONFIG_DIR` moves the Claude file into that directory as `.claude.json`. `QWEN_HOME` expands `~` against the injected home. A set but empty `JCODE_HOME` is refused. OpenCode and Gemini honor absolute `XDG_CONFIG_HOME` and `GEMINI_CLI_HOME` respectively, with an empty value treated as unset. [Version evidence](https://github.com/STAIxBWLB/agent-hosts/pull/5)
25
+ `HOSTS` records the file scopes, environment overrides, format, entry fields, and verified versions. `HostDefinition.entry` lists the minimum fields read by the host. Extra fields, including `env`, pass through. `CLAUDE_CONFIG_DIR` moves the Claude file into that directory as `.claude.json`. `QWEN_HOME` expands `~` against the injected home. A set but empty `JCODE_HOME` is refused. OpenCode and Gemini honor absolute `XDG_CONFIG_HOME` and `GEMINI_CLI_HOME` respectively, with an empty value treated as unset. Version evidence is available in [PR #5](https://github.com/STAIxBWLB/agent-hosts/pull/5), the [six-host verification receipt](docs/verification/2026-11-28-host-versions.md), and the [Antigravity 1.5.18 receipt](docs/verification/2026-11-27-agy-1.5.18.md).
25
26
 
26
- The direct workspace Antigravity (`agy`) configuration remains with each consumer for 0.1.0. See the [spec ruling](https://github.com/STAIxBWLB/agent-hosts/issues/1#antigravity-agy-is-not-in-010) and [fixture divergences](fixtures/DIVERGENCES.md).
27
+ Version 0.2.0 adds Antigravity support for the direct workspace file. On the verified version, `agy mcp list` listed the user-scope control and omitted both project files. Pass `scopes: ["project"]` and `workspaceRoot` to resolve the project file.
27
28
 
28
29
  ## API
29
30
 
@@ -48,7 +49,7 @@ if (plan.change === "refused") throw new Error(plan.reason);
48
49
  ```
49
50
 
50
51
  - `realPath(path)` resolves an existing physical path and throws for a missing path or dangling link. It handles Bun's backslash and symlink-parent edge cases.
51
- - `resolveHostPaths({ env, home, workspaceRoot?, hosts?, scopes?, redirectManagedProfiles? })` returns `home`, per-host `paths`, pre-redirect `legacyPaths`, `redirects`, per-host `refusals`, and per-host `roots.current` and `roots.legacy` for locating sibling files such as hooks. Pass the environment and home explicitly. It selects user files by default. Supply `scopes: ["project"]` and `workspaceRoot` for Kimi's project file. Select exactly one file per host when calling the entry API. Managed Claude and Codex profiles redirect to the personal source by default. Set `redirectManagedProfiles: false` to keep the configured path. The resolver trims Claude, Codex, Kimi, and Pi overrides and omits files whose location override is invalid. Other hosts remain available.
52
+ - `resolveHostPaths({ env, home, workspaceRoot?, hosts?, scopes?, redirectManagedProfiles? })` returns `home`, per-host `paths`, pre-redirect `legacyPaths`, `redirects`, per-host `refusals`, and per-host `roots.current` and `roots.legacy` for locating sibling files such as hooks. Pass the environment and home explicitly. It selects user files by default. Supply `scopes: ["project"]` and `workspaceRoot` for Kimi or Antigravity project files. Select exactly one file per host when calling the entry API. Managed Claude and Codex profiles redirect to the personal source by default. Set `redirectManagedProfiles: false` to keep the configured path. The resolver trims Claude, Codex, Kimi, and Pi overrides and omits files whose location override is invalid. Other hosts remain available.
52
53
  - `planEntry({ host, paths, name, entry })` returns `add`, `replace`, `remove`, `unchanged`, or `refused` with a stable `code` and a human-readable `reason`. A successful preview contains the decoded `current` entry (or `undefined`), the before and after images, and an intent digest. Supply a plain JSON-compatible entry object or use `entry: null` to remove an entry with an undo receipt. Removing an absent entry is unchanged. Preview writes nothing.
53
54
  - `applyEntry(plan, { receiptDir, env? })` rechecks file state and host policy under an exclusive lock, publishes the change, and records a versioned receipt. Use an absolute receipt directory. Generate a fresh plan if the file changed since preview. A matching entry with no receipt stays unclaimed. OpenCode requires fresh injected `env` on every apply. The plan carries routing-variable names without storing their values.
54
55
  - `undoEntry({ host, paths, name, receiptDir })` restores the prior owned entry or removes the one it installed. A conflicting edit to the entry is left in place and the error names the file. The result identifies the config and receipt paths. If `legacy: true` is returned, the legacy receipt still exists and the consumer manages its cleanup. An unchanged undo carries a code from `UNDO_NOOP_CODES`. If someone deleted an installed entry, undo consumes its package receipt without restoring the prior entry. An explicit removal remains undoable.
@@ -87,19 +88,49 @@ The JSON codec accepts strict JSON and keeps unrelated bytes. The TOML codecs us
87
88
  | `RefusalCode`, `UndoNoopCode` | Machine-readable identifiers from `REFUSAL_CODES` and `UNDO_NOOP_CODES`. |
88
89
  | `ConfigImage`, `JsonMcpCodecOptions` | Base64 `bytes` or `null` for an absent file, plus numeric `mode`, and the JSON codec's key and entry options. |
89
90
 
91
+ ## Skill roots and links
92
+
93
+ `SKILL_HOSTS` lists verified user installation roots for Claude, Codex, Pi, Qwen, OpenCode, and Gemini. Each definition lists its verified host versions. `resolveSkillRoots({ home, env, hosts?, scopes?, workspaceRoot?, redirectManagedProfiles? })` returns roots, redirects and refusals. Use the injected home and environment. The resolver applies the same override validation and optional managed-profile redirects as MCP. For OpenCode, it selects `OPENCODE_CONFIG_DIR/skills` ahead of `XDG_CONFIG_HOME/opencode/skills`. Project scope has no supported skill roots in this release. See the [versioned skill root verification](docs/verification/2026-11-29-skill-roots.md).
94
+
95
+ ```ts
96
+ import { applySkillEntry, planSkillEntry, resolveSkillRoots, undoSkillEntry } from "@staix/agent-hosts";
97
+
98
+ const { roots } = resolveSkillRoots({ home, env, hosts: ["codex"] });
99
+ const root = roots.codex?.[0];
100
+ if (!root) throw new Error("No Codex skill root resolved");
101
+
102
+ const target = { host: "codex" as const, root, name: "example", receiptDir };
103
+ const preview = planSkillEntry({ ...target, sourcePath });
104
+ if (preview.change === "refused") throw new Error(preview.reason);
105
+ applySkillEntry(preview);
106
+ // Later, with the same target and receipt directory:
107
+ undoSkillEntry(target);
108
+ ```
109
+
110
+ Pass absolute physical paths for `root`, `receiptDir` and `sourcePath`. The source is an existing directory whose contents the caller manages. Preview writes nothing. Apply installs a relative symlink and records versioned ownership in the receipt directory. `classifySkillTarget({ targetPath, host?, receiptDir? })` recognizes an owned link when its recorded identity matches. Existing foreign links, unmanaged files or directories, sibling-tool ownership markers and the reserved `.system` name are refused.
111
+
112
+ Use the same `receiptDir` for each operation on a host and skill name. A changed profile root requires `retarget: true` in a new preview. Apply then publishes at the new root and removes the unchanged old link. Undo removes only the unchanged recorded link. If the link has already been deleted, undo retires the receipt and reports `entry-already-absent`. To resume an interrupted apply, preview and apply the same root and source again.
113
+
90
114
  ## Consumer migration
91
115
 
92
- Use one PR per consumer and pin `@staix/agent-hosts` to the exact release. Keep the existing entry name and pass the consumer's existing setup directory as `receiptDir` so undo can find earlier receipts. Replay the [copy fixtures](fixtures/copies/) and [legacy receipts](fixtures/receipts/), and list behavior changes in the consumer PR. [Fixture divergences](fixtures/DIVERGENCES.md)
116
+ For each migration, use one PR per consumer and pin `@staix/agent-hosts` to the exact release. Keep the existing entry name and pass the consumer's existing setup directory as `receiptDir` so undo can find earlier receipts. Replay the [copy fixtures](fixtures/copies/) and [legacy receipts](fixtures/receipts/), and list behavior changes in the consumer PR. [Fixture divergences](fixtures/DIVERGENCES.md)
93
117
 
94
118
  | Consumer | Migration |
95
119
  | --- | --- |
96
- | vault-mem | Pass entry name `vmem` and `<vault-mem home>/setup`. Remove the migrated host table and writers in the same PR. Keep the CLI output, console manifest, and Antigravity writer local. After a successful undo returning `legacy: true`, the consumer deletes the retained receipt. |
97
- | agent-research | Pass `ares` and `<family home>/research/setup`. Remove the migrated host table and writers in the same PR. Keep the CLI output, console manifest, and Antigravity writer local. After a successful undo returning `legacy: true`, the consumer deletes the retained receipt. |
98
- | agent-mem | Land the `@staix/agent-mem/platform` re-export of `realPath` first. Move MCP paths, lexical codecs, and entry handling to this package. Pass `amem` and `<memory home>/setup`. Keep hooks, the Pi extension, drift reports, writer roots, and the Antigravity writer local. Retain the prior journal when undo returns `legacy: true` because it also owns hook history. |
120
+ | vault-mem | Pass entry name `vmem` and `<vault-mem home>/setup`. Remove the migrated host table and writers in the same PR. Keep the CLI output and console manifest local. Move the Antigravity writer to this package in 0.2.0 using the workspace root guidance below. After a successful undo returning `legacy: true`, the consumer deletes the retained receipt. |
121
+ | agent-research | Pass `ares` and `<family home>/research/setup`. Remove the migrated host table and writers in the same PR. Keep the CLI output and console manifest local. Move the Antigravity writer to this package in 0.2.0 using the workspace root guidance below. After a successful undo returning `legacy: true`, the consumer deletes the retained receipt. |
122
+ | agent-mem | Migration deferred. Agent-mem keeps its own resolver, codecs, and `realPath`. Revisit when this package can be pinned under its writer attestation. [agent-mem #648](https://github.com/STAIxBWLB/agent-mem/issues/648) |
99
123
  | agent-hub | Optionally adopt the path and format table after the other migrations if it removes duplicate code. Keep its project-scoped writers and adapter policy local. |
100
124
 
101
125
  Vault-mem and agent-research gain Qwen tilde expansion and refuse an explicitly empty Jcode override. Both can disable managed-profile redirects to preserve their literal-path behavior. The package validates host overrides. When apply returns `legacy: true` and `supersedes`, the package receipt now owns the original baseline. Retire the superseded receipt after success. Agent-mem preserves any hook records it still needs before retiring a journal.
102
126
 
127
+ With 0.2.0, vault-mem and agent-research can drop their local Antigravity project writers. Select `hosts: ["agy"]` and `scopes: ["project"]` and supply the same `workspaceRoot` the previous writer used.
128
+
129
+ - When agent-mem revisits migration, pass the Git top-level directory normalized with `realPath`. Its legacy journal filename uses a digest of that root.
130
+ - Vault-mem and agent-research pass the same working directory their previous release used as the root. Their legacy receipt filenames hash the literal configuration file path.
131
+
132
+ A different root targets a different file. With respect to the original receipt, apply returns no `supersedes` and undo returns `no-receipt`.
133
+
103
134
  Treat export and entry result shapes, host metadata, and the version 1 receipt layout and location as the shared 0.1.0 protocol. Branch on refusal codes. Human-readable reasons may change in a patch. A new host or scope widens a closed union and requires a minor release with a changelog note. Newly verified versions and optional fields can be added in a patch. Later 0.x releases continue to read earlier 0.x receipts.
104
135
 
105
136
  ## Development and release
@@ -2,9 +2,7 @@
2
2
 
3
3
  | Copy | Case | Consumer result | Package result | Reason |
4
4
  | --- | --- | --- | --- | --- |
5
- | vault-mem | Antigravity (`agy`) | Writes and undoes the project MCP entry | Excluded from 0.1.0 | Project MCP shape lacks exact-version evidence, per #1 |
6
- | agent-research | Antigravity (`agy`) | Writes and undoes the project MCP entry | Excluded from 0.1.0 | Project MCP shape lacks exact-version evidence, per #1 |
7
- | agent-mem | Antigravity (`agy`) | Writes and undoes the project MCP entry | Excluded from 0.1.0 | Project MCP shape lacks exact-version evidence, per #1 |
5
+ | agent-mem | Antigravity Git and directory ownership | Binds setup to a Git root, refuses tracked config, and tracks a created directory for cleanup | Resolves the supplied project root and owns only the MCP entry | Git checks and directory ownership stay with the consumer |
8
6
  | vault-mem | Legacy receipt undo | Deletes the consumed v1 receipt | Retains the legacy file | Legacy receipts remain with the consumer |
9
7
  | agent-research | Legacy receipt undo | Deletes the consumed v1 receipt | Retains the legacy file | Legacy receipts remain with the consumer |
10
8
  | agent-mem | Legacy receipt undo | Restores MCP and hook changes, then removes the journal | Restores the MCP entry and retains the journal | The consumer owns hook state and history |
@@ -580,6 +580,67 @@
580
580
  "mcp"
581
581
  ]
582
582
  }
583
+ },
584
+ {
585
+ "id": "agy-standard",
586
+ "host": "agy",
587
+ "name": "amem",
588
+ "key": "mcpServers",
589
+ "file": "$FIXTURE/workspace/.agents/mcp_config.json",
590
+ "env": {
591
+ "HOME": "$FIXTURE",
592
+ "PATH": "$FIXTURE/bin:/usr/bin:/bin",
593
+ "TMPDIR": "$FIXTURE",
594
+ "AMEM_HOME": "$FIXTURE/memory",
595
+ "VMEM_HOME": "$FIXTURE/vault",
596
+ "AGENTHUB_HOME": "$FIXTURE/hub",
597
+ "CLAUDE_CONFIG_DIR": "$FIXTURE/.claude",
598
+ "CODEX_HOME": "$FIXTURE/.codex",
599
+ "KIMI_CODE_HOME": "$FIXTURE/.kimi-code",
600
+ "PI_CODING_AGENT_DIR": "$FIXTURE/.pi/agent",
601
+ "QWEN_HOME": "$FIXTURE/.qwen",
602
+ "JCODE_HOME": "$FIXTURE/.jcode",
603
+ "XDG_CONFIG_HOME": "$FIXTURE/.config",
604
+ "XDG_DATA_HOME": "$FIXTURE/.local/share",
605
+ "XDG_CACHE_HOME": "$FIXTURE/.cache",
606
+ "XDG_STATE_HOME": "$FIXTURE/.local/state",
607
+ "GEMINI_CLI_HOME": "$FIXTURE",
608
+ "ORCA_USER_DATA_PATH": "$FIXTURE/orca"
609
+ },
610
+ "workspaceRoot": "$FIXTURE/workspace",
611
+ "plan": {
612
+ "change": "add",
613
+ "files": [
614
+ "$FIXTURE/workspace/.agents/mcp_config.json"
615
+ ]
616
+ },
617
+ "before": {
618
+ "$FIXTURE/workspace/.agents/mcp_config.json": {
619
+ "text": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"/fixture/keep\"\n }\n },\n \"fixture\": true\n}\n",
620
+ "mode": 384
621
+ }
622
+ },
623
+ "afterApply": {
624
+ "$FIXTURE/workspace/.agents/mcp_config.json": {
625
+ "text": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"/fixture/keep\"\n },\"amem\":{\"command\":\"$FIXTURE/bin/bun\",\"args\":[\"--smol\",\"$FIXTURE/release/node_modules/@staix/agent-mem/bin/amem.js\",\"mcp\"],\"cwd\":\"$FIXTURE/workspace\"}\n },\n \"fixture\": true\n}\n",
626
+ "mode": 384
627
+ }
628
+ },
629
+ "afterUndo": {
630
+ "$FIXTURE/workspace/.agents/mcp_config.json": {
631
+ "text": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"/fixture/keep\"\n }\n },\n \"fixture\": true\n}\n",
632
+ "mode": 384
633
+ }
634
+ },
635
+ "entry": {
636
+ "command": "$FIXTURE/bin/bun",
637
+ "args": [
638
+ "--smol",
639
+ "$FIXTURE/release/node_modules/@staix/agent-mem/bin/amem.js",
640
+ "mcp"
641
+ ],
642
+ "cwd": "$FIXTURE/workspace"
643
+ }
583
644
  }
584
645
  ]
585
646
  }
@@ -356,6 +356,66 @@
356
356
  ]
357
357
  }
358
358
  },
359
+ {
360
+ "id": "agy-standard",
361
+ "host": "agy",
362
+ "name": "ares",
363
+ "key": "mcpServers",
364
+ "file": "$FIXTURE/workspace/.agents/mcp_config.json",
365
+ "env": {
366
+ "HOME": "$FIXTURE",
367
+ "PATH": "$FIXTURE/bin:/usr/bin:/bin",
368
+ "TMPDIR": "$FIXTURE",
369
+ "AMEM_HOME": "$FIXTURE/memory",
370
+ "VMEM_HOME": "$FIXTURE/vault",
371
+ "AGENTHUB_HOME": "$FIXTURE/hub",
372
+ "CLAUDE_CONFIG_DIR": "$FIXTURE/.claude",
373
+ "CODEX_HOME": "$FIXTURE/.codex",
374
+ "KIMI_CODE_HOME": "$FIXTURE/.kimi-code",
375
+ "PI_CODING_AGENT_DIR": "$FIXTURE/.pi/agent",
376
+ "QWEN_HOME": "$FIXTURE/.qwen",
377
+ "JCODE_HOME": "$FIXTURE/.jcode",
378
+ "XDG_CONFIG_HOME": "$FIXTURE/.config",
379
+ "XDG_DATA_HOME": "$FIXTURE/.local/share",
380
+ "XDG_CACHE_HOME": "$FIXTURE/.cache",
381
+ "XDG_STATE_HOME": "$FIXTURE/.local/state",
382
+ "GEMINI_CLI_HOME": "$FIXTURE",
383
+ "ORCA_USER_DATA_PATH": "$FIXTURE/orca"
384
+ },
385
+ "workspaceRoot": "$FIXTURE/workspace",
386
+ "plan": {
387
+ "change": "add",
388
+ "files": [
389
+ "$FIXTURE/workspace/.agents/mcp_config.json"
390
+ ]
391
+ },
392
+ "before": {
393
+ "$FIXTURE/workspace/.agents/mcp_config.json": {
394
+ "text": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"/fixture/keep\"\n }\n },\n \"fixture\": true\n}\n",
395
+ "mode": 384
396
+ }
397
+ },
398
+ "afterApply": {
399
+ "$FIXTURE/workspace/.agents/mcp_config.json": {
400
+ "text": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"/fixture/keep\"\n },\n \"ares\": {\n \"command\": \"bun\",\n \"args\": [\n \"--smol\",\n \"$FIXTURE/release/bin/ares.js\",\n \"mcp\"\n ]\n }\n },\n \"fixture\": true\n}\n",
401
+ "mode": 384
402
+ }
403
+ },
404
+ "afterUndo": {
405
+ "$FIXTURE/workspace/.agents/mcp_config.json": {
406
+ "text": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"/fixture/keep\"\n }\n },\n \"fixture\": true\n}\n",
407
+ "mode": 384
408
+ }
409
+ },
410
+ "entry": {
411
+ "command": "bun",
412
+ "args": [
413
+ "--smol",
414
+ "$FIXTURE/release/bin/ares.js",
415
+ "mcp"
416
+ ]
417
+ }
418
+ },
359
419
  {
360
420
  "id": "qwen-tilde-home",
361
421
  "host": "qwen",
@@ -344,6 +344,64 @@
344
344
  ]
345
345
  }
346
346
  },
347
+ {
348
+ "id": "agy-standard",
349
+ "host": "agy",
350
+ "name": "vmem",
351
+ "key": "mcpServers",
352
+ "file": "$FIXTURE/workspace/.agents/mcp_config.json",
353
+ "env": {
354
+ "HOME": "$FIXTURE",
355
+ "PATH": "$FIXTURE/bin:/usr/bin:/bin",
356
+ "TMPDIR": "$FIXTURE",
357
+ "AMEM_HOME": "$FIXTURE/memory",
358
+ "VMEM_HOME": "$FIXTURE/vault",
359
+ "AGENTHUB_HOME": "$FIXTURE/hub",
360
+ "CLAUDE_CONFIG_DIR": "$FIXTURE/.claude",
361
+ "CODEX_HOME": "$FIXTURE/.codex",
362
+ "KIMI_CODE_HOME": "$FIXTURE/.kimi-code",
363
+ "PI_CODING_AGENT_DIR": "$FIXTURE/.pi/agent",
364
+ "QWEN_HOME": "$FIXTURE/.qwen",
365
+ "JCODE_HOME": "$FIXTURE/.jcode",
366
+ "XDG_CONFIG_HOME": "$FIXTURE/.config",
367
+ "XDG_DATA_HOME": "$FIXTURE/.local/share",
368
+ "XDG_CACHE_HOME": "$FIXTURE/.cache",
369
+ "XDG_STATE_HOME": "$FIXTURE/.local/state",
370
+ "GEMINI_CLI_HOME": "$FIXTURE",
371
+ "ORCA_USER_DATA_PATH": "$FIXTURE/orca"
372
+ },
373
+ "workspaceRoot": "$FIXTURE/workspace",
374
+ "plan": {
375
+ "change": "add",
376
+ "files": [
377
+ "$FIXTURE/workspace/.agents/mcp_config.json"
378
+ ]
379
+ },
380
+ "before": {
381
+ "$FIXTURE/workspace/.agents/mcp_config.json": {
382
+ "text": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"/fixture/keep\"\n }\n },\n \"fixture\": true\n}\n",
383
+ "mode": 384
384
+ }
385
+ },
386
+ "afterApply": {
387
+ "$FIXTURE/workspace/.agents/mcp_config.json": {
388
+ "text": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"/fixture/keep\"\n },\n \"vmem\": {\n \"command\": \"$FIXTURE/bin/bun\",\n \"args\": [\n \"mcp\"\n ]\n }\n },\n \"fixture\": true\n}\n",
389
+ "mode": 384
390
+ }
391
+ },
392
+ "afterUndo": {
393
+ "$FIXTURE/workspace/.agents/mcp_config.json": {
394
+ "text": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"/fixture/keep\"\n }\n },\n \"fixture\": true\n}\n",
395
+ "mode": 384
396
+ }
397
+ },
398
+ "entry": {
399
+ "command": "$FIXTURE/bin/bun",
400
+ "args": [
401
+ "mcp"
402
+ ]
403
+ }
404
+ },
347
405
  {
348
406
  "id": "qwen-tilde-home",
349
407
  "host": "qwen",
@@ -0,0 +1,35 @@
1
+ {
2
+ "commit": "e37eb63d8be0e681aafb96d290023009d78e53ff",
3
+ "host": "agy",
4
+ "name": "amem",
5
+ "file": "$FIXTURE/workspace/.agents/mcp_config.json",
6
+ "workspaceRoot": "$FIXTURE/workspace",
7
+ "receiptDir": "$FIXTURE/memory/setup",
8
+ "mode": 384,
9
+ "before": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"keep\"\n },\n \"amem\": {\"command\":\"/fixture/prior\",\"args\":[\"mcp\"]}\n },\n \"fixture\": true\n}\n",
10
+ "after": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"keep\"\n },\n \"amem\": {\"command\":\"$FIXTURE/bin/bun\",\"args\":[\"--smol\",\"$FIXTURE/release/node_modules/@staix/agent-mem/bin/amem.js\",\"mcp\"],\"cwd\":\"$FIXTURE/workspace\"}\n },\n \"fixture\": true\n}\n",
11
+ "receipt": {
12
+ "version": 1,
13
+ "target": "agy",
14
+ "intent": "3d70e6e3faeb1ebe1b74d7347ed938fd184072486c9ca31b452e1a359eb90c71",
15
+ "phase": "applied",
16
+ "changes": [
17
+ {
18
+ "key": "agy:0",
19
+ "path": "$FIXTURE/workspace/.agents/mcp_config.json",
20
+ "before": {
21
+ "bytes": "ewogICJtY3BTZXJ2ZXJzIjogewogICAgIm90aGVyIjogewogICAgICAiY29tbWFuZCI6ICJrZWVwIgogICAgfSwKICAgICJhbWVtIjogeyJjb21tYW5kIjoiL2ZpeHR1cmUvcHJpb3IiLCJhcmdzIjpbIm1jcCJdfQogIH0sCiAgImZpeHR1cmUiOiB0cnVlCn0K",
22
+ "mode": 384
23
+ },
24
+ "after": {
25
+ "bytes": "ewogICJtY3BTZXJ2ZXJzIjogewogICAgIm90aGVyIjogewogICAgICAiY29tbWFuZCI6ICJrZWVwIgogICAgfSwKICAgICJhbWVtIjogeyJjb21tYW5kIjoiJEZJWFRVUkUvYmluL2J1biIsImFyZ3MiOlsiLS1zbW9sIiwiJEZJWFRVUkUvcmVsZWFzZS9ub2RlX21vZHVsZXMvQHN0YWl4L2FnZW50LW1lbS9iaW4vYW1lbS5qcyIsIm1jcCJdLCJjd2QiOiIkRklYVFVSRS93b3Jrc3BhY2UifQogIH0sCiAgImZpeHR1cmUiOiB0cnVlCn0K",
26
+ "mode": 384
27
+ },
28
+ "start": {
29
+ "bytes": "ewogICJtY3BTZXJ2ZXJzIjogewogICAgIm90aGVyIjogewogICAgICAiY29tbWFuZCI6ICJrZWVwIgogICAgfSwKICAgICJhbWVtIjogeyJjb21tYW5kIjoiL2ZpeHR1cmUvcHJpb3IiLCJhcmdzIjpbIm1jcCJdfQogIH0sCiAgImZpeHR1cmUiOiB0cnVlCn0K",
30
+ "mode": 384
31
+ }
32
+ }
33
+ ]
34
+ }
35
+ }
@@ -0,0 +1,33 @@
1
+ {
2
+ "commit": "05699c24953a0cd5a37721fc8255703d20a9b295",
3
+ "host": "agy",
4
+ "name": "ares",
5
+ "file": "$FIXTURE/workspace/.agents/mcp_config.json",
6
+ "workspaceRoot": "$FIXTURE/workspace",
7
+ "receiptDir": "$FIXTURE/hub/research/setup",
8
+ "mode": 384,
9
+ "before": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"keep\"\n },\n \"ares\": {\"command\":\"/fixture/prior\",\"args\":[\"mcp\"]}\n },\n \"fixture\": true\n}\n",
10
+ "after": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"keep\"\n },\n \"ares\": {\n \"command\": \"bun\",\n \"args\": [\n \"--smol\",\n \"$FIXTURE/release/bin/ares.js\",\n \"mcp\"\n ]\n }\n },\n \"fixture\": true\n}\n",
11
+ "receipt": {
12
+ "v": 1,
13
+ "target": "agy",
14
+ "file": "$FIXTURE/workspace/.agents/mcp_config.json",
15
+ "existed": true,
16
+ "keyExisted": true,
17
+ "priorPresent": true,
18
+ "prior": {
19
+ "command": "/fixture/prior",
20
+ "args": [
21
+ "mcp"
22
+ ]
23
+ },
24
+ "installed": {
25
+ "command": "bun",
26
+ "args": [
27
+ "--smol",
28
+ "$FIXTURE/release/bin/ares.js",
29
+ "mcp"
30
+ ]
31
+ }
32
+ }
33
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "commit": "9b9a4a5333aaa73453858a541b82028c63f8f7f8",
3
+ "host": "agy",
4
+ "name": "vmem",
5
+ "file": "$FIXTURE/workspace/.agents/mcp_config.json",
6
+ "workspaceRoot": "$FIXTURE/workspace",
7
+ "receiptDir": "$FIXTURE/vault/setup",
8
+ "mode": 384,
9
+ "before": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"keep\"\n },\n \"vmem\": {\"command\":\"/fixture/prior\",\"args\":[\"mcp\"]}\n },\n \"fixture\": true\n}\n",
10
+ "after": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"keep\"\n },\n \"vmem\": {\n \"command\": \"$FIXTURE/bin/bun\",\n \"args\": [\n \"mcp\"\n ]\n }\n },\n \"fixture\": true\n}\n",
11
+ "receipt": {
12
+ "version": 1,
13
+ "target": "agy",
14
+ "file": "$FIXTURE/workspace/.agents/mcp_config.json",
15
+ "existed": true,
16
+ "keyExisted": true,
17
+ "prior": {
18
+ "command": "/fixture/prior",
19
+ "args": [
20
+ "mcp"
21
+ ]
22
+ },
23
+ "installed": {
24
+ "command": "$FIXTURE/bin/bun",
25
+ "args": [
26
+ "mcp"
27
+ ]
28
+ }
29
+ }
30
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-hosts",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Host configuration and MCP server entry management for Bun",
5
5
  "type": "module",
6
6
  "repository": {
package/src/fs-safe.ts CHANGED
@@ -43,13 +43,18 @@ function checkPath(file: string, directory = false): Stats | undefined {
43
43
  return stat;
44
44
  }
45
45
 
46
+ /** Inspect a directory chain without following a link at any point. */
47
+ export function checkPhysicalDirectory(directory: string): Stats | undefined {
48
+ return checkPath(directory, true);
49
+ }
50
+
46
51
  function assertPhysical(file: string, existing: string): void {
47
52
  if (realPath(existing) !== existing) {
48
53
  throw new EntryRefusal("unsafe-path", `${file}: redirected path; use the exact physical path spelling`, { file: file });
49
54
  }
50
55
  }
51
56
 
52
- function ensureDirectory(directory: string): void {
57
+ export function ensureDirectory(directory: string): void {
53
58
  checkPath(directory, true);
54
59
  mkdirSync(directory, { recursive: true, mode: 0o700 });
55
60
  checkPath(directory, true);
package/src/hosts.ts CHANGED
@@ -56,7 +56,7 @@ export const HOSTS = {
56
56
  }],
57
57
  format: { kind: "toml", table: ["mcp_servers"] },
58
58
  entry: stdio,
59
- verified: ["0.165.0"],
59
+ verified: ["0.165.0", "0.172.0"],
60
60
  },
61
61
  kimi: {
62
62
  id: "kimi",
@@ -73,21 +73,21 @@ export const HOSTS = {
73
73
  files: [{ scope: "user", path: "mcp.json", override: { key: "PI_CODING_AGENT_DIR", rule: "trim-presence", directory: ".pi/agent" } }],
74
74
  format: mcpServers,
75
75
  entry: stdio,
76
- verified: ["1.6.0"],
76
+ verified: ["1.6.0", "1.6.1"],
77
77
  },
78
78
  qwen: {
79
79
  id: "qwen",
80
80
  files: [{ scope: "user", path: "settings.json", override: { key: "QWEN_HOME", rule: "expand-tilde", directory: ".qwen" } }],
81
81
  format: mcpServers,
82
82
  entry: stdio,
83
- verified: ["0.26.1"],
83
+ verified: ["0.26.1", "0.27.1"],
84
84
  },
85
85
  jcode: {
86
86
  id: "jcode",
87
87
  files: [{ scope: "user", path: "mcp.json", override: { key: "JCODE_HOME", rule: "empty-means-set", directory: ".jcode" } }],
88
88
  format: { kind: "json", key: "servers", aliases: ["mcpServers"] },
89
89
  entry: { ...stdio, shared: "boolean" },
90
- verified: ["0.99.1"],
90
+ verified: ["0.99.1", "1.0.3"],
91
91
  },
92
92
  opencode: {
93
93
  id: "opencode",
@@ -100,15 +100,69 @@ export const HOSTS = {
100
100
  }],
101
101
  format: { kind: "json", key: "mcp" },
102
102
  entry: { type: "local", command: "string[]", enabled: "boolean" },
103
- verified: ["1.18.35"],
103
+ verified: ["1.18.35", "1.19.5"],
104
104
  },
105
105
  gemini: {
106
106
  id: "gemini",
107
107
  files: [{ scope: "user", path: ".gemini/settings.json", override: { key: "GEMINI_CLI_HOME", rule: "absolute-only", directory: "" } }],
108
108
  format: mcpServers,
109
109
  entry: stdio,
110
- verified: ["0.61.0"],
110
+ verified: ["0.61.0", "0.67.0"],
111
+ },
112
+ agy: {
113
+ id: "agy",
114
+ files: [{ scope: "project", path: ".agents/mcp_config.json" }],
115
+ format: mcpServers,
116
+ entry: stdio,
117
+ verified: ["1.5.18"],
111
118
  },
112
119
  } as const satisfies Record<string, HostDefinition>;
113
120
 
114
121
  export type HostId = keyof typeof HOSTS;
122
+
123
+ export interface HostSkillDefinition {
124
+ readonly path: string;
125
+ readonly override: HomeOverride;
126
+ readonly preferredOverride?: HomeOverride;
127
+ readonly managedProfile?: "claude" | "codex";
128
+ readonly verified: readonly [string, ...string[]];
129
+ }
130
+
131
+ /** Verified user installation roots. Hosts may discover skills from additional locations. */
132
+ export const SKILL_HOSTS = {
133
+ claude: {
134
+ path: "skills",
135
+ override: { key: "CLAUDE_CONFIG_DIR", rule: "trim-presence", directory: ".claude" },
136
+ managedProfile: "claude",
137
+ verified: ["2.1.332"],
138
+ },
139
+ codex: {
140
+ path: "skills",
141
+ override: HOSTS.codex.files[0].override,
142
+ managedProfile: "codex",
143
+ verified: ["0.172.0"],
144
+ },
145
+ pi: {
146
+ path: "skills",
147
+ override: HOSTS.pi.files[0].override,
148
+ verified: ["1.6.1"],
149
+ },
150
+ qwen: {
151
+ path: "skills",
152
+ override: HOSTS.qwen.files[0].override,
153
+ verified: ["0.26.9", "0.27.1"],
154
+ },
155
+ opencode: {
156
+ path: "opencode/skills",
157
+ override: HOSTS.opencode.files[0].override,
158
+ preferredOverride: { key: "OPENCODE_CONFIG_DIR", rule: "absolute-only", directory: "" },
159
+ verified: ["1.19.5"],
160
+ },
161
+ gemini: {
162
+ path: ".gemini/skills",
163
+ override: HOSTS.gemini.files[0].override,
164
+ verified: ["0.67.0"],
165
+ },
166
+ } as const satisfies Partial<Record<HostId, HostSkillDefinition>>;
167
+
168
+ export type SkillHostId = keyof typeof SKILL_HOSTS;
package/src/index.ts CHANGED
@@ -5,3 +5,6 @@ export { HOSTS, type HostConfig, type HostDefinition, type HostFormat, type Host
5
5
  export { resolveHostPaths, type HostPaths, type HostRedirect, type HostRefusal, type ResolveHostPathsOptions } from "./paths.ts";
6
6
  export { applyEntry, planEntry, readEntryReceipt, undoEntry, UNDO_NOOP_CODES, type ApplyEntryOptions, type EntryPlan, type EntryReceipt, type EntryResult, type EntryTarget, type PlanEntryOptions, type UndoNoopCode } from "./entry.ts";
7
7
  export { EntryRefusal, REFUSAL_CODES, type RefusalCode } from "./refusal.ts";
8
+ export { SKILL_HOSTS, type HostSkillDefinition, type SkillHostId } from "./hosts.ts";
9
+ export { resolveSkillRoots, type ResolveSkillRootsOptions, type SkillRoots } from "./paths.ts";
10
+ export { applySkillEntry, classifySkillTarget, planSkillEntry, undoSkillEntry, type PlanSkillEntryOptions, type SkillEntryPlan, type SkillEntryResult, type SkillEntryTarget, type SkillTargetClassification } from "./skills.ts";
package/src/paths.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
2
- import { HOSTS, type HostDefinition, type HostId, type HostScope, type HomeOverride } from "./hosts.ts";
2
+ import { HOSTS, SKILL_HOSTS, type HostSkillDefinition, type SkillHostId, type HostDefinition, type HostId, type HostScope, type HomeOverride } from "./hosts.ts";
3
3
  import { realPath } from "./platform.ts";
4
4
  import type { RefusalCode } from "./refusal.ts";
5
5
 
@@ -142,3 +142,56 @@ export function resolveHostPaths(options: ResolveHostPathsOptions): HostPaths {
142
142
  }
143
143
  return { home, paths, legacyPaths, redirects, refusals, roots };
144
144
  }
145
+
146
+ export interface ResolveSkillRootsOptions extends Omit<ResolveHostPathsOptions, "hosts"> {
147
+ hosts?: readonly HostId[];
148
+ }
149
+
150
+ export interface SkillRoots {
151
+ roots: Partial<Record<SkillHostId, string[]>>;
152
+ redirects: HostRedirect[];
153
+ refusals: HostRefusal[];
154
+ }
155
+
156
+ /** Select one verified installation root per host without writing to disk. */
157
+ export function resolveSkillRoots(options: ResolveSkillRootsOptions): SkillRoots {
158
+ const { env, scopes = ["user"], redirectManagedProfiles = true } = options;
159
+ const home = canonical(options.home);
160
+ const result: SkillRoots = { roots: {}, redirects: [], refusals: [] };
161
+ for (const id of new Set(options.hosts ?? (Object.keys(SKILL_HOSTS) as SkillHostId[]))) {
162
+ if (!Object.hasOwn(SKILL_HOSTS, id)) continue;
163
+ const host = id as SkillHostId;
164
+ const definition: HostSkillDefinition = SKILL_HOSTS[host];
165
+ if (!scopes.includes("user")) {
166
+ result.roots[host] = [];
167
+ continue;
168
+ }
169
+ const preferred = definition.preferredOverride;
170
+ const override = preferred && env[preferred.key] ? preferred : definition.override;
171
+ if (env[override.key]?.includes(String.fromCharCode(0))) {
172
+ result.refusals.push({
173
+ host, variable: override.key, code: "invalid-skill-override",
174
+ reason: `${override.key} contains a NUL character; supply an absolute directory or unset the override`,
175
+ });
176
+ continue;
177
+ }
178
+ const root = configRoot(override, env, home);
179
+ if (typeof root !== "string") {
180
+ result.refusals.push({ host, ...root });
181
+ continue;
182
+ }
183
+ const from = join(root, override === preferred ? "skills" : definition.path);
184
+ const personal = join(home, definition.override.directory, definition.path);
185
+ const orcaRoot = env.ORCA_USER_DATA_PATH?.trim() || join(home, "Library", "Application Support", "orca");
186
+ if (redirectManagedProfiles && definition.managedProfile && from !== personal
187
+ && orcaHome(root, definition.managedProfile, orcaRoot)) {
188
+ result.roots[host] = [personal];
189
+ result.redirects.push({
190
+ target: host, from, to: personal, reason: "The managed profile uses the personal skill root",
191
+ });
192
+ continue;
193
+ }
194
+ result.roots[host] = [from];
195
+ }
196
+ return result;
197
+ }
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
- import { join } from "node:path";
2
+ import { dirname, join } from "node:path";
3
3
  import type { ConfigImage } from "./json.ts";
4
- import { isConfigImage, readReceiptValue, type ReceiptTarget } from "./receipt.ts";
4
+ import { digest, isConfigImage, readReceiptValue, type ReceiptTarget } from "./receipt.ts";
5
5
  import { SETUP_CONFIG_BYTES } from "./toml.ts";
6
6
  import { EntryRefusal } from "./refusal.ts";
7
7
 
@@ -59,9 +59,12 @@ function entryReceipt(path: string, target: ReceiptTarget, file: string, raw: un
59
59
  export function readLegacyReceipt(directory: string, target: ReceiptTarget, legacyPaths: readonly string[] = []): LegacyReceipt | undefined {
60
60
  const candidates = [...new Set([target.file, ...legacyPaths])];
61
61
  if (target.name === "amem") {
62
- const path = join(directory, `${target.host}.json`);
62
+ // Agent-mem keys its direct agy journal by the Git workspace root.
63
+ const workspace = target.host === "agy" ? dirname(dirname(target.file)) : undefined;
64
+ const filename = workspace === undefined ? `${target.host}.json` : `agy-${digest(workspace)}.json`;
65
+ const path = join(directory, filename);
63
66
  const { image, value } = readReceiptValue(path, 12 * SETUP_CONFIG_BYTES);
64
- return image.bytes === null ? undefined : memoryReceipt(path, target, candidates, value);
67
+ return image.bytes === null ? undefined : memoryReceipt(path, target, workspace === undefined ? candidates : [target.file], value);
65
68
  }
66
69
  if (target.name !== "vmem" && target.name !== "ares") return undefined;
67
70
 
package/src/refusal.ts CHANGED
@@ -19,6 +19,12 @@ export const REFUSAL_CODES = [
19
19
  "managed-entry-changed",
20
20
  "pending-operation",
21
21
  "io-error",
22
+ "invalid-skill-override",
23
+ "foreign-skill-link",
24
+ "skill-tool-marker",
25
+ "system-reserved-skill",
26
+ "unmanaged-skill-target",
27
+ "profile-root-changed",
22
28
  ] as const;
23
29
 
24
30
  export type RefusalCode = typeof REFUSAL_CODES[number];
package/src/skills.ts ADDED
@@ -0,0 +1,404 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { lstatSync, readlinkSync, renameSync, symlinkSync, unlinkSync, type Stats } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { checkPhysicalDirectory, ensureDirectory, publishImage, readImage, withConfigLock } from "./fs-safe.ts";
5
+ import { SKILL_HOSTS, type SkillHostId } from "./hosts.ts";
6
+ import type { ConfigImage } from "./json.ts";
7
+ import { asEntryRefusal, EntryRefusal, type RefusalCode } from "./refusal.ts";
8
+
9
+ const markers = [".ahub-skill.json", ".vmem-skill.json", ".amem-skill.json", ".arev-skill.json"] as const;
10
+ const receiptLimit = 64 * 1024;
11
+ const absentImage: ConfigImage = { bytes: null, mode: 0o600 };
12
+ const reserved = new Set([".system"]);
13
+
14
+ interface LinkIdentity {
15
+ targetPath: string;
16
+ link: string;
17
+ device: string;
18
+ inode: string;
19
+ birth: string;
20
+ }
21
+
22
+ interface SkillReceipt {
23
+ version: 1;
24
+ host: SkillHostId;
25
+ name: string;
26
+ installed: LinkIdentity;
27
+ pending?: { temporary: LinkIdentity; previous: LinkIdentity | null };
28
+ }
29
+
30
+ export interface SkillEntryTarget {
31
+ host: SkillHostId;
32
+ root: string;
33
+ name: string;
34
+ receiptDir: string;
35
+ }
36
+
37
+ export interface PlanSkillEntryOptions extends SkillEntryTarget {
38
+ sourcePath: string;
39
+ retarget?: boolean;
40
+ }
41
+
42
+ export type SkillTargetClassification =
43
+ | { kind: "absent" | "system-reserved" | "unmanaged-directory" | "unmanaged-file" }
44
+ | { kind: "owned-symlink" | "foreign-symlink"; link: string }
45
+ | { kind: "tool-marker"; marker: typeof markers[number] };
46
+
47
+ type SkillChange = "add" | "replace" | "retarget" | "unchanged";
48
+ type SkillPreview = {
49
+ change: SkillChange;
50
+ targetPath: string;
51
+ options: PlanSkillEntryOptions;
52
+ intent: string;
53
+ };
54
+ export type SkillEntryPlan = SkillPreview
55
+ | { change: "refused"; code: RefusalCode; reason: string; file?: string };
56
+
57
+ export interface SkillEntryResult {
58
+ change: SkillChange | "removed";
59
+ targetPath: string;
60
+ receipt: string;
61
+ code?: "no-receipt" | "entry-already-absent";
62
+ }
63
+
64
+ function fail(code: RefusalCode, file: string, reason: string): never {
65
+ throw new EntryRefusal(code, `${file}: ${reason}`, { file });
66
+ }
67
+
68
+ function stat(path: string): Stats | undefined {
69
+ try {
70
+ return lstatSync(path);
71
+ } catch (error) {
72
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
73
+ throw error;
74
+ }
75
+ }
76
+
77
+ function plainAbsolute(path: unknown): path is string {
78
+ return typeof path === "string" && path.length <= 4096 && !path.includes(String.fromCharCode(0))
79
+ && isAbsolute(path) && resolve(path) === path;
80
+ }
81
+
82
+ function sameLink(a: LinkIdentity | undefined | null, b: LinkIdentity | undefined | null): boolean {
83
+ return !!a && !!b && a.targetPath === b.targetPath && a.link === b.link
84
+ && a.device === b.device && a.inode === b.inode && a.birth === b.birth;
85
+ }
86
+
87
+ function identify(targetPath: string, named: Stats): LinkIdentity {
88
+ const link = readlinkSync(targetPath);
89
+ const current = stat(targetPath);
90
+ if (!current?.isSymbolicLink() || named.ino !== current.ino || named.dev !== current.dev
91
+ || named.ctimeMs !== current.ctimeMs) {
92
+ fail("file-changed", targetPath, "link changed during inspection; inspect it and retry");
93
+ }
94
+ return { targetPath, link, device: String(named.dev), inode: String(named.ino), birth: String(named.birthtimeMs) };
95
+ }
96
+
97
+ function inspect(targetPath: string, owned?: LinkIdentity): {
98
+ classification: SkillTargetClassification; identity?: LinkIdentity;
99
+ } {
100
+ if (!plainAbsolute(targetPath)) fail("unsafe-path", targetPath, "use an absolute physical skill path");
101
+ if (reserved.has(basename(targetPath))) return { classification: { kind: "system-reserved" } };
102
+ checkPhysicalDirectory(dirname(targetPath));
103
+ const named = stat(targetPath);
104
+ if (!named) return { classification: { kind: "absent" } };
105
+ if (named.isSymbolicLink()) {
106
+ const identity = identify(targetPath, named);
107
+ return {
108
+ identity,
109
+ classification: { kind: sameLink(identity, owned) ? "owned-symlink" : "foreign-symlink", link: identity.link },
110
+ };
111
+ }
112
+ if (!named.isDirectory()) return { classification: { kind: "unmanaged-file" } };
113
+ checkPhysicalDirectory(targetPath);
114
+ for (const marker of markers) {
115
+ if (stat(join(targetPath, marker))) return { classification: { kind: "tool-marker", marker } };
116
+ }
117
+ return { classification: { kind: "unmanaged-directory" } };
118
+ }
119
+
120
+ /** Classify ownership only when a validated receipt is supplied by host, name and directory. */
121
+ export function classifySkillTarget(options: {
122
+ targetPath: string; host?: SkillHostId; receiptDir?: string;
123
+ }): SkillTargetClassification {
124
+ const { targetPath, host, receiptDir } = options;
125
+ const owned = host !== undefined && receiptDir !== undefined
126
+ ? readSkillReceipt({ host, name: basename(targetPath), root: dirname(targetPath), receiptDir }).receipt?.installed
127
+ : undefined;
128
+ return inspect(targetPath, owned).classification;
129
+ }
130
+
131
+ function targetFor(options: SkillEntryTarget): { targetPath: string; receiptPath: string } {
132
+ const { host, root, name, receiptDir } = options;
133
+ if (!Object.hasOwn(SKILL_HOSTS, host) || !/^(?:[A-Za-z0-9][A-Za-z0-9._-]{0,127}|\.system)$/.test(name)) {
134
+ fail("invalid-target", root, "supply a verified skill host and a single skill name");
135
+ }
136
+ if (!plainAbsolute(root) || !plainAbsolute(receiptDir)) {
137
+ fail("unsafe-path", root, "use absolute physical skill and receipt directories");
138
+ }
139
+ const key = createHash("sha256").update(JSON.stringify([host, name])).digest("hex");
140
+ return { targetPath: join(root, name), receiptPath: join(receiptDir, `skill-${key}.json`) };
141
+ }
142
+
143
+ function validLink(value: unknown): value is LinkIdentity {
144
+ if (typeof value !== "object" || value === null) return false;
145
+ const link = value as Partial<LinkIdentity>;
146
+ return plainAbsolute(link.targetPath) && typeof link.link === "string" && link.link.length > 0
147
+ && link.link.length <= 4096 && !isAbsolute(link.link) && !link.link.includes(String.fromCharCode(0))
148
+ && /^\d+$/.test(link.device ?? "") && /^\d+$/.test(link.inode ?? "")
149
+ && /^\d+(\.\d+)?$/.test(link.birth ?? "");
150
+ }
151
+
152
+ function readSkillReceipt(options: SkillEntryTarget): {
153
+ path: string; image: ConfigImage; receipt?: SkillReceipt;
154
+ } {
155
+ const { receiptPath: path } = targetFor(options);
156
+ const image = readImage(path, receiptLimit);
157
+ if (image.bytes === null) return { path, image };
158
+ let value: SkillReceipt;
159
+ try {
160
+ value = JSON.parse(Buffer.from(image.bytes, "base64").toString("utf8"));
161
+ } catch {
162
+ fail("invalid-receipt", path, "receipt is malformed; inspect it before retrying");
163
+ }
164
+ if (!value || value.version !== 1 || value.host !== options.host || value.name !== options.name
165
+ || !validLink(value.installed) || basename(value.installed.targetPath) !== value.name
166
+ || (value.pending !== undefined && (!value.pending || !validLink(value.pending.temporary)
167
+ || dirname(value.pending.temporary.targetPath) !== dirname(value.installed.targetPath)
168
+ || !/^\.agent-hosts-skill-[a-f0-9-]{36}\.tmp$/.test(basename(value.pending.temporary.targetPath))
169
+ || !sameLink({ ...value.pending.temporary, targetPath: value.installed.targetPath }, value.installed)
170
+ || (value.pending.previous !== null && (!validLink(value.pending.previous)
171
+ || basename(value.pending.previous.targetPath) !== value.name))))) {
172
+ fail("invalid-receipt", path, "receipt does not match this skill; inspect it before retrying");
173
+ }
174
+ return { path, image, receipt: value };
175
+ }
176
+
177
+ function receiptImage(receipt: SkillReceipt): ConfigImage {
178
+ return { bytes: Buffer.from(JSON.stringify(receipt) + "\n").toString("base64"), mode: 0o600 };
179
+ }
180
+
181
+ function checkAvailable(targetPath: string, owned?: LinkIdentity): boolean {
182
+ const { classification } = inspect(targetPath, owned);
183
+ switch (classification.kind) {
184
+ case "absent": return false;
185
+ case "owned-symlink": return true;
186
+ case "foreign-symlink":
187
+ return fail(owned ? "managed-entry-changed" : "foreign-skill-link", targetPath,
188
+ "link is outside this receipt's ownership; move it aside or restore the recorded link, then retry");
189
+ case "tool-marker":
190
+ return fail("skill-tool-marker", targetPath, `owned by ${classification.marker}; manage it with its owning tool`);
191
+ case "system-reserved":
192
+ return fail("system-reserved-skill", targetPath, "name is reserved for host skills; choose another name");
193
+ default:
194
+ return fail("unmanaged-skill-target", targetPath, "entry already exists; move it aside or choose another name");
195
+ }
196
+ }
197
+
198
+ function sourceLink(options: PlanSkillEntryOptions, targetPath: string): string {
199
+ if (!plainAbsolute(options.sourcePath) || !checkPhysicalDirectory(options.sourcePath)) {
200
+ fail("invalid-entry", String(options.sourcePath), "supply an existing physical source directory");
201
+ }
202
+ const outside = (path: string): boolean => path === ".." || path.startsWith(".." + sep);
203
+ if (!outside(relative(targetPath, options.sourcePath)) || !outside(relative(options.sourcePath, targetPath))) {
204
+ fail("invalid-entry", targetPath, "source and destination overlap and may create a recursive skill link; choose a source in a separate directory");
205
+ }
206
+ return relative(dirname(targetPath), options.sourcePath);
207
+ }
208
+
209
+ function plan(options: PlanSkillEntryOptions): SkillPreview {
210
+ const { targetPath } = targetFor(options);
211
+ const { receipt, image } = readSkillReceipt(options);
212
+ const link = sourceLink(options, targetPath);
213
+ const prior = receipt?.pending ? receipt.pending.previous ?? undefined : receipt?.installed;
214
+ const moved = !!prior && prior.targetPath !== targetPath;
215
+ if (receipt?.pending && (receipt.installed.targetPath !== targetPath || receipt.installed.link !== link)) {
216
+ fail("pending-operation", targetPath,
217
+ `preview and apply the interrupted publication for ${receipt.installed.targetPath} from ${resolve(dirname(receipt.installed.targetPath), receipt.installed.link)} first`);
218
+ }
219
+ if (moved && !options.retarget) {
220
+ fail("profile-root-changed", targetPath, `recorded skill root is ${dirname(prior.targetPath)}; pass retarget: true to move it`);
221
+ }
222
+ if (receipt?.pending) {
223
+ const change = moved ? "retarget" : prior ? "replace" : "add";
224
+ return { change, targetPath, options: { ...options }, intent: pendingIntent(image) };
225
+ }
226
+ const present = checkAvailable(targetPath, moved ? undefined : prior);
227
+ const oldPresent = moved && atRecordedRoot(prior, () => checkAvailable(prior.targetPath, prior));
228
+ const change = moved ? "retarget" : !present ? "add" : prior?.link === link ? "unchanged" : "replace";
229
+ const intent = createHash("sha256").update(JSON.stringify([targetPath, link, image.bytes, image.mode, present, oldPresent])).digest("hex");
230
+ return { change, targetPath, options: { ...options }, intent };
231
+ }
232
+
233
+ export function planSkillEntry(options: PlanSkillEntryOptions): SkillEntryPlan {
234
+ try {
235
+ return plan(options);
236
+ } catch (error) {
237
+ const refusal = asEntryRefusal(error, "Plan skill entry");
238
+ return { change: "refused", code: refusal.code, reason: refusal.reason, file: refusal.file };
239
+ }
240
+ }
241
+
242
+ function removeOwned(link: LinkIdentity): boolean {
243
+ if (!checkAvailable(link.targetPath, link)) return false;
244
+ unlinkSync(link.targetPath);
245
+ return true;
246
+ }
247
+
248
+ function atRecordedRoot<T>(link: LinkIdentity, action: () => T): T {
249
+ try {
250
+ return action();
251
+ } catch (error) {
252
+ if (!(error instanceof EntryRefusal) || error.code !== "unsafe-path") throw error;
253
+ fail("unsafe-path", link.targetPath,
254
+ `recorded skill root is redirected or unsafe; restore ${dirname(link.targetPath)} as a physical directory for undo, or move the receipt aside to stop tracking this link without following it`);
255
+ }
256
+ }
257
+
258
+ function pendingIntent(image: ConfigImage): string {
259
+ return createHash("sha256").update(JSON.stringify(["pending", image.bytes, image.mode])).digest("hex");
260
+ }
261
+
262
+ function rollback(path: string, image: ConfigImage, temporary: LinkIdentity, restoration: ConfigImage): void {
263
+ try {
264
+ const current = inspect(temporary.targetPath).identity;
265
+ if (sameLink(current, temporary)) unlinkSync(temporary.targetPath);
266
+ } finally {
267
+ // A redirected directory may make the staged link unreachable. Never follow it.
268
+ publishImage(path, receiptLimit, image, restoration);
269
+ }
270
+ }
271
+
272
+ /** Finish a publication that reached rename, or roll back one that did not. */
273
+ function recover(options: SkillEntryTarget): boolean {
274
+ const { path, image, receipt } = readSkillReceipt(options);
275
+ if (!receipt?.pending) return false;
276
+ const { installed, pending: { previous, temporary } } = receipt;
277
+ const current = atRecordedRoot(installed, () => inspect(installed.targetPath).identity);
278
+ if (sameLink(current, installed)) {
279
+ if (previous && previous.targetPath !== installed.targetPath) {
280
+ atRecordedRoot(previous, () => removeOwned(previous));
281
+ }
282
+ const { pending: _pending, ...committed } = receipt;
283
+ publishImage(path, receiptLimit, image, receiptImage(committed));
284
+ return true;
285
+ }
286
+ const restoration = previous ? receiptImage({ version: 1, host: receipt.host, name: receipt.name, installed: previous }) : absentImage;
287
+ rollback(path, image, temporary, restoration);
288
+ return false;
289
+ }
290
+
291
+ export function applySkillEntry(preview: SkillEntryPlan): SkillEntryResult {
292
+ if (preview.change === "refused") throw new EntryRefusal(preview.code, preview.reason, { file: preview.file });
293
+ const options = preview.options;
294
+ const { targetPath, receiptPath } = targetFor(options);
295
+ try {
296
+ return withConfigLock(receiptPath, () => {
297
+ if (targetPath !== preview.targetPath) {
298
+ fail("changed-since-preview", targetPath, "skill target changed; preview it again before applying");
299
+ }
300
+ const staged = readSkillReceipt(options);
301
+ const freshPendingPreview = staged.receipt?.pending !== undefined && preview.intent === pendingIntent(staged.image);
302
+ const resumed = staged.receipt?.pending ? plan(options) : undefined;
303
+ if (recover(options) && resumed) {
304
+ return { change: resumed.change, targetPath, receipt: receiptPath };
305
+ }
306
+ const current = plan(options);
307
+ if (!freshPendingPreview
308
+ && (current.intent !== preview.intent || current.change !== preview.change)) {
309
+ fail("changed-since-preview", targetPath, "skill state changed; preview it again before applying");
310
+ }
311
+ const result = { change: current.change, targetPath, receipt: receiptPath };
312
+ if (current.change === "unchanged") return result;
313
+
314
+ const { receipt, image } = readSkillReceipt(options);
315
+ const parentPath = dirname(targetPath);
316
+ ensureDirectory(parentPath);
317
+ const parent = checkPhysicalDirectory(parentPath)!;
318
+ const temporaryPath = join(parentPath, `.agent-hosts-skill-${randomUUID()}.tmp`);
319
+ let created = false;
320
+ let named: Stats | undefined;
321
+ let journal: { image: ConfigImage; link: LinkIdentity } | undefined;
322
+ let renamed = false;
323
+ try {
324
+ symlinkSync(sourceLink(options, targetPath), temporaryPath);
325
+ created = true;
326
+ named = lstatSync(temporaryPath);
327
+ const temporary = identify(temporaryPath, named);
328
+ const pending: SkillReceipt = {
329
+ version: 1, host: options.host, name: options.name, installed: { ...temporary, targetPath },
330
+ pending: { temporary, previous: receipt?.installed ?? null },
331
+ };
332
+ const stagedImage = receiptImage(pending);
333
+ publishImage(receiptPath, receiptLimit, image, stagedImage);
334
+ journal = { image: stagedImage, link: temporary };
335
+ const refreshed = checkPhysicalDirectory(parentPath);
336
+ if (!refreshed || parent.dev !== refreshed.dev || parent.ino !== refreshed.ino
337
+ || !sameLink(inspect(temporaryPath).identity, temporary)) {
338
+ fail("file-changed", targetPath, "destination directory or staged link changed; inspect it before retrying");
339
+ }
340
+ const previous = receipt?.installed;
341
+ const stillPresent = checkAvailable(targetPath, previous?.targetPath === targetPath ? previous : undefined);
342
+ const expectedPresent = current.change === "replace";
343
+ if (stillPresent !== expectedPresent) {
344
+ fail("changed-since-preview", targetPath, "destination changed after staging; inspect it before retrying");
345
+ }
346
+ // ponytail: rename(2) can replace a foreign file or link created after this check.
347
+ // The receipt lock coordinates cooperating writers only.
348
+ renameSync(temporaryPath, targetPath);
349
+ renamed = true;
350
+ recover(options);
351
+ return result;
352
+ } catch (error) {
353
+ if (journal && !renamed) {
354
+ try {
355
+ rollback(receiptPath, journal.image, journal.link, image);
356
+ } catch (rollbackError) {
357
+ throw new AggregateError([error, rollbackError], "Skill staging failed and cleanup needs inspection");
358
+ }
359
+ } else if (created && !journal) {
360
+ try {
361
+ const currentParent = checkPhysicalDirectory(parentPath);
362
+ const current = stat(temporaryPath);
363
+ if (currentParent?.dev === parent.dev && currentParent.ino === parent.ino
364
+ && current?.isSymbolicLink() && (!named || (current.dev === named.dev && current.ino === named.ino))) {
365
+ unlinkSync(temporaryPath);
366
+ }
367
+ } catch {
368
+ // Do not replace the publication error with a cleanup error.
369
+ }
370
+ }
371
+ throw error;
372
+ }
373
+ });
374
+ } catch (error) {
375
+ throw asEntryRefusal(error, "Apply skill entry", targetPath);
376
+ }
377
+ }
378
+
379
+ export function undoSkillEntry(options: SkillEntryTarget): SkillEntryResult {
380
+ const { targetPath, receiptPath } = targetFor(options);
381
+ try {
382
+ if (!readSkillReceipt(options).receipt) return { change: "unchanged", code: "no-receipt", targetPath, receipt: receiptPath };
383
+ return withConfigLock(receiptPath, () => {
384
+ const staged = readSkillReceipt(options).receipt;
385
+ if (staged && staged.installed.targetPath !== targetPath) {
386
+ fail("profile-root-changed", targetPath, `use the recorded root ${dirname(staged.installed.targetPath)} to undo this skill`);
387
+ }
388
+ recover(options);
389
+ const { receipt, image } = readSkillReceipt(options);
390
+ if (!receipt) return { change: "unchanged", code: "no-receipt", targetPath, receipt: receiptPath };
391
+ const installed = receipt.installed;
392
+ if (installed.targetPath !== targetPath) {
393
+ fail("profile-root-changed", targetPath, `use the recorded root ${dirname(installed.targetPath)} to undo this skill`);
394
+ }
395
+ const removed = atRecordedRoot(installed, () => removeOwned(installed));
396
+ publishImage(receiptPath, receiptLimit, image, absentImage);
397
+ return removed
398
+ ? { change: "removed", targetPath, receipt: receiptPath }
399
+ : { change: "unchanged", code: "entry-already-absent", targetPath, receipt: receiptPath };
400
+ });
401
+ } catch (error) {
402
+ throw asEntryRefusal(error, "Undo skill entry", targetPath);
403
+ }
404
+ }