@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
package/dist/src/keys.js CHANGED
@@ -1,17 +1,27 @@
1
1
  import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync } from 'node:crypto';
2
- import { lstat } from 'node:fs/promises';
2
+ import { lstat, unlink } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
- import { readRegularFile, writeNewFile } from "./fs-safe.js";
4
+ import { readRegularFile, realpathAllowingMissing, writeNewFile } from "./fs-safe.js";
5
+ import { SKILL_FILENAME } from "./tree-digest.js";
5
6
  export const KEY_ID_PATTERN = /^sha256:[0-9a-f]{64}$/u;
6
7
  const BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
8
+ const MAX_SPKI_BASE64_LEN = 256;
9
+ const MAX_KEY_FILE_BYTES = 64 * 1024;
10
+ const PRIVATE_KEY_MODE = 0o600;
11
+ const PUBLIC_KEY_MODE = 0o644;
12
+ const GROUP_OTHER_PERMS = 0o077;
7
13
  export function keyIdFromSpkiDer(der) {
8
14
  return `sha256:${createHash('sha256').update(der).digest('hex')}`;
9
15
  }
10
- function describe(publicKey) {
16
+ function describePublicKey(publicKey) {
11
17
  if (publicKey.asymmetricKeyType !== 'ed25519')
12
18
  throw new Error('Key is not Ed25519');
13
19
  const der = publicKey.export({ format: 'der', type: 'spki' });
14
- return { keyId: keyIdFromSpkiDer(der), publicKey, spki: der.toString('base64') };
20
+ return {
21
+ keyId: keyIdFromSpkiDer(der),
22
+ publicKey,
23
+ spki: der.toString('base64'),
24
+ };
15
25
  }
16
26
  export function validateKeyId(value, label) {
17
27
  if (typeof value !== 'string' || !KEY_ID_PATTERN.test(value))
@@ -20,89 +30,134 @@ export function validateKeyId(value, label) {
20
30
  }
21
31
  /** Parses a canonical base64 Ed25519 SPKI and, if given, checks it hashes to `expectedKeyId`. */
22
32
  export function parseSpki(spki, label, expectedKeyId) {
23
- if (typeof spki !== 'string' || spki.length === 0 || spki.length > 256 || !BASE64_PATTERN.test(spki)) {
33
+ let publicKey;
34
+ if (expectedKeyId !== undefined)
35
+ validateKeyId(expectedKeyId, `${label} expectedKeyId`);
36
+ if (typeof spki !== 'string' ||
37
+ spki.length === 0 ||
38
+ spki.length > MAX_SPKI_BASE64_LEN ||
39
+ !BASE64_PATTERN.test(spki)) {
24
40
  throw new Error(`${label} must be canonical base64 SubjectPublicKeyInfo`);
25
41
  }
26
42
  const der = Buffer.from(spki, 'base64');
27
43
  if (der.toString('base64') !== spki)
28
44
  throw new Error(`${label} must be canonical base64 SubjectPublicKeyInfo`);
29
- let publicKey;
30
45
  try {
31
46
  publicKey = createPublicKey({ key: der, format: 'der', type: 'spki' });
32
47
  }
33
48
  catch {
34
49
  throw new Error(`${label} is not a valid public key`);
35
50
  }
36
- const info = describe(publicKey);
51
+ const info = describePublicKey(publicKey);
37
52
  if (info.spki !== spki)
38
53
  throw new Error(`${label} is not in canonical DER form`);
39
54
  if (expectedKeyId !== undefined && info.keyId !== expectedKeyId)
40
55
  throw new Error(`${label} does not match key id ${expectedKeyId}`);
41
56
  return info;
42
57
  }
43
- /** Private keys must never be written where a Skill (and so its certificate and hosts) could include them. */
44
- async function refuseInsideSkill(filePath) {
45
- let directory = path.dirname(filePath);
58
+ async function refuseInsideSkillAt(targetPath) {
59
+ let directory = path.dirname(targetPath);
46
60
  while (true) {
61
+ let hasSkillMd = false;
47
62
  try {
48
- await lstat(path.join(directory, 'SKILL.md'));
49
- throw new Error(`Refusing to write a private key inside a Skill directory (${directory}); keep keys outside every Skill tree`);
63
+ await lstat(path.join(directory, SKILL_FILENAME));
64
+ hasSkillMd = true;
50
65
  }
51
66
  catch (error) {
52
- if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR')
67
+ const code = error?.code;
68
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
53
69
  throw error;
54
70
  }
71
+ if (hasSkillMd) {
72
+ throw new Error(`Refusing to write a private key inside a Skill directory (${directory}); keep keys outside every Skill tree`);
73
+ }
55
74
  const parent = path.dirname(directory);
56
75
  if (parent === directory)
57
76
  return;
58
77
  directory = parent;
59
78
  }
60
79
  }
80
+ /** Private keys must never be written where a Skill (and so its certificate and hosts) could include them. */
81
+ async function refuseInsideSkill(filePath) {
82
+ const lexicalTarget = path.resolve(filePath);
83
+ const canonicalTarget = await realpathAllowingMissing(lexicalTarget);
84
+ await refuseInsideSkillAt(lexicalTarget);
85
+ if (canonicalTarget !== lexicalTarget)
86
+ await refuseInsideSkillAt(canonicalTarget);
87
+ }
61
88
  export async function generateKeyPair(privatePath, publicPath) {
62
89
  const privateTarget = path.resolve(privatePath);
63
90
  const publicTarget = path.resolve(publicPath);
64
- if (privateTarget === publicTarget)
91
+ const canonicalPrivate = await realpathAllowingMissing(privateTarget);
92
+ const canonicalPublic = await realpathAllowingMissing(publicTarget);
93
+ if (privateTarget === publicTarget || canonicalPrivate === canonicalPublic)
65
94
  throw new Error('Private and public key paths must differ');
66
95
  await refuseInsideSkill(privateTarget);
67
96
  const pair = generateKeyPairSync('ed25519');
68
- const privatePem = pair.privateKey.export({ type: 'pkcs8', format: 'pem' });
69
- const publicPem = pair.publicKey.export({ type: 'spki', format: 'pem' });
70
- await writeNewFile(privateTarget, Buffer.from(privatePem), 0o600);
97
+ const privatePem = Buffer.from(pair.privateKey.export({ type: 'pkcs8', format: 'pem' }));
98
+ const publicPem = Buffer.from(pair.publicKey.export({ type: 'spki', format: 'pem' }));
71
99
  try {
72
- await writeNewFile(publicTarget, Buffer.from(publicPem), 0o644);
100
+ await writeNewFile(privateTarget, privatePem, PRIVATE_KEY_MODE);
101
+ try {
102
+ await writeNewFile(publicTarget, publicPem, PUBLIC_KEY_MODE);
103
+ }
104
+ catch (error) {
105
+ await unlink(privateTarget).catch(() => { });
106
+ throw error;
107
+ }
73
108
  }
74
- catch (error) {
75
- const { unlink } = await import('node:fs/promises');
76
- await unlink(privateTarget).catch(() => { });
77
- throw error;
109
+ finally {
110
+ privatePem.fill(0);
78
111
  }
79
- return { ...describe(pair.publicKey), privatePath: privateTarget, publicPath: publicTarget };
112
+ return {
113
+ ...describePublicKey(pair.publicKey),
114
+ privatePath: privateTarget,
115
+ publicPath: publicTarget,
116
+ };
80
117
  }
81
118
  export async function loadPrivateKey(filePath) {
82
119
  const entry = await lstat(filePath);
83
- if (process.platform !== 'win32' && (entry.mode & 0o077) !== 0) {
120
+ if (entry.isSymbolicLink() || !entry.isFile())
121
+ throw new Error('Private key must be a regular, non-symlink file');
122
+ if (process.platform !== 'win32' && (entry.mode & GROUP_OTHER_PERMS) !== 0)
84
123
  throw new Error('Private key permissions must deny group and other access (chmod 600)');
124
+ const pem = await readRegularFile(filePath, 'Private key', MAX_KEY_FILE_BYTES);
125
+ try {
126
+ return loadPrivateKeyBytes(pem);
127
+ }
128
+ finally {
129
+ pem.fill(0);
85
130
  }
86
- const pem = await readRegularFile(filePath, 'Private key', 64 * 1024);
131
+ }
132
+ /** Parses a PKCS#8 Ed25519 PEM from bytes the caller already read. The caller zeroes `pem`. */
133
+ export function loadPrivateKeyBytes(pem) {
87
134
  let privateKey;
88
135
  try {
89
- privateKey = createPrivateKey(pem);
136
+ privateKey = createPrivateKey({ key: pem, format: 'pem', type: 'pkcs8' });
90
137
  }
91
138
  catch {
92
139
  throw new Error('Private key is not a valid PKCS#8 key');
93
140
  }
94
141
  if (privateKey.asymmetricKeyType !== 'ed25519')
95
142
  throw new Error('Private key is not Ed25519');
96
- return { ...describe(createPublicKey(privateKey)), privateKey };
143
+ return {
144
+ ...describePublicKey(createPublicKey(privateKey)),
145
+ privateKey,
146
+ };
97
147
  }
98
148
  export async function loadPublicKey(filePath) {
99
- const pem = await readRegularFile(filePath, 'Public key', 64 * 1024);
149
+ return loadPublicKeyBytes(await readRegularFile(filePath, 'Public key', MAX_KEY_FILE_BYTES));
150
+ }
151
+ /** Parses an Ed25519 SPKI PEM from bytes the caller already read (at most 64 KiB). */
152
+ export function loadPublicKeyBytes(pem) {
153
+ if (pem.byteLength > MAX_KEY_FILE_BYTES)
154
+ throw new Error('Public key is too large');
100
155
  let publicKey;
101
156
  try {
102
- publicKey = createPublicKey(pem);
157
+ publicKey = createPublicKey({ key: pem, format: 'pem', type: 'spki' });
103
158
  }
104
159
  catch {
105
160
  throw new Error('Public key is not a valid SPKI PEM key');
106
161
  }
107
- return describe(publicKey);
162
+ return describePublicKey(publicKey);
108
163
  }
@@ -7,9 +7,9 @@ import { fileURLToPath } from 'node:url';
7
7
  */
8
8
  export function isMainModule(moduleUrl) {
9
9
  const entry = process.argv[1];
10
+ const self = fileURLToPath(moduleUrl);
10
11
  if (!entry)
11
12
  return false;
12
- const self = fileURLToPath(moduleUrl);
13
13
  try {
14
14
  return realpathSync(entry) === realpathSync(self);
15
15
  }
package/dist/src/names.js CHANGED
@@ -2,16 +2,14 @@ const SKILL_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
2
2
  const SCOPE_PATTERN = /^(?:\*|[A-Za-z0-9][A-Za-z0-9._-]{0,127}\*?)$/u;
3
3
  const DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/u;
4
4
  export function validateSkillName(value, label = 'Skill name') {
5
- if (typeof value !== 'string' || !SKILL_NAME_PATTERN.test(value)) {
5
+ if (typeof value !== 'string' || !SKILL_NAME_PATTERN.test(value))
6
6
  throw new Error(`${label} must be 1-128 ASCII letters, digits, dot, underscore or hyphen, starting with a letter or digit`);
7
- }
8
7
  return value;
9
8
  }
10
9
  /** Scopes: "*" (every Skill), "prefix*" (names starting with prefix), or an exact Skill name. */
11
10
  export function validateScope(value, label = 'scope') {
12
- if (typeof value !== 'string' || !SCOPE_PATTERN.test(value)) {
11
+ if (typeof value !== 'string' || !SCOPE_PATTERN.test(value))
13
12
  throw new Error(`${label} must be "*", an exact Skill name, or a name prefix ending in "*"`);
14
- }
15
13
  return value;
16
14
  }
17
15
  export function scopeMatches(scope, skillName) {
@@ -1,11 +1,52 @@
1
+ import { type RecoverySet, type RootWalk } from './root-events.ts';
1
2
  import { type CertificateSource, type TrustContext, type TrustContextResult, type VerificationResult } from './verify.ts';
2
3
  export declare const POLICY_VERSION = "mago.policy/v1";
4
+ /** Adds root recovery and freshness; a v2 host reads v1 policies unchanged. */
5
+ export declare const POLICY_VERSION_V2 = "mago.policy/v2";
3
6
  export declare const STATE_TYPE = "mago.host-state/v1";
4
- export declare const DEFAULT_POLICY_PATH: string;
7
+ export declare const STATE_TYPE_V2 = "mago.host-state/v2";
8
+ /** Per-Skill budget across all certificate candidates (explicit file, policy directories, in-Skill file). */
9
+ export declare const MAX_CERTIFICATE_CANDIDATES = 64;
10
+ export declare const MAX_CERTIFICATE_TOTAL_BYTES: number;
5
11
  export type Mode = 'shadow' | 'enforce';
12
+ interface RootState {
13
+ trust_root_version: number;
14
+ revocations_version: number;
15
+ }
16
+ /** Host state: versions per root key (v1), plus root event progress per pinned root and timestamp versions per key (v2). */
17
+ export interface HostState {
18
+ roots: Record<string, RootState>;
19
+ /** `revoked` is set when the last applied event left the root revoked (written only when true). */
20
+ rootEvents: Record<string, {
21
+ sequence: number;
22
+ event_digest: string;
23
+ revoked?: true;
24
+ }>;
25
+ timestamps: Record<string, {
26
+ version: number;
27
+ }>;
28
+ /** The state was read as v2; it is never written back as v1. */
29
+ v2: boolean;
30
+ }
31
+ export declare function defaultPolicyPath(env?: NodeJS.ProcessEnv, home?: string): string;
32
+ export interface FreshnessPolicy {
33
+ timestampPath: string;
34
+ /** The timestamp key trusted before any root event. */
35
+ keyId: string;
36
+ maxLifetimeMs: number;
37
+ }
38
+ export interface RecoveryPolicy {
39
+ /** The recovery set trusted before any root event. */
40
+ set: RecoverySet;
41
+ rootEventsPath: string;
42
+ /** How many events root_fingerprint, recovery and freshness.key_id already reflect. */
43
+ eventsAfter: number;
44
+ freshness: FreshnessPolicy | null;
45
+ }
6
46
  export interface Policy {
7
47
  path: string;
8
48
  mode: Mode;
49
+ /** The pinned root key: the one trusted before any root event (it does not change after a rotation). */
9
50
  rootKeyId: string;
10
51
  trustRootPath: string;
11
52
  revocationsPath: string;
@@ -13,12 +54,107 @@ export interface Policy {
13
54
  skillDirs: string[];
14
55
  statePath: string | null;
15
56
  decisionLogPath: string | null;
57
+ /** Root recovery (policy v2 with a "recovery" block); null behaves exactly as a v1 policy. */
58
+ recovery: RecoveryPolicy | null;
16
59
  }
17
60
  /** Policy files are hand-edited JSON; paths are relative to the policy file's directory. */
18
61
  export declare function loadPolicy(policyPath: string): Promise<Policy>;
19
- /** Loads trust documents for a policy, enforcing rollback protection through the state file. */
20
- export declare function loadPolicyTrust(policy: Policy, now: Date): Promise<TrustContextResult>;
21
- /** Certificate lookup order: explicit file, policy certificate directories (<name>.cert.json), then the in-Skill certificate. */
62
+ /** The host state file exists and was read, but its content or kind is wrong. Every other read error is not this. */
63
+ export declare class HostStateFormatError extends Error {
64
+ constructor(message: string);
65
+ }
66
+ /** The host state file as it is now (a missing file is an empty state). The GUI memory uses this format too. */
67
+ export declare function readHostState(statePath: string): Promise<HostState>;
68
+ /**
69
+ * Combines this load's state with the state file as it is now, so two hosts sharing one state file (two Pi sessions,
70
+ * Pi and the CLI) cannot erase each other's progress: every counter keeps its highest value, the root event entry
71
+ * with the higher sequence wins (on a tie with different digests, the one already on disk stays, so the fork is
72
+ * reported on the next load), and v2 is never written back as v1.
73
+ */
74
+ export declare function mergeHostState(ours: HostState, disk: HostState): HostState;
75
+ /**
76
+ * Records document versions in a host state file (the GUI memory), merging with what is on disk: every counter keeps
77
+ * its highest value, so this never lowers anything within the retry budget of `persistState` (it fails closed otherwise). A root entry takes each given half and `1` (the lowest valid
78
+ * value) for a missing one. Throws when the file cannot be read or written.
79
+ */
80
+ export declare function recordDocumentVersions(statePath: string, v: {
81
+ rootKeyId?: string;
82
+ trustRoot?: number;
83
+ revocations?: number;
84
+ timestamp?: {
85
+ keyId: string;
86
+ version: number;
87
+ };
88
+ }): Promise<void>;
89
+ /** The lowest versions this computer's memory allows for each document; 0 where nothing is recorded. */
90
+ export declare function memoryMinimums(state: HostState, rootKeyId: string, timestampKeyId: string | null): {
91
+ trustRoot: number;
92
+ revocations: number;
93
+ timestamp: number;
94
+ };
95
+ export interface ForbiddenKey {
96
+ keyId: string;
97
+ why: 'root' | 'recovery' | 'timestamp' | 'retired' | 'formerRecovery' | 'revoked';
98
+ }
99
+ /**
100
+ * Keys that must not be approvers in this organisation: the root, the recovery set, the timestamp key, keys that left
101
+ * the root or timestamp role, keys that left a recovery set, and every revoked key. Neither reads nor writes host state.
102
+ * Throws when the root event log or the revocation list cannot be checked, and `StaleDocumentError` when the revocation
103
+ * list is older than `minimumRevocations` (the caller's memory; the CLI passes none).
104
+ */
105
+ export declare function forbiddenApproverKeys(policy: Policy, now: Date, o?: {
106
+ minimumRevocations?: number;
107
+ }): Promise<ForbiddenKey[]>;
108
+ export type StateErrorKind = 'corrupt' | 'unreadable' | 'write';
109
+ export type PolicyRootResult = {
110
+ ok: true;
111
+ walk: RootWalk | null;
112
+ activeRootKeyId: string;
113
+ } | {
114
+ ok: false;
115
+ reason: string;
116
+ rootRevoked: boolean;
117
+ walk: RootWalk | null;
118
+ rollback?: true;
119
+ stateError?: StateErrorKind;
120
+ };
121
+ /**
122
+ * Only the root-event part of `loadPolicyTrust`: which root key is active, whether it is revoked, and the walk. It
123
+ * reads the state and the log, checks rollback and forks the same way, and with `recordVersions` (the default) and a
124
+ * state file records the progress with the same merge-before-write. A policy without `recovery` reads nothing.
125
+ */
126
+ export declare function loadPolicyRoot(policy: Policy, now: Date, options?: {
127
+ recordVersions?: boolean;
128
+ }): Promise<PolicyRootResult>;
129
+ /**
130
+ * Loads trust documents for a policy, enforcing rollback protection through the state file.
131
+ * With `recordVersions: false` the state file is still read (the same rollback minimums apply) but never written:
132
+ * for observers such as the GUI, which must not move a host's rollback memory.
133
+ *
134
+ * With root recovery (policy v2), the order is: walk the root event log, check rollback and forks, stop if the active
135
+ * root is revoked (`rootRevoked`, which blocks in every mode), check the timestamp, then the trust root and revocation
136
+ * list against the active root, then record the new state.
137
+ */
138
+ export declare function loadPolicyTrust(policy: Policy, now: Date, options?: {
139
+ recordVersions?: boolean;
140
+ }): Promise<TrustContextResult>;
141
+ /** Documents a preview substitutes for the files on disk (the GUI's "what would hosts say after this write"). */
142
+ export interface PreviewOverride {
143
+ trustRoot?: Buffer;
144
+ revocations?: Buffer;
145
+ timestamp?: Buffer;
146
+ }
147
+ /**
148
+ * The host's own trust load, for a preview: never records versions, may replace the documents read from disk with
149
+ * in-memory bytes (`override`, subject to the same size limits), and with `skipFreshness` skips reading and checking
150
+ * the timestamp and its binding to the documents (`context.root.timestamp` is then null). Only the GUI service uses it.
151
+ */
152
+ export declare function loadTrustForPreview(policy: Policy, now: Date, o?: {
153
+ override?: PreviewOverride;
154
+ skipFreshness?: boolean;
155
+ }): Promise<TrustContextResult>;
156
+ export declare function iterateCertificates(skillName: string, skillRoot: string, certificateDirs: string[], explicit?: string): AsyncGenerator<CertificateSource>;
157
+ /** Collects every candidate (within the same budget). Prefer `iterateCertificates`, which retains nothing. */
22
158
  export declare function discoverCertificates(skillName: string, skillRoot: string, certificateDirs: string[], explicit?: string): Promise<CertificateSource[]>;
23
159
  /**
24
160
  * Finds Skill directories (directories containing SKILL.md) under the given roots.
@@ -26,12 +162,24 @@ export declare function discoverCertificates(skillName: string, skillRoot: strin
26
162
  * directory or a linked SKILL.md is returned as a Skill, and verification then rejects it.
27
163
  */
28
164
  export declare const MAX_DISCOVERY_DEPTH = 16;
165
+ /** Work budget for one discovery run over untrusted trees; exceeding either throws DiscoveryBudgetError. */
166
+ export declare const MAX_DISCOVERED_SKILLS = 1000;
167
+ export declare const MAX_DISCOVERY_ENTRIES = 50000;
168
+ export interface DiscoveryLimits {
169
+ /** Maximum Skills (including directories reported as too deep) found. */
170
+ maxSkills?: number;
171
+ /** Maximum directory entries visited across all roots. */
172
+ maxEntries?: number;
173
+ }
174
+ /** Discovery stopped because the tree is larger than the budget. It never returns a partial list: callers must fail closed. */
175
+ export declare class DiscoveryBudgetError extends Error {
176
+ constructor(message: string);
177
+ }
29
178
  export interface SkillDiscovery {
30
179
  skillDirs: string[];
31
- /** Directories at the depth limit that have subdirectories; Skills below them were not searched. */
32
180
  tooDeep: string[];
33
181
  }
34
- export declare function findSkillDirs(roots: string[], maxDepth?: number): Promise<SkillDiscovery>;
182
+ export declare function findSkillDirs(roots: string[], maxDepth?: number, limits?: DiscoveryLimits): Promise<SkillDiscovery>;
35
183
  /** Result for a directory discovery could not search; it fails in enforce mode and is reported in shadow mode. */
36
184
  export declare function tooDeepResult(directory: string, now: Date): VerificationResult;
37
185
  export interface DecisionRecord {
@@ -47,6 +195,24 @@ export interface DecisionRecord {
47
195
  verdict: string;
48
196
  reason: string;
49
197
  }
198
+ /** Event names for a failure of the trust documents, reported once per host instead of once per Skill. */
199
+ export type TrustFailureEvent = 'root-revoked' | 'trust-unavailable';
200
+ export declare function trustFailureEvent(failure: {
201
+ rootRevoked?: boolean | undefined;
202
+ }): TrustFailureEvent;
203
+ /**
204
+ * The mode a host acts in for this trust state. A revoked root is a signed statement that the trust anchor is not
205
+ * sound, so it blocks in shadow mode too; no policy setting changes that. Every other failure follows the policy.
206
+ */
207
+ export declare function effectiveMode(mode: Mode, trust: TrustContextResult | {
208
+ ok: false;
209
+ rootRevoked?: boolean | undefined;
210
+ } | null | undefined): Mode;
211
+ /** The single decision-log record for a trust failure: empty skill and skill_dir, null digest and certificate_id. */
212
+ export declare function trustFailureRecord(failure: {
213
+ reason: string;
214
+ rootRevoked?: boolean | undefined;
215
+ }, mode: Mode, now: Date, host?: string): DecisionRecord;
50
216
  export declare function actionFor(mode: Mode, verified: boolean): DecisionRecord['action'];
51
217
  export declare function appendDecision(logPath: string | null, record: DecisionRecord): Promise<void>;
52
218
  export declare function decisionRecord(result: VerificationResult, mode: Mode, event: string, host?: string): DecisionRecord;
@@ -57,3 +223,4 @@ export declare function verifyWithPolicy(policy: Policy, skillDir: string, optio
57
223
  certificate?: string;
58
224
  context?: TrustContext;
59
225
  }): Promise<VerificationResult>;
226
+ export {};