@mago-foundation/mago-ski 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.
Files changed (91) hide show
  1. package/README.md +54 -9
  2. package/action.yml +2 -2
  3. package/dist/hosts/github/run.d.ts +9 -1
  4. package/dist/hosts/github/run.js +64 -11
  5. package/dist/hosts/pi/index.d.ts +5 -3
  6. package/dist/hosts/pi/index.js +219 -14
  7. package/dist/src/admin.d.ts +140 -1
  8. package/dist/src/admin.js +328 -63
  9. package/dist/src/canonical-json.js +73 -28
  10. package/dist/src/certificate.js +23 -15
  11. package/dist/src/cli.js +590 -89
  12. package/dist/src/diff.d.ts +0 -4
  13. package/dist/src/diff.js +326 -70
  14. package/dist/src/dsse.d.ts +6 -4
  15. package/dist/src/dsse.js +22 -6
  16. package/dist/src/fs-safe.d.ts +32 -3
  17. package/dist/src/fs-safe.js +193 -31
  18. package/dist/src/gate/adapters/claude-code-hook.d.ts +1 -0
  19. package/dist/src/gate/adapters/claude-code-hook.js +4 -0
  20. package/dist/src/gate/adapters/claude-code-settings.d.ts +13 -0
  21. package/dist/src/gate/adapters/claude-code-settings.js +49 -0
  22. package/dist/src/gate/adapters/claude-code.d.ts +33 -0
  23. package/dist/src/gate/adapters/claude-code.js +193 -0
  24. package/dist/src/gate/adapters/client.d.ts +13 -0
  25. package/dist/src/gate/adapters/client.js +57 -0
  26. package/dist/src/gate/adapters/codex-hook.d.ts +1 -0
  27. package/dist/src/gate/adapters/codex-hook.js +5 -0
  28. package/dist/src/gate/adapters/codex-requirements.d.ts +19 -0
  29. package/dist/src/gate/adapters/codex-requirements.js +56 -0
  30. package/dist/src/gate/adapters/codex.d.ts +16 -0
  31. package/dist/src/gate/adapters/codex.js +574 -0
  32. package/dist/src/gate/adapters/hook-main.d.ts +7 -0
  33. package/dist/src/gate/adapters/hook-main.js +35 -0
  34. package/dist/src/gate/adapters/host-pid.d.ts +1 -0
  35. package/dist/src/gate/adapters/host-pid.js +20 -0
  36. package/dist/src/gate/admission.d.ts +54 -0
  37. package/dist/src/gate/admission.js +490 -0
  38. package/dist/src/gate/contract.d.ts +51 -0
  39. package/dist/src/gate/contract.js +94 -0
  40. package/dist/src/gate/decision-log.d.ts +38 -0
  41. package/dist/src/gate/decision-log.js +251 -0
  42. package/dist/src/gate/generations.d.ts +67 -0
  43. package/dist/src/gate/generations.js +518 -0
  44. package/dist/src/gate/proc.d.ts +31 -0
  45. package/dist/src/gate/proc.js +79 -0
  46. package/dist/src/gate/refresh.d.ts +11 -0
  47. package/dist/src/gate/refresh.js +30 -0
  48. package/dist/src/gate/run-verifier.d.ts +23 -0
  49. package/dist/src/gate/run-verifier.js +89 -0
  50. package/dist/src/gate/service.d.ts +80 -0
  51. package/dist/src/gate/service.js +722 -0
  52. package/dist/src/gate/strict-json.d.ts +11 -0
  53. package/dist/src/gate/strict-json.js +190 -0
  54. package/dist/src/gate/trust-store.d.ts +36 -0
  55. package/dist/src/gate/trust-store.js +251 -0
  56. package/dist/src/gate/verifier-worker.d.ts +8 -0
  57. package/dist/src/gate/verifier-worker.js +66 -0
  58. package/dist/src/index.d.ts +2 -0
  59. package/dist/src/index.js +2 -0
  60. package/dist/src/keys.d.ts +4 -0
  61. package/dist/src/keys.js +85 -30
  62. package/dist/src/main-module.js +1 -1
  63. package/dist/src/names.js +2 -4
  64. package/dist/src/policy.d.ts +173 -6
  65. package/dist/src/policy.js +685 -54
  66. package/dist/src/recovery-admin.d.ts +173 -0
  67. package/dist/src/recovery-admin.js +400 -0
  68. package/dist/src/revocations.js +3 -1
  69. package/dist/src/root-events.d.ts +107 -0
  70. package/dist/src/root-events.js +376 -0
  71. package/dist/src/time.d.ts +19 -3
  72. package/dist/src/time.js +50 -8
  73. package/dist/src/timestamp.d.ts +61 -0
  74. package/dist/src/timestamp.js +107 -0
  75. package/dist/src/tree-digest.d.ts +4 -0
  76. package/dist/src/tree-digest.js +41 -16
  77. package/dist/src/trust-root.d.ts +5 -0
  78. package/dist/src/trust-root.js +34 -13
  79. package/dist/src/verify.d.ts +69 -13
  80. package/dist/src/verify.js +309 -61
  81. package/docs/hosts/adapter-interface.md +8 -2
  82. package/docs/hosts/github-action.md +3 -3
  83. package/docs/hosts/pi.md +10 -3
  84. package/docs/spec/gui-admin-rack-v1.md +289 -0
  85. package/docs/spec/root-recovery-v1.md +451 -0
  86. package/docs/spec/skill-certificate-v1.md +1 -1
  87. package/docs/spec/skill-tree-v2.md +2 -2
  88. package/docs/spec/trust-documents-v1.md +12 -6
  89. package/docs/spec/verification.md +20 -3
  90. package/docs/threat-model.md +9 -6
  91. package/package.json +49 -44
