@mago-foundation/mago-ski 0.4.0 → 0.5.0-beta.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 (59) hide show
  1. package/README.md +5 -3
  2. package/action.yml +21 -2
  3. package/dist/hosts/github/check.d.ts +21 -0
  4. package/dist/hosts/github/check.js +124 -0
  5. package/dist/hosts/github/publish.d.ts +7 -0
  6. package/dist/hosts/github/publish.js +52 -0
  7. package/dist/hosts/github/run.d.ts +12 -0
  8. package/dist/hosts/github/run.js +32 -18
  9. package/dist/hosts/pi/index.js +40 -18
  10. package/dist/src/admin.d.ts +2 -1
  11. package/dist/src/admin.js +3 -2
  12. package/dist/src/admission-evidence.d.ts +15 -0
  13. package/dist/src/admission-evidence.js +48 -0
  14. package/dist/src/admission.d.ts +102 -0
  15. package/dist/src/admission.js +316 -0
  16. package/dist/src/canonical-json.d.ts +6 -0
  17. package/dist/src/canonical-json.js +11 -0
  18. package/dist/src/cli.d.ts +2 -0
  19. package/dist/src/cli.js +229 -5
  20. package/dist/src/diff.d.ts +9 -0
  21. package/dist/src/diff.js +3 -2
  22. package/dist/src/dsse.js +2 -2
  23. package/dist/src/experimental/sigstore.d.ts +30 -0
  24. package/dist/src/experimental/sigstore.js +35 -5
  25. package/dist/src/fs-safe.d.ts +15 -2
  26. package/dist/src/fs-safe.js +68 -50
  27. package/dist/src/gate/adapters/claude-code.js +8 -5
  28. package/dist/src/gate/adapters/codex.js +5 -6
  29. package/dist/src/gate/generations.js +2 -0
  30. package/dist/src/gate/instance.js +7 -7
  31. package/dist/src/gate/proc.d.ts +6 -0
  32. package/dist/src/gate/proc.js +14 -3
  33. package/dist/src/gate/service.js +3 -0
  34. package/dist/src/gate/setup.d.ts +5 -5
  35. package/dist/src/gate/setup.js +128 -88
  36. package/dist/src/policy.d.ts +7 -0
  37. package/dist/src/policy.js +19 -2
  38. package/dist/src/profile.d.ts +34 -0
  39. package/dist/src/profile.js +182 -0
  40. package/dist/src/published-by.d.ts +64 -0
  41. package/dist/src/published-by.js +227 -0
  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/dist/src/usf-check.d.ts +28 -0
  48. package/dist/src/usf-check.js +128 -0
  49. package/dist/src/usf.d.ts +48 -0
  50. package/dist/src/usf.js +238 -0
  51. package/docs/hosts/publish.md +65 -0
  52. package/docs/hosts/skill-check.md +91 -0
  53. package/docs/spec/admission-v0.md +84 -0
  54. package/docs/spec/gui-admin-rack-v1.md +1 -1
  55. package/docs/spec/observed-profile-v1.md +51 -0
  56. package/docs/spec/root-recovery-v1.md +3 -2
  57. package/docs/spec/trust-documents-v1.md +1 -1
  58. package/docs/threat-model.md +12 -0
  59. package/package.json +5 -1
package/README.md CHANGED
@@ -41,7 +41,7 @@ Host (Pi, CI) pins the root fingerprint and checks that a certificate chai
41
41
 
42
42
  ## Quickstart
43
43
 
