@glassbox-ai/engine 0.1.0 → 0.1.2

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 (48) hide show
  1. package/README.md +2 -0
  2. package/dist/action/acc.d.ts +1 -1
  3. package/dist/action/agent-clis.d.ts +44 -0
  4. package/dist/action/agent-clis.js +175 -0
  5. package/dist/action/builtin-tools.d.ts +5 -0
  6. package/dist/action/builtin-tools.js +74 -0
  7. package/dist/action/inline.js +2 -2
  8. package/dist/action/paths.js +1 -1
  9. package/dist/action/powershell.js +10 -4
  10. package/dist/action/schedule.d.ts +7 -0
  11. package/dist/action/schedule.js +10 -0
  12. package/dist/action/shell/analyze.js +75 -15
  13. package/dist/action/shell/parse.js +1 -1
  14. package/dist/action/shell/view.js +1 -1
  15. package/dist/action/sql.js +1 -1
  16. package/dist/action/tools.js +70 -3
  17. package/dist/action/upload.d.ts +6 -2
  18. package/dist/action/upload.js +32 -7
  19. package/dist/analysis/fields.js +3 -3
  20. package/dist/analysis/findings.js +1 -1
  21. package/dist/analysis/gate.js +8 -6
  22. package/dist/analysis/manifest.js +2 -2
  23. package/dist/analysis/match.js +2 -2
  24. package/dist/analysis/scan.js +1 -1
  25. package/dist/canon/decode.js +1 -1
  26. package/dist/canon/views.js +1 -1
  27. package/dist/evidence/evidence.js +1 -1
  28. package/dist/fingerprint/diff.js +1 -1
  29. package/dist/index.d.ts +5 -1
  30. package/dist/index.js +6 -2
  31. package/dist/intake/json.js +1 -1
  32. package/dist/intake/snapshot.js +1 -1
  33. package/dist/policy/decide.d.ts +14 -1
  34. package/dist/policy/decide.js +68 -15
  35. package/dist/ruleset/load.d.ts +2 -3
  36. package/dist/ruleset/load.js +20 -6
  37. package/dist/ruleset/schema.d.ts +1 -1
  38. package/dist/ruleset/schema.js +1 -1
  39. package/dist/ruleset-entry.js +1 -1
  40. package/dist/secrets/detect.js +2 -2
  41. package/dist/secrets/redact.js +1 -1
  42. package/dist/types.d.ts +21 -0
  43. package/dist/types.js +1 -1
  44. package/dist/util/jcs.js +1 -1
  45. package/dist/util/re.js +1 -1
  46. package/dist/version.d.ts +1 -1
  47. package/dist/version.js +1 -1
  48. package/package.json +7 -6
@@ -1,8 +1,10 @@
1
1
  import { get, getString, isRecord } from "../util/misc.js";
2
2
  import { Acc } from "./acc.js";
3
3
  import { coversProtectedRead, globCoversProtectedRead, isProtected, isProtectedRead, normalizePath, persistenceHit, sensitiveLabel, } from "./paths.js";
4
+ import { builtinCategory } from "./builtin-tools.js";
4
5
  import { analyzePowerShell } from "./powershell.js";
5
6
  import { isProtectedWrite } from "./protected-write.js";
7
+ import { agentConfigWrite } from "./agent-clis.js";
6
8
  import { analyzeShellCommand } from "./shell/analyze.js";
7
9
  import { analyzeSql } from "./sql.js";
8
10
  const READ_TOOLS = new Set(["read", "glob", "grep", "ls", "lsp", "websearch", "todowrite", "todoread", "askuserquestion", "exitplanmode", "notebookread", "bashoutput", "taskoutput", "listmcpresourcestool", "readmcpresourcetool", "toolsearch"]);