@@ -1,134 +1,382 @@
1
- import { readFile } from 'node:fs/promises';
2
1
  import path from 'node:path';
3
2
  import { parseCertificate } from "./certificate.js";
4
3
  import { verifyEnvelopeSignature } from "./dsse.js";
5
- import { scopeMatches, skillNameFromFrontmatter, validateSkillName } from "./names.js";
4
+ import { readRegularFile } from "./fs-safe.js";
5
+ import { scopeMatches, skillNameFromFrontmatter, validateDigest, validateSkillName } from "./names.js";
6
6
  import { verifyRevocations } from "./revocations.js";
7
- import { CLOCK_SKEW_MS, formatTimestamp } from "./time.js";
8
- import { collectSkillTree } from "./tree-digest.js";
7
+ import { CLOCK_SKEW_MS, formatTimestamp, requireValidDate } from "./time.js";
8
+ import { collectSkillTree, MAX_FILE_BYTES, SKILL_FILENAME } from "./tree-digest.js";
9
9
  import { TrustDocumentError, verifyTrustRoot } from "./trust-root.js";
10
- export const VERDICTS = ['VERIFIED', 'UNAPPROVED_CHANGE', 'NO_CERTIFICATE', 'UNTRUSTED_SIGNER', 'REVOKED', 'EXPIRED', 'UNVERIFIABLE'];
11
- /** When no certificate verifies, the most informative failure is reported. */
12
- const FAILURE_PRIORITY = ['REVOKED', 'UNAPPROVED_CHANGE', 'EXPIRED', 'UNTRUSTED_SIGNER', 'UNVERIFIABLE', 'NO_CERTIFICATE'];
10
+ export const VERDICTS = [
11
+ 'VERIFIED',
12
+ 'UNAPPROVED_CHANGE',
13
+ 'NO_CERTIFICATE',
14
+ 'UNTRUSTED_SIGNER',
15
+ 'REVOKED',
16
+ 'EXPIRED',
17
+ 'UNVERIFIABLE',
18
+ ];
19
+ /**
20
+ * Precedence rank for candidate selection (lower rank wins):
21
+ * VERIFIED (0) beats all failures, followed by the failure priority order.
22
+ */
23
+ export const VERDICT_RANK = {
24
+ VERIFIED: 0,
25
+ REVOKED: 1,
26
+ UNAPPROVED_CHANGE: 2,
27
+ EXPIRED: 3,
28
+ UNTRUSTED_SIGNER: 4,
29
+ UNVERIFIABLE: 5,
30
+ NO_CERTIFICATE: 6,
31
+ };
32
+ const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
33
+ function errorMessage(error) {
34
+ return error instanceof Error ? error.message : String(error);
35
+ }
36
+ function requireValidMinimumVersion(value, label) {
37
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {
38
+ throw new Error(`${label} must be a positive integer`);
39
+ }
40
+ }
13
41
  /** Verifies the trust root and revocation list once; every Skill check reuses the result. */
14
42
  export function loadTrustContext(options) {
15
43
  try {
44
+ // Inside the try, so a bad clock or minimum version becomes an UNVERIFIABLE result like any other failure here.
45
+ requireValidDate(options.now, 'Verification time');
46
+ if (options.minimum !== undefined) {
47
+ requireValidMinimumVersion(options.minimum.trustRootVersion, 'Minimum trust root version');
48
+ requireValidMinimumVersion(options.minimum.revocationsVersion, 'Minimum revocation list version');
49
+ }
16
50
  const trustRoot = verifyTrustRoot(options.trustRootBytes, options.rootKeyId, options.now);
17
51
  const revocations = verifyRevocations(options.revocationsBytes, trustRoot, options.now);
18
52
  if (options.minimum && trustRoot.version < options.minimum.trustRootVersion) {
19
- return { ok: false, verdict: 'UNVERIFIABLE', reason: `trust root version ${trustRoot.version} is older than version ${options.minimum.trustRootVersion} already seen (rollback)` };
53
+ return {
54
+ ok: false,
55
+ verdict: 'UNVERIFIABLE',
56
+ reason: `trust root version ${trustRoot.version} is older than version ${options.minimum.trustRootVersion} already seen (rollback)`,
57
+ rollback: true,
58
+ };
20
59
  }
21
60
  if (options.minimum && revocations.version < options.minimum.revocationsVersion) {
22
- return { ok: false, verdict: 'UNVERIFIABLE', reason: `revocation list version ${revocations.version} is older than version ${options.minimum.revocationsVersion} already seen (rollback)` };
61
+ return {
62
+ ok: false,
63
+ verdict: 'UNVERIFIABLE',
64
+ reason: `revocation list version ${revocations.version} is older than version ${options.minimum.revocationsVersion} already seen (rollback)`,
65
+ rollback: true,
66
+ };
23
67
  }
24
68
  return { ok: true, context: { trustRoot, revocations } };
25
69
  }
26
70
  catch (error) {
27
- if (error instanceof TrustDocumentError)
71
+ if (error instanceof TrustDocumentError) {
28
72
  return { ok: false, verdict: error.code, reason: error.message };
29
- return { ok: false, verdict: 'UNVERIFIABLE', reason: error.message };
73
+ }
74
+ return { ok: false, verdict: 'UNVERIFIABLE', reason: errorMessage(error) };
30
75
  }
31
76
  }
