@noppu-labs/opencode-permission-reviewer 2.4.1 → 3.0.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 (46) hide show
  1. package/CHANGELOG.md +64 -1
  2. package/LICENSE +21 -201
  3. package/LICENSE-APACHE +201 -0
  4. package/NOTICE +14 -6
  5. package/README.md +100 -750
  6. package/SECURITY.md +41 -22
  7. package/dist/explain.js +4932 -3522
  8. package/dist/index.d.ts +520 -513
  9. package/dist/index.js +12595 -9115
  10. package/dist/rpc.js +4 -1
  11. package/dist/tui/config/jsonc.ts +71 -63
  12. package/dist/tui/config/layer-read.ts +120 -0
  13. package/dist/tui/config/loader.ts +61 -513
  14. package/dist/tui/config/risk-policy-clamp.ts +80 -0
  15. package/dist/tui/config/trust-boundary-keys.ts +100 -0
  16. package/dist/tui/config/trust-boundary.ts +135 -0
  17. package/dist/tui/config/trusted-degradation.ts +97 -0
  18. package/dist/tui/config-fields.ts +55 -0
  19. package/dist/tui/config-knobs.ts +119 -0
  20. package/dist/tui/config-policy-rules.ts +86 -0
  21. package/dist/tui/config-risk-policy.ts +59 -0
  22. package/dist/tui/config-rule-condition.ts +150 -0
  23. package/dist/tui/config.ts +61 -430
  24. package/dist/tui/descriptor-io.ts +42 -0
  25. package/dist/tui/is-record.ts +13 -0
  26. package/dist/tui/opencode/event-normalizer.ts +41 -31
  27. package/dist/tui/reviewer-model.ts +87 -0
  28. package/dist/tui/tui.tsx +87 -99
  29. package/dist/tui/types.ts +171 -538
  30. package/dist/tui/ui/components.tsx +32 -136
  31. package/dist/tui/ui/review-connection.ts +32 -0
  32. package/dist/tui/ui/review-feed.ts +131 -0
  33. package/dist/tui/ui/review-overlay.tsx +83 -0
  34. package/dist/tui/ui/review-result.tsx +56 -0
  35. package/dist/tui/ui/review-store.ts +88 -0
  36. package/dist/tui/ui/review-theme.ts +63 -0
  37. package/dist/tui/ui/rpc.ts +5 -2
  38. package/dist/tui/ui/v1-host.ts +39 -0
  39. package/dist/tui/ui/v2.tsx +66 -220
  40. package/dist/tui/ui-protocol.ts +63 -118
  41. package/dist/tui/ui-state.ts +71 -64
  42. package/dist/tui/ui-status-parse.ts +74 -0
  43. package/package.json +18 -17
  44. package/rpc.js +2 -1
  45. package/server.js +2 -2
  46. package/tui.tsx +2 -1
@@ -1,204 +1,39 @@
1
- import { closeSync, constants as fsConstants, fstatSync, openSync, readSync } from "node:fs"
2
- import { homedir } from "node:os"
3
- import { join } from "node:path"
4
- import { parseJsoncStrict } from "./jsonc.ts"
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { DEFAULT_CONFIG, resolveConfig } from "../config.ts";
4
+ import { countInvalidPolicyRules } from "../config-policy-rules.ts";
5
+ import type { ReviewerConfig } from "../types.ts";
6
+ import { type ConfigLayer, readConfigLayer } from "./layer-read.ts";
7
+ import type { InlineOptionsTrust } from "./sources.ts";
8
+ import { mergeWithTrustBoundary } from "./trust-boundary.ts";
9
+ import { TRUST_BOUNDARY_KEYS } from "./trust-boundary-keys.ts";
5
10
  import {
6
- countInvalidPolicyRules,
7
- resolveConfig,
8
- DEFAULT_CONFIG,
9
- DEFAULT_RISK_POLICY,
10
- isValidEscalationReviewer,
11
- } from "../config.ts"
12
- import type { PolicyRule, ReviewerConfig } from "../types.ts"
13
- import type { InlineOptionsTrust } from "./sources.ts"
14
-
15
- const O_RDONLY = typeof fsConstants.O_RDONLY === "number" ? fsConstants.O_RDONLY : 0
16
- const O_NOFOLLOW = typeof fsConstants.O_NOFOLLOW === "number" ? fsConstants.O_NOFOLLOW : 0
17
- const O_NONBLOCK = typeof fsConstants.O_NONBLOCK === "number" ? fsConstants.O_NONBLOCK : 0
18
-
19
- /** Cap on a single config file read: the project layer is repository-controlled
20
- * and read at startup, so an unbounded read lets a committed symlink to an
21
- * endless source exhaust memory. A file over the cap is treated like any
22
- * other unreadable layer (warned about and ignored). */
23
- const CONFIG_READ_CAP_BYTES = 1024 * 1024
24
-
25
- type LayerStatus = "missing" | "ok" | "read-error" | "malformed"
26
-
27
- interface ConfigLayer {
28
- raw: Record<string, unknown>
29
- status: LayerStatus
30
- /** Set when the file exists but could not be interpreted; a silently
31
- * unreadable trusted layer must be visible, not indistinguishable from an
32
- * absent one. */
33
- warning?: string
34
- }
35
-
36
- /** Read a JSONC config file. A missing file is the common case (status
37
- * "missing", no warning). A file that exists but cannot be read or parsed
38
- * keeps the plugin working with an empty layer, but the status lets the
39
- * caller treat an unusable TRUSTED layer as a fail-closed condition rather
40
- * than silently falling back to defaults.
41
- *
42
- * The read goes through an explicitly opened descriptor: O_NOFOLLOW rejects
43
- * a symlinked layer (a committed link to a FIFO would otherwise hang startup
44
- * and a link to an endless source would exhaust memory), O_NONBLOCK keeps a
45
- * FIFO from blocking before fstat can reject it, fstat requires a regular
46
- * file, and the byte cap bounds the read. */
47
- function readConfigLayer(path: string): ConfigLayer {
48
- const read = readLayerText(path)
49
- if (!("text" in read)) return read
50
- try {
51
- return { raw: parseJsoncStrict(read.text), status: "ok" }
52
- } catch (error) {
53
- return {
54
- raw: {},
55
- status: "malformed",
56
- warning: `permission-reviewer config at ${path} is malformed and was ignored (${error instanceof Error ? error.message : String(error)})`,
57
- }
58
- }
59
- }
60
-
61
- /** Read at most the capped bytes through the open descriptor. A missing file
62
- * is the common case (status "missing", no warning); anything else that
63
- * prevents honoring the layer degrades to the same warn-and-ignore outcome
64
- * the loader already uses for malformed files. Never throws. */
65
- function readLayerText(path: string): ConfigLayer | { status: "ok"; text: string } {
66
- const readError = (warning: string): ConfigLayer => ({ raw: {}, status: "read-error", warning })
67
- let fd: number | undefined
68
- try {
69
- try {
70
- // Read-only descriptor open of an existing config path; no file is
71
- // created here and the descriptor must pass the regular-file check below.
72
- // codeql[js/insecure-temporary-file]
73
- fd = openSync(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW)
74
- } catch (error) {
75
- const code = (error as { code?: unknown }).code
76
- if (code === "ENOENT") return { raw: {}, status: "missing" }
77
- return readError(
78
- `permission-reviewer config at ${path} exists but could not be read (${code ?? "unknown error"}); the layer was ignored`,
79
- )
80
- }
81
- const info = fstatSync(fd)
82
- if (!info.isFile()) {
83
- return readError(
84
- `permission-reviewer config at ${path} is not a regular file and was ignored`,
85
- )
86
- }
87
- if (info.size > CONFIG_READ_CAP_BYTES) {
88
- return readError(
89
- `permission-reviewer config at ${path} exceeds the size limit (${CONFIG_READ_CAP_BYTES} bytes) and was ignored`,
90
- )
91
- }
92
- const length = info.size
93
- const buffer = Buffer.alloc(length)
94
- let read = 0
95
- while (read < length) {
96
- const count = readSync(fd, buffer, read, length - read, read)
97
- if (count === 0) break
98
- read += count
99
- }
100
- // A concurrent shrink can end the read early; decode only the bytes
101
- // actually read so no zero-padding leaks into the parser.
102
- const text = (read < length ? buffer.subarray(0, read) : buffer).toString("utf8")
103
- return { status: "ok", text }
104
- } catch (error) {
105
- const code = (error as { code?: unknown }).code
106
- return readError(
107
- `permission-reviewer config at ${path} exists but could not be read (${code ?? "unknown error"}); the layer was ignored`,
108
- )
109
- } finally {
110
- if (fd !== undefined) {
111
- try {
112
- closeSync(fd)
113
- } catch {
114
- // Best effort; the read already succeeded or failed on its own.
115
- }
116
- }
117
- }
118
- }
11
+ globalLayerDegradation,
12
+ inlineDegradation,
13
+ } from "./trusted-degradation.ts";
119
14
 
120
15
  /** Optional override used by unit tests so a developer's personal global config
121
16
  * cannot leak into loader assertions. Production always uses the real path. */
122
- let globalConfigPathOverride: string | undefined
17
+ let globalConfigPathOverride: string | undefined;
123
18
 
124
19
  /** Path to the global user config. Exposed for testability. */
125
20
  export function globalConfigPath(): string {
126
21
  return (
127
- globalConfigPathOverride ?? join(homedir(), ".config", "opencode", "permission-reviewer.jsonc")
128
- )
22
+ globalConfigPathOverride ??
23
+ join(homedir(), ".config", "opencode", "permission-reviewer.jsonc")
24
+ );
129
25
  }
130
26
 
131
27
  /** Test-only: redirect (or clear) the global config path. */
132
28
  export function setGlobalConfigPathForTests(path: string | undefined): void {
133
- globalConfigPathOverride = path
29
+ globalConfigPathOverride = path;
134
30
  }
135
31
 
136
32
  /** Path to the project-local config. Exposed for testability. */
137
33
  export function projectConfigPath(directory: string): string {
138
- return join(directory, ".opencode", "permission-reviewer.jsonc")
34
+ return join(directory, ".opencode", "permission-reviewer.jsonc");
139
35
  }
140
36
 
141
- /** Fields managed by the trust boundary. For these, the boundary's output is
142
- * final: the project layer may only tighten them against the trusted
143
- * baseline (which already includes inline), and a later inline value must not
144
- * undo that tightening. For every other field the documented precedence
145
- * applies and inline (trusted, most specific) wins over the project. The
146
- * reviewer resource knobs (timeouts, context budgets) are the strictest
147
- * case: the project cannot set them at all, in either direction. */
148
- const TRUST_BOUNDARY_KEYS = new Set([
149
- "confidenceThreshold",
150
- "systemOneConfidenceThreshold",
151
- "systemOneReasoningThreshold",
152
- "audit",
153
- "auditPath",
154
- "model",
155
- "escalationReviewer",
156
- "policy",
157
- "repositoryTrust",
158
- "actorProfiles",
159
- "enforcementMode",
160
- "riskPolicy",
161
- "escalationMode",
162
- "policyRules",
163
- "variant",
164
- "outputFormat",
165
- "retainReviewSessions",
166
- "timeoutMs",
167
- "reviewBudgetMs",
168
- "maxContextChars",
169
- "maxPartChars",
170
- "maxEnrichmentChars",
171
- "maxIntentChars",
172
- "transcriptMessages",
173
- "intentMessages",
174
- "historyMessages",
175
- "maxSessionDepth",
176
- "maxParentSessions",
177
- "askDecisions",
178
- "debug",
179
- ])
180
-
181
- /** Reviewer resource knobs: how long a review may run and how much context
182
- * (transcript, evidence, session chains) it may consume. These are NOT
183
- * monotonic security fields: raising them means more conversation sent to
184
- * the provider, more cost, and longer processing, so a repository may not
185
- * move them in either direction. Only trusted global/inline config sets
186
- * them; the project layer is restricted to genuinely monotonic hardening
187
- * (deny/manual rules, allowed thresholds, repositoryTrust). */
188
- const TRUSTED_ONLY_RESOURCE_KEYS = [
189
- "timeoutMs",
190
- "reviewBudgetMs",
191
- "maxContextChars",
192
- "maxPartChars",
193
- "maxEnrichmentChars",
194
- "maxIntentChars",
195
- "transcriptMessages",
196
- "intentMessages",
197
- "historyMessages",
198
- "maxSessionDepth",
199
- "maxParentSessions",
200
- ] as const
201
-
202
37
  /** Load and merge config from global, project, and inline sources.
203
38
  *
204
39
  * Precedence (lowest to highest): builtin defaults → global → project → inline,
@@ -214,360 +49,73 @@ export function loadResolvedConfig(
214
49
  directory?: string,
215
50
  inlineTrust: InlineOptionsTrust = "trusted",
216
51
  ): ReviewerConfig {
217
- const globalLayer = readConfigLayer(globalConfigPath())
52
+ const globalLayer = readConfigLayer(globalConfigPath());
218
53
  const projectLayer: ConfigLayer =
219
54
  directory !== undefined
220
55
  ? readConfigLayer(projectConfigPath(directory))
221
- : { raw: {}, status: "missing" }
56
+ : { raw: {}, status: "missing" };
222
57
  for (const layer of [globalLayer, projectLayer]) {
223
- if (layer.warning !== undefined) console.warn(layer.warning)
224
- }
225
-
226
- // A TRUSTED layer that exists but cannot be honored may have lost the very
227
- // restrictions it was supposed to carry (deny rules, enforce mode, stricter
228
- // thresholds). That must degrade the config — automatic approval stays off
229
- // until the file is fixed — instead of quietly reactivating defaults.
230
- const degraded: string[] = []
231
- if (globalLayer.status === "malformed") {
232
- degraded.push("global config file is malformed and was ignored")
233
- } else if (globalLayer.status === "read-error") {
234
- degraded.push("global config file exists but could not be read")
235
- } else if (globalLayer.status === "ok") {
236
- if (
237
- globalLayer.raw.escalationReviewer !== undefined &&
238
- !isValidEscalationReviewer(globalLayer.raw.escalationReviewer)
239
- ) {
240
- degraded.push("global config escalationReviewer is invalid and was ignored")
241
- console.warn(
242
- "permission-reviewer: global config escalationReviewer is invalid and was ignored; automatic approval stays disabled until it is fixed",
243
- )
244
- }
245
- const invalidRules = countInvalidPolicyRules(globalLayer.raw.policyRules)
246
- if (invalidRules > 0) {
247
- degraded.push(
248
- `${invalidRules} policy rule(s) from the global config were dropped by validation`,
249
- )
250
- console.warn(
251
- `permission-reviewer: ${invalidRules} policy rule(s) in the global config are invalid and were dropped; automatic approval stays disabled until they are fixed`,
252
- )
253
- }
254
- // A mistyped mode silently falls back to the less restrictive default in
255
- // resolveConfig, so it gets the same fail-closed treatment as a dropped
256
- // rule: visible degradation instead of a quiet downgrade.
257
- const globalEnforcement = globalLayer.raw.enforcementMode
258
- if (
259
- globalEnforcement !== undefined &&
260
- globalEnforcement !== "enforce" &&
261
- globalEnforcement !== "observe"
262
- ) {
263
- degraded.push(
264
- `global config enforcementMode ${JSON.stringify(globalEnforcement)} is invalid and was ignored`,
265
- )
266
- console.warn(
267
- `permission-reviewer: global config enforcementMode ${JSON.stringify(globalEnforcement)} is invalid and was ignored; automatic approval stays disabled until it is fixed`,
268
- )
269
- }
270
- const globalEscalation = globalLayer.raw.escalationMode
271
- if (
272
- globalEscalation !== undefined &&
273
- globalEscalation !== "manual" &&
274
- globalEscalation !== "deny"
275
- ) {
276
- degraded.push(
277
- `global config escalationMode ${JSON.stringify(globalEscalation)} is invalid and was ignored`,
278
- )
279
- console.warn(
280
- `permission-reviewer: global config escalationMode ${JSON.stringify(globalEscalation)} is invalid and was ignored; automatic approval stays disabled until it is fixed`,
281
- )
282
- }
58
+ if (layer.warning !== undefined) console.warn(layer.warning);
283
59
  }
284
-
285
- const invalidInlineRules =
286
- inlineTrust === "trusted" ? countInvalidPolicyRules(inlineOptions?.policyRules) : 0
287
- if (invalidInlineRules > 0) {
288
- degraded.push(
289
- `${invalidInlineRules} policy rule(s) from inline config were dropped by validation`,
290
- )
291
- }
292
-
293
- // Same visibility for trusted inline modes (no console.warn, matching the
294
- // inline policyRules treatment above). resolveConfig still clamps the value
295
- // to the safe default; this only records that the trusted input was lost.
296
- if (inlineTrust === "trusted" && inlineOptions !== undefined) {
297
- if (
298
- inlineOptions.escalationReviewer !== undefined &&
299
- !isValidEscalationReviewer(inlineOptions.escalationReviewer)
300
- ) {
301
- degraded.push("inline config escalationReviewer is invalid and was ignored")
302
- }
303
- const inlineEnforcement = inlineOptions.enforcementMode
304
- if (
305
- inlineEnforcement !== undefined &&
306
- inlineEnforcement !== "enforce" &&
307
- inlineEnforcement !== "observe"
308
- ) {
309
- degraded.push(
310
- `inline config enforcementMode ${JSON.stringify(inlineEnforcement)} is invalid and was ignored`,
311
- )
312
- }
313
- const inlineEscalation = inlineOptions.escalationMode
314
- if (
315
- inlineEscalation !== undefined &&
316
- inlineEscalation !== "manual" &&
317
- inlineEscalation !== "deny"
318
- ) {
319
- degraded.push(
320
- `inline config escalationMode ${JSON.stringify(inlineEscalation)} is invalid and was ignored`,
321
- )
322
- }
323
- }
324
-
60
+ const degraded = [
61
+ ...globalLayerDegradation(globalLayer),
62
+ ...inlineDegradation(inlineOptions, inlineTrust),
63
+ ];
325
64
  // Dropped project rules are warned about but never degrade the config:
326
65
  // configDegraded describes trusted sources only, and project rules cannot
327
66
  // weaken trusted restrictions anyway.
328
- const invalidProjectRules = countInvalidPolicyRules(projectLayer.raw.policyRules)
67
+ const invalidProjectRules = countInvalidPolicyRules(
68
+ projectLayer.raw.policyRules,
69
+ );
329
70
  if (invalidProjectRules > 0) {
330
71
  console.warn(
331
72
  `permission-reviewer: ${invalidProjectRules} policy rule(s) in the project config are invalid and were dropped`,
332
- )
333
- }
73
+ );
74
+ }
75
+ const out = mergeLayers(
76
+ globalLayer.raw,
77
+ projectLayer.raw,
78
+ inlineOptions ?? {},
79
+ inlineTrust,
80
+ );
81
+ if (degraded.length > 0) out.configDegraded = degraded;
82
+ return resolveConfig(out);
83
+ }
334
84
 
85
+ function mergeLayers(
86
+ globalRaw: Record<string, unknown>,
87
+ projectRaw: Record<string, unknown>,
88
+ inline: Record<string, unknown>,
89
+ inlineTrust: InlineOptionsTrust,
90
+ ): Record<string, unknown> {
91
+ const trustedInline = inlineTrust === "trusted";
335
92
  // The trusted baseline is seeded with builtin defaults (so clamping always
336
93
  // has a floor) and includes inline, which participates as a trusted source
337
94
  // the project layer is clamped against.
338
95
  const trusted: Record<string, unknown> = {
339
96
  ...DEFAULT_CONFIG,
340
- ...globalLayer.raw,
341
- ...(inlineTrust === "trusted" ? (inlineOptions ?? {}) : {}),
342
- }
343
- let merged = mergeWithTrustBoundary(trusted, projectLayer.raw)
344
- if (inlineTrust !== "trusted") {
97
+ ...globalRaw,
98
+ ...(trustedInline ? inline : {}),
99
+ };
100
+ const merged = mergeWithTrustBoundary(trusted, projectRaw);
101
+ if (!trustedInline) {
345
102
  // Unknown-origin options may only contribute boundary-controlled hardening.
346
- const restrictions = Object.fromEntries(
347
- Object.entries(inlineOptions ?? {}).filter(([key]) => TRUST_BOUNDARY_KEYS.has(key)),
348
- )
349
- merged = mergeWithTrustBoundary(merged, restrictions)
103
+ return mergeWithTrustBoundary(merged, boundaryFields(inline));
350
104
  }
351
105
  // Inline keeps documented precedence over the project layer for every
352
106
  // non-security field (the boundary's own keys are exempt: re-applying inline
353
107
  // there could undo project hardening clamped against it).
354
- const out: Record<string, unknown> = { ...merged }
355
- for (const [key, value] of Object.entries(inlineOptions ?? {})) {
356
- if (inlineTrust === "trusted" && !TRUST_BOUNDARY_KEYS.has(key)) out[key] = value
357
- }
358
- if (degraded.length > 0) out.configDegraded = degraded
359
- return resolveConfig(out)
360
- }
361
-
362
- /** Whether the key is present in the layer (a `null`/wrong-type value must be
363
- * handled as a present-but-invalid override, never silently forwarded). */
364
- function hasKey(object: Record<string, unknown>, key: string): boolean {
365
- return Object.prototype.hasOwnProperty.call(object, key)
366
- }
367
-
368
- function isPlainObject(value: unknown): value is Record<string, unknown> {
369
- return typeof value === "object" && value !== null && !Array.isArray(value)
370
- }
371
-
372
- /** Merge the trusted baseline with the untrusted project layer. Project config
373
- * can only TIGHTEN security-sensitive fields, never weaken them. A project
374
- * value of the wrong type (including `null`) is dropped so it can never fall
375
- * through to `resolveConfig`'s defaults and reset a trusted restriction. */
376
- function mergeWithTrustBoundary(
377
- trusted: Record<string, unknown>,
378
- project: Record<string, unknown>,
379
- ): Record<string, unknown> {
380
- const clamped = { ...project }
381
-
382
- // configDegraded describes the state of TRUSTED sources; the project layer
383
- // has no say in it (injecting fake degradation would only tighten, but the
384
- // field must stay authoritative for the loader that computes it).
385
- delete clamped.configDegraded
386
-
387
- // Numeric floors: project config can raise but not lower them; non-numeric
388
- // values (including null) are ignored so they cannot reset a trusted floor.
389
- // Confidence floors guard the decision gate and are monotonic hardening:
390
- // a stricter threshold is always safer, so the project may add one.
391
- for (const key of [
392
- "confidenceThreshold",
393
- "systemOneConfidenceThreshold",
394
- "systemOneReasoningThreshold",
395
- ] as const) {
396
- if (hasKey(clamped, key)) {
397
- if (typeof clamped[key] !== "number" || !Number.isFinite(clamped[key])) {
398
- delete clamped[key]
399
- } else {
400
- const floor =
401
- typeof trusted[key] === "number"
402
- ? (trusted[key] as number)
403
- : (DEFAULT_CONFIG[key as keyof typeof DEFAULT_CONFIG] as number)
404
- if (clamped[key] < floor) clamped[key] = floor
405
- }
406
- }
407
- }
408
-
409
- // Reviewer resource knobs (timeouts and context budgets) are deleted
410
- // outright: they are not monotonic, so neither raising nor lowering them
411
- // from a repository is safe. Wrong-typed values are dropped with them.
412
- for (const key of TRUSTED_ONLY_RESOURCE_KEYS) {
413
- delete clamped[key]
414
- }
415
-
416
- // audit: project can enable but not disable.
417
- if (clamped.audit === false && trusted.audit !== false) {
418
- delete clamped.audit
419
- }
420
-
421
- // askDecisions: prior user answers are scoped-authorization evidence for
422
- // the reviewer. Only trusted layers may decide whether the reviewer sees
423
- // them; a repository can neither strip them nor inject them.
424
- delete clamped.askDecisions
425
-
426
- // auditPath: only trusted global/inline config may choose the audit
427
- // destination. A repository must never be able to redirect or silence the
428
- // audit trail by pointing it at /dev/null or a path it controls.
429
- delete clamped.auditPath
430
-
431
- // model and policy: the reviewer destination and the tenant policy text are
432
- // trusted decisions. A repository must not choose where code/context is sent
433
- // for review, nor rewrite the policy the reviewer enforces. The reasoning
434
- // variant, the decision output format, and review-session retention are the
435
- // same class of decision: a weaker variant, a looser output format, or
436
- // silenced retention must not be selectable from a repository.
437
- delete clamped.model
438
- delete clamped.escalationReviewer
439
- delete clamped.policy
440
- delete clamped.variant
441
- delete clamped.outputFormat
442
- delete clamped.retainReviewSessions
443
- delete clamped.debug
444
-
445
- // repositoryTrust: the project layer may only declare its own repository
446
- // untrusted; it cannot grant "trusted" or reset a trusted "untrusted".
447
- if (clamped.repositoryTrust !== "untrusted") {
448
- delete clamped.repositoryTrust
449
- }
450
-
451
- // actorProfiles: name→profile mappings are a trust delegation (which agent
452
- // gets which capability profile). Only trusted global/inline config may
453
- // grant them; otherwise a repository could promote its own agent to a
454
- // higher-privilege profile ("build" → "operator"). trustedProjects opt-in is
455
- // a future item; until then the project layer cannot define mappings at all.
456
- delete clamped.actorProfiles
457
-
458
- // enforcementMode: project cannot enable OR disable enforcement — only
459
- // global/inline can. A project "enforce" is deleted (can't enable), and a
460
- // project "observe" when the trusted baseline is "enforce" is also deleted
461
- // (can't downgrade from a global enforcement setting).
462
- if (clamped.enforcementMode !== undefined) {
463
- if (clamped.enforcementMode === "enforce" || trusted.enforcementMode === "enforce") {
464
- delete clamped.enforcementMode
465
- }
466
- }
467
-
468
- // riskPolicy: project can narrow allow cells and harden failure knobs, never
469
- // relax a trusted deny or widen an allow cell. A non-object value (including
470
- // null) is ignored entirely so it cannot wipe the trusted matrix.
471
- if (hasKey(clamped, "riskPolicy")) {
472
- if (isPlainObject(clamped.riskPolicy)) {
473
- const trustedPolicy = isPlainObject(trusted.riskPolicy)
474
- ? trusted.riskPolicy
475
- : (DEFAULT_RISK_POLICY as unknown as Record<string, unknown>)
476
- clamped.riskPolicy = clampRiskPolicy(clamped.riskPolicy, trustedPolicy)
477
- } else {
478
- delete clamped.riskPolicy
479
- }
480
- }
481
-
482
- // escalationMode: project can only harden manual → deny, never relax deny →
483
- // manual. Invalid values are dropped so they cannot override a trusted deny
484
- // through resolveConfig's "anything but deny → manual" fallback.
485
- if (clamped.escalationMode !== undefined) {
486
- if (clamped.escalationMode !== "manual" && clamped.escalationMode !== "deny") {
487
- delete clamped.escalationMode
488
- } else if (clamped.escalationMode === "manual" && trusted.escalationMode === "deny") {
489
- delete clamped.escalationMode
490
- }
491
- }
492
-
493
- // policyRules: the project layer ADDS rules (which can only tighten — its
494
- // allow rules are filtered by the engine), it never erases trusted
495
- // global/inline deny/manual rules. Combine instead of replace so a repo
496
- // cannot weaken policy by declaring an empty or narrower rule set. Project
497
- // rules are also re-tagged source:"project" so they cannot spoof
498
- // source:"inline" to bypass the project-allow filter.
499
- if (Array.isArray(clamped.policyRules)) {
500
- const projectRules = (clamped.policyRules as Array<Record<string, unknown>>).map((rule) => ({
501
- ...rule,
502
- source: "project" as PolicyRule["source"],
503
- }))
504
- const trustedRules = Array.isArray(trusted.policyRules) ? trusted.policyRules : []
505
- clamped.policyRules = [...trustedRules, ...projectRules]
506
- } else if (Array.isArray(trusted.policyRules)) {
507
- // Project omitted policyRules entirely: preserve the trusted rules.
508
- clamped.policyRules = trusted.policyRules
108
+ const out: Record<string, unknown> = { ...merged };
109
+ for (const [key, value] of Object.entries(inline)) {
110
+ if (!TRUST_BOUNDARY_KEYS.has(key)) out[key] = value;
509
111
  }
510
-
511
- return { ...trusted, ...clamped }
112
+ return out;
512
113
  }
513
114
 
514
- /** Ensure project riskPolicy can only tighten the trusted baseline. */
515
- function clampRiskPolicy(
516
- project: Record<string, unknown>,
517
- trusted: Record<string, unknown>,
115
+ function boundaryFields(
116
+ options: Record<string, unknown>,
518
117
  ): Record<string, unknown> {
519
- const projectAllow =
520
- typeof project.allow === "object" && project.allow !== null
521
- ? (project.allow as Record<string, unknown>)
522
- : undefined
523
- const trustedAllow =
524
- typeof trusted.allow === "object" && trusted.allow !== null
525
- ? (trusted.allow as Record<string, unknown>)
526
- : {}
527
- const clampedAllow: Record<string, unknown> = {}
528
- for (const risk of ["low", "medium", "high", "critical"] as const) {
529
- const trustedCell = Array.isArray(trustedAllow[risk]) ? (trustedAllow[risk] as unknown[]) : []
530
- if (projectAllow === undefined) {
531
- // Project omitted allow entirely: keep the trusted cells.
532
- clampedAllow[risk] = trustedCell
533
- continue
534
- }
535
- const projectCell = Array.isArray(projectAllow[risk]) ? (projectAllow[risk] as unknown[]) : []
536
- // Intersection: project can only remove, never add. Missing project cell →
537
- // empty intersection (most restrictive) when the project provided an allow
538
- // object at all.
539
- clampedAllow[risk] = trustedCell.filter((auth) => projectCell.includes(auth))
540
- }
541
-
542
- // Start from trusted so partial project objects cannot wipe failure knobs.
543
- const out: Record<string, unknown> = {
544
- ...trusted,
545
- allow: clampedAllow,
546
- }
547
-
548
- // Failure knobs: project may harden manual → deny only.
549
- if (project.onInvalidDecision === "deny" || trusted.onInvalidDecision === "deny") {
550
- out.onInvalidDecision = "deny"
551
- } else if (project.onInvalidDecision === "manual" || project.onInvalidDecision === undefined) {
552
- out.onInvalidDecision = trusted.onInvalidDecision ?? "manual"
553
- }
554
-
555
- if (project.onReviewerFailure === "deny" || trusted.onReviewerFailure === "deny") {
556
- out.onReviewerFailure = "deny"
557
- } else if (project.onReviewerFailure === "manual" || project.onReviewerFailure === undefined) {
558
- out.onReviewerFailure = trusted.onReviewerFailure ?? "manual"
559
- }
560
-
561
- // minimumConfidence: project can raise but not lower.
562
- const trustedMin =
563
- typeof trusted.minimumConfidence === "number" && Number.isFinite(trusted.minimumConfidence)
564
- ? trusted.minimumConfidence
565
- : DEFAULT_RISK_POLICY.minimumConfidence
566
- if (typeof project.minimumConfidence === "number" && Number.isFinite(project.minimumConfidence)) {
567
- out.minimumConfidence = Math.max(trustedMin, project.minimumConfidence)
568
- } else {
569
- out.minimumConfidence = trustedMin
570
- }
571
-
572
- return out
118
+ return Object.fromEntries(
119
+ Object.entries(options).filter(([key]) => TRUST_BOUNDARY_KEYS.has(key)),
120
+ );
573
121
  }