@mago-foundation/mago-ski 0.1.0 → 0.2.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.
@@ -20,21 +20,11 @@ export type TrustContextResult = {
20
20
  verdict: 'EXPIRED' | 'UNVERIFIABLE';
21
21
  reason: string;
22
22
  };
23
- /** Verifies the trust root and revocation list once; every Skill check reuses the result. */
24
- export declare function loadTrustContext(options: {
25
- trustRootBytes: Uint8Array;
26
- revocationsBytes: Uint8Array;
27
- rootKeyId: string;
28
- now: Date;
29
- minimum?: MinimumVersions | undefined;
30
- }): TrustContextResult;
31
23
  export interface CertificateEvaluation {
32
24
  verdict: Verdict;
33
25
  reason: string;
34
26
  certificate?: Certificate;
35
27
  }
36
- /** Checks one certificate for one Skill: trust chain, scope, signature, expiry, revocation, then bytes. */
37
- export declare function evaluateCertificate(bytes: Uint8Array, skillName: string, digest: string, context: TrustContext, now: Date): CertificateEvaluation;
38
28
  export interface CertificateSource {
39
29
  source: string;
40
30
  bytes: Uint8Array;
@@ -53,21 +43,54 @@ export interface VerificationResult {
53
43
  excluded: string[];
54
44
  checkedAt: string;
55
45
  }
46
+ /** Verifies the trust root and revocation list once; every Skill check reuses the result. */
47
+ export declare function loadTrustContext(options: {
48
+ trustRootBytes: Uint8Array;
49
+ revocationsBytes: Uint8Array;
50
+ rootKeyId: string;
51
+ now: Date;
52
+ minimum?: MinimumVersions | undefined;
53
+ }): TrustContextResult;
54
+ /** Checks one certificate for one Skill: trust chain, scope, signature, expiry, revocation, then bytes. */
55
+ export declare function evaluateCertificate(bytes: Uint8Array, skillName: string, digest: string, context: TrustContext, now: Date): CertificateEvaluation;
56
+ /**
57
+ * The Skill name from SKILL.md's bytes: an explicit name, else frontmatter "name", else the directory name.
58
+ * Pure, so a caller that hashes and signs those bytes can derive the name from the very same buffer.
59
+ */
60
+ export declare function skillNameFromSkillFile(skillDir: string, skillFile: Uint8Array | undefined, explicit?: string): string;
61
+ /**
62
+ * Resolves the Skill name. SKILL.md comes from an untrusted checkout, so it is read only if it is a regular,
63
+ * non-symlink file no larger than the tree collector's per-file limit; anything else throws (UNVERIFIABLE).
64
+ */
56
65
  export declare function resolveSkillName(skillDir: string, explicit?: string): Promise<string>;
66
+ /** Says what differs between the approved file list and the tree on disk, e.g. an executable bit with no byte changed. */
67
+ export declare function describeTreeChange(approved: readonly TreeFile[], found: readonly TreeFile[]): string;
57
68
  export declare function decide(options: {
58
69
  skillDir: string;
59
70
  skillName: string;
60
71
  tree: SkillTree;
61
- certificates: CertificateSource[];
72
+ certificates: readonly CertificateSource[];
62
73
  context: TrustContext;
63
74
  now: Date;
64
75
  }): VerificationResult;
76
+ /**
77
+ * Same verdict as `decide`, but candidates are evaluated one at a time as they are produced, so only the best
78
+ * one is retained and the first VERIFIED candidate ends the scan (later candidates are never read).
79
+ */
80
+ export declare function decideStreaming(options: {
81
+ skillDir: string;
82
+ skillName: string;
83
+ tree: SkillTree;
84
+ certificates: AsyncIterable<CertificateSource> | Iterable<CertificateSource>;
85
+ context: TrustContext;
86
+ now: Date;
87
+ }): Promise<VerificationResult>;
65
88
  /** Full check of one Skill directory against an already-verified trust context. */
66
89
  export declare function verifySkill(options: {
67
90
  skillDir: string;
68
91
  skillName?: string | undefined;
69
- certificates: CertificateSource[] | ((skillName: string, root: string) => Promise<CertificateSource[]>);
92
+ certificates: readonly CertificateSource[] | ((skillName: string, root: string) => Promise<readonly CertificateSource[]> | AsyncIterable<CertificateSource>);
70
93
  context: TrustContext;
71
94
  now: Date;
72
95
  }): Promise<VerificationResult>;
73
- export declare function unverifiable(skillDir: string, skillName: string, reason: string, now: Date, verdict?: Verdict): VerificationResult;
96
+ export declare function unverifiable(skillDir: string, skillName: string, reason: string, now: Date, verdict?: Exclude<Verdict, 'VERIFIED'>): VerificationResult;
@@ -1,134 +1,380 @@
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
+ 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
+ };
20
58
  }