32
77
  /** Checks one certificate for one Skill: trust chain, scope, signature, expiry, revocation, then bytes. */
33
78
  export function evaluateCertificate(bytes, skillName, digest, context, now) {
79
+ // The issued-in-the-future and expiry checks compare against `now`; an invalid Date would pass them all.
80
+ requireValidDate(now, 'Verification time');
34
81
  let certificate;
35
82
  try {
83
+ validateSkillName(skillName, 'Skill name');
84
+ validateDigest(digest, 'Skill tree digest');
36
85
  certificate = parseCertificate(bytes);
37
86
  }
38
87
  catch (error) {
39
- return { verdict: 'UNVERIFIABLE', reason: `malformed certificate: ${error.message}` };
88
+ return { verdict: 'UNVERIFIABLE', reason: `malformed certificate: ${errorMessage(error)}` };
40
89
  }
41
90
  if (certificate.skillName !== skillName) {
42
- return { verdict: 'NO_CERTIFICATE', reason: `certificate is for Skill "${certificate.skillName}", not "${skillName}"`, certificate };
91
+ return {
92
+ verdict: 'NO_CERTIFICATE',
93
+ reason: `certificate is for Skill "${certificate.skillName}", not "${skillName}"`,
94
+ certificate,
95
+ };
43
96
  }
44
97
  const { trustRoot, revocations } = context;
45
98
  const revokedKey = revocations.keys.find((entry) => entry.keyId === certificate.approverKeyId);
46
- if (revokedKey)
47
- return { verdict: 'REVOKED', reason: `approver key ${certificate.approverKeyId} is revoked: ${revokedKey.reason}`, certificate };
99
+ if (revokedKey) {
100
+ return {
101
+ verdict: 'REVOKED',
102
+ reason: `approver key ${certificate.approverKeyId} is revoked: ${revokedKey.reason}`,
103
+ certificate,
104
+ };
105
+ }
48
106
  const approver = trustRoot.approvers.find((entry) => entry.keyId === certificate.approverKeyId);
49
- if (!approver)
50
- return { verdict: 'UNTRUSTED_SIGNER', reason: `signer ${certificate.approverKeyId} is not an approver in trust root v${trustRoot.version}`, certificate };
107
+ if (!approver) {
108
+ return {
109
+ verdict: 'UNTRUSTED_SIGNER',
110
+ reason: `signer ${certificate.approverKeyId} is not an approver in trust root v${trustRoot.version}`,
111
+ certificate,
112
+ };
113
+ }
51
114
  if (!approver.scopes.some((scope) => scopeMatches(scope, skillName))) {
52
- return { verdict: 'UNTRUSTED_SIGNER', reason: `approver "${approver.name}" is not authorized for Skill "${skillName}" (scopes: ${approver.scopes.join(', ')})`, certificate };
115
+ return {
116
+ verdict: 'UNTRUSTED_SIGNER',
117
+ reason: `approver "${approver.name}" is not authorized for Skill "${skillName}" (scopes: ${approver.scopes.join(', ')})`,
118
+ certificate,
119
+ };
53
120
  }
54
121
  if (!verifyEnvelopeSignature(certificate.envelope, approver.publicKey)) {
55
- return { verdict: 'UNVERIFIABLE', reason: 'certificate signature is invalid', certificate };
122
+ return {
123
+ verdict: 'UNVERIFIABLE',
124
+ reason: 'certificate signature is invalid',
125
+ certificate,
126
+ };
56
127
  }
57
128
  if (certificate.issuedAt.getTime() > now.getTime() + CLOCK_SKEW_MS) {
58
- return { verdict: 'UNVERIFIABLE', reason: `certificate is issued in the future (${formatTimestamp(certificate.issuedAt)})`, certificate };
129
+ return {
130
+ verdict: 'UNVERIFIABLE',
131
+ reason: `certificate is issued in the future (${formatTimestamp(certificate.issuedAt)})`,
132
+ certificate,
133
+ };
59
134
  }
60
135
  if (certificate.issuedAt >= approver.expiresAt) {
61
- return { verdict: 'UNTRUSTED_SIGNER', reason: `certificate was issued after approver "${approver.name}" expired`, certificate };
136
+ return {
137
+ verdict: 'UNTRUSTED_SIGNER',
138
+ reason: `certificate was issued after approver "${approver.name}" expired`,
139
+ certificate,
140
+ };
141
+ }
142
+ if (approver.expiresAt <= now) {
143
+ return {
144
+ verdict: 'EXPIRED',
145
+ reason: `approver "${approver.name}" expired at ${formatTimestamp(approver.expiresAt)}`,
146
+ certificate,
147
+ };
148
+ }
149
+ if (certificate.expiresAt <= now) {
150
+ return {
151
+ verdict: 'EXPIRED',
152
+ reason: `certificate expired at ${formatTimestamp(certificate.expiresAt)}`,
153
+ certificate,
154
+ };
62
155
  }
63
- if (approver.expiresAt <= now)
64
- return { verdict: 'EXPIRED', reason: `approver "${approver.name}" expired at ${formatTimestamp(approver.expiresAt)}`, certificate };
65
- if (certificate.expiresAt <= now)
66
- return { verdict: 'EXPIRED', reason: `certificate expired at ${formatTimestamp(certificate.expiresAt)}`, certificate };
67
156
  const revokedDigest = revocations.digests.find((entry) => entry.digest === certificate.digest);
68
- if (revokedDigest)
69
- return { verdict: 'REVOKED', reason: `approved version ${certificate.digest} is revoked: ${revokedDigest.reason}`, certificate };
157
+ if (revokedDigest) {
158
+ return {
159
+ verdict: 'REVOKED',
160
+ reason: `approved version ${certificate.digest} is revoked: ${revokedDigest.reason}`,
161
+ certificate,
162
+ };
163
+ }
70
164
  if (certificate.digest !== digest) {
71
- return { verdict: 'UNAPPROVED_CHANGE', reason: `Skill bytes changed since approval (approved ${certificate.digest}, found ${digest}); a new certificate is required`, certificate };
165
+ return {
166
+ verdict: 'UNAPPROVED_CHANGE',
167
+ reason: `Skill bytes changed since approval (approved ${certificate.digest}, found ${digest}); a new certificate is required`,
168
+ certificate,
169
+ };
72
170
  }
73
- return { verdict: 'VERIFIED', reason: `approved by "${approver.name}" until ${formatTimestamp(certificate.expiresAt)}`, certificate };
171
+ return {
172
+ verdict: 'VERIFIED',
173
+ reason: `approved by "${approver.name}" until ${formatTimestamp(certificate.expiresAt)}`,
174
+ certificate,
175
+ };
74
176
  }