44
- Requires Node.js 22.23.4, 24.22.1 or 26.12.1 or newer in its line (the October 2026 security releases), on Linux or macOS. No runtime dependencies.
44
+ Requires Node.js 22.23.4, 24.22.1 or 26.12.1 or newer in its line (the October 2026 security releases), on Linux or macOS. One runtime dependency: [`yaml`](https://github.com/eemeli/yaml), to read Skill frontmatter as other YAML readers do.
45
45
 
46
46
  ```bash
47
47
  npm install -g @mago-foundation/mago-ski # installs the mago-ski command
@@ -113,6 +113,8 @@ mago-ski 0.4 supports **Linux and macOS** (Node.js 22.23.4, 24.22.1 or 26.12.1 o
113
113
  | Host | What it does | Docs |
114
114
  |---|---|---|
115
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) |
116
+ | **Skill check Action** (free, no keys) | For any Skill repository: shows what each Skill's files contain (websites, scripts, shell code) and, for Skills that declare their needs in an [OWASP USF](https://github.com/OWASP/www-project-agentic-skills-top-10/blob/main/universal-skill-format.md) manifest, fails when the declaration does not cover it. Lists what a pull request adds | [docs/hosts/skill-check.md](docs/hosts/skill-check.md) |
117
+ | **Publish Action** (keyless) | Signs a published-by statement for each Skill with the repository's own GitHub identity (`actions/attest`, public Sigstore log); `mago-ski attestation verify` checks it offline | [docs/hosts/publish.md](docs/hosts/publish.md) |
116
118
  | **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) |
117
119
  | **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
120
  | **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) |
@@ -163,9 +165,9 @@ Capability scanners such as SkilLock report what a Skill change does at pull-req
163
165
 
164
166
  - [What mago-ski can do](docs/capabilities.md): what is released and what is not done, in plain language
165
167
  - [Threat model](docs/threat-model.md): what is and is not protected
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)
168
+ - 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), [observed profile](docs/spec/observed-profile-v1.md) (draft), [admission rules](docs/spec/admission-v0.md) (draft), [GUI administration rack](docs/spec/gui-admin-rack-v1.md) (draft)
167
169
  - [Test vectors](tests/vectors/) for other implementations
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)
170
+ - 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), [Skill check Action](docs/hosts/skill-check.md), [Publish Action](docs/hosts/publish.md), [adapter interface](docs/hosts/adapter-interface.md)
169
171
  - [Live scenario guide](scenarios/START-HERE.md): try the gate with Claude Code or Codex in an isolated Linux environment
170
172
  - [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)
171
173
  - [Security policy](SECURITY.md): how to report a vulnerability
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.
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ import { type SkillCheck } from '../../src/usf-check.ts';
3
+ export interface SkillCheckRunOptions {
4
+ /** Checkout under review. */
5
+ workspace: string;
6
+ /** Where to look for Skills, relative to the workspace. */
7
+ searchPath: string;
8
+ /** Checkout of the pull request's base revision, when there is one. */
9
+ baseRoot?: string;
10
+ /** Fail Skills without a readable USF manifest. */
11
+ requireManifest?: boolean;
12
+ }
13
+ export interface SkillCheckRun {
14
+ checks: SkillCheck[];
15
+ additions: Map<string, string[]>;
16
+ /** Set when the run could not check the repository at all. */
17
+ error?: string;
18
+ exitCode: number;
19
+ summary: string;
20
+ }
21
+ export declare function runSkillCheck({ workspace, searchPath, baseRoot, requireManifest }: SkillCheckRunOptions): Promise<SkillCheckRun>;
@@ -0,0 +1,124 @@
1
+ #!/usr/bin/env node
2
+ // Runner for the free Skill check Action (check/action.yml). No keys, no accounts, no network: it reads the
3
+ // repository, compares each Skill's USF manifest with its files, and on pull requests lists what the change adds.
4
+ // The pass/fail result depends only on the pull request's own files; the base revision only feeds the list of additions.
5
+ import { appendFile, lstat } from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { isMainModule } from "../../src/main-module.js";
8
+ import { findSkillDirs } from "../../src/policy.js";
9
+ import { checkSkill, describeAdditions, suggestedManifest } from "../../src/usf-check.js";
10
+ import { annotationLine, escapeAnnotation, markdownCell, MAX_ANNOTATIONS, MAX_SUMMARY_ROWS, withinReal } from "./run.js";
11
+ async function isDirectory(target) {
12
+ try {
13
+ return (await lstat(target)).isDirectory();
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ export async function runSkillCheck({ workspace, searchPath, baseRoot, requireManifest = false }) {
20
+ const root = path.resolve(workspace);
21
+ const additions = new Map();
22
+ const failed = (error) => ({
23
+ checks: [], additions, error, exitCode: 2, summary: `### mago-ski skill check: could not run\n\n${markdownCell(error)}\n`,
24
+ });
25
+ let skillDirs;
26
+ let tooDeep;
27
+ try {
28
+ const searchRoot = await withinReal(root, path.resolve(root, searchPath), 'path');
29
+ ({ skillDirs, tooDeep } = await findSkillDirs([searchRoot]));
30
+ }
31
+ catch (error) {
32
+ // DiscoveryBudgetError, a path outside the workspace, or an unreadable folder.
33
+ if (error instanceof Error)
34
+ return failed(error.message);
35
+ throw error;
36
+ }
37
+ if (skillDirs.length === 0 && tooDeep.length === 0)
38
+ return failed(`no Skill (a folder with SKILL.md) was found under ${searchPath}`);
39
+ const checks = [];
40
+ for (const skillDir of skillDirs) {
41
+ const check = await checkSkill(skillDir, root, { requireManifest });
42
+ checks.push(check);
43
+ if (baseRoot !== undefined) {
44
+ const baseDir = path.join(path.resolve(baseRoot), check.dir);
45
+ // The base is only described, never trusted; a Skill missing there is new.
46
+ const base = (await isDirectory(baseDir)) ? await checkSkill(baseDir, path.resolve(baseRoot)) : null;
47
+ additions.set(check.dir, describeAdditions(base, check));
48
+ }
49
+ }
50
+ for (const directory of tooDeep) {
51
+ checks.push({
52
+ format: 'owasp.usf/v1.0', dir: path.relative(root, directory), ok: false, profile: null, manifest: null, declared: false, manifestError: null, undeclaredHosts: [],
53
+ problems: ['this folder is too deeply nested; Skills below it were not checked. Point the path input closer to the Skills'], notes: [],
54
+ });
55
+ }
56
+ const failures = checks.filter((check) => !check.ok);
57
+ const ordered = [...failures, ...checks.filter((check) => check.ok)];
58
+ const shown = ordered.slice(0, MAX_SUMMARY_ROWS);
59
+ const lines = [
60
+ `### mago-ski skill check: ${checks.length - failures.length}/${checks.length} Skills pass`,
61
+ '',
62
+ '_Shows what each Skill\'s files contain, and, for Skills that declare their needs in an OWASP Universal Skill Format manifest, whether the declaration covers it. It does not say a Skill is safe._',
63
+ '',
64
+ ];
65
+ for (const check of shown) {
66
+ lines.push(`#### ${check.ok ? 'pass' : 'fail'}: ${markdownCell(check.dir)}`, '');
67
+ for (const problem of check.problems)
68
+ lines.push(`- ${markdownCell(problem)}`);
69
+ if (check.profile) {
70
+ const p = check.profile;
71
+ const none = (values) => (values.length === 0 ? 'none' : values.slice(0, 20).join(', ') + (values.length > 20 ? ` and ${values.length - 20} more` : ''));
72
+ lines.push(`- Websites in its files: ${markdownCell(none(p.web_hosts))}`);
73
+ lines.push(`- Scripts and shell code: ${markdownCell(none(p.scripts.map((s) => `${s.path} (${s.reason})`)))}`);
74
+ if (p.programs.length > 0)
75
+ lines.push(`- Programs named in shell code: ${markdownCell(none(p.programs))}`);
76
+ lines.push(`- Declared in USF: ${check.manifest ? 'yes' : check.declared ? 'unreadable' : 'no'}`);
77
+ }
78
+ const added = additions.get(check.dir);
79
+ if (added && added.length > 0) {
80
+ lines.push('', 'This change:');
81
+ for (const line of added)
82
+ lines.push(`- ${markdownCell(line)}`);
83
+ }
84
+ for (const note of check.notes)
85
+ lines.push(`- _note:_ ${markdownCell(note)}`);
86
+ if ((check.profile !== null && !check.declared) || (!check.ok && check.manifest !== null)) {
87
+ // suggestedManifest lists only plain host names, which cannot close this fence.
88
+ lines.push('', `To declare what was found, add this to the SKILL.md frontmatter (review it first: it lists what the files contain, not what the Skill should be allowed to do):`, '', '```yaml', suggestedManifest(check), '```');
89
+ }
90
+ lines.push('');
91
+ }
92
+ if (ordered.length > MAX_SUMMARY_ROWS)
93
+ lines.push(`_${ordered.length - MAX_SUMMARY_ROWS} more Skills not listed (failures are listed first)._`, '');
94
+ return { checks, additions, exitCode: failures.length > 0 ? 1 : 0, summary: lines.join('\n') };
95
+ }
96
+ async function main() {
97
+ const [workspace, searchPath, requireManifest, baseRoot] = process.argv.slice(2);
98
+ if (!workspace || !searchPath || (requireManifest !== 'true' && requireManifest !== 'false'))
99
+ throw new Error('usage: check.ts WORKSPACE PATH true|false [BASE_ROOT]');
100
+ const result = await runSkillCheck({ workspace, searchPath, requireManifest: requireManifest === 'true', ...(baseRoot ? { baseRoot } : {}) });
101
+ if (result.error)
102
+ process.stdout.write(`::error title=mago-ski skill check::${escapeAnnotation(result.error)}\n`);
103
+ let annotations = 0;
104
+ for (const check of result.checks) {
105
+ if (check.ok)
106
+ continue;
107
+ if (annotations >= MAX_ANNOTATIONS) {
108
+ process.stdout.write(`::notice title=mago-ski skill check::${MAX_ANNOTATIONS} annotations shown; see the job summary for the rest\n`);
109
+ break;
110
+ }
111
+ annotations += 1;
112
+ process.stdout.write(annotationLine('error', path.join(check.dir, 'SKILL.md'), 'skill check', check.problems.join('; ')));
113
+ }
114
+ process.stdout.write(`${result.summary}\n`);
115
+ if (process.env.GITHUB_STEP_SUMMARY)
116
+ await appendFile(process.env.GITHUB_STEP_SUMMARY, `${result.summary}\n`);
117
+ process.exitCode = result.exitCode;
118
+ }
119
+ if (isMainModule(import.meta.url)) {
120
+ main().catch((error) => {
121
+ process.stdout.write(`::error title=mago-ski skill check::${escapeAnnotation(error.message)}\n`);
122
+ process.exitCode = 2;
123
+ });
124
+ }
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { type PublishedByPredicate } from '../../src/published-by.ts';
3
+ export declare function preparePublish(workspace: string, searchPath: string, outDir: string, requireManifest: boolean): Promise<{
4
+ exitCode: number;
5
+ summary: string;
6
+ predicate?: PublishedByPredicate;
7
+ }>;
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+ // Runner for the publish Action (publish/action.yml): checks every Skill like the Skill check Action, and when all
3
+ // pass, writes the published-by predicate and the subject list that actions/attest then signs with the repository's
4
+ // own GitHub identity. Nothing is signed when any Skill fails its check.
5
+ import { mkdir, writeFile } from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { isMainModule } from "../../src/main-module.js";
8
+ import { describeSkill, packageVersion, subjectChecksums } from "../../src/published-by.js";
9
+ import { escapeAnnotation } from "./run.js";
10
+ import { runSkillCheck } from "./check.js";
11
+ export async function preparePublish(workspace, searchPath, outDir, requireManifest) {
12
+ const result = await runSkillCheck({ workspace, searchPath, requireManifest });
13
+ if (result.exitCode !== 0)
14
+ return { exitCode: result.exitCode, summary: `${result.summary}\n_Nothing was signed: every Skill must pass the check first._\n` };
15
+ const root = path.resolve(workspace);
16
+ const skills = [];
17
+ for (const check of result.checks) {
18
+ const skill = await describeSkill(path.join(root, check.dir), root);
19
+ // Sign only the bytes that were checked.
20
+ if (skill.digest !== check.profile?.digest)
21
+ return { exitCode: 2, summary: `${result.summary}\n_Nothing was signed: ${check.dir} changed after it was checked._\n` };
22
+ skills.push(skill);
23
+ }
24
+ const predicate = { generator: { name: 'mago-ski', version: packageVersion() }, skills };
25
+ await mkdir(outDir, { recursive: true, mode: 0o700 });
26
+ await writeFile(path.join(outDir, 'predicate.json'), `${JSON.stringify(predicate)}\n`, { mode: 0o600 });
27
+ await writeFile(path.join(outDir, 'subjects.txt'), subjectChecksums(skills), { mode: 0o600 });
28
+ const rows = skills.map((skill) => `| \`${skill.path.replace(/[`|\\]/gu, '_')}\` | \`${skill.digest}\` |`);
29
+ return {
30
+ exitCode: 0,
31
+ predicate,
32
+ summary: [result.summary, '', `### mago-ski publish: ${skills.length} Skill${skills.length === 1 ? '' : 's'} to sign as published-by`, '', '| Skill | Digest |', '|---|---|', ...rows, ''].join('\n'),
33
+ };
34
+ }
35
+ async function main() {
36
+ const [workspace, searchPath, requireManifest, outDir] = process.argv.slice(2);
37
+ if (!workspace || !searchPath || !outDir || (requireManifest !== 'true' && requireManifest !== 'false'))
38
+ throw new Error('usage: publish.ts WORKSPACE PATH true|false OUT_DIR');
39
+ const result = await preparePublish(workspace, searchPath, outDir, requireManifest === 'true');
40
+ process.stdout.write(`${result.summary}\n`);
41
+ if (process.env.GITHUB_STEP_SUMMARY) {
42
+ const { appendFile } = await import('node:fs/promises');
43
+ await appendFile(process.env.GITHUB_STEP_SUMMARY, `${result.summary}\n`);
44
+ }
45
+ process.exitCode = result.exitCode;
46
+ }
47
+ if (isMainModule(import.meta.url)) {
48
+ main().catch((error) => {
49
+ process.stdout.write(`::error title=mago-ski publish::${escapeAnnotation(error.message)}\n`);
50
+ process.exitCode = 2;
51
+ });
52
+ }
@@ -26,4 +26,16 @@ export interface GitHubCheckResult {
26
26
  }
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
+ export declare function within(root: string, target: string, label: string): string;
30
+ /** Containment on resolved paths, so a symlink cannot point a policy path outside its checkout. */
31
+ export declare function withinReal(root: string, target: string, label: string): Promise<string>;
29
32
  export declare function runGitHubCheck(options: GitHubCheckOptions): Promise<GitHubCheckResult>;