21
59
  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)` };
60
+ return {
61
+ ok: false,
62
+ verdict: 'UNVERIFIABLE',
63
+ reason: `revocation list version ${revocations.version} is older than version ${options.minimum.revocationsVersion} already seen (rollback)`,
64
+ };
23
65
  }
24
66
  return { ok: true, context: { trustRoot, revocations } };
25
67
  }
26
68
  catch (error) {
27
- if (error instanceof TrustDocumentError)
69
+ if (error instanceof TrustDocumentError) {
28
70
  return { ok: false, verdict: error.code, reason: error.message };
29
- return { ok: false, verdict: 'UNVERIFIABLE', reason: error.message };
71
+ }
72
+ return { ok: false, verdict: 'UNVERIFIABLE', reason: errorMessage(error) };
30
73
  }
31
74
  }
32
75
  /** Checks one certificate for one Skill: trust chain, scope, signature, expiry, revocation, then bytes. */
33
76
  export function evaluateCertificate(bytes, skillName, digest, context, now) {
77
+ // The issued-in-the-future and expiry checks compare against `now`; an invalid Date would pass them all.
78
+ requireValidDate(now, 'Verification time');
34
79
  let certificate;
35
80
  try {
81
+ validateSkillName(skillName, 'Skill name');
82
+ validateDigest(digest, 'Skill tree digest');
36
83
  certificate = parseCertificate(bytes);
37
84
  }
38
85
  catch (error) {
39
- return { verdict: 'UNVERIFIABLE', reason: `malformed certificate: ${error.message}` };
86
+ return { verdict: 'UNVERIFIABLE', reason: `malformed certificate: ${errorMessage(error)}` };
40
87
  }
41
88
  if (certificate.skillName !== skillName) {
42
- return { verdict: 'NO_CERTIFICATE', reason: `certificate is for Skill "${certificate.skillName}", not "${skillName}"`, certificate };
89
+ return {
90
+ verdict: 'NO_CERTIFICATE',
91
+ reason: `certificate is for Skill "${certificate.skillName}", not "${skillName}"`,
92
+ certificate,
93
+ };
43
94
  }
44
95
  const { trustRoot, revocations } = context;
45
96
  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 };
97
+ if (revokedKey) {
98
+ return {
99
+ verdict: 'REVOKED',
100
+ reason: `approver key ${certificate.approverKeyId} is revoked: ${revokedKey.reason}`,
101
+ certificate,
102
+ };
103
+ }
48
104
  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 };
105
+ if (!approver) {
106
+ return {
107
+ verdict: 'UNTRUSTED_SIGNER',
108
+ reason: `signer ${certificate.approverKeyId} is not an approver in trust root v${trustRoot.version}`,
109
+ certificate,
110
+ };
111
+ }
51
112
  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 };
113
+ return {
114
+ verdict: 'UNTRUSTED_SIGNER',
115
+ reason: `approver "${approver.name}" is not authorized for Skill "${skillName}" (scopes: ${approver.scopes.join(', ')})`,
116
+ certificate,
117
+ };
53
118
  }
54
119
  if (!verifyEnvelopeSignature(certificate.envelope, approver.publicKey)) {
55
- return { verdict: 'UNVERIFIABLE', reason: 'certificate signature is invalid', certificate };
120
+ return {
121
+ verdict: 'UNVERIFIABLE',
122
+ reason: 'certificate signature is invalid',
123
+ certificate,
124
+ };
56
125
  }
57
126
  if (certificate.issuedAt.getTime() > now.getTime() + CLOCK_SKEW_MS) {
58
- return { verdict: 'UNVERIFIABLE', reason: `certificate is issued in the future (${formatTimestamp(certificate.issuedAt)})`, certificate };
127
+ return {
128
+ verdict: 'UNVERIFIABLE',
129
+ reason: `certificate is issued in the future (${formatTimestamp(certificate.issuedAt)})`,
130
+ certificate,
131
+ };
59
132
  }
60
133
  if (certificate.issuedAt >= approver.expiresAt) {
61
- return { verdict: 'UNTRUSTED_SIGNER', reason: `certificate was issued after approver "${approver.name}" expired`, certificate };
134
+ return {
135
+ verdict: 'UNTRUSTED_SIGNER',
136
+ reason: `certificate was issued after approver "${approver.name}" expired`,
137
+ certificate,
138
+ };
139
+ }
140
+ if (approver.expiresAt <= now) {
141
+ return {
142
+ verdict: 'EXPIRED',
143
+ reason: `approver "${approver.name}" expired at ${formatTimestamp(approver.expiresAt)}`,
144
+ certificate,
145
+ };
146
+ }
147
+ if (certificate.expiresAt <= now) {
148
+ return {
149
+ verdict: 'EXPIRED',
150
+ reason: `certificate expired at ${formatTimestamp(certificate.expiresAt)}`,
151
+ certificate,
152
+ };
62
153
  }
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
154
  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 };
155
+ if (revokedDigest) {
156
+ return {
157
+ verdict: 'REVOKED',
158
+ reason: `approved version ${certificate.digest} is revoked: ${revokedDigest.reason}`,
159
+ certificate,
160
+ };
161
+ }
70
162
  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 };
163
+ return {
164
+ verdict: 'UNAPPROVED_CHANGE',
165
+ reason: `Skill bytes changed since approval (approved ${certificate.digest}, found ${digest}); a new certificate is required`,
166
+ certificate,
167
+ };
72
168
  }
73
- return { verdict: 'VERIFIED', reason: `approved by "${approver.name}" until ${formatTimestamp(certificate.expiresAt)}`, certificate };
169
+ return {
170
+ verdict: 'VERIFIED',
171
+ reason: `approved by "${approver.name}" until ${formatTimestamp(certificate.expiresAt)}`,
172
+ certificate,
173
+ };
74
174
  }
75
- export async function resolveSkillName(skillDir, explicit) {
76
- if (explicit)
175
+ /**
176
+ * The Skill name from SKILL.md's bytes: an explicit name, else frontmatter "name", else the directory name.
177
+ * Pure, so a caller that hashes and signs those bytes can derive the name from the very same buffer.
178
+ */
179
+ export function skillNameFromSkillFile(skillDir, skillFile, explicit) {
180
+ if (explicit) {
77
181
  return validateSkillName(explicit);
182
+ }
78
183
  let text;
184
+ if (skillFile !== undefined) {
185
+ try {
186
+ text = utf8Decoder.decode(skillFile);
187
+ }
188
+ catch {
189
+ throw new Error(`${SKILL_FILENAME} is not valid UTF-8`);
190
+ }
191
+ }
192
+ const fromFrontmatter = text === undefined ? undefined : skillNameFromFrontmatter(text);
193
+ if (fromFrontmatter) {
194
+ return validateSkillName(fromFrontmatter, `${SKILL_FILENAME} name`);
195
+ }
196
+ return validateSkillName(path.basename(path.resolve(skillDir)), 'Skill directory name');
197
+ }
198
+ /**
199
+ * Resolves the Skill name. SKILL.md comes from an untrusted checkout, so it is read only if it is a regular,
200
+ * non-symlink file no larger than the tree collector's per-file limit; anything else throws (UNVERIFIABLE).
201
+ */
202
+ export async function resolveSkillName(skillDir, explicit) {
203
+ if (explicit) {
204
+ return validateSkillName(explicit);
205
+ }
206
+ let rawBytes;
79
207
  try {
80
- text = await readFile(path.join(skillDir, 'SKILL.md'), 'utf8');
208
+ rawBytes = await readRegularFile(path.join(skillDir, SKILL_FILENAME), SKILL_FILENAME, MAX_FILE_BYTES);
81
209
  }
82
210
  catch (error) {
83
- if (error?.code !== 'ENOENT')
211
+ if (error?.code !== 'ENOENT') {
84
212
  throw error;
213
+ }
85
214
  }
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');
215
+ return skillNameFromSkillFile(skillDir, rawBytes);
90
216
  }
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;
217
+ /** Keeps the best candidate seen so far: VERIFIED beats any failure, then VERDICT_RANK; the first of equals wins. */
218
+ function selectBetterCandidate(current, next) {
219
+ if (!current) {
220
+ return next;
221
+ }
222
+ const currentRank = VERDICT_RANK[current.evaluation.verdict];
223
+ const nextRank = VERDICT_RANK[next.evaluation.verdict];
224
+ return nextRank < currentRank ? next : current;
225
+ }
226
+ function buildDecision(chosen) {
227
+ if (!chosen) {
228
+ return {
229
+ verdict: 'NO_CERTIFICATE',
230
+ reason: 'no certificate found for this Skill',
231
+ files: null,
232
+ certificateId: null,
233
+ certificateSource: null,
234
+ approverKeyId: null,
235
+ };
236
+ }
237
+ const { evaluation, source } = chosen;
238
+ const certificate = evaluation.certificate;
239
+ const verifiedFiles = evaluation.verdict === 'VERIFIED' && certificate
240
+ ? certificate.files.map((file) => ({ ...file }))
241
+ : null;
105
242
  return {
106
- ...base,
107
- verdict: chosen.evaluation.verdict,
108
- reason: chosen.evaluation.reason,
109
- files: chosen.evaluation.verdict === 'VERIFIED' ? certificate.files : null,
243
+ verdict: evaluation.verdict,
244
+ reason: evaluation.reason,
245
+ files: verifiedFiles,
110
246
  certificateId: certificate?.id ?? null,
111
- certificateSource: chosen.source.source,
247
+ certificateSource: source.source,
112
248
  approverKeyId: certificate?.approverKeyId ?? null,
113
249
  };
114
250
  }
251
+ const MAX_NAMED_PATHS = 3;
252
+ /**
253
+ * Paths come from the Skill (untrusted): quoted, so a name cannot imitate the reason's own wording, and with DEL, C1 controls
254
+ * and bidi or invisible characters escaped, which tree paths may contain and terminals and annotations would apply.
255
+ */
256
+ function quotePath(file) {
257
+ 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')}`);
258
+ }
259
+ function namePaths(paths) {
260
+ const shown = paths.slice(0, MAX_NAMED_PATHS).join(', ');
261
+ return paths.length > MAX_NAMED_PATHS ? `${shown} and ${paths.length - MAX_NAMED_PATHS} more` : shown;
262
+ }
263
+ /** Says what differs between the approved file list and the tree on disk, e.g. an executable bit with no byte changed. */
264
+ export function describeTreeChange(approved, found) {
265
+ const before = new Map(approved.map((file) => [file.path, file]));
266
+ const content = [];
267
+ const mode = [];
268
+ const added = [];
269
+ for (const file of found) {
270
+ const old = before.get(file.path);
271
+ before.delete(file.path);
272
+ if (!old) {
273
+ added.push(file.exec ? `${quotePath(file.path)} (executable)` : quotePath(file.path));
274
+ continue;
275
+ }
276
+ if (old.sha256 !== file.sha256 || old.size !== file.size)
277
+ content.push(quotePath(file.path));
278
+ // Reported even when the content changed too: a file becoming executable matters on its own.
279
+ if (old.exec !== file.exec)
280
+ mode.push(`${quotePath(file.path)} (${file.exec ? 'now executable' : 'no longer executable'})`);
281
+ }
282
+ const removed = [...before.keys()].map(quotePath);
283
+ const parts = [
284
+ content.length ? `content changed in ${namePaths(content)}` : '',
285
+ mode.length ? `executable bit changed on ${namePaths(mode)}` : '',
286
+ added.length ? `added ${namePaths(added)}` : '',
287
+ removed.length ? `removed ${namePaths(removed)}` : '',
288
+ ].filter(Boolean);
289
+ return parts.length ? parts.join('; ') : 'files changed';
290
+ }
291
+ /** Replaces the generic UNAPPROVED_CHANGE reason with one naming the changed files, when the certificate lists them. */
292
+ function explainChange(decision, best, tree) {
293
+ const certificate = best?.evaluation.certificate;
294
+ if (decision.verdict !== 'UNAPPROVED_CHANGE' || !certificate)
295
+ return decision;
296
+ return {
297
+ ...decision,
298
+ reason: `Skill changed since approval: ${describeTreeChange(certificate.files, tree.files)} (approved ${certificate.digest}, found ${tree.digest}); a new certificate is required`,
299
+ };
300
+ }
301
+ function buildBaseResult(options) {
302
+ return {
303
+ skillName: options.skillName,
304
+ skillDir: options.tree.root,
305
+ digest: options.tree.digest,
306
+ excluded: [...options.tree.excluded],
307
+ checkedAt: formatTimestamp(options.now),
308
+ };
309
+ }
310
+ export function decide(options) {
311
+ requireValidDate(options.now, 'Verification time');
312
+ let best;
313
+ for (const source of options.certificates) {
314
+ const evaluation = evaluateCertificate(source.bytes, options.skillName, options.tree.digest, options.context, options.now);
315
+ best = selectBetterCandidate(best, { source, evaluation });
316
+ if (evaluation.verdict === 'VERIFIED') {
317
+ break;
318
+ }
319
+ }
320
+ return { ...buildBaseResult(options), ...explainChange(buildDecision(best), best, options.tree) };
321
+ }
322
+ /**
323
+ * Same verdict as `decide`, but candidates are evaluated one at a time as they are produced, so only the best
324
+ * one is retained and the first VERIFIED candidate ends the scan (later candidates are never read).
325
+ */
326
+ export async function decideStreaming(options) {
327
+ requireValidDate(options.now, 'Verification time');
328
+ let best;
329
+ for await (const source of options.certificates) {
330
+ const evaluation = evaluateCertificate(source.bytes, options.skillName, options.tree.digest, options.context, options.now);
331
+ best = selectBetterCandidate(best, { source, evaluation });
332
+ if (evaluation.verdict === 'VERIFIED') {
333
+ break;
334
+ }
335
+ }
336
+ return { ...buildBaseResult(options), ...explainChange(buildDecision(best), best, options.tree) };
337
+ }
115
338
  /** Full check of one Skill directory against an already-verified trust context. */