75
- export async function resolveSkillName(skillDir, explicit) {
76
- if (explicit)
177
+ /**
178
+ * The Skill name from SKILL.md's bytes: an explicit name, else frontmatter "name", else the directory name.
179
+ * Pure, so a caller that hashes and signs those bytes can derive the name from the very same buffer.
180
+ */
181
+ export function skillNameFromSkillFile(skillDir, skillFile, explicit) {
182
+ if (explicit) {
77
183
  return validateSkillName(explicit);
184
+ }
78
185
  let text;
186
+ if (skillFile !== undefined) {
187
+ try {
188
+ text = utf8Decoder.decode(skillFile);
189
+ }
190
+ catch {
191
+ throw new Error(`${SKILL_FILENAME} is not valid UTF-8`);
192
+ }
193
+ }
194
+ const fromFrontmatter = text === undefined ? undefined : skillNameFromFrontmatter(text);
195
+ if (fromFrontmatter) {
196
+ return validateSkillName(fromFrontmatter, `${SKILL_FILENAME} name`);
197
+ }
198
+ return validateSkillName(path.basename(path.resolve(skillDir)), 'Skill directory name');
199
+ }
200
+ /**
201
+ * Resolves the Skill name. SKILL.md comes from an untrusted checkout, so it is read only if it is a regular,
202
+ * non-symlink file no larger than the tree collector's per-file limit; anything else throws (UNVERIFIABLE).
203
+ */
204
+ export async function resolveSkillName(skillDir, explicit) {
205
+ if (explicit) {
206
+ return validateSkillName(explicit);
207
+ }
208
+ let rawBytes;
79
209
  try {
80
- text = await readFile(path.join(skillDir, 'SKILL.md'), 'utf8');
210
+ rawBytes = await readRegularFile(path.join(skillDir, SKILL_FILENAME), SKILL_FILENAME, MAX_FILE_BYTES);
81
211
  }
82
212
  catch (error) {
83
- if (error?.code !== 'ENOENT')
213
+ if (error?.code !== 'ENOENT') {
84
214
  throw error;
215
+ }
85
216
  }
86
- const fromFrontmatter = text === undefined ? undefined : skillNameFromFrontmatter(text);
87
- if (fromFrontmatter)
88
- return validateSkillName(fromFrontmatter, 'SKILL.md name');
89
- return validateSkillName(path.basename(path.resolve(skillDir)), 'Skill directory name');
217
+ return skillNameFromSkillFile(skillDir, rawBytes);
90
218
  }
91
- export function decide(options) {
92
- const base = {
93
- skillName: options.skillName, skillDir: options.tree.root, digest: options.tree.digest,
94
- excluded: options.tree.excluded, checkedAt: formatTimestamp(options.now),
95
- };
96
- if (options.certificates.length === 0) {
97
- return { ...base, verdict: 'NO_CERTIFICATE', reason: 'no certificate found for this Skill', files: null, certificateId: null, certificateSource: null, approverKeyId: null };
98
- }
99
- const evaluations = options.certificates.map((source) => ({
100
- source, evaluation: evaluateCertificate(source.bytes, options.skillName, options.tree.digest, options.context, options.now),
101
- }));
102
- const verified = evaluations.find((entry) => entry.evaluation.verdict === 'VERIFIED');
103
- const chosen = verified ?? evaluations.sort((a, b) => FAILURE_PRIORITY.indexOf(a.evaluation.verdict) - FAILURE_PRIORITY.indexOf(b.evaluation.verdict))[0];
104
- const certificate = chosen.evaluation.certificate;
219
+ /** Keeps the best candidate seen so far: VERIFIED beats any failure, then VERDICT_RANK; the first of equals wins. */
220
+ function selectBetterCandidate(current, next) {
221
+ if (!current) {
222
+ return next;
223
+ }
224
+ const currentRank = VERDICT_RANK[current.evaluation.verdict];
225
+ const nextRank = VERDICT_RANK[next.evaluation.verdict];
226
+ return nextRank < currentRank ? next : current;
227
+ }
228
+ function buildDecision(chosen) {
229
+ if (!chosen) {
230
+ return {
231
+ verdict: 'NO_CERTIFICATE',
232
+ reason: 'no certificate found for this Skill',
233
+ files: null,
234
+ certificateId: null,
235
+ certificateSource: null,
236
+ approverKeyId: null,
237
+ };
238
+ }
239
+ const { evaluation, source } = chosen;
240
+ const certificate = evaluation.certificate;
241
+ const verifiedFiles = evaluation.verdict === 'VERIFIED' && certificate
242
+ ? certificate.files.map((file) => ({ ...file }))
243
+ : null;
105
244
  return {
106
- ...base,
107
- verdict: chosen.evaluation.verdict,
108
- reason: chosen.evaluation.reason,
109
- files: chosen.evaluation.verdict === 'VERIFIED' ? certificate.files : null,
245
+ verdict: evaluation.verdict,
246
+ reason: evaluation.reason,
247
+ files: verifiedFiles,
110
248
  certificateId: certificate?.id ?? null,
111
- certificateSource: chosen.source.source,
249
+ certificateSource: source.source,
112
250
  approverKeyId: certificate?.approverKeyId ?? null,
113
251
  };
114
252
  }
253
+ const MAX_NAMED_PATHS = 3;
254
+ /**
255
+ * Paths come from the Skill (untrusted): quoted, so a name cannot imitate the reason's own wording, and with DEL, C1 controls
256
+ * and bidi or invisible characters escaped, which tree paths may contain and terminals and annotations would apply.
257
+ */
258
+ function quotePath(file) {
259
+ return JSON.stringify(file).replace(/[\u007f-\u009f\u200b-\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069\ufeff]/gu, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
260
+ }
261
+ function namePaths(paths) {
262
+ const shown = paths.slice(0, MAX_NAMED_PATHS).join(', ');
263
+ return paths.length > MAX_NAMED_PATHS ? `${shown} and ${paths.length - MAX_NAMED_PATHS} more` : shown;
264
+ }
265
+ /** Says what differs between the approved file list and the tree on disk, e.g. an executable bit with no byte changed. */
266
+ export function describeTreeChange(approved, found) {
267
+ const before = new Map(approved.map((file) => [file.path, file]));
268
+ const content = [];
269
+ const mode = [];
270
+ const added = [];
271
+ for (const file of found) {
272
+ const old = before.get(file.path);
273
+ before.delete(file.path);
274
+ if (!old) {
275
+ added.push(file.exec ? `${quotePath(file.path)} (executable)` : quotePath(file.path));
276
+ continue;
277
+ }
278
+ if (old.sha256 !== file.sha256 || old.size !== file.size)
279
+ content.push(quotePath(file.path));
280
+ // Reported even when the content changed too: a file becoming executable matters on its own.
281
+ if (old.exec !== file.exec)
282
+ mode.push(`${quotePath(file.path)} (${file.exec ? 'now executable' : 'no longer executable'})`);
283
+ }
284
+ const removed = [...before.keys()].map(quotePath);
285
+ const parts = [
286
+ content.length ? `content changed in ${namePaths(content)}` : '',
287
+ mode.length ? `executable bit changed on ${namePaths(mode)}` : '',
288
+ added.length ? `added ${namePaths(added)}` : '',
289
+ removed.length ? `removed ${namePaths(removed)}` : '',
290
+ ].filter(Boolean);
291
+ return parts.length ? parts.join('; ') : 'files changed';
292
+ }
293
+ /** Replaces the generic UNAPPROVED_CHANGE reason with one naming the changed files, when the certificate lists them. */
294
+ function explainChange(decision, best, tree) {
295
+ const certificate = best?.evaluation.certificate;
296
+ if (decision.verdict !== 'UNAPPROVED_CHANGE' || !certificate)
297
+ return decision;
298
+ return {
299
+ ...decision,
300
+ reason: `Skill changed since approval: ${describeTreeChange(certificate.files, tree.files)} (approved ${certificate.digest}, found ${tree.digest}); a new certificate is required`,
301
+ };
302
+ }
303
+ function buildBaseResult(options) {
304
+ return {
305
+ skillName: options.skillName,
306
+ skillDir: options.tree.root,
307
+ digest: options.tree.digest,
308
+ excluded: [...options.tree.excluded],
309
+ checkedAt: formatTimestamp(options.now),
310
+ };
311
+ }
312
+ export function decide(options) {
313
+ requireValidDate(options.now, 'Verification time');
314
+ let best;
315
+ for (const source of options.certificates) {
316
+ const evaluation = evaluateCertificate(source.bytes, options.skillName, options.tree.digest, options.context, options.now);
317
+ best = selectBetterCandidate(best, { source, evaluation });
318
+ if (evaluation.verdict === 'VERIFIED') {
319
+ break;
320
+ }
321
+ }
322
+ return { ...buildBaseResult(options), ...explainChange(buildDecision(best), best, options.tree) };
323
+ }
324
+ /**
325
+ * Same verdict as `decide`, but candidates are evaluated one at a time as they are produced, so only the best
326
+ * one is retained and the first VERIFIED candidate ends the scan (later candidates are never read).
327
+ */
328
+ export async function decideStreaming(options) {
329
+ requireValidDate(options.now, 'Verification time');
330
+ let best;
331
+ for await (const source of options.certificates) {
332
+ const evaluation = evaluateCertificate(source.bytes, options.skillName, options.tree.digest, options.context, options.now);
333
+ best = selectBetterCandidate(best, { source, evaluation });
334
+ if (evaluation.verdict === 'VERIFIED') {
335
+ break;
336
+ }
337
+ }
338
+ return { ...buildBaseResult(options), ...explainChange(buildDecision(best), best, options.tree) };
339
+ }
115
340
  /** Full check of one Skill directory against an already-verified trust context. */
116
341
  export async function verifySkill(options) {
342
+ // Before the try: its catch builds an UNVERIFIABLE result, which needs a valid time for `checkedAt`.
343
+ requireValidDate(options.now, 'Verification time');
117
344
  const skillDir = path.resolve(options.skillDir);
118
345
  let skillName = options.skillName ?? path.basename(skillDir);
119
346
  try {
120
347
  skillName = await resolveSkillName(skillDir, options.skillName);
121
348
  const tree = await collectSkillTree(skillDir);
122
- const certificates = typeof options.certificates === 'function' ? await options.certificates(skillName, tree.root) : options.certificates;
123
- return decide({ skillDir, skillName, tree, certificates, context: options.context, now: options.now });
349
+ const provided = typeof options.certificates === 'function'
350
+ ? options.certificates(skillName, tree.root)
351
+ : options.certificates;
352
+ const certificates = Symbol.asyncIterator in provided ? provided : await provided;
353
+ return await decideStreaming({
354
+ skillDir,
355
+ skillName,
356
+ tree,
357
+ certificates,
358
+ context: options.context,
359
+ now: options.now,
360
+ });
124
361
  }
125
362
  catch (error) {
126
- return unverifiable(skillDir, skillName, error.message, options.now);
363
+ return unverifiable(skillDir, skillName, errorMessage(error), options.now);
127
364
  }
128
365
  }
129
366
  export function unverifiable(skillDir, skillName, reason, now, verdict = 'UNVERIFIABLE') {
367
+ requireValidDate(now, 'Verification time');
368
+ const safeVerdict = verdict === 'VERIFIED' || !Object.hasOwn(VERDICT_RANK, verdict) ? 'UNVERIFIABLE' : verdict;
130
369
  return {
131
- verdict, reason, skillName, skillDir, digest: null, files: null, certificateId: null,
132
- certificateSource: null, approverKeyId: null, excluded: [], checkedAt: formatTimestamp(now),
370
+ verdict: safeVerdict,
371
+ reason,
372
+ skillName,
373
+ skillDir,
374
+ digest: null,
375
+ files: null,
376
+ certificateId: null,
377
+ certificateSource: null,
378
+ approverKeyId: null,
379
+ excluded: [],
380
+ checkedAt: formatTimestamp(now),
133
381
  };
134
382
  }
@@ -28,6 +28,12 @@ const current = await hashFile(absolutePath, relativePath); // compare with res
28
28
  await appendDecision(policy.decisionLogPath, decisionRecord(result, policy.mode, 'advertise'));
29
29
  ```
30
30
 
31
- ## Claude Code (planned)
31
+ When `loadPolicyTrust` fails, report it once for the host (`trustFailureRecord`), not once per Skill. If the failure has `rootRevoked: true`, block every Skill **whatever the policy mode** (`effectiveMode(policy.mode, trust)` returns `enforce`): a root key revoked by a root event blocks in shadow mode too ([Root recovery](../spec/root-recovery-v1.md#revoked-root-blocked-in-every-mode)).
32
32
 
33
- Claude Code hooks (`PreToolUse`, `UserPromptSubmit`) cover H2–H5. Whether H1 is possible (removing a Skill from what the model is told) needs the same spike Pi had; if not, the verified-install store applies.
33
+ ## Claude Code (built, not yet tested live)
34
+
35
+ The [Claude Code spike](../spikes/claude-code-interception.md) found that no hook can change the Skill list (H1) and that a project's settings can turn user hooks off, so enforcement needs managed settings. Without them, only shadow mode is possible.
36
+
37
+ The company gate (`src/gate/`, Linux only, not yet released) follows that finding with one change of store. Instead of a mago-ski plugin holding verified copies (the spike's proposal), the gate service installs approved Skills into Claude Code's admin-managed Skill folder (each `<folder>/<name>` is a link to the verified, read-only copy, removed on uninstall or revocation), and the generated managed settings (`src/gate/adapters/claude-code-settings.ts`) set `strictPluginOnlyCustomization: ["skills", "hooks", "agents", "mcp"]`, an empty `strictKnownMarketplaces` and `disableSideloadFlags`, so only managed-folder Skills load. Managed `PreToolUse` (Skill tool) and `UserPromptExpansion` (`/name`) hooks ask the service about every use (H2–H5) and block when it cannot answer. The plugin store stays a possible alternative; both kinds of Skill ran under the lock in our earlier tests. The [live test](../spikes/claude-code-gate-live.md) ran this setup against the real Claude Code 2.1.318 in non-interactive mode (`-p`), with the real service and hook: only gate-installed Skills (symlinks in the managed folder) were listed and loaded, planted and revoked Skills were denied by the hooks, and with the service stopped every use was denied. It passed as root and with Claude Code running as an unprivileged user. Interactive sessions and subagents are not covered by it yet.
38
+
39
+ The same gate serves Codex through `/etc/codex/requirements.toml` and the Codex hook adapter. Its [live test](../spikes/codex-gate-live.md) (codex-cli 0.163.0 and 0.166.0) shows weaker coverage. Codex has no Skill lock, and `deny_read` does not hide user Skills from its catalog, so repo and user Skills stay listed and only the hooks stop their use. The hooks did block every route tested, and failed closed. Because Codex always installs its own bundled Skills, an admin Skill can be invoked only by its linked mention `[$name](/etc/codex/skills/name/SKILL.md)`, never by a bare `$name`.
@@ -20,7 +20,7 @@ jobs:
20
20
  policy: .mago-ski/policy.json
21
21
  ```
22
22
 
23
- Use a Linux or macOS runner; the action stops on Windows runners (not supported in 0.1). Pin the action to a full commit SHA: the verifier runs from the action's own checkout, so the pin decides which verifier code runs.
23
+ Use a Linux or macOS runner; the action stops on Windows runners (not supported yet). Pin the action to a full commit SHA: the verifier runs from the action's own checkout, so the pin decides which verifier code runs.
24
24
 
25
25
  ## Repository layout
26
26
 
@@ -38,8 +38,8 @@ skills/
38
38
 
39
39
  On pull requests, `policy.json`, `trust-root.json` and `revocations.json` are read from the **base** revision. A pull request can add or update certificates (they are signed), but changes it makes to the trust documents take effect only after merge, so a pull request cannot add its own approver. Certificate directories and Skill directories are read from the pull request.
40
40
 
41
- Symlinked Skill directories and symlinked `SKILL.md` files are reported as `UNVERIFIABLE`, not skipped (Pi follows such links). Discovery searches up to 16 directory levels below each `skill_dirs` entry. Anything deeper is reported as `UNVERIFIABLE` instead of being skipped: it fails the check in `enforce` mode and is reported in `shadow` mode. Policy, trust and Skill directories must resolve inside their checkout.
41
+ Symlinked Skill directories and symlinked `SKILL.md` files are reported as `UNVERIFIABLE`, not skipped (Pi follows such links). Discovery searches up to 16 directory levels below each `skill_dirs` entry. Anything deeper is reported as `UNVERIFIABLE` instead of being skipped: it fails the check in `enforce` mode and is reported in `shadow` mode. Discovery is bounded (1,000 Skills, 50,000 directory entries); a larger tree is reported as a single failure and no Skill is checked. Policy, trust and Skill directories must resolve inside their checkout.
42
42
 
43
- The action writes a summary table to the job summary and an annotation on each failing Skill's `SKILL.md`. In `shadow` mode it reports but does not fail. CI keeps no state file; rollback protection comes from reading trust documents from the protected base revision.
43
+ The action writes a summary table to the job summary (at most 200 Skills, failures first) and an annotation on each failing Skill's `SKILL.md` (at most 50; a notice says when more were omitted, and the summary has the rest). In `shadow` mode it reports but does not fail. When the trust documents fail (trust root, revocation list, root event log, timestamp), the summary has one line and no per-Skill rows; a root key revoked by a root event fails the check in `shadow` mode too. CI keeps no state file; rollback protection comes from reading trust documents from the protected base revision.
44
44
 
45
45
  Run it alongside a capability scanner such as SkilLock: the scanner explains what changed, mago-ski makes sure someone approved exactly that.
package/docs/hosts/pi.md CHANGED
@@ -5,13 +5,15 @@ The Pi extension (`hosts/pi/index.ts`) enforces certificates inside a normal [Pi
5
5
  ## Install
6
6
 
7
7
  ```bash
8
- pi install npm:@mago-foundation/mago-ski@0.1.0 # or for one session: pi -e npm:@mago-foundation/mago-ski@0.1.0
8
+ pi install npm:@mago-foundation/mago-ski # or for one session: pi -e npm:@mago-foundation/mago-ski
9
9
  mkdir -p ~/.mago-ski
10
10
  cp policy.json trust-root.json revocations.json ~/.mago-ski/
11
11
  ```
12
12
 
13
13
  The extension reads its policy from `MAGO_SKI_POLICY` or `~/.mago-ski/policy.json`. It never reads policy from the project directory, because project files may be controlled by the code under review. Without a policy it warns once and checks nothing. If a policy exists but cannot be loaded, it blocks every Skill.
14
14
 
15
+ `MAGO_SKI_POLICY` (and the `policyPath` option of the extension) must be an absolute path, or start with `~/`. A relative path is refused, because it would resolve against whatever directory Pi was started in. A path that resolves inside the project is refused too: the session directory, or the repository containing it (the nearest `.git`, searched up to but not including your home directory), after following symlinks. Paths under `~/.mago-ski/` are always accepted. A refused path is treated like a policy that cannot be loaded: every Skill is blocked and Pi shows an error naming the reason. It never falls back to the home default.
16
+
15
17
  Start in `"mode": "shadow"` to see what would be blocked (the decision log records `would-block`), then switch to `"enforce"`.
16
18
 
17
19
  ## What it does
@@ -21,15 +23,20 @@ Start in `"mode": "shadow"` to see what would be blocked (the decision log recor
21
23
  | Before each run (`before_agent_start`) | Verifies every discovered Skill; only `VERIFIED` Skills stay in the list sent to the model. Status bar: `mago-ski enforce: 3/4 Skills verified` | Same check, nothing removed |
22
24
  | `/skill:name` (`input`) | Verified: re-verified and expanded from the verified bytes, so Pi never re-reads the file. Unverified: refused, the model is not called. Not seen yet in this session: rewritten into a plain request, so Pi does not expand it unchecked | Allowed |
23
25
  | `read`, `find`, `ls`, `edit`, `write` (`tool_call`) | Refused for paths in unverified Skills. Paths are resolved the way Pi's tools resolve them (a leading `@`, `file://` URLs, `~`, Unicode spaces, Windows shell paths, and the filename variants `read` tries), and matched both before and after resolving symlinks. Reads from verified Skills are re-hashed against the certificate; changed files, files not in the certificate, and paths that leave the Skill through a link are refused. Edits to verified Skills are refused. `find` and `ls` of verified Skills are allowed (names only) | Logged |
26
+ | `find`, `ls` over a directory that contains unverified Skills (`tool_result`) | The call runs, but entries that are, or are inside, an unverified Skill are removed from the result before the model sees it (links into one included), and a fixed note says how many were hidden. A line that does not name a real path (part of a file name containing a newline) is removed as well. Verified Skills and everything else stay listed | Result unchanged; logged |
24
27
  | `grep` | Refused when it searches in or over an unverified Skill, or a verified Skill that has files excluded from its certificate (`.git`, ignored files, or an in-tree `.mago-ski-cert.json` that is not the certificate that verified the Skill). Otherwise the Skill is re-verified first and its exclusions checked again | Logged |
25
28
  | `bash`, `powershell` | Refused when the command names an unverified Skill's directory; verified Skills it names are re-verified first. Best-effort (see the [threat model](../threat-model.md)) | Logged |
26
29
  | Verification error | A Skill that cannot be checked is `UNVERIFIABLE`. If checking crashes outright, no Skills are advertised and file and shell tools touching any Skill path are blocked for that run | Logged |
30
+ | Trust documents fail (trust root, revocation list, root event log, timestamp) | Every Skill is blocked. One notice when the failure starts or changes, the status bar shows it, and one `trust-unavailable` decision record; no per-Skill notices or records | Same report, nothing blocked (`would-block`) |
31
+ | Root key revoked by a root event | Every Skill is blocked. Status bar: `mago-ski: ROOT KEY REVOKED - all Skills blocked`; one error notice and one `root-revoked` record | **Blocked as in enforce mode.** Switching to shadow mode does not help; only a rotate root event does |
32
+
33
+ Skill paths are shown to the model in Pi's Skill list and in the `/skill:` block, but the certificate does not cover the Skill directory, so a contributor can rename it. Below your working directory and your home directory, a Skill path may therefore use only `A-Z a-z 0-9 . _ / ~ @ + -`. A verified Skill with any other character in its path (spaces, non-ASCII letters, newlines, quotes, angle brackets) is not advertised and `/skill:` refuses it with a notice; rename or move the directory. The working and home directories themselves may contain spaces, but not control, quote or angle-bracket characters. Skill names are already limited to ASCII letters, digits, `.`, `_` and `-`.
27
34
 
28
- When a verdict changes, it is written to the policy's `decision_log` (if configured and writable) with the event, verdict and reason. Verdicts other than `VERIFIED` are also shown as a notification when Pi has a UI.
35
+ When a verdict changes, it is written to the policy's `decision_log` (if configured and writable; it must be a regular file inside the policy's directory) with the event, verdict and reason. Verdicts other than `VERIFIED` are also shown as a notification when Pi has a UI.
29
36
 
30
37
  ## Limits
31
38
 
32
- - Linux and macOS only in 0.1. On Windows the extension shows a warning: executable bits are not covered, so Skills approved elsewhere may not verify.
39
+ - Linux and macOS only. On Windows the extension shows a warning: executable bits are not covered, so Skills approved elsewhere may not verify.
33
40
  - Standalone Markdown Skills (a `.md` file without its own directory and `SKILL.md`) cannot be certified and are always unverified.
34
41
  - Pi runs extensions in load order; another extension can change the Skill list after mago-ski. Load mago-ski last.
35
42
  - Custom tools and MCP tools that read files are not checked.