33
+ /** Escapes the message part of a workflow command (after the `::`). */
34
+ export declare function escapeAnnotation(value: string): string;
35
+ /**
36
+ * Escapes a property value of a workflow command (`file=...`). Properties are separated by `,` and end at `::`, so a path
37
+ * from the pull request must not be able to add a property or end the list: `:` and `,` are escaped as well.
38
+ */
39
+ export declare function escapeAnnotationProperty(value: string): string;
40
+ /** One annotation line for a failing Skill. */
41
+ 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";
@@ -19,31 +19,31 @@ export function markdownCell(value) {
19
19
  .replace(/[\\`*_[\]<>|#!~(){}]/gu, (char) => `\\${char}`)
20
20
  .slice(0, 500);
21
21
  }
22
- function within(root, target, label) {
22
+ export function within(root, target, label) {
23
23
  if (!isInside(root, target))
24
24
  throw new Error(`${label} must stay inside ${root}`);
25
25
  return target;
26
26
  }
27
27
  /** Containment on resolved paths, so a symlink cannot point a policy path outside its checkout. */
28
- async function withinReal(root, target, label) {
28
+ export 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
  }
@@ -0,0 +1,15 @@
1
+ import { type Policy } from './policy.ts';
2
+ import type { SkillFacts } from './admission.ts';
3
+ import type { TrustContext } from './verify.ts';
4
+ export interface SigstoreInputs {
5
+ trustedRootPath: string;
6
+ cosignPath: string;
7
+ }
8
+ export interface SkillEvidence {
9
+ /** Organisation policy (mago.policy) whose trust root vouches for reviews; without it no review counts. */
10
+ policy?: Policy;
11
+ trust?: TrustContext;
12
+ /** A published-by bundle for these bytes. */
13
+ publishedBy?: string;
14
+ }
15
+ export declare function collectSkillFacts(skillDir: string, evidence: SkillEvidence, sigstore: SigstoreInputs | undefined, now: Date): Promise<SkillFacts>;