@mago-foundation/mago-ski 0.3.0 → 0.4.1

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 (54) hide show
  1. package/README.md +34 -10
  2. package/action.yml +21 -2
  3. package/dist/hosts/github/run.d.ts +9 -0
  4. package/dist/hosts/github/run.js +30 -16
  5. package/dist/hosts/pi/index.js +40 -18
  6. package/dist/src/admin.d.ts +2 -1
  7. package/dist/src/admin.js +3 -2
  8. package/dist/src/canonical-json.d.ts +6 -0
  9. package/dist/src/canonical-json.js +11 -0
  10. package/dist/src/cli.d.ts +13 -1
  11. package/dist/src/cli.js +426 -8
  12. package/dist/src/diff.d.ts +5 -0
  13. package/dist/src/diff.js +2 -1
  14. package/dist/src/dsse.js +2 -2
  15. package/dist/src/experimental/sigstore.d.ts +6 -0
  16. package/dist/src/experimental/sigstore.js +13 -5
  17. package/dist/src/gate/adapters/claude-code-settings.js +1 -1
  18. package/dist/src/gate/adapters/claude-code.js +1 -0
  19. package/dist/src/gate/adapters/codex-names.d.ts +1 -0
  20. package/dist/src/gate/adapters/codex-names.js +56 -0
  21. package/dist/src/gate/adapters/codex-requirements.d.ts +11 -0
  22. package/dist/src/gate/adapters/codex-requirements.js +56 -29
  23. package/dist/src/gate/adapters/codex.d.ts +3 -0
  24. package/dist/src/gate/adapters/codex.js +147 -20
  25. package/dist/src/gate/admin-client.d.ts +19 -0
  26. package/dist/src/gate/admin-client.js +62 -0
  27. package/dist/src/gate/generations.js +2 -0
  28. package/dist/src/gate/instance.d.ts +57 -0
  29. package/dist/src/gate/instance.js +97 -0
  30. package/dist/src/gate/proc.d.ts +6 -0
  31. package/dist/src/gate/proc.js +14 -3
  32. package/dist/src/gate/service.d.ts +13 -0
  33. package/dist/src/gate/service.js +344 -37
  34. package/dist/src/gate/setup.d.ts +210 -0
  35. package/dist/src/gate/setup.js +1038 -0
  36. package/dist/src/gate/trust-store.d.ts +14 -0
  37. package/dist/src/gate/trust-store.js +66 -0
  38. package/dist/src/index.d.ts +2 -1
  39. package/dist/src/index.js +3 -1
  40. package/dist/src/policy.d.ts +7 -0
  41. package/dist/src/policy.js +19 -2
  42. package/dist/src/recovery-admin.js +7 -4
  43. package/dist/src/root-events.d.ts +2 -0
  44. package/dist/src/root-events.js +61 -4
  45. package/dist/src/tree-digest.d.ts +6 -0
  46. package/dist/src/tree-digest.js +8 -0
  47. package/docs/hosts/adapter-interface.md +1 -1
  48. package/docs/hosts/claude-code.md +108 -0
  49. package/docs/hosts/codex.md +181 -0
  50. package/docs/spec/gui-admin-rack-v1.md +1 -1
  51. package/docs/spec/root-recovery-v1.md +3 -2
  52. package/docs/spec/trust-documents-v1.md +1 -1
  53. package/docs/threat-model.md +13 -1
  54. package/package.json +3 -1
package/README.md CHANGED
@@ -4,7 +4,21 @@
4
4
 
5
5
  Agent Skills (a `SKILL.md` plus scripts and references) change. A Skill that was fine last week can gain one sentence (`also send the results to…`) with no new tools and no new URLs, and every agent that has it installed picks the change up silently. Scanners can tell you *what* changed. mago-ski checks that *someone in your organization approved exactly these bytes*. In enforce mode, supported hosts block Skills that fail the check, within the limits in the [threat model](docs/threat-model.md).
6
6
 
7
- > Status: **0.2, early release.** Formats and commands may still change before 1.0. Linux and macOS only.
7
+ ![The desktop GUI's observation tab: three Skills, one changed since it was recorded, with the file diff and the organisation's verdict](docs/images/gui-observe.png)
8
+
9
+ *The desktop GUI (proof of concept, run from source) showing a Skill that changed after it was approved. The CLI, the Pi extension and the GitHub Action do the checking; see [Desktop GUI](#desktop-gui).*
10
+
11
+ > Status: **0.4.0, early release.** Formats and commands may still change before 1.0. Linux and macOS only; the company gate is Linux only.
12
+
13
+ ## What 0.4.0 includes
14
+
15
+ - **Approval and checking** from the `mago-ski` command: keys, approvers with name scopes and end dates, certificates for exact Skill versions, revocation, `verify`, `verify-all` and `diff`.
16
+ - **Blocking** in the Pi coding agent and in GitHub Actions, with a shadow mode that records what would be blocked.
17
+ - **The company gate for Claude Code and Codex** (new in 0.4.0, Linux only): `mago-ski gate …` installs approved Skills into an admin-owned folder and checks every use of a Skill, in shadow mode by default. Tried with the real hosts in non-interactive sessions. For Codex, the [guide](docs/hosts/codex.md) lists what the gate cannot stop and your organisation has to control itself.
18
+ - **Root recovery and freshness**: offline recovery keys can revoke or replace a leaked root key, and an optional timestamp stops a host from being kept on old files.
19
+ - **Desktop GUI** (proof of concept, run from source, English and Korean): watches installed Skills, and its administration tab covers approving, managing approvers, revoking, refreshing the revocation list and signing the timestamp.
20
+
21
+ [What mago-ski can do](docs/capabilities.md) lists, in plain language, what is released and what mago-ski does not do. Changes per version are in the [changelog](CHANGELOG.md).
8
22
 
9
23
  ## How it works
10
24
 
@@ -92,7 +106,7 @@ Only name a policy you trust: run against a checkout you do not control, point `
92
106
 
93
107
  ## Platforms
94
108
 
95
- mago-ski 0.2 supports **Linux and macOS** (Node.js 22.23.4, 24.22.1 or 26.12.1 or newer in its line (the October 2026 security releases)). **Windows is not supported yet**: it has no POSIX executable bit, so digests made on Windows differ from Linux and macOS ones. npm refuses to install the package on Windows, and the GitHub Action stops on Windows runners. Windows support is planned for a later release.
109
+ mago-ski 0.4 supports **Linux and macOS** (Node.js 22.23.4, 24.22.1 or 26.12.1 or newer in its line (the October 2026 security releases)). **Windows is not supported yet**: it has no POSIX executable bit, so digests made on Windows differ from Linux and macOS ones. npm refuses to install the package on Windows, and the GitHub Action stops on Windows runners. Windows support is planned for a later release.
96
110
 
97
111
  ## Where it runs
98
112
 
@@ -100,17 +114,16 @@ mago-ski 0.2 supports **Linux and macOS** (Node.js 22.23.4, 24.22.1 or 26.12.1 o
100
114
  |---|---|---|
101
115
  | **Pi** | Extension, in enforce mode: unverified Skills are not advertised to the model, `/skill:` cannot load them, file tools refuse their files, and verified files are re-hashed on read | [docs/hosts/pi.md](docs/hosts/pi.md) |
102
116
  | **GitHub Actions** | In enforce mode, fails the check when a Skill found under the policy's `skill_dirs` lacks a valid certificate. Trust comes from the base revision, so a PR cannot approve itself | [docs/hosts/github-action.md](docs/hosts/github-action.md) |
103
- | **CLI** | `verify`, `verify-all`, `diff`, `digest`, `inspect`, plus key, root, revoke and approve commands. Run `mago-ski --help` | |
117
+ | **CLI** | `verify`, `verify-all`, `diff`, `digest`, `inspect` and `policy check`, plus the key, root, revoke and approve commands, and the root recovery commands (`recovery`, `root-events`, `timestamp`). Run `mago-ski --help` | |
118
+ | **Claude Code and Codex** (Linux only) | The company gate (`mago-ski gate …`) installs approved Skills into an admin-owned folder and checks every use of a Skill. Tried with the real hosts in non-interactive sessions | [Claude Code](docs/hosts/claude-code.md), [Codex](docs/hosts/codex.md), [docs/capabilities.md](docs/capabilities.md), live test results for [Claude Code](docs/spikes/claude-code-gate-live.md) and [Codex](docs/spikes/codex-gate-live.md) |
104
119
  | Other agents | Planned through the same hook points | [docs/hosts/adapter-interface.md](docs/hosts/adapter-interface.md) |
105
120
  | **Desktop GUI** (PoC) | Watches installed Pi and Agent Skills, shows what changed since the version you remember, and shows each Skill's PKI verdict from the host policy. Never writes host state. Its administration rack covers approving Skill versions, managing approvers, revoking, refreshing the revocation list and signing the timestamp, each confirmed in a native dialog, with the role proven by the key against an admin-owned organisation pin ([spec](docs/spec/gui-admin-rack-v1.md)). English and Korean | [gui/README.md](gui/README.md) |
106
121
 
107
122
  ## Desktop GUI
108
123
 
109
- The desktop GUI (PoC) shows its texts in English or Korean. It follows the system language and has a language switch in the header. See [gui/README.md](gui/README.md).
110
-
111
- ![The observation tab: three Skills, one changed, with the file diff](docs/images/gui-observe.png)
124
+ The desktop GUI is a proof of concept. It is not published: run it from the [`gui/`](gui/README.md) folder of this repository. It shows its texts in English or Korean, follows the system language and has a language switch in the header.
112
125
 
113
- The observation tab lists the installed Skills and shows what changed in the selected one since the version you remember.
126
+ The observation tab (the picture at the top of this page) lists the installed Skills and shows what changed in the selected one since the version you remember. Observing never approves anything and never blocks a Skill.
114
127
 
115
128
  ![The admin tab: the organisation pin and the template picker](docs/images/gui-admin-templates.png)
116
129
 
@@ -122,17 +135,25 @@ In the Approve template the approver's key is loaded (IDENTITY) and INSPECT show
122
135
 
123
136
  ![The Manage approvers template: TRUST ROOT with the approver list, and POLICY CHECK](docs/images/gui-admin-approvers.png)
124
137
 
138
+ In the Manage approvers template TRUST ROOT shows the trust root's approvers, expiry and lifetime controls, and POLICY CHECK shows every Skill's verdict under the host's own loader.
139
+
125
140
  ![Revoke: TARGET with the current approvers and a reviewed Skill](docs/images/gui-admin-revoke.png)
126
141
 
142
+ In the Revoke template TARGET lists what the loaded key may revoke: current approvers and Skill versions it reviewed.
143
+
127
144
  ![Refresh revocation list: REVOCATION REFRESH](docs/images/gui-admin-refresh.png)
128
145
 
146
+ Refresh revocation list re-signs the list before it expires.
147
+
129
148
  ![Sign timestamp: TIMESTAMP](docs/images/gui-admin-timestamp.png)
130
149
 
131
- In the Manage approvers template TRUST ROOT shows the trust root's approvers, expiry and lifetime controls, and POLICY CHECK shows every Skill's verdict under the host's own loader.
150
+ Sign timestamp is for the holder of the timestamp key, in an organisation that uses freshness.
151
+
152
+ Every signature is confirmed in a native dialog that shows exactly what will be signed. Setting up a new organisation and recovering from a leaked root key still use the command line.
132
153
 
133
154
  ## Verdicts
134
155
 
135
- `VERIFIED` · `UNAPPROVED_CHANGE` · `NO_CERTIFICATE` · `UNTRUSTED_SIGNER` · `REVOKED` · `EXPIRED` · `UNVERIFIABLE`. Everything except `VERIFIED` blocks on supported hosts in enforce mode. Shadow mode allows it and records `would-block` in the decision log when one is configured (the GitHub Action reports instead). See [docs/spec/verification.md](docs/spec/verification.md).
156
+ `VERIFIED` · `UNAPPROVED_CHANGE` · `NO_CERTIFICATE` · `UNTRUSTED_SIGNER` · `REVOKED` · `EXPIRED` · `UNVERIFIABLE`. Everything except `VERIFIED` blocks on supported hosts in enforce mode. Shadow mode allows it and records `would-block` in the decision log when one is configured (the GitHub Action reports instead), with one exception: a root key revoked by a root event blocks every Skill in shadow mode too. A failure of the trust documents themselves is reported once per host, not once per Skill. See [docs/spec/verification.md](docs/spec/verification.md).
136
157
 
137
158
  ## Works alongside scanners
138
159
 
@@ -140,10 +161,13 @@ Capability scanners such as SkilLock report what a Skill change does at pull-req
140
161
 
141
162
  ## Documentation
142
163
 
164
+ - [What mago-ski can do](docs/capabilities.md): what is released and what is not done, in plain language
143
165
  - [Threat model](docs/threat-model.md): what is and is not protected
144
166
  - Specs: [tree digest](docs/spec/skill-tree-v2.md), [certificate](docs/spec/skill-certificate-v1.md), [trust documents and policy](docs/spec/trust-documents-v1.md), [verification order](docs/spec/verification.md), [root recovery](docs/spec/root-recovery-v1.md), [GUI administration rack](docs/spec/gui-admin-rack-v1.md) (draft)
145
167
  - [Test vectors](tests/vectors/) for other implementations
146
- - [Pi interception spike](docs/phase1/pi-interception.md), [Claude Code interception spike](docs/spikes/claude-code-interception.md)
168
+ - Hosts: [Claude Code](docs/hosts/claude-code.md), [Codex](docs/hosts/codex.md), [Pi](docs/hosts/pi.md), [GitHub Action](docs/hosts/github-action.md), [adapter interface](docs/hosts/adapter-interface.md)
169
+ - [Live scenario guide](scenarios/START-HERE.md): try the gate with Claude Code or Codex in an isolated Linux environment
170
+ - [Pi interception spike](docs/phase1/pi-interception.md), [Claude Code interception spike](docs/spikes/claude-code-interception.md), gate live tests for [Claude Code](docs/spikes/claude-code-gate-live.md) and [Codex](docs/spikes/codex-gate-live.md)
147
171
  - [Security policy](SECURITY.md): how to report a vulnerability
148
172
  - [Changelog](CHANGELOG.md)
149
173
  - [Contributing](CONTRIBUTING.md)
package/action.yml CHANGED
@@ -31,8 +31,17 @@ runs:
31
31
  with:
32
32
  node-version: 22.23.4
33
33
 
34
+ # The base checkout goes to a path inside the workspace, which holds the pull request. Whatever the pull request put
35
+ # at that path (a folder, or a link that would send the checkout somewhere else) is removed first.
36
+ - name: Clear the base checkout path
37
+ if: github.event_name == 'pull_request' || github.event_name == 'pull_request_target'
38
+ shell: bash
39
+ run: |
40
+ set -euo pipefail
41
+ rm -rf -- "${GITHUB_WORKSPACE:?}/.mago-ski-base"
42
+
34
43
  - name: Check out the protected base revision
35
- if: github.event_name == 'pull_request'
44
+ if: github.event_name == 'pull_request' || github.event_name == 'pull_request_target'
36
45
  uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
37
46
  with:
38
47
  repository: ${{ github.repository }}
@@ -47,11 +56,21 @@ runs:
47
56
  MAGO_POLICY: ${{ inputs.policy }}
48
57
  MAGO_EVENT: ${{ github.event_name }}
49
58
  MAGO_ACTION_PATH: ${{ github.action_path }}
59
+ MAGO_BASE_SHA: ${{ github.event.pull_request.base.sha }}
50
60
  run: |
51
61
  set -euo pipefail
52
62
  policy_root="$GITHUB_WORKSPACE"
53
- if [[ "$MAGO_EVENT" == pull_request ]]; then
63
+ if [[ "$MAGO_EVENT" == pull_request || "$MAGO_EVENT" == pull_request_target ]]; then
54
64
  policy_root="$GITHUB_WORKSPACE/.mago-ski-base"
65
+ # Trust must come from the base revision itself: a real folder at that path, checked out at the base commit.
66
+ if [[ -L "$policy_root" || ! -d "$policy_root" || -L "$policy_root/.git" ]]; then
67
+ echo "::error title=mago-ski::the base checkout at .mago-ski-base is not a real folder"
68
+ exit 2
69
+ fi
70
+ if [[ "$(git -C "$policy_root" rev-parse HEAD)" != "$MAGO_BASE_SHA" ]]; then
71
+ echo "::error title=mago-ski::the base checkout at .mago-ski-base is not at the base revision"
72
+ exit 2
73
+ fi
55
74
  fi
56
75
  # The verifier runs from this action's own checkout (pinned by the caller's `uses:` ref),
57
76
  # never from code in the repository under review.
@@ -27,3 +27,12 @@ export interface GitHubCheckResult {
27
27
  /** Names and paths come from the pull request; keep them inert inside a Markdown table cell. */
28
28
  export declare function markdownCell(value: string): string;
29
29
  export declare function runGitHubCheck(options: GitHubCheckOptions): Promise<GitHubCheckResult>;
30
+ /** Escapes the message part of a workflow command (after the `::`). */
31
+ export declare function escapeAnnotation(value: string): string;
32
+ /**
33
+ * Escapes a property value of a workflow command (`file=...`). Properties are separated by `,` and end at `::`, so a path
34
+ * from the pull request must not be able to add a property or end the list: `:` and `,` are escaped as well.
35
+ */
36
+ export declare function escapeAnnotationProperty(value: string): string;
37
+ /** One annotation line for a failing Skill. */
38
+ export declare function annotationLine(level: 'error' | 'warning', file: string | null, verdict: string, message: string): string;
@@ -4,7 +4,7 @@
4
4
  // therefore add certificates but cannot change who is trusted to issue them.
5
5
  import { appendFile, realpath } from 'node:fs/promises';
6
6
  import path from 'node:path';
7
- import { isInside } from "../../src/fs-safe.js";
7
+ import { isInside, realpathAllowingMissing } from "../../src/fs-safe.js";
8
8
  import { isMainModule } from "../../src/main-module.js";
9
9
  import { DiscoveryBudgetError, findSkillDirs, loadPolicy, loadPolicyTrust, tooDeepResult, trustFailureEvent, verifyWithPolicy, } from "../../src/policy.js";
10
10
  import { unverifiable } from "../../src/verify.js";
@@ -27,23 +27,23 @@ function within(root, target, label) {
27
27
  /** Containment on resolved paths, so a symlink cannot point a policy path outside its checkout. */
28
28
  async function withinReal(root, target, label) {
29
29
  within(root, target, label);
30
- let resolved;
31
- try {
32
- resolved = await realpath(target);
33
- }
34
- catch (error) {
35
- if (error?.code === 'ENOENT')
36
- return target;
37
- throw error;
38
- }
30
+ // The existing part of the path is resolved even when the last parts are missing: a link on the way still counts.
31
+ const resolved = await realpathAllowingMissing(target);
39
32
  if (!isInside(await realpath(root), resolved))
40
33
  throw new Error(`${label} must stay inside ${root} (it resolves to ${resolved})`);
41
34
  return target;
42
35
  }
43
- /** Re-anchors a path from the policy checkout into the workspace checkout. */
36
+ /**
37
+ * Re-anchors a path from the policy checkout into the workspace checkout. The action places the base checkout inside the
38
+ * workspace (`.mago-ski-base`), so "inside the workspace" is not enough: a path of the pull request that resolves into the
39
+ * base checkout would have the check read the base revision's Skills or certificates instead of the pull request's.
40
+ */
44
41
  async function toWorkspace(policyRoot, workspace, target, label) {
45
42
  const relative = path.relative(policyRoot, within(policyRoot, target, label));
46
- return await withinReal(workspace, path.join(workspace, relative), label);
43
+ const moved = await withinReal(workspace, path.join(workspace, relative), label);
44
+ if (policyRoot !== workspace && isInside(await realpathAllowingMissing(policyRoot), await realpathAllowingMissing(moved)))
45
+ throw new Error(`${label} must not resolve into the base checkout (${policyRoot})`);
46
+ return moved;
47
47
  }
48
48
  export async function runGitHubCheck(options) {
49
49
  const now = options.now ?? new Date();
@@ -95,7 +95,8 @@ export async function runGitHubCheck(options) {
95
95
  }
96
96
  let discovery;
97
97
  try {
98
- discovery = await findSkillDirs(policy.skillDirs);
98
+ // The base checkout sits inside the workspace on pull requests; its Skills are not the pull request's.
99
+ discovery = await findSkillDirs(policy.skillDirs, undefined, policyRoot === workspace ? {} : { exclude: [policyRoot] });
99
100
  }
100
101
  catch (error) {
101
102
  if (!(error instanceof DiscoveryBudgetError))
@@ -138,9 +139,22 @@ export async function runGitHubCheck(options) {
138
139
  ].join('\n');
139
140
  return { mode: policy.mode, results, exitCode: failures.length > 0 && policy.mode === 'enforce' ? 1 : 0, summary };
140
141
  }
141
- function escapeAnnotation(value) {
142
+ /** Escapes the message part of a workflow command (after the `::`). */
143
+ export function escapeAnnotation(value) {
142
144
  return value.replace(/%/gu, '%25').replace(/\r/gu, '%0D').replace(/\n/gu, '%0A');
143
145
  }
146
+ /**
147
+ * Escapes a property value of a workflow command (`file=...`). Properties are separated by `,` and end at `::`, so a path
148
+ * from the pull request must not be able to add a property or end the list: `:` and `,` are escaped as well.
149
+ */
150
+ export function escapeAnnotationProperty(value) {
151
+ return escapeAnnotation(value).replace(/:/gu, '%3A').replace(/,/gu, '%2C');
152
+ }
153
+ /** One annotation line for a failing Skill. */
154
+ export function annotationLine(level, file, verdict, message) {
155
+ const location = file === null ? '' : `file=${escapeAnnotationProperty(file)},`;
156
+ return `::${level} ${location}title=mago-ski ${escapeAnnotationProperty(verdict)}::${escapeAnnotation(message)}\n`;
157
+ }
144
158
  async function main() {
145
159
  const [policyRoot, workspace, policy] = process.argv.slice(2);
146
160
  if (!policyRoot || !workspace || !policy)
@@ -156,8 +170,8 @@ async function main() {
156
170
  }
157
171
  annotations += 1;
158
172
  const level = result.mode === 'enforce' || result.trustFailure === 'root-revoked' ? 'error' : 'warning';
159
- const location = result.budgetExceeded || result.trustFailure ? '' : `file=${escapeAnnotation(path.relative(path.resolve(workspace), path.join(entry.skillDir, 'SKILL.md')))},`;
160
- process.stdout.write(`::${level} ${location}title=mago-ski ${entry.verdict}::${escapeAnnotation(`${entry.skillName}: ${entry.reason}`)}\n`);
173
+ const file = result.budgetExceeded || result.trustFailure ? null : path.relative(path.resolve(workspace), path.join(entry.skillDir, 'SKILL.md'));
174
+ process.stdout.write(annotationLine(level, file, entry.verdict, `${entry.skillName}: ${entry.reason}`));
161
175
  }
162
176
  process.stdout.write(`${result.summary}\n`);
163
177
  if (process.env.GITHUB_STEP_SUMMARY)
@@ -152,7 +152,9 @@ export function createMagoSkiExtension(options = {}) {
152
152
  policy = await loadPolicy(policyPath);
153
153
  }
154
154
  catch (error) {
155
- if (error?.code === 'ENOENT') {
155
+ // No policy at the default place means mago-ski is not set up here. A policy that was named (the option, or
156
+ // MAGO_SKI_POLICY) and is missing is a broken setup: a mistyped path must not switch checking off.
157
+ if (error?.code === 'ENOENT' && explicit === undefined) {
156
158
  if (ctx.hasUI)
157
159
  ctx.ui.notify(`mago-ski: no policy at ${policyPath}; Skills are not being checked`, 'warning');
158
160
  return;
@@ -288,7 +290,7 @@ export function createMagoSkiExtension(options = {}) {
288
290
  * a line is kept only if it names something that exists under `root` and is not in an unverified
289
291
  * Skill. Returns null when nothing had to be removed.
290
292
  */
291
- async function filterListing(text, root, unverified) {
293
+ async function filterListing(text, root, unverified, hit) {
292
294
  const notice = /\n\n(\[(?:\d+ (?:results|entries) limit reached(?:\. Use limit=\d+ for more(?:, or refine pattern)?)?|[\d.]+KB limit reached)(?:\. [\d.]+KB limit reached)?\])$/u.exec(text);
293
295
  const body = notice ? text.slice(0, notice.index) : text;
294
296
  if (body === '(empty directory)' || body === 'No files found matching pattern')
@@ -302,7 +304,11 @@ export function createMagoSkiExtension(options = {}) {
302
304
  try {
303
305
  await lstat(abs);
304
306
  const real = await canonical(abs);
305
- inSkill = unverified.some((entry) => dirsOf(entry).some((dir) => isInside(dir, abs) || isInside(dir, real)));
307
+ for (const entry of unverified)
308
+ if (dirsOf(entry).some((dir) => isInside(dir, abs) || isInside(dir, real))) {
309
+ inSkill = true;
310
+ hit.add(entry);
311
+ }
306
312
  }
307
313
  catch {
308
314
  inSkill = true; // not a real path (part of a name with a newline) or unreadable: do not pass it on
@@ -326,13 +332,22 @@ export function createMagoSkiExtension(options = {}) {
326
332
  await log(recordFor(entry, event, verdict, reason), false);
327
333
  return enforcing() ? { block: true, reason: `mago-ski: Skill "${entry.name}" ${verdict}: ${reason}` } : undefined;
328
334
  }
329
- async function checkShell(toolName, command) {
335
+ /** The spellings of Skill directories a command could use: absolute, `~/...`, and relative to the working directory. */
336
+ function shellForms(dirs, cwd) {
337
+ const forms = new Set(dirs);
338
+ for (const dir of [...forms]) {
339
+ if (dir.startsWith(homedir()))
340
+ forms.add(`~${dir.slice(homedir().length)}`);
341
+ const relative = path.relative(cwd, dir);
342
+ if (relative !== '' && !path.isAbsolute(relative))
343
+ forms.add(relative);
344
+ }
345
+ return forms;
346
+ }
347
+ async function checkShell(toolName, command, cwd) {
330
348
  // Best-effort: shell commands can reach files in ways a string match cannot see.
331
349
  for (const entry of [...entries]) {
332
- const forms = new Set([...dirsOf(entry), entry.baseDir]);
333
- for (const dir of [...forms])
334
- if (dir.startsWith(homedir()))
335
- forms.add(`~${dir.slice(homedir().length)}`);
350
+ const forms = shellForms([...dirsOf(entry), entry.baseDir], cwd);
336
351
  if (![...forms].some((form) => command.includes(form)))
337
352
  continue;
338
353
  const current = entry.result.verdict === 'VERIFIED' ? await reverify(entry) : entry;
@@ -399,7 +414,7 @@ export function createMagoSkiExtension(options = {}) {
399
414
  const unverified = inside.find((entry) => entry.result.verdict !== 'VERIFIED');
400
415
  if (unverified)
401
416
  return await judge(unverified, `tool:${toolName}`, unverified.result.verdict, unverified.result.reason);
402
- const entry = inside[0];
417
+ let entry = inside[0];
403
418
  if (!entry)
404
419
  return undefined;
405
420
  if (toolName === 'edit' || toolName === 'write') {
@@ -407,6 +422,11 @@ export function createMagoSkiExtension(options = {}) {
407
422
  }
408
423
  if (toolName !== 'read')
409
424
  return undefined; // find and ls show names, not contents
425
+ // Like the shell, grep and /skill: paths: the whole Skill and its trust are checked again, so a revocation, an expiry
426
+ // or a change to another file of the Skill since the run started also stops a read.
427
+ entry = await reverify(entry);
428
+ if (entry.result.verdict !== 'VERIFIED')
429
+ return await judge(entry, 'tool:read', entry.result.verdict, entry.result.reason);
410
430
  const opened = piReadTarget(piPath);
411
431
  const resolved = await canonical(opened).catch(() => opened);
412
432
  if (!isInside(entry.realDir, resolved)) {
@@ -432,10 +452,7 @@ export function createMagoSkiExtension(options = {}) {
432
452
  const reason = 'mago-ski: Skill verification failed earlier in this run; Skill files are blocked until it succeeds';
433
453
  if (SHELL_TOOLS.has(toolName)) {
434
454
  const command = String(input.command ?? '');
435
- const forms = new Set(knownDirs);
436
- for (const dir of knownDirs)
437
- if (dir.startsWith(homedir()))
438
- forms.add(`~${dir.slice(homedir().length)}`);
455
+ const forms = shellForms(knownDirs, cwd);
439
456
  return [...forms].some((form) => command.includes(form)) ? { block: true, reason } : undefined;
440
457
  }
441
458
  const rawPath = typeof input.path === 'string' && input.path !== '' ? input.path : '.';
@@ -465,7 +482,7 @@ export function createMagoSkiExtension(options = {}) {
465
482
  // Pi lists each Skill's path to the model; a verified Skill whose path is not plainly spelled stays out of the list.
466
483
  const unsafe = new Set();
467
484
  for (const entry of checked) {
468
- const problem = promptPathProblem(entry.filePath, [ctx.cwd, homedir()]);
485
+ const problem = promptPathProblem(entry.filePath, [ctx.cwd, homedir()]) ?? promptPathProblem(entry.baseDir, [ctx.cwd, homedir()]);
469
486
  if (!problem || entry.result.verdict !== 'VERIFIED')
470
487
  continue;
471
488
  unsafe.add(entry.lexDir);
@@ -543,16 +560,19 @@ export function createMagoSkiExtension(options = {}) {
543
560
  const input = event.input;
544
561
  const rawPath = typeof input.path === 'string' && input.path !== '' ? input.path : '.';
545
562
  const { targets, piPath } = await toolTargets(event.toolName, rawPath, ctx.cwd);
546
- const unverified = contained(targets).filter((entry) => entry.result.verdict !== 'VERIFIED');
563
+ // Every unverified Skill, not only those below the searched directory: a link inside it can lead to one elsewhere.
564
+ const unverified = entries.filter((entry) => entry.result.verdict !== 'VERIFIED');
547
565
  if (unverified.length === 0)
548
566
  return undefined;
567
+ const hit = new Set();
568
+ const below = new Set(contained(targets));
549
569
  const content = [...event.content];
550
570
  let list;
551
571
  let removed = 0;
552
572
  for (const [index, item] of content.entries()) {
553
573
  if (item.type !== 'text')
554
574
  continue;
555
- const filtered = await filterListing(item.text, piPath, unverified);
575
+ const filtered = await filterListing(item.text, piPath, unverified, hit);
556
576
  if (!filtered)
557
577
  continue;
558
578
  content[index] = { ...item, text: filtered.text };
@@ -561,8 +581,10 @@ export function createMagoSkiExtension(options = {}) {
561
581
  }
562
582
  if (removed === 0)
563
583
  return undefined;
584
+ // Lines hidden for another reason (not a real path) are attributed to the unverified Skills below the searched directory.
564
585
  for (const entry of unverified)
565
- await judge(entry, `tool:${event.toolName}`, entry.result.verdict, entry.result.reason);
586
+ if (hit.has(entry) || (hit.size === 0 && below.has(entry)))
587
+ await judge(entry, `tool:${event.toolName}`, entry.result.verdict, entry.result.reason);
566
588
  if (!enforcing())
567
589
  return undefined;
568
590
  // The truncation record in `details` carries the unfiltered text too.
@@ -584,7 +606,7 @@ export function createMagoSkiExtension(options = {}) {
584
606
  if (entries.length === 0)
585
607
  return undefined;
586
608
  if (SHELL_TOOLS.has(toolName))
587
- return await checkShell(toolName, typeof input.command === 'string' ? input.command : '');
609
+ return await checkShell(toolName, typeof input.command === 'string' ? input.command : '', ctx.cwd);
588
610
  const rawPath = typeof input.path === 'string' && input.path !== '' ? input.path : '.';
589
611
  return await checkFileTool(toolName, rawPath, ctx.cwd);
590
612
  });
@@ -205,5 +205,6 @@ export declare function approveSkill(options: {
205
205
  skillName: string;
206
206
  digest: string;
207
207
  certificateId: string;
208
- expiresAt: Date;
208
+ expiresAt: Date; /** Paths a `.skilldigestignore` keeps out of the digest: this approval does not cover them. */
209
+ notCovered: string[];
209
210
  }>;
package/dist/src/admin.js CHANGED
@@ -8,7 +8,7 @@ import { validateDigest, validateScope } from "./names.js";
8
8
  import { isDisplaySafeText } from "./root-events.js";
9
9
  import { readRevocationsForUpdate, signRevocations } from "./revocations.js";
10
10
  import { addDuration, truncateToSecond } from "./time.js";
11
- import { CERTIFICATE_FILENAME, collectSkillTree, sha256Hex, requireSkillRoot, SKILL_FILENAME } from "./tree-digest.js";
11
+ import { CERTIFICATE_FILENAME, collectSkillTree, pathsNotCovered, sha256Hex, requireSkillRoot, SKILL_FILENAME } from "./tree-digest.js";
12
12
  import { MAX_APPROVERS, MAX_SCOPES, readTrustRootForUpdate, signTrustRoot } from "./trust-root.js";
13
13
  import { skillNameFromSkillFile } from "./verify.js";
14
14
  export const DEFAULT_TRUST_ROOT_EXPIRY = '365d';
@@ -368,13 +368,14 @@ export async function approveSkill(options) {
368
368
  await options.beforeSign?.({ skillName, digest: tree.digest });
369
369
  const targetPath = options.out
370
370
  ?? (options.outDir === undefined ? path.join(tree.root, CERTIFICATE_FILENAME) : path.join(options.outDir, `${skillName}.cert.json`));
371
+ const parsed = parseCertificate(bytes); // before the write: a certificate that cannot be read back is never left on disk
371
372
  const written = await writeFileAtomic(targetPath, bytes);
372
- const parsed = parseCertificate(bytes);
373
373
  return {
374
374
  path: written,
375
375
  skillName,
376
376
  digest: tree.digest,
377
377
  certificateId: parsed.id,
378
378
  expiresAt,
379
+ notCovered: pathsNotCovered(tree.excluded),
379
380
  };
380
381
  }
@@ -5,6 +5,12 @@ export type JsonValue = null | boolean | number | string | JsonValue[] | {
5
5
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
6
6
  export declare function serializeCanonicalJson(value: unknown): string;
7
7
  export declare function canonicalBytes(value: unknown): Buffer;
8
+ /**
9
+ * canonicalBytes for a document that will be read back with parseCanonicalJsonBytes: refuses bytes the reader would refuse
10
+ * for size. A signed document must not be written when no verifier can load it (a revocation list that grew too large
11
+ * would otherwise replace a working one and block every host).
12
+ */
13
+ export declare function readableCanonicalBytes(value: unknown, label: string): Buffer;
8
14
  export declare function parseCanonicalJsonBytes(input: Uint8Array, label?: string): unknown;
9
15
  export declare function exactKeys(value: unknown, keys: readonly string[], label: string): Record<string, unknown>;
10
16
  export declare function requireString(value: unknown, label: string, maxLength?: number): string;
@@ -65,6 +65,17 @@ export function serializeCanonicalJson(value) {
65
65
  export function canonicalBytes(value) {
66
66
  return Buffer.from(serializeCanonicalJson(value), 'utf8');
67
67
  }
68
+ /**
69
+ * canonicalBytes for a document that will be read back with parseCanonicalJsonBytes: refuses bytes the reader would refuse
70
+ * for size. A signed document must not be written when no verifier can load it (a revocation list that grew too large
71
+ * would otherwise replace a working one and block every host).
72
+ */
73
+ export function readableCanonicalBytes(value, label) {
74
+ const bytes = canonicalBytes(value);
75
+ if (bytes.byteLength > MAX_CANONICAL_JSON_BYTES)
76
+ throw new Error(`${label} would be ${bytes.byteLength} bytes; the limit for a document is ${MAX_CANONICAL_JSON_BYTES} bytes. Nothing was written`);
77
+ return bytes;
78
+ }
68
79
  export function parseCanonicalJsonBytes(input, label = 'JSON document') {
69
80
  let text;
70
81
  let value;
package/dist/src/cli.d.ts CHANGED
@@ -1,2 +1,14 @@
1
1
  #!/usr/bin/env node
2
- export declare function runCli(argv?: string[], now?: Date): Promise<number>;
2
+ import type { AskAdmin } from './gate/admin-client.ts';
3
+ import type { DoctorOptions, InitOptions } from './gate/setup.ts';
4
+ /** Text from a Skill or its folder, for one terminal line: control, line-separator and bidirectional characters are escaped. */
5
+ export declare function terminalSafe(value: string): string;
6
+ export interface GateCliSeams extends Pick<InitOptions, 'base' | 'rootUid' | 'platform' | 'installRoot' | 'nodePath' | 'envPath' | 'checkExec' | 'resolveHostExe' | 'chattr' | 'isImmutable'> {
7
+ /** The calling uid (default process.getuid()). */
8
+ uid?: number;
9
+ ask?: AskAdmin;
10
+ /** `gate run` stops when this settles (default: SIGTERM or SIGINT). */
11
+ stop?: Promise<void>;
12
+ doctor?: Pick<DoctorOptions, 'somaxconn' | 'procMounts' | 'codexVersion' | 'isImmutable'>;
13
+ }
14
+ export declare function runCli(argv?: string[], now?: Date, gateSeams?: GateCliSeams): Promise<number>;