116
339
  export async function verifySkill(options) {
340
+ // Before the try: its catch builds an UNVERIFIABLE result, which needs a valid time for `checkedAt`.
341
+ requireValidDate(options.now, 'Verification time');
117
342
  const skillDir = path.resolve(options.skillDir);
118
343
  let skillName = options.skillName ?? path.basename(skillDir);
119
344
  try {
120
345
  skillName = await resolveSkillName(skillDir, options.skillName);
121
346
  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 });
347
+ const provided = typeof options.certificates === 'function'
348
+ ? options.certificates(skillName, tree.root)
349
+ : options.certificates;
350
+ const certificates = Symbol.asyncIterator in provided ? provided : await provided;
351
+ return await decideStreaming({
352
+ skillDir,
353
+ skillName,
354
+ tree,
355
+ certificates,
356
+ context: options.context,
357
+ now: options.now,
358
+ });
124
359
  }
125
360
  catch (error) {
126
- return unverifiable(skillDir, skillName, error.message, options.now);
361
+ return unverifiable(skillDir, skillName, errorMessage(error), options.now);
127
362
  }
128
363
  }
129
364
  export function unverifiable(skillDir, skillName, reason, now, verdict = 'UNVERIFIABLE') {
365
+ requireValidDate(now, 'Verification time');
366
+ const safeVerdict = verdict === 'VERIFIED' || !(verdict in VERDICT_RANK) ? 'UNVERIFIABLE' : verdict;
130
367
  return {
131
- verdict, reason, skillName, skillDir, digest: null, files: null, certificateId: null,
132
- certificateSource: null, approverKeyId: null, excluded: [], checkedAt: formatTimestamp(now),
368
+ verdict: safeVerdict,
369
+ reason,
370
+ skillName,
371
+ skillDir,
372
+ digest: null,
373
+ files: null,
374
+ certificateId: null,
375
+ certificateSource: null,
376
+ approverKeyId: null,
377
+ excluded: [],
378
+ checkedAt: formatTimestamp(now),
133
379
  };
134
380
  }
@@ -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. 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,18 @@ 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 |
27
30
 
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.
31
+ 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 `-`.
32
+
33
+ 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
34
 
30
35
  ## Limits
31
36
 
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.
37
+ - Linux and macOS only. On Windows the extension shows a warning: executable bits are not covered, so Skills approved elsewhere may not verify.
33
38
  - Standalone Markdown Skills (a `.md` file without its own directory and `SKILL.md`) cannot be certified and are always unverified.
34
39
  - Pi runs extensions in load order; another extension can change the Skill list after mago-ski. Load mago-ski last.
35
40
  - Custom tools and MCP tools that read files are not checked.