@@ -13,6 +15,7 @@ export function writePath(path, acc, t) {
13
15
  acc.protect("CP-SELF-001", "changes a file that controls the agent or Glassbox");
14
16
  acc.persist(persistenceHit(np, t.pctx), "changes", np.path);
15
17
  acc.wrote(np.path);
18
+ agentConfigWrite(np, t.pctx, acc);
16
19
  const p = (np.path ?? np.suffix ?? "").toLowerCase();
17
20
  if (p.includes("/.git/hooks/") || p.endsWith("/.git/config") || p.includes("/.husky/") || p.endsWith("/.envrc") || p.endsWith("/.bashrc") || p.endsWith("/.zshrc") || p.endsWith("/.profile") || p.endsWith("/.bash_profile") || p.endsWith("/.pre-commit-config.yaml") || p.endsWith("profile.ps1") || p.includes("/library/launchagents/") || p.includes("/.config/systemd/user/")) {
18
21
  acc.tag("high-risk", "config.agent");
@@ -68,6 +71,26 @@ export function classifyBuiltin(toolName, args, t) {
68
71
  writePath(p, acc, t);
69
72
  return acc;
70
73
  }
74
+ if (name === "monitor") {
75
+ // Monitor runs a background shell command (or watches a WebSocket) and streams its output
76
+ // to the agent. The command gets the full shell analysis, like Bash.
77
+ const cmd = str("command");
78
+ let out = cmd !== undefined ? analyzeShellCommand(cmd, { pctx: t.pctx, depth: 0, maxBytes: t.maxCommandBytes }) : null;
79
+ const wsUrl = getString(get(args, "ws"), "url");
80
+ if (wsUrl !== undefined) {
81
+ const a = out ?? acc;
82
+ a.tag("high-risk", "net.egress");
83
+ a.network = true;
84
+ const h = hostOf(wsUrl);
85
+ a.reason(h ? `watches a WebSocket on ${h}` : "watches a WebSocket on an unknown host");
86
+ out = a;
87
+ }
88
+ if (out === null) {
89
+ acc.unanalyzable("Monitor call without a command string");
90
+ return acc;
91
+ }
92
+ return out;
93
+ }
71
94
  if (name === "webfetch") {
72
95
  acc.tag("high-risk", "net.egress");
73
96
  acc.network = true;
@@ -75,6 +98,19 @@ export function classifyBuiltin(toolName, args, t) {
75
98
  acc.reason(h ? `destination host: ${h}` : "destination host unknown");
76
99
  return acc;
77
100
  }
101
+ if (name === "enterworktree") {
102
+ acc.tag("write-reversible", "fs.write");
103
+ const p = str("path");
104
+ if (p !== undefined)
105
+ writePath(p, acc, t);
106
+ acc.reason("creates or enters a git worktree");
107
+ return acc;
108
+ }
109
+ if (name === "exitworktree") {
110
+ acc.tag("write-reversible", "fs.write");
111
+ acc.reason("leaves a git worktree");
112
+ return acc;
113
+ }
78
114
  if (READ_TOOLS.has(name)) {
79
115
  if (name === "read" || name === "notebookread" || name === "lsp") {
80
116
  const p = str("file_path") ?? str("filePath") ?? str("path") ?? str("notebook_path");
@@ -95,8 +131,39 @@ export function classifyBuiltin(toolName, args, t) {
95
131
  }
96
132
  return acc;
97
133
  }
98
- acc.tag("write-reversible", "exec.unknown");
99
- acc.reason(`runs the agent tool ${toolName.slice(0, 40)}`);
134
+ const label = toolName.slice(0, 40);
135
+ switch (builtinCategory(toolName)) {
136
+ case "network":
137
+ // Artifact, ShareOnboardingGuide: publish local content to a hosted page.
138
+ acc.tag("high-risk", "net.egress");
139
+ acc.network = true;
140
+ acc.reason(`sends content off the machine (${label})`);
141
+ return acc;
142
+ case "agent":
143
+ if (name === "remotetrigger") {
144
+ acc.tag("high-risk", "exec.nested-agent");
145
+ acc.reason("creates or runs a scheduled agent in the cloud, where these checks don't run");
146
+ return acc;
147
+ }
148
+ // Agent, Workflow, Skill, SendMessage, CronCreate, ScheduleWakeup: the work they start runs
149
+ // as ordinary tool calls in this Claude Code, and each of those is checked.
150
+ acc.raise("write-reversible");
151
+ acc.reason(`starts agent work (${label}); its tool calls are checked one by one`);
152
+ return acc;
153
+ case "other":
154
+ acc.raise("write-reversible");
155
+ acc.reason(`acts inside the session (${label})`);
156
+ return acc;
157
+ case "read":
158
+ return acc;
159
+ case "command":
160
+ case "write":
161
+ case undefined:
162
+ break;
163
+ }
164
+ // A built-in tool this engine doesn't know: it may run commands or write files, and nothing
165
+ // here can tell. Unanalyzable (ask; deny in autopilot), never "harmless".
166
+ acc.unanalyzable(`unknown agent tool ${label}`);
100
167
  return acc;
101
168
  }
102
169
  // ── MCP tools ────────────────────────────────────────────────────────────
@@ -218,7 +285,7 @@ export function classifyMcp(name, args, descriptor, t) {
218
285
  }
219
286
  }
220
287
  if (sqlSeen) {
221
- // The statement decides, not the tool's verb (§7.1 step 3).
288
+ // The statement decides, not the tool's verb.
222
289
  const keep = new Acc();
223
290
  keep.merge(sqlAcc);
224
291
  for (const f of acc.findings)
@@ -10,8 +10,12 @@ export declare function isLoopbackHost(host: string): boolean;
10
10
  export declare function hostOf(v: string): string | null;
11
11
  /** Destinations are known and all on this machine. */
12
12
  export declare function allLoopback(destinations: readonly (string | null)[]): boolean;
13
- /** Classifies an uploaded file. `projectDir` is the session's project directory. */
14
- export declare function classifyUpload(np: NormPath | null, pctx: PathCtx, projectDir: string | null): UploadKind;
13
+ /**
14
+ * Classifies an uploaded file. `projectDir` is the session's project directory (raw, as the
15
+ * caller gave it); `raw` is the file argument as written. Since 0.1.2 the project directory is
16
+ * normalized like the file path (before, on Windows every upload counted as "outside").
17
+ */
18
+ export declare function classifyUpload(np: NormPath | null, pctx: PathCtx, projectDir: string | null, raw?: string | null): UploadKind;
15
19
  /** Records one uploaded file (the caller has checked the destination isn't loopback). */
16
20
  export declare function recordUpload(acc: Acc, kind: UploadKind, what: string): void;
17
21
  //# sourceMappingURL=upload.d.ts.map
@@ -1,4 +1,4 @@
1
- import { isProtectedRead, sensitiveLabel } from "./paths.js";
1
+ import { isProtectedRead, normalizeFull, normalizePath, sensitiveLabel } from "./paths.js";
2
2
  /** True for loopback host names and addresses. */
3
3
  export function isLoopbackHost(host) {
4
4
  const h = host.toLowerCase().replace(/^\[|\]$/g, "");
@@ -39,8 +39,20 @@ export function allLoopback(destinations) {
39
39
  return false;
40
40
  return destinations.every((d) => d !== null && (() => { const h = hostOf(d); return h !== null && isLoopbackHost(h); })());
41
41
  }
42
- /** Classifies an uploaded file. `projectDir` is the session's project directory. */
43
- export function classifyUpload(np, pctx, projectDir) {
42
+ /**
43
+ * Windows paths whose meaning differs from their lexical form: UNC shares (also \\localhost\C$),
44
+ * and the \\?\ (literal: ".." is not collapsed) and \\.\ (device) namespaces. An upload from
45
+ * such a path is never shown to be a project file.
46
+ */
47
+ const WIN_SPECIAL_PREFIX = /^[\\/]{2}/;
48
+ /** `C:notes.txt` is relative to drive C's own current directory, not to the project. */
49
+ const WIN_DRIVE_RELATIVE = /^[A-Za-z]:(?![\\/])/;
50
+ /**
51
+ * Classifies an uploaded file. `projectDir` is the session's project directory (raw, as the
52
+ * caller gave it); `raw` is the file argument as written. Since 0.1.2 the project directory is
53
+ * normalized like the file path (before, on Windows every upload counted as "outside").
54
+ */
55
+ export function classifyUpload(np, pctx, projectDir, raw) {
44
56
  if (np === null || np.path === null) {
45
57
  if (np !== null && sensitiveLabel(np, pctx))
46
58
  return "sensitive";
@@ -48,12 +60,25 @@ export function classifyUpload(np, pctx, projectDir) {
48
60
  }
49
61
  if (isProtectedRead(np, pctx) || sensitiveLabel(np, pctx))
50
62
  return "sensitive";
63
+ // Where the path really leads, when the caller resolved it (junctions, symlinks).
64
+ const resolved = pctx.resolved?.[np.path];
65
+ const real = resolved === undefined ? null : normalizePath(resolved, { ...pctx, cwd: null, resolved: undefined });
66
+ if (real !== null && real.path !== null && (isProtectedRead(real, pctx) || sensitiveLabel(real, pctx)))
67
+ return "sensitive";
51
68
  if (projectDir === null)
52
69
  return "outside";
53
- const fold = (s) => (pctx.caseInsensitive ? s.toLowerCase() : s);
54
- const root = fold(projectDir.endsWith("/") ? projectDir.slice(0, -1) : projectDir);
55
- const p = fold(np.path);
56
- return p === root || p.startsWith(root + "/") ? "project" : "outside";
70
+ if (pctx.platform === "win32" && typeof raw === "string" && (WIN_SPECIAL_PREFIX.test(raw.trim()) || WIN_DRIVE_RELATIVE.test(raw.trim())))
71
+ return "outside";
72
+ const rootFull = normalizeFull(projectDir, { ...pctx, cwd: null });
73
+ if (rootFull === null)
74
+ return "outside";
75
+ const root = rootFull.length > 1 && rootFull.endsWith("/") ? rootFull.slice(0, -1) : rootFull;
76
+ const inside = (p) => p === root || p.startsWith(root.endsWith("/") ? root : root + "/");
77
+ if (!inside(np.path))
78
+ return "outside";
79
+ if (real !== null && (real.path === null || !inside(real.path)))
80
+ return "outside";
81
+ return "project";
57
82
  }
58
83
  /** Records one uploaded file (the caller has checked the destination isn't loopback). */
59
84
  export function recordUpload(acc, kind, what) {
@@ -1,4 +1,4 @@
1
- // C3 (engine-spec §5.3): field enumeration with roles, per surface. Iterative.
1
+ // C3: field enumeration with roles, per surface. Iterative.
2
2
  import { jcs } from "../util/jcs.js";
3
3
  import { isRecord, ptrSeg } from "../util/misc.js";
4
4
  function walk(root, base, emit, maxNodes = 200_000) {
@@ -49,7 +49,7 @@ function schemaRole(path, isKey) {
49
49
  export function manifestFields(m, maxTools) {
50
50
  const out = [];
51
51
  walk(m, "", (w, isKey) => {
52
- // "key~dupN" (a duplicated JSON key, §5.2) takes the role of "key".
52
+ // "key~dupN" takes the role of "key".
53
53
  const p = w.path.map((seg) => seg.replace(/~dup\d+$/, ""));
54
54
  let role = "manifest.other";
55
55
  let toolIndex;
@@ -84,7 +84,7 @@ export function manifestFields(m, maxTools) {
84
84
  return;
85
85
  out.push({ pointer: w.pointer, kind: isKey ? "key" : "string", role, text: String(w.v), keyName: w.key, ...(toolIndex !== undefined ? { toolIndex } : {}) });
86
86
  });
87
- // Non-string enum/default/const values are scanned in JCS form (§5.3).
87
+ // Non-string enum/default/const values are scanned in JCS form.
88
88
  const tools = isRecord(m) && Array.isArray(m["tools"]) ? m["tools"] : [];
89
89
  tools.slice(0, maxTools).forEach((t, ti) => {
90
90
  for (const s of ["inputSchema", "outputSchema"]) {
@@ -1,4 +1,4 @@
1
- // Finding construction (engine-spec §4.1, §8.3) and the rule-metadata lookup.
1
+ // Finding construction and the rule-metadata lookup.
2
2
  import { makeEvidence } from "../evidence/evidence.js";
3
3
  import { sha256Hex } from "../util/hash.js";
4
4
  /** Minimal metadata for engine-emitted rules, used only if a ruleset lacks the rule. */
@@ -1,4 +1,4 @@
1
- // The gate: checkToolCall / checkToolResult / checkServerRequest (engine-spec §4, §6).
1
+ // The gate: checkToolCall / checkToolResult / checkServerRequest.
2
2
  import { Acc } from "../action/acc.js";
3
3
  import { normalizePath, pathCtxFrom } from "../action/paths.js";
4
4
  import { commandFiles, cronLines, desktopJob, JOB_LABEL, plistJob, psTaskJob, unitJob } from "../action/schedule.js";
@@ -20,7 +20,7 @@ import { tokenize } from "./match.js";
20
20
  import { scanFields } from "./scan.js";
21
21
  const now = () => performance.now();
22
22
  /**
23
- * The gate's time backstop (spec §11, hardStopMs): true once this call has run longer than
23
+ * The gate's time backstop: true once this call has run longer than
24
24
  * the limit, not counting one-time initialization (regex compiles, tables), which the first
25
25
  * call in a process pays and later calls don't.
26
26
  */
@@ -338,13 +338,15 @@ export function checkToolCallImpl(input, ctxIn, t0) {
338
338
  if (c.protectionDegraded)
339
339
  signals.push({ kind: "protection-degraded", reason: degradedReason(c), atCall: at });
340
340
  // A job that creates or changes something runs its files later. The caller keeps this signal
341
- // only if the call is approved and runs (engine-spec §4.5); it doesn't expire.
341
+ // only if the call is approved and runs; it doesn't expire.
342
342
  for (const j of jobs)
343
343
  if (j.verb !== "removes" && j.files.length > 0)
344
344
  signals.push({ kind: "scheduled-job", job: j.kind, schedule: j.schedule, files: j.files, atCall: at });
345
345
  const out = decide({
346
346
  kind: "call", risk, findings: fs, degraded, protectionDegraded: c.protectionDegraded, ruleset: c.ruleset, policy: c.raw.policy,
347
- minConfidence: c.limits.minConfidenceForVerdict, serverId, toolName, remembered: Array.isArray(c.raw.remembered) ? c.raw.remembered : [],
347
+ minConfidence: c.limits.minConfidenceForVerdict, serverId, toolName, remembered: Array.isArray(c.raw.remembered) ? c.raw.remembered.slice(0, 1000) : [],
348
+ projectIdHash: typeof c.raw.projectIdHash === "string" ? c.raw.projectIdHash : undefined, sessionId: typeof c.raw.sessionId === "string" ? c.raw.sessionId : "",
349
+ sessionGrants: Array.isArray(c.raw.sessionGrants) ? c.raw.sessionGrants.slice(0, 1000) : [],
348
350
  });
349
351
  return {
350
352
  verdict: out.verdict,
@@ -462,7 +464,7 @@ export function checkToolResultImpl(input, ctxIn, t0) {
462
464
  signals.push({ kind: "protection-degraded", reason: degradedReason(c), atCall: at });
463
465
  const out = decide({
464
466
  kind: "result", risk, findings: fs, degraded, protectionDegraded: c.protectionDegraded, ruleset: c.ruleset, policy: c.raw.policy,
465
- minConfidence: c.limits.minConfidenceForVerdict, serverId, toolName, remembered: [],
467
+ minConfidence: c.limits.minConfidenceForVerdict, serverId, toolName, remembered: [], sessionId: "", sessionGrants: [],
466
468
  });
467
469
  let resultRewrite;
468
470
  if (out.verdict === "deny") {
@@ -556,7 +558,7 @@ export function checkServerRequestImpl(input, ctxIn, t0) {
556
558
  const degraded = ink.degraded || scan.windowed || scan.timedOut;
557
559
  const out = decide({
558
560
  kind: "server-request", risk, findings: fs, degraded, protectionDegraded: c.protectionDegraded, ruleset: c.ruleset, policy: c.raw.policy,
559
- minConfidence: c.limits.minConfidenceForVerdict, serverId, toolName: method, remembered: [], requestVerdict: { verdict: choice, locked },
561
+ minConfidence: c.limits.minConfidenceForVerdict, serverId, toolName: method, remembered: [], sessionId: "", sessionGrants: [], requestVerdict: { verdict: choice, locked },
560
562
  });
561
563
  return {
562
564
  verdict: out.verdict,
@@ -1,4 +1,4 @@
1
- // analyzeServer (engine-spec §4.2, grading.md): metadata-only analysis of an MCP manifest.
1
+ // analyzeServer: metadata-only analysis of an MCP manifest.
2
2
  import { buildViews } from "../canon/views.js";
3
3
  import { profileMcpTool, nameWords } from "../action/tools.js";
4
4
  import { fingerprintOf } from "../fingerprint/fingerprint.js";
@@ -143,7 +143,7 @@ export function analyzeServerImpl(manifestIn, opts, t0) {
143
143
  const tools = toolsRaw.slice(0, limits.maxTools);
144
144
  // Layer 1 over every field.
145
145
  const fields = manifestFields(m, limits.maxTools);
146
- // The grader's time backstop (spec §11: hardStopMs 2,000 for the grader).
146
+ // The grader's time backstop.
147
147
  const deadline = t0 + (opts?.limits?.hardStopMs ?? 2000);
148
148
  const scan = scanFields(fields, "manifest", ff, ruleset.rules, limits, true, deadline);
149
149
  findings.push(...scan.findings);
@@ -1,4 +1,4 @@
1
- // Layer 1 declarative matching (engine-spec §3.2, §6.6, §10.1).
1
+ // Layer 1 declarative matching.
2
2
  import { findDecodable } from "../canon/decode.js";
3
3
  import { buildViews, normChar } from "../canon/views.js";
4
4
  import { detectSecrets } from "../secrets/detect.js";
@@ -7,7 +7,7 @@ const RE_WORDCH = /^[\p{L}\p{M}\p{N}]$/u;
7
7
  const RE_WS = /^\p{White_Space}$/u;
8
8
  function rawNormOf(s) {
9
9
  // Like norm, but invisibles/ANSI/bidi/tags are NOT removed: used to tell whether a
10
- // match only exists because hidden characters were stripped (§6.6 invisible-stripped).
10
+ // match only exists because hidden characters were stripped.
11
11
  let out = "";
12
12
  let space = false;
13
13
  for (const ch of s) {
@@ -20,7 +20,7 @@ export function mixedScript(text) {
20
20
  }
21
21
  export function scanFields(fields, surface, ff, rules, limits, hidden, deadline = Number.POSITIVE_INFINITY) {
22
22
  // The time backstop: checked before each field and between rules, so one large field
23
- // can't run far past it (spec §11, hardStopMs).
23
+ // can't run far past it.
24
24
  const late = typeof deadline === "function" ? deadline : () => performance.now() > deadline;
25
25
  const findings = [];
26
26
  const scans = new Map();
@@ -1,4 +1,4 @@
1
- // C5 (engine-spec §5.5): find encoded blobs with a linear scanner and decode them.
1
+ // C5: find encoded blobs with a linear scanner and decode them.
2
2
  // Kept only if the result is valid UTF-8 with ≥ 80% printable code points.
3
3
  import { trimEndChars } from "../util/misc.js";
4
4
  const B64 = new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/-_=");
@@ -1,4 +1,4 @@
1
- // C4 (engine-spec §5.4): Unicode views with offset maps back to the original string.
1
+ // C4: Unicode views with offset maps back to the original string.
2
2
  // All transforms are per code point (after invisible/ANSI removal), so each view is
3
3
  // idempotent (P1) and every output position maps to an original position.
4
4
  import { CONFUSABLES } from "./confusables.generated.js";
@@ -1,4 +1,4 @@
1
- // Evidence construction (engine-spec §8.3) and renderForModel (§8.5).
1
+ // Evidence construction and renderForModel.
2
2
  import { DEFAULT_LIMITS } from "../limits.js";
3
3
  import { redactString } from "../secrets/redact.js";
4
4
  const MARKUP = new Set(["\\", "`", "*", "_", "[", "]", "(", ")", "<", ">", "#", "|", "~", "!", "{", "}", '"']);
@@ -1,4 +1,4 @@
1
- // Fingerprint diff (engine-spec §9.3) and the cloaking check (§9.4).
1
+ // Fingerprint diff and the cloaking check.
2
2
  import { FindingFactory } from "../analysis/findings.js";
3
3
  import { displayTokens } from "../evidence/evidence.js";
4
4
  import { EMBEDDED_BASELINE } from "../ruleset/baseline.js";
package/dist/index.d.ts CHANGED
@@ -1,8 +1,12 @@
1
1
  import type { ActionContext, ActionRisk, AnalyzeOptions, Decision, DiffOptions, Finding, Fingerprint, FingerprintResult, LoadedRuleset, ManifestDiff, RedactOptions, Redacted, ServerReport, SessionContext } from "./types.js";
2
2
  export * from "./types.js";
3
+ /** Built-in Claude Code tools the engine knows, by category. Any other built-in tool is unanalyzable. */
4
+ export { BUILTIN_TOOLS } from "./action/builtin-tools.js";
5
+ /** Actions that always ask (deny in autopilot), whatever the user set up or the ruleset says. */
6
+ export { HARD_FLOOR_TAGS } from "./policy/decide.js";
3
7
  export declare const ENGINE_VERSION: string;
4
8
  export declare const EMBEDDED_BASELINE: LoadedRuleset;
5
- /** The only wording a grade may be presented with (engine-spec §9a). */
9
+ /** The only wording a grade may be presented with. */
6
10
  export declare const GRADE_SCOPE_STATEMENT = "A grade checks what a server says about its tools. It doesn't inspect the server's code.";
7
11
  export declare function analyzeServer(manifest: unknown, opts?: AnalyzeOptions): ServerReport;
8
12
  export declare function fingerprint(manifest: unknown): FingerprintResult;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- // @glassbox-ai/engine public API (engine-spec §4). Every function is synchronous, pure and
1
+ // @glassbox-ai/engine public API. Every function is synchronous, pure and
2
2
  // total: none of them throws, and a failure never becomes a silent allow.
3
3
  import { classifyBuiltin, classifyMcp } from "./action/tools.js";
4
4
  import { pathCtxFrom } from "./action/paths.js";
@@ -15,9 +15,13 @@ import { get, getString, isRecord } from "./util/misc.js";
15
15
  import { ENGINE_VERSION as VERSION } from "./version.js";
16
16
  import { resolveLimits } from "./limits.js";
17
17
  export * from "./types.js";
18
+ /** Built-in Claude Code tools the engine knows, by category. Any other built-in tool is unanalyzable. */
19
+ export { BUILTIN_TOOLS } from "./action/builtin-tools.js";
20
+ /** Actions that always ask (deny in autopilot), whatever the user set up or the ruleset says. */
21
+ export { HARD_FLOOR_TAGS } from "./policy/decide.js";
18
22
  export const ENGINE_VERSION = VERSION;
19
23
  export const EMBEDDED_BASELINE = BASELINE;
20
- /** The only wording a grade may be presented with (engine-spec §9a). */
24
+ /** The only wording a grade may be presented with. */
21
25
  export const GRADE_SCOPE_STATEMENT = "A grade checks what a server says about its tools. It doesn't inspect the server's code.";
22
26
  const t = () => performance.now();
23
27
  export function analyzeServer(manifest, opts) {
@@ -1,4 +1,4 @@
1
- // C1–C2 (engine-spec §5.2): strict, bounded, iterative JSON parser.
1
+ // C1–C2: strict, bounded, iterative JSON parser.
2
2
  // - builds null-prototype objects; __proto__/constructor/prototype are plain data (CP-PARSE-003)
3
3
  // - duplicate keys are kept as "key~dupN" (CP-PARSE-001)
4
4
  // - lone surrogates (escaped or raw) are flagged (CP-PARSE-005)
@@ -1,4 +1,4 @@
1
- // C2.4 (engine-spec §5.2): snapshot an object input into frozen null-prototype data.
1
+ // C2.4: snapshot an object input into frozen null-prototype data.
2
2
  // Reads only own enumerable data properties via descriptors (getters are never invoked),
3
3
  // detects cycles, drops non-JSON values, survives hostile Proxies, bounded and iterative.
4
4
  import { parseJsonStrict } from "./json.js";
@@ -1,4 +1,4 @@
1
- import type { ActionRisk, Finding, LoadedRuleset, RememberedRule, UserPolicy, Verdict } from "../types.js";
1
+ import type { ActionRisk, ActionTag, Finding, LoadedRuleset, RememberedRule, SessionGrant, UserPolicy, Verdict } from "../types.js";
2
2
  export declare const vmax: (a: Verdict, b: Verdict) => Verdict;
3
3
  export interface DecideInput {
4
4
  kind: "call" | "result" | "server-request";
@@ -12,6 +12,10 @@ export interface DecideInput {
12
12
  serverId: string;
13
13
  toolName: string;
14
14
  remembered: readonly RememberedRule[];
15
+ /** The current project; a remembered rule applies only when its projectIdHash equals this. */
16
+ projectIdHash?: string | undefined;
17
+ sessionId: string;
18
+ sessionGrants: readonly SessionGrant[];
15
19
  /** checkServerRequest: verdict from the kind's policy (R13) and whether it's locked (R14). */
16
20
  requestVerdict?: {
17
21
  verdict: Verdict;
@@ -22,5 +26,14 @@ export interface DecideOutput {
22
26
  verdict: Verdict;
23
27
  verdictBeforeMode?: Verdict;
24
28
  }
29
+ /** Fixed in the engine, not in the ruleset: no ruleset can remove a tag from the hard floor. */
30
+ export declare const HARD_FLOOR_TAGS: readonly ActionTag[];
31
+ /**
32
+ * Persistence outside the project (rev 11, engine 0.1.2): startup files and profiles
33
+ * (CP-SELF-005) and scheduled jobs and autostart, including Windows Run keys (CP-SELF-006).
34
+ * A session grant covering the call may lift these findings; a remembered rule never does, so
35
+ * "Allow & remember" can't silence them for good. Fixed in the engine, like the hard floor.
36
+ */
37
+ export declare const GRANT_LIFTABLE_FINDINGS: readonly string[];
25
38
  export declare function decide(d: DecideInput): DecideOutput;
26
39
  //# sourceMappingURL=decide.d.ts.map
@@ -2,43 +2,96 @@ const ORDER = ["allow", "warn", "ask", "deny"];
2
2
  export const vmax = (a, b) => (ORDER.indexOf(a) >= ORDER.indexOf(b) ? a : b);
3
3
  const SEV = ["info", "low", "medium", "high", "critical"];
4
4
  /**
5
- * R3 by mode (spec §6.2, rev 5). Irreversible-or-public tags ask in every mode, so in
6
- * autopilot they become deny through R15 unless a tag override or a remembered rule lifts
7
- * the ask first. Other high-risk tags: strict asks, balanced and autopilot warn.
5
+ * R3 by mode.
6
+ * - Hard floor (HARD_FLOOR_TAGS, whatever the ruleset says): force push,
7
+ * history rewrite, wipes, payments, production deploys and publishing ask in every mode, and
8
+ * autopilot turns that into deny (R15). Nothing the user set up earlier lowers them: a
9
+ * tagOverride can only raise them to deny; remembered rules and session grants never lift them.
10
+ * - Other irreversible-or-public tags ask in every mode by default, but they are ordinary
11
+ * mode asks: a tagOverride, remembered rule or session grant can lift them.
12
+ * - Other high-risk tags: strict asks, balanced and autopilot warn.
8
13
  */
9
14
  function modeVerdict(tag, mode, irreversible) {
10
15
  if (tag !== null && irreversible.has(tag))
11
16
  return "ask";
12
17
  return mode === "strict" ? "ask" : "warn";
13
18
  }
19
+ /** Fixed in the engine, not in the ruleset: no ruleset can remove a tag from the hard floor. */
20
+ export const HARD_FLOOR_TAGS = Object.freeze(["vcs.force-push", "vcs.history-rewrite", "fs.destroy", "payment", "deploy.prod", "publish.public"]);
21
+ // Private copy used for decisions: a Set can't be frozen, so the exported list is a frozen array
22
+ // and changing anything a caller can reach doesn't change the floor.
23
+ const HARD_FLOOR = new Set(HARD_FLOOR_TAGS);
24
+ const str = (x) => typeof x === "string" && x.length > 0;
25
+ /**
26
+ * Persistence outside the project (rev 11, engine 0.1.2): startup files and profiles
27
+ * (CP-SELF-005) and scheduled jobs and autostart, including Windows Run keys (CP-SELF-006).
28
+ * A session grant covering the call may lift these findings; a remembered rule never does, so
29
+ * "Allow & remember" can't silence them for good. Fixed in the engine, like the hard floor.
30
+ */
31
+ export const GRANT_LIFTABLE_FINDINGS = Object.freeze(["CP-SELF-005", "CP-SELF-006"]);
32
+ const GRANT_LIFTABLE = new Set(GRANT_LIFTABLE_FINDINGS);
33
+ /** A session grant (this session only, never a remembered rule) covering (server, tool, tag). */
34
+ function grantCovers(d, tag) {
35
+ const own = (m, k, want) => Object.hasOwn(m, k) && m[k] === want;
36
+ return str(d.sessionId) && d.sessionGrants.some((g) => typeof g === "object" && g !== null &&
37
+ own(g, "serverId", d.serverId) && own(g, "toolName", d.toolName) && own(g, "actionTag", tag) && own(g, "sessionId", d.sessionId));
38
+ }
39
+ /** A remembered rule (this project) or session grant (this session) covering (server, tool, tag). */
40
+ function lifted(d, tag) {
41
+ // Own string properties only: a field inherited through a prototype doesn't count.
42
+ const own = (m, k, want) => Object.hasOwn(m, k) && m[k] === want;
43
+ const match = (m, scopeKey, scope) => typeof m === "object" && m !== null && own(m, "serverId", d.serverId) && own(m, "toolName", d.toolName) && own(m, "actionTag", tag) && own(m, scopeKey, scope);
44
+ const project = d.projectIdHash;
45
+ if (str(project) && d.remembered.some((m) => match(m, "projectIdHash", project)))
46
+ return true;
47
+ return str(d.sessionId) && d.sessionGrants.some((g) => match(g, "sessionId", d.sessionId));
48
+ }
14
49
  export function decide(d) {
15
50
  const mode = d.policy.mode;
16
51
  let v = "allow";
17
52
  const irreversible = new Set(d.ruleset.irreversibleTags);
18
- // R3 (calls only): high-risk action, by mode, then tagOverrides, then remembered rules.
53
+ // Set in R3: a session grant covers every liftable tag of this call (used for persistence findings below).
54
+ let grantLiftsPersistence = false;
55
+ // R3 (calls only): high-risk action, by mode, then tagOverrides, then remembered rules and
56
+ // session grants (mode-driven asks only, never the hard floor).
19
57
  if (d.kind === "call" && d.risk.level === "high-risk") {
20
58
  const tags = d.risk.tags.filter((t) => t !== "self-protection");
21
59
  let r3 = "allow";
22
- const askTags = [];
60
+ let floorAsk = false;
61
+ const liftable = [];
23
62
  const list = tags.length > 0 ? tags : [null];
24
63
  for (const t of list) {
25
- let tv = modeVerdict(t, mode, irreversible);
26
64
  const o = t !== null ? d.policy.tagOverrides?.[t] : undefined;
27
- if (o === "allow" || o === "ask" || o === "deny")
28
- tv = o;
29
- if (tv === "ask" && t !== null)
30
- askTags.push(t);
65
+ let tv;
66
+ if (t !== null && HARD_FLOOR.has(t)) {
67
+ tv = o === "deny" ? "deny" : "ask";
68
+ if (tv === "ask")
69
+ floorAsk = true;
70
+ }
71
+ else {
72
+ tv = modeVerdict(t, mode, irreversible);
73
+ if (o === "allow" || o === "ask" || o === "deny")
74
+ tv = o;
75
+ if (tv === "ask" && t !== null)
76
+ liftable.push(t);
77
+ }
31
78
  r3 = vmax(r3, tv);
32
79
  }
33
- if (r3 === "ask" && askTags.length > 0 && askTags.every((t) => d.remembered.some((m) => m.serverId === d.serverId && m.toolName === d.toolName && m.actionTag === t)))
80
+ if (r3 === "ask" && !floorAsk && liftable.length > 0 && liftable.every((t) => lifted(d, t)))
34
81
  r3 = "allow";
82
+ grantLiftsPersistence = !floorAsk && liftable.length > 0 && liftable.every((t) => grantCovers(d, t));
35
83
  v = vmax(v, r3);
36
84
  }
37
- // R4–R7: findings (confidence ≥ threshold).
85
+ // R4–R7: findings (confidence ≥ threshold). Persistence outside the project (high, not
86
+ // critical) is skipped only when a session grant covers the call; every other finding counts.
38
87
  let top = -1;
39
- for (const f of d.findings)
40
- if (f.confidence >= d.minConfidence)
41
- top = Math.max(top, SEV.indexOf(f.severity));
88
+ for (const f of d.findings) {
89
+ if (f.confidence < d.minConfidence)
90
+ continue;
91
+ if (grantLiftsPersistence && f.severity === "high" && GRANT_LIFTABLE.has(f.ruleId))
92
+ continue;
93
+ top = Math.max(top, SEV.indexOf(f.severity));
94
+ }
42
95
  if (top === 2)
43
96
  v = vmax(v, mode === "strict" ? "ask" : "warn");
44
97
  if (top === 3)
@@ -1,9 +1,8 @@
1
1
  import type { LoadedRuleset, LoadRulesetOptions, TrustedKey } from "../types.js";
2
2
  import { type RulesetPayload } from "./schema.js";
3
3
  /**
4
- * Trusted signing keys embedded in the engine build. Empty until the first production
5
- * key is created at release time: until then every signed cache is rejected and the
6
- * embedded baseline is used (the fail-safe direction).
4
+ * A copy for callers to inspect. Typed arrays can't be frozen, so verification uses the
5
+ * private list above: changing these bytes doesn't change which keys the engine trusts.
7
6
  */
8
7
  export declare const EMBEDDED_TRUSTED_KEYS: readonly TrustedKey[];
9
8
  export declare const REVOKED_KEY_IDS: readonly string[];
@@ -1,4 +1,4 @@
1
- // Ruleset loading (engine-spec §10.2, Q9 rev 4).
1
+ // Ruleset loading.
2
2
  import { ed25519 } from "@noble/curves/ed25519.js";
3
3
  import * as v from "valibot";
4
4
  import { decodeBase64 } from "../canon/decode.js";
@@ -11,11 +11,25 @@ import { EMBEDDED_BASELINE } from "./baseline.js";
11
11
  import { EnvelopeSchema, PayloadSchema } from "./schema.js";
12
12
  import { runRuleSelfTests } from "./selftest.js";
13
13
  /**
14
- * Trusted signing keys embedded in the engine build. Empty until the first production
15
- * key is created at release time: until then every signed cache is rejected and the
16
- * embedded baseline is used (the fail-safe direction).
14
+ * Trusted signing keys embedded in the engine build (Ed25519, raw 32-byte public keys).
15
+ * The private keys are held offline by the maintainer and are never on a server, in CI or in
16
+ * this repository. Rotation: a release adds the new key, rulesets are re-signed, and a later
17
+ * release lists the old keyId in REVOKED_KEY_IDS.
18
+ *
19
+ * gbx-2026-a: created 2026-11-25. SHA-256 of the raw key:
20
+ * 67872a7dd309ddc3c7eb69e20a67125c77767673976bae97149ec782799f62a0
17
21
  */
18
- export const EMBEDDED_TRUSTED_KEYS = Object.freeze([]);
22
+ const TRUSTED = Object.freeze([
23
+ Object.freeze({
24
+ keyId: "gbx-2026-a",
25
+ publicKey: new Uint8Array([190, 180, 255, 177, 167, 215, 118, 25, 172, 139, 36, 151, 55, 199, 138, 140, 220, 236, 181, 189, 112, 11, 85, 89, 56, 26, 137, 165, 154, 237, 99, 79]),
26
+ }),
27
+ ]);
28
+ /**
29
+ * A copy for callers to inspect. Typed arrays can't be frozen, so verification uses the
30
+ * private list above: changing these bytes doesn't change which keys the engine trusts.
31
+ */
32
+ export const EMBEDDED_TRUSTED_KEYS = Object.freeze(TRUSTED.map((k) => Object.freeze({ keyId: k.keyId, publicKey: k.publicKey.slice() })));
19
33
  export const REVOKED_KEY_IDS = Object.freeze([]);
20
34
  const DOMAIN = utf8("glassbox-ruleset-v1\u0000");
21
35
  const MAX_RULESET_BYTES = 4 * 1024 * 1024;
@@ -99,7 +113,7 @@ export function buildLoaded(payload, now, extra = {}) {
99
113
  }
100
114
  export function loadRuleset(envelope, opts) {
101
115
  try {
102
- const keys = opts?.trustedKeys ?? EMBEDDED_TRUSTED_KEYS;
116
+ const keys = opts?.trustedKeys ?? TRUSTED;
103
117
  const minSequence = typeof opts?.minSequence === "number" ? opts.minSequence : 0;
104
118
  const now = typeof opts?.now === "string" ? opts.now : "";
105
119
  const size = typeof envelope === "string" ? envelope.length : envelope instanceof Uint8Array ? envelope.length : -1;
@@ -71,7 +71,7 @@ export declare const PayloadSchema: v.ObjectSchema<{
71
71
  }, undefined>, undefined>, v.MaxLengthAction<{
72
72
  id: string;
73
73
  revision: number;
74
- category: "self-protection" | "tool-poisoning" | "hidden-content" | "prompt-injection" | "shadowing" | "rug-pull" | "exfiltration" | "secret-exposure" | "dangerous-action" | "obfuscation" | "capability-mismatch" | "integrity" | "resource-limit" | "hygiene" | "server-request" | "toxic-flow";
74
+ category: "tool-poisoning" | "hidden-content" | "prompt-injection" | "shadowing" | "rug-pull" | "exfiltration" | "secret-exposure" | "dangerous-action" | "obfuscation" | "capability-mismatch" | "self-protection" | "integrity" | "resource-limit" | "hygiene" | "server-request" | "toxic-flow";
75
75
  severity: "info" | "low" | "medium" | "high" | "critical";
76
76
  confidence: number;
77
77
  surfaces: ("server-request" | "manifest" | "call" | "result")[];
@@ -1,4 +1,4 @@
1
- // Ruleset payload schema (engine-spec §10.1–10.2), validated with valibot.
1
+ // Ruleset payload schema, validated with valibot.
2
2
  import * as v from "valibot";
3
3
  import { ACTION_TAGS } from "../types.js";
4
4
  const CATEGORIES = [