@noppu-labs/opencode-permission-reviewer 2.4.2 → 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 +44 -1
  2. package/LICENSE +21 -201
  3. package/LICENSE-APACHE +201 -0
  4. package/NOTICE +14 -6
  5. package/README.md +100 -787
  6. package/SECURITY.md +41 -22
  7. package/dist/explain.js +4932 -3522
  8. package/dist/index.d.ts +508 -547
  9. package/dist/index.js +12454 -9030
  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 +170 -597
  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 +16 -15
  44. package/rpc.js +2 -1
  45. package/server.js +2 -2
  46. package/tui.tsx +2 -1
package/dist/index.d.ts CHANGED
@@ -1,6 +1,17 @@
1
1
  import { Plugin as Plugin$1 } from '@opencode-ai/plugin';
2
2
  import { Plugin } from '@opencode/plugin';
3
3
 
4
+ interface VerifiedScriptEvidence {
5
+ sha256: string;
6
+ destination: string;
7
+ port?: number;
8
+ shell: "bash" | "sh";
9
+ bytes?: number;
10
+ status: "full" | "reused" | "unavailable";
11
+ text: string;
12
+ cacheKey?: string;
13
+ }
14
+
4
15
  interface ShellToken {
5
16
  /** Original text including any surrounding quotes. */
6
17
  raw: string;
@@ -32,15 +43,160 @@ interface ShellSegment {
32
43
  precededBy?: string;
33
44
  }
34
45
 
35
- interface VerifiedScriptEvidence {
36
- sha256: string;
37
- destination: string;
38
- port?: number;
39
- shell: "bash" | "sh";
40
- bytes?: number;
41
- status: "full" | "reused" | "unavailable";
42
- text: string;
43
- cacheKey?: string;
46
+ /** How completely the command could be statically analyzed. */
47
+ type ParserCompleteness =
48
+ /** Fully parsed: no variables, globs, substitutions, or heredoc bodies. */
49
+ "complete-for-supported-form"
50
+ /** Some constructs could not be resolved (variables, partial heredoc). */
51
+ | "partial"
52
+ /** Heavy dynamic constructs (command substitution, eval, dynamic heredoc). */
53
+ | "opaque";
54
+ /** A redirection extracted from a parsed command segment. */
55
+ interface Redirection {
56
+ /** `>` `>>` `<` `2>` `&>` etc. */
57
+ operator: string;
58
+ /** Target path (file descriptor targets normalized to a path when possible). */
59
+ target: string;
60
+ /** Whether the target was quoted in the source (affects literal-ness). */
61
+ quoted: boolean;
62
+ }
63
+ /** A heredoc extracted before lexing so its body never reaches the lexer/brake. */
64
+ interface HeredocRecord {
65
+ /** The literal delimiter token as it appeared (`EOF`, `END`, …). */
66
+ delimiter: string;
67
+ /** `<<` (expansion on) or `<<-` (tabs stripped) — normalized form. */
68
+ operator: string;
69
+ /** Whether the delimiter was quoted, disabling expansion (`<<'EOF'`). */
70
+ expansionDisabled: boolean;
71
+ /** Bounded + redacted body (truncated to a safe length). */
72
+ bodyBounded: string;
73
+ /** SHA-256 of the full, unredacted body (stable identity without leaking it). */
74
+ bodySha256: string;
75
+ /** Whether the body was truncated for storage. */
76
+ truncated: boolean;
77
+ /** Output path associated with the heredoc when a `> path` precedes it. */
78
+ outputTarget?: string;
79
+ /** Whether the body is dynamically constructed (unresolvable expansion). */
80
+ dynamic: boolean;
81
+ }
82
+ /** A command parsed into a reusable structure. Wraps the existing lexer output
83
+ * plus pre-extracted redirections and heredocs. */
84
+ interface ParsedCommand {
85
+ /** The command after heredoc bodies were replaced with placeholders. */
86
+ sanitizedCommand: string;
87
+ /** Lexed segments of the sanitized command. */
88
+ segments: ShellSegment[];
89
+ /** Effective commands (wrappers peeled) per segment. */
90
+ effective: ShellToken[][];
91
+ /** Redirections grouped by segment index. */
92
+ redirections: Redirection[][];
93
+ /** Heredocs extracted before lexing. */
94
+ heredocs: HeredocRecord[];
95
+ /** Whether the original command contained any dynamic constructs. */
96
+ hasDynamicConstructs: boolean;
97
+ /** True when the lexer's depth or expansion budget stopped command-string
98
+ * resolution early; `effective` is then a prefix of the real structure and
99
+ * deterministic facts do not cover the whole command. */
100
+ analysisTruncated: boolean;
101
+ }
102
+ /** What the action can do, what it appears to do, and analysis confidence. */
103
+ interface CapabilityAssessment {
104
+ /** Best single-label summary of the dominant capability. */
105
+ actionClass: Provenanced<CapabilityActionClass>;
106
+ /** Human-readable summary of the detected surface. */
107
+ summary: string;
108
+ /** Executes an interpreter or runtime (sh, python, node, bun, …). */
109
+ executesCode: Provenanced<boolean | "unknown">;
110
+ /** Executes code that lives in the repository (scripts, test files). */
111
+ executesRepositoryCode: Provenanced<boolean | "unknown">;
112
+ /** Executes ad-hoc code generated by the agent (heredoc/inline). */
113
+ createsAdHocCode: Provenanced<boolean | "unknown">;
114
+ /** Invokes a known test runner (pytest, jest, bun test, …). */
115
+ invokesExistingTestRunner: Provenanced<boolean | "unknown">;
116
+ /** Runs a package manager that may execute lifecycle scripts. */
117
+ invokesPackageLifecycleScripts: Provenanced<boolean | "unknown">;
118
+ /** Reads literal credential material through a known file reader. */
119
+ credentialRead: Provenanced<boolean | "unknown">;
120
+ /** Detected file-write surface. */
121
+ writeEffects: {
122
+ temporaryWrite: Provenanced<boolean | "unknown">;
123
+ workspaceWrite: Provenanced<boolean | "unknown">;
124
+ externalWrite: Provenanced<boolean | "unknown">;
125
+ deletion: Provenanced<boolean | "unknown">;
126
+ };
127
+ /** Detected network surface. */
128
+ network: {
129
+ observed: Provenanced<boolean | "unknown">;
130
+ possible: Provenanced<boolean | "unknown">;
131
+ /** Hosts/destinations observed literally in the command. */
132
+ destinations: string[];
133
+ observedAccess: Provenanced<boolean | "unknown">;
134
+ possibleAccess: Provenanced<boolean | "unknown">;
135
+ };
136
+ /** Detected process side-effects. */
137
+ process: {
138
+ childProcesses: Provenanced<boolean | "unknown">;
139
+ persistence: Provenanced<boolean | "unknown">;
140
+ privilegeEscalation: Provenanced<boolean | "unknown">;
141
+ };
142
+ /** Detected remote-operation surface (ssh, etc.). */
143
+ remote: {
144
+ enabled: Provenanced<boolean | "unknown">;
145
+ mutationHint: Provenanced<boolean | "unknown">;
146
+ };
147
+ /** Detected git mutation surface. */
148
+ git: {
149
+ observed: Provenanced<boolean | "unknown">;
150
+ possible: Provenanced<boolean | "unknown">;
151
+ observedAccess: Provenanced<boolean | "unknown">;
152
+ possibleAccess: Provenanced<boolean | "unknown">;
153
+ };
154
+ /** How completely the command could be analyzed. */
155
+ parserCompleteness: ParserCompleteness;
156
+ /** Free-form warnings about analysis limitations. */
157
+ analysisWarnings: string[];
158
+ }
159
+
160
+ declare const SYSTEM_ONE_BASES: readonly ["authorized_routine", "authorized_reversible_change", "insufficient_authorization", "scope_mismatch", "insufficient_evidence", "destructive_effect", "credential_or_private_data", "security_or_privilege_change", "external_or_remote_effect", "trusted_policy_restriction", "conflicting_evidence"];
161
+ type SystemOnePrimaryBasis = (typeof SYSTEM_ONE_BASES)[number];
162
+ interface SystemOneChoiceScore<T extends string> {
163
+ choice: T;
164
+ confidence: number;
165
+ }
166
+ /** Probability (0-1) that each safety question is true. */
167
+ interface SystemOneSignals {
168
+ materialAuthorization: number;
169
+ withinIntentScope: number;
170
+ unauthorizedDataLoss: number;
171
+ untrustedSensitiveDisclosure: number;
172
+ excessiveCredentialAccess: number;
173
+ unauthorizedSecurityChange: number;
174
+ unauthorizedExternalMutation: number;
175
+ essentialEvidenceMissing: number;
176
+ absolutePolicyDeny: number;
177
+ }
178
+ /**
179
+ * Jev's own answer, kept apart from the final decision because a reasoning
180
+ * reviewer may replace it. Numbers, enum choices, fixed contradiction strings,
181
+ * and the provider-reported model ID only; never evidence text.
182
+ */
183
+ interface SystemOneScores {
184
+ /** Versioned model ID the provider reported as having answered. */
185
+ returnedModel: string;
186
+ outcome: SystemOneChoiceScore<ReviewOutcome> & {
187
+ probabilities: Record<ReviewOutcome, number>;
188
+ };
189
+ supporting: {
190
+ riskLevel: SystemOneChoiceScore<RiskLevel>;
191
+ userAuthorization: SystemOneChoiceScore<UserAuthorization>;
192
+ scopeAlignment: SystemOneChoiceScore<ScopeAlignment>;
193
+ evidenceCompleteness: SystemOneChoiceScore<EvidenceSufficiency>;
194
+ primaryBasis: SystemOneChoiceScore<SystemOnePrimaryBasis>;
195
+ };
196
+ signals: SystemOneSignals;
197
+ /** Consistency checks that failed; any one marks an allow or deny difficult. */
198
+ contradictions: string[];
199
+ reasoningRecommended: boolean;
44
200
  }
45
201
 
46
202
  type RiskLevel = "low" | "medium" | "high" | "critical";
@@ -273,219 +429,26 @@ interface ReviewEnvelope {
273
429
  * prompt (USER_ASK_DECISIONS) and audit, never into enforcement. */
274
430
  askDecisions?: AskDecision[];
275
431
  }
276
- /** Which layer produced the final decision for a request. Threaded into the
277
- * audit record so reports can split outcomes by source. */
278
- type DecisionSource = "emergency-brake" | "deterministic-policy" | "llm-reviewer" | "system-one-reviewer" | "manual-superseded" | "failure-safe";
279
- interface ReviewAuditRecord {
280
- /**
281
- * Audit schema version. Present on every record; readers default a missing
282
- * field to `1` (additive — old records are still valid).
283
- * Bump only on a breaking change to the record shape.
284
- */
285
- schemaVersion?: number;
286
- reviewID?: string;
287
- hostRequestID?: string;
288
- hostGeneration?: "v1" | "v2";
289
- hostVersion?: string;
290
- generation?: string;
291
- nativeAction?: string;
292
- directory?: string;
293
- application?: "evaluation-returned" | "reply-accepted" | "human-pending" | "superseded" | "cancelled" | "unknown";
294
- pluginVersion?: string;
295
- effectiveConfigHash?: string;
296
- actionFingerprint?: string;
297
- /** Version of the structured-decision schema the reviewer was asked to emit. */
298
- decisionSchemaVersion?: number;
299
- /** Version of the reviewer system prompt used for this decision. */
300
- promptVersion?: string;
301
- /** Which layer produced the outcome (brake, policy, reviewer, supersede,
302
- * failure-safe). Absent on legacy v1 records. */
303
- decisionSource?: DecisionSource;
304
- timestamp: string;
305
- durationMs: number;
432
+ interface ApprovedAnnotation {
306
433
  requestID: string;
307
434
  sessionID: string;
308
- permission: string;
309
- /** Stable hash of the canonical request (permission, patterns, metadata,
310
- * tool) for cross-record correlation. Absent on legacy v1 records. */
311
- actionHash?: string;
312
- outcome: ReviewExecutionResult["kind"];
435
+ decision: ReviewDecision;
436
+ }
437
+ interface ReviewExecutionResult {
438
+ kind: "allow" | "deny" | "escalate";
439
+ decision?: ReviewDecision;
313
440
  reason: string;
314
- riskLevel?: RiskLevel;
315
- userAuthorization?: UserAuthorization;
316
- /** How well the action aligned with the recovered intent (from the reviewer
317
- * decision). Absent when no reviewer decision was reached. */
318
- scopeAlignment?: ScopeAlignment;
319
- confidence?: number;
320
- /**
321
- * Structured outcome emitted by the reviewer LLM before gates/disposition.
322
- * Absent when no valid structured decision was produced (brake, policy,
323
- * failure-safe, supersede).
324
- */
325
- reviewerOutcome?: ReviewOutcome;
326
- /**
327
- * How an internal escalate was disposed. Present only when the logical result
328
- * was escalate (or a gate converted allow→escalate) and enforcement chose
329
- * manual or deny. Absent for explicit deny, allow, and manual-superseded.
330
- */
331
- escalationDisposition?: EscalationDisposition;
332
- /** The model that produced the final reviewer decision. */
441
+ reviewSessionID?: string;
442
+ /** Which layer produced this result; threaded into the audit record. */
443
+ decisionSource?: DecisionSource;
444
+ /** Actual model that produced the final reviewer decision. */
333
445
  reviewerModel?: string;
334
- /** Present when a System One result was handed to a reasoning reviewer. */
446
+ /** Primary model and routing reason when a second reviewer was used. */
335
447
  reviewerEscalatedFrom?: {
336
448
  model: string;
337
449
  reason: string;
338
450
  };
339
- /** Jev's scores whenever it returned a parsed decision, including when a
340
- * reasoning reviewer made the final call. */
341
- systemOne?: SystemOneScores;
342
- /** Per-phase timings. Absent on legacy v1 records and on deterministic paths
343
- * that never reach that phase. */
344
- timings?: {
345
- contextMs?: number;
346
- enrichmentMs?: number;
347
- reviewerMs?: number;
348
- replyMs?: number;
349
- };
350
- /** Non-fatal warnings accumulated during evidence collection/analysis. */
351
- warnings?: string[];
352
- reviewerSessionID?: string;
353
- /** Content identity and inspection mode only; never script text or local path. */
354
- verifiedScript?: {
355
- sha256: string;
356
- status: "full" | "reused" | "unavailable";
357
- bytes?: number;
358
- };
359
- /** Root session of the request's ancestry (additive; absent when lineage was
360
- * unavailable). */
361
- rootSessionID?: string;
362
- /** Overall evidence completeness for the request (additive). */
363
- evidenceCompleteness?: string;
364
- /** Resolved actor snapshot for audit (additive). Uses identityCompleteness
365
- * (not the decision's numeric confidence) to avoid field ambiguity; v2 also
366
- * carries identitySource + confidence. */
367
- actor?: {
368
- name?: string;
369
- mode?: string;
370
- profile: ActorProfile;
371
- identityCompleteness: "complete" | "partial" | "unknown";
372
- /** How the agent identity was established (tool-message, session-api,
373
- * unavailable, …). Absent on legacy v1 records. */
374
- identitySource?: string;
375
- /** Reliability of the identity claim. Absent on legacy v1 records. */
376
- confidence?: EvidenceConfidence;
377
- delegationDepth?: number;
378
- };
379
- ssh?: Array<{
380
- destination: string;
381
- port?: string;
382
- remoteCommandSha256?: string;
383
- stdinSource?: string;
384
- stdinStatus?: string;
385
- stdinReason?: string;
386
- }>;
387
- /** Additive capability snapshot for audit (observe-only). */
388
- capability?: {
389
- actionClass: string;
390
- summary: string;
391
- parserCompleteness: string;
392
- executesCode?: boolean;
393
- createsAdHocCode?: boolean;
394
- invokesPackageLifecycleScripts?: boolean;
395
- writeEffects?: {
396
- temporaryWrite?: boolean;
397
- workspaceWrite?: boolean;
398
- externalWrite?: boolean;
399
- deletion?: boolean;
400
- };
401
- networkObserved?: boolean;
402
- credentialRead?: boolean;
403
- privilegeEscalation?: boolean;
404
- persistence?: boolean;
405
- remoteEnabled?: boolean;
406
- gitMutation?: boolean;
407
- };
408
- /** Additive policy trace for audit (observe-only). */
409
- policyTrace?: {
410
- effectivePolicyHash: string;
411
- matchedRules: Array<{
412
- id: string;
413
- source: string;
414
- effect: string;
415
- reason: string;
416
- }>;
417
- finalRoute: string;
418
- mode: string;
419
- };
420
- /** Additive snapshot of the ask decisions surfaced to the reviewer prompt
421
- * (observe-only; capped to the most recent few). */
422
- askDecisions?: Array<{
423
- at: number;
424
- question: string;
425
- answer: string;
426
- }>;
427
- }
428
- declare const SYSTEM_ONE_BASES: readonly ["authorized_routine", "authorized_reversible_change", "insufficient_authorization", "scope_mismatch", "insufficient_evidence", "destructive_effect", "credential_or_private_data", "security_or_privilege_change", "external_or_remote_effect", "trusted_policy_restriction", "conflicting_evidence"];
429
- type SystemOnePrimaryBasis = (typeof SYSTEM_ONE_BASES)[number];
430
- interface SystemOneChoiceScore<T extends string> {
431
- choice: T;
432
- confidence: number;
433
- }
434
- /** Probability (0-1) that each safety question is true. */
435
- interface SystemOneSignals {
436
- materialAuthorization: number;
437
- withinIntentScope: number;
438
- unauthorizedDataLoss: number;
439
- untrustedSensitiveDisclosure: number;
440
- excessiveCredentialAccess: number;
441
- unauthorizedSecurityChange: number;
442
- unauthorizedExternalMutation: number;
443
- essentialEvidenceMissing: number;
444
- absolutePolicyDeny: number;
445
- }
446
- /**
447
- * Jev's own answer, kept apart from the final decision because a reasoning
448
- * reviewer may replace it. Numbers, enum choices, fixed contradiction strings,
449
- * and the provider-reported model ID only; never evidence text.
450
- */
451
- interface SystemOneScores {
452
- /** Versioned model ID the provider reported as having answered. */
453
- returnedModel: string;
454
- outcome: SystemOneChoiceScore<ReviewOutcome> & {
455
- probabilities: Record<ReviewOutcome, number>;
456
- };
457
- supporting: {
458
- riskLevel: SystemOneChoiceScore<RiskLevel>;
459
- userAuthorization: SystemOneChoiceScore<UserAuthorization>;
460
- scopeAlignment: SystemOneChoiceScore<ScopeAlignment>;
461
- evidenceCompleteness: SystemOneChoiceScore<EvidenceSufficiency>;
462
- primaryBasis: SystemOneChoiceScore<SystemOnePrimaryBasis>;
463
- };
464
- signals: SystemOneSignals;
465
- /** Consistency checks that failed; any one marks an allow or deny difficult. */
466
- contradictions: string[];
467
- reasoningRecommended: boolean;
468
- }
469
- interface ApprovedAnnotation {
470
- requestID: string;
471
- sessionID: string;
472
- decision: ReviewDecision;
473
- }
474
- interface ReviewExecutionResult {
475
- kind: "allow" | "deny" | "escalate";
476
- decision?: ReviewDecision;
477
- reason: string;
478
- reviewSessionID?: string;
479
- /** Which layer produced this result; threaded into the audit record. */
480
- decisionSource?: DecisionSource;
481
- /** Actual model that produced the final reviewer decision. */
482
- reviewerModel?: string;
483
- /** Primary model and routing reason when a second reviewer was used. */
484
- reviewerEscalatedFrom?: {
485
- model: string;
486
- reason: string;
487
- };
488
- /** Jev's scores whenever it returned a parsed decision. */
451
+ /** Jev's scores whenever it returned a parsed decision. */
489
452
  systemOne?: SystemOneScores;
490
453
  /**
491
454
  * Structured outcome from the reviewer LLM before gates/disposition.
@@ -499,6 +462,11 @@ interface ReviewExecutionResult {
499
462
  */
500
463
  escalationDisposition?: EscalationDisposition;
501
464
  }
465
+ /** Generic policy templates, NOT automatic trust levels. */
466
+ type ActorProfile = "read-only" | "validation" | "workspace" | "operator" | "reviewer" | "unknown";
467
+ /** High-level classification of what the action does. */
468
+ type CapabilityActionClass = "read-only" | "workspace-write" | "temporary-write" | "external-write" | "destruction" | "code-execution" | "package-management" | "git-mutation" | "network" | "remote-operation" | "service-management" | "persistence" | "privilege-escalation" | "unknown";
469
+
502
470
  /** Reliability of a derived fact. */
503
471
  type EvidenceConfidence = "confirmed" | "high" | "medium" | "low" | "unknown";
504
472
  /** Every non-trivial derived fact carries provenance so the LLM and audit can
@@ -509,8 +477,6 @@ interface Provenanced<T> {
509
477
  confidence: EvidenceConfidence;
510
478
  notes?: string[];
511
479
  }
512
- /** Generic policy templates, NOT automatic trust levels. */
513
- type ActorProfile = "read-only" | "validation" | "workspace" | "operator" | "reviewer" | "unknown";
514
480
  /** Normalized effective-permission summary when the SDK exposes it.
515
481
  * The v1 SDK does not expose effective rules, so this stays `undefined`. */
516
482
  interface EffectivePermissionSummary {
@@ -607,122 +573,164 @@ interface ActionPurpose {
607
573
  source: "agent-context" | "intent-derived" | "unavailable";
608
574
  confidence: EvidenceConfidence;
609
575
  }
610
- /** How completely the command could be statically analyzed. */
611
- type ParserCompleteness =
612
- /** Fully parsed: no variables, globs, substitutions, or heredoc bodies. */
613
- "complete-for-supported-form"
614
- /** Some constructs could not be resolved (variables, partial heredoc). */
615
- | "partial"
616
- /** Heavy dynamic constructs (command substitution, eval, dynamic heredoc). */
617
- | "opaque";
618
- /** A redirection extracted from a parsed command segment. */
619
- interface Redirection {
620
- /** `>` `>>` `<` `2>` `&>` etc. */
621
- operator: string;
622
- /** Target path (file descriptor targets normalized to a path when possible). */
623
- target: string;
624
- /** Whether the target was quoted in the source (affects literal-ness). */
625
- quoted: boolean;
626
- }
627
- /** A heredoc extracted before lexing so its body never reaches the lexer/brake. */
628
- interface HeredocRecord {
629
- /** The literal delimiter token as it appeared (`EOF`, `END`, …). */
630
- delimiter: string;
631
- /** `<<` (expansion on) or `<<-` (tabs stripped) — normalized form. */
632
- operator: string;
633
- /** Whether the delimiter was quoted, disabling expansion (`<<'EOF'`). */
634
- expansionDisabled: boolean;
635
- /** Bounded + redacted body (truncated to a safe length). */
636
- bodyBounded: string;
637
- /** SHA-256 of the full, unredacted body (stable identity without leaking it). */
638
- bodySha256: string;
639
- /** Whether the body was truncated for storage. */
640
- truncated: boolean;
641
- /** Output path associated with the heredoc when a `> path` precedes it. */
642
- outputTarget?: string;
643
- /** Whether the body is dynamically constructed (unresolvable expansion). */
644
- dynamic: boolean;
645
- }
646
- /** A command parsed into a reusable structure. Wraps the existing lexer output
647
- * plus pre-extracted redirections and heredocs. */
648
- interface ParsedCommand {
649
- /** The command after heredoc bodies were replaced with placeholders. */
650
- sanitizedCommand: string;
651
- /** Lexed segments of the sanitized command. */
652
- segments: ShellSegment[];
653
- /** Effective commands (wrappers peeled) per segment. */
654
- effective: ShellToken[][];
655
- /** Redirections grouped by segment index. */
656
- redirections: Redirection[][];
657
- /** Heredocs extracted before lexing. */
658
- heredocs: HeredocRecord[];
659
- /** Whether the original command contained any dynamic constructs. */
660
- hasDynamicConstructs: boolean;
661
- /** True when the lexer's depth or expansion budget stopped command-string
662
- * resolution early; `effective` is then a prefix of the real structure and
663
- * deterministic facts do not cover the whole command. */
664
- analysisTruncated: boolean;
665
- }
666
- /** High-level classification of what the action does. */
667
- type CapabilityActionClass = "read-only" | "workspace-write" | "temporary-write" | "external-write" | "destruction" | "code-execution" | "package-management" | "git-mutation" | "network" | "remote-operation" | "service-management" | "persistence" | "privilege-escalation" | "unknown";
668
- /** What the action can do, what it appears to do, and analysis confidence. */
669
- interface CapabilityAssessment {
670
- /** Best single-label summary of the dominant capability. */
671
- actionClass: Provenanced<CapabilityActionClass>;
672
- /** Human-readable summary of the detected surface. */
673
- summary: string;
674
- /** Executes an interpreter or runtime (sh, python, node, bun, …). */
675
- executesCode: Provenanced<boolean | "unknown">;
676
- /** Executes code that lives in the repository (scripts, test files). */
677
- executesRepositoryCode: Provenanced<boolean | "unknown">;
678
- /** Executes ad-hoc code generated by the agent (heredoc/inline). */
679
- createsAdHocCode: Provenanced<boolean | "unknown">;
680
- /** Invokes a known test runner (pytest, jest, bun test, …). */
681
- invokesExistingTestRunner: Provenanced<boolean | "unknown">;
682
- /** Runs a package manager that may execute lifecycle scripts. */
683
- invokesPackageLifecycleScripts: Provenanced<boolean | "unknown">;
684
- /** Reads literal credential material through a known file reader. */
685
- credentialRead: Provenanced<boolean | "unknown">;
686
- /** Detected file-write surface. */
687
- writeEffects: {
688
- temporaryWrite: Provenanced<boolean | "unknown">;
689
- workspaceWrite: Provenanced<boolean | "unknown">;
690
- externalWrite: Provenanced<boolean | "unknown">;
691
- deletion: Provenanced<boolean | "unknown">;
576
+
577
+ /** Which layer produced the final decision for a request. Threaded into the
578
+ * audit record so reports can split outcomes by source. */
579
+ type DecisionSource = "emergency-brake" | "deterministic-policy" | "llm-reviewer" | "system-one-reviewer" | "manual-superseded" | "failure-safe";
580
+ interface ReviewAuditRecord {
581
+ /**
582
+ * Audit schema version. Present on every record; readers default a missing
583
+ * field to `1` (additive — old records are still valid).
584
+ * Bump only on a breaking change to the record shape.
585
+ */
586
+ schemaVersion?: number;
587
+ reviewID?: string;
588
+ hostRequestID?: string;
589
+ hostGeneration?: "v1" | "v2";
590
+ hostVersion?: string;
591
+ generation?: string;
592
+ nativeAction?: string;
593
+ directory?: string;
594
+ application?: "evaluation-returned" | "reply-accepted" | "human-pending" | "superseded" | "cancelled" | "unknown";
595
+ pluginVersion?: string;
596
+ effectiveConfigHash?: string;
597
+ actionFingerprint?: string;
598
+ /** Version of the structured-decision schema the reviewer was asked to emit. */
599
+ decisionSchemaVersion?: number;
600
+ /** Version of the reviewer system prompt used for this decision. */
601
+ promptVersion?: string;
602
+ /** Which layer produced the outcome (brake, policy, reviewer, supersede,
603
+ * failure-safe). Absent on legacy v1 records. */
604
+ decisionSource?: DecisionSource;
605
+ timestamp: string;
606
+ durationMs: number;
607
+ requestID: string;
608
+ sessionID: string;
609
+ permission: string;
610
+ /** Stable hash of the canonical request (permission, patterns, metadata,
611
+ * tool) for cross-record correlation. Absent on legacy v1 records. */
612
+ actionHash?: string;
613
+ outcome: ReviewExecutionResult["kind"];
614
+ reason: string;
615
+ riskLevel?: RiskLevel;
616
+ userAuthorization?: UserAuthorization;
617
+ /** How well the action aligned with the recovered intent (from the reviewer
618
+ * decision). Absent when no reviewer decision was reached. */
619
+ scopeAlignment?: ScopeAlignment;
620
+ confidence?: number;
621
+ /**
622
+ * Structured outcome emitted by the reviewer LLM before gates/disposition.
623
+ * Absent when no valid structured decision was produced (brake, policy,
624
+ * failure-safe, supersede).
625
+ */
626
+ reviewerOutcome?: ReviewOutcome;
627
+ /**
628
+ * How an internal escalate was disposed. Present only when the logical result
629
+ * was escalate (or a gate converted allow→escalate) and enforcement chose
630
+ * manual or deny. Absent for explicit deny, allow, and manual-superseded.
631
+ */
632
+ escalationDisposition?: EscalationDisposition;
633
+ /** The model that produced the final reviewer decision. */
634
+ reviewerModel?: string;
635
+ /** Present when a System One result was handed to a reasoning reviewer. */
636
+ reviewerEscalatedFrom?: {
637
+ model: string;
638
+ reason: string;
692
639
  };
693
- /** Detected network surface. */
694
- network: {
695
- observed: Provenanced<boolean | "unknown">;
696
- possible: Provenanced<boolean | "unknown">;
697
- /** Hosts/destinations observed literally in the command. */
698
- destinations: string[];
699
- observedAccess: Provenanced<boolean | "unknown">;
700
- possibleAccess: Provenanced<boolean | "unknown">;
640
+ /** Jev's scores whenever it returned a parsed decision, including when a
641
+ * reasoning reviewer made the final call. */
642
+ systemOne?: SystemOneScores;
643
+ /** Per-phase timings. Absent on legacy v1 records and on deterministic paths
644
+ * that never reach that phase. */
645
+ timings?: {
646
+ contextMs?: number;
647
+ enrichmentMs?: number;
648
+ reviewerMs?: number;
649
+ replyMs?: number;
701
650
  };
702
- /** Detected process side-effects. */
703
- process: {
704
- childProcesses: Provenanced<boolean | "unknown">;
705
- persistence: Provenanced<boolean | "unknown">;
706
- privilegeEscalation: Provenanced<boolean | "unknown">;
651
+ /** Non-fatal warnings accumulated during evidence collection/analysis. */
652
+ warnings?: string[];
653
+ reviewerSessionID?: string;
654
+ /** Content identity and inspection mode only; never script text or local path. */
655
+ verifiedScript?: {
656
+ sha256: string;
657
+ status: "full" | "reused" | "unavailable";
658
+ bytes?: number;
707
659
  };
708
- /** Detected remote-operation surface (ssh, etc.). */
709
- remote: {
710
- enabled: Provenanced<boolean | "unknown">;
711
- mutationHint: Provenanced<boolean | "unknown">;
660
+ /** Root session of the request's ancestry (additive; absent when lineage was
661
+ * unavailable). */
662
+ rootSessionID?: string;
663
+ /** Overall evidence completeness for the request (additive). */
664
+ evidenceCompleteness?: string;
665
+ /** Resolved actor snapshot for audit (additive). Uses identityCompleteness
666
+ * (not the decision's numeric confidence) to avoid field ambiguity; v2 also
667
+ * carries identitySource + confidence. */
668
+ actor?: {
669
+ name?: string;
670
+ mode?: string;
671
+ profile: ActorProfile;
672
+ identityCompleteness: "complete" | "partial" | "unknown";
673
+ /** How the agent identity was established (tool-message, session-api,
674
+ * unavailable, …). Absent on legacy v1 records. */
675
+ identitySource?: string;
676
+ /** Reliability of the identity claim. Absent on legacy v1 records. */
677
+ confidence?: EvidenceConfidence;
678
+ delegationDepth?: number;
712
679
  };
713
- /** Detected git mutation surface. */
714
- git: {
715
- observed: Provenanced<boolean | "unknown">;
716
- possible: Provenanced<boolean | "unknown">;
717
- observedAccess: Provenanced<boolean | "unknown">;
718
- possibleAccess: Provenanced<boolean | "unknown">;
680
+ ssh?: Array<{
681
+ destination: string;
682
+ port?: string;
683
+ remoteCommandSha256?: string;
684
+ stdinSource?: string;
685
+ stdinStatus?: string;
686
+ stdinReason?: string;
687
+ }>;
688
+ /** Additive capability snapshot for audit (observe-only). */
689
+ capability?: {
690
+ actionClass: string;
691
+ summary: string;
692
+ parserCompleteness: string;
693
+ executesCode?: boolean;
694
+ createsAdHocCode?: boolean;
695
+ invokesPackageLifecycleScripts?: boolean;
696
+ writeEffects?: {
697
+ temporaryWrite?: boolean;
698
+ workspaceWrite?: boolean;
699
+ externalWrite?: boolean;
700
+ deletion?: boolean;
701
+ };
702
+ networkObserved?: boolean;
703
+ credentialRead?: boolean;
704
+ privilegeEscalation?: boolean;
705
+ persistence?: boolean;
706
+ remoteEnabled?: boolean;
707
+ gitMutation?: boolean;
719
708
  };
720
- /** How completely the command could be analyzed. */
721
- parserCompleteness: ParserCompleteness;
722
- /** Free-form warnings about analysis limitations. */
723
- analysisWarnings: string[];
709
+ /** Additive policy trace for audit (observe-only). */
710
+ policyTrace?: {
711
+ effectivePolicyHash: string;
712
+ matchedRules: Array<{
713
+ id: string;
714
+ source: string;
715
+ effect: string;
716
+ reason: string;
717
+ }>;
718
+ finalRoute: string;
719
+ mode: string;
720
+ };
721
+ /** Additive snapshot of the ask decisions surfaced to the reviewer prompt
722
+ * (observe-only; capped to the most recent few). */
723
+ askDecisions?: Array<{
724
+ at: number;
725
+ question: string;
726
+ answer: string;
727
+ }>;
724
728
  }
725
729
 
730
+ declare const DEFAULT_AUDIT_PATH = "~/.local/share/opencode/permission-reviewer-audit.jsonl";
731
+ type AuditLogger = (message: string, details?: unknown) => void;
732
+ declare function createAuditWriter(config: ReviewerConfig, logger?: AuditLogger): ((record: ReviewAuditRecord) => Promise<void>) | undefined;
733
+
726
734
  /** The host passing an options object does not attest who authored it. */
727
735
  type InlineOptionsTrust = "trusted" | "project" | "unknown";
728
736
 
@@ -738,9 +746,158 @@ type InlineOptionsTrust = "trusted" | "project" | "unknown";
738
746
  * byte-identical to calling `resolveConfig(inlineOptions)` directly. */
739
747
  declare function loadResolvedConfig(inlineOptions: Record<string, unknown> | undefined, directory?: string, inlineTrust?: InlineOptionsTrust): ReviewerConfig;
740
748
 
749
+ type ReviewUiPhase = "reviewing" | "approved" | "denied" | "manual" | "unknown";
750
+ interface ReviewUiStatus {
751
+ version: 1;
752
+ requestID: string;
753
+ sessionID: string;
754
+ phase: ReviewUiPhase;
755
+ permission: string;
756
+ action: string;
757
+ model: string;
758
+ variant: string;
759
+ emittedAt: number;
760
+ timeoutMs: number;
761
+ reason?: string;
762
+ decision?: ReviewDecision;
763
+ /**
764
+ * When phase is `denied` and this is `"deny"`, the block came from fail-closed
765
+ * escalation disposition rather than an explicit reviewer/policy deny.
766
+ */
767
+ escalationDisposition?: EscalationDisposition;
768
+ /** Resolved actor (absent on the initial "reviewing" phase, before context
769
+ * collection completes). */
770
+ actorName?: string;
771
+ actorProfile?: ActorProfile;
772
+ }
773
+ declare function permissionAction(request: PermissionRequest): string;
774
+ declare function createUiStatus(request: PermissionRequest, phase: ReviewUiPhase, options: {
775
+ model: string;
776
+ variant: string;
777
+ timeoutMs: number;
778
+ reason?: string;
779
+ decision?: ReviewDecision;
780
+ escalationDisposition?: EscalationDisposition;
781
+ emittedAt?: number;
782
+ actorName?: string;
783
+ actorProfile?: ActorProfile;
784
+ }): ReviewUiStatus;
785
+ declare function encodeUiStatus(status: ReviewUiStatus): string;
786
+ declare function decodeUiStatus(command: string): ReviewUiStatus | undefined;
787
+
788
+ /**
789
+ * Captures user answers to agent ask dialogs (the `question` tool) from the
790
+ * OpenCode event stream and exposes them as compact, session-scoped
791
+ * authorization evidence for the reviewer prompt.
792
+ *
793
+ * The host runs questions through a dedicated service (`question.asked` /
794
+ * `question.replied` / `question.rejected` events) that never touches the
795
+ * permission pipeline, so these decisions are invisible to a permission-only
796
+ * observer. This registry is the counterpart capture layer: it is
797
+ * enrichment-only — question events never trigger, supersede, or enforce
798
+ * anything — and it is total (malformed events are dropped, never thrown).
799
+ *
800
+ * Robustness rules:
801
+ * - One logical ask = one record, keyed by the per-ask request ID. The v1 and
802
+ * v2 event spellings of the same ask upsert into the same entry, and a
803
+ * replayed reply or rejection is ignored.
804
+ * - A reply or rejection without a matching pending ask is dropped (the
805
+ * question text is unknowable after the fact).
806
+ * - Pending asks expire (TTL) so a very late reply cannot pair with a stale
807
+ * question from another context.
808
+ * - Resolved decisions are FIFO-bounded globally; the per-review limit is
809
+ * applied at query time, not storage time.
810
+ * - Question and answer text is redacted before storage; a credential pasted
811
+ * as a custom answer must never land in the registry, prompt, or audit.
812
+ */
813
+ /** Marker recorded when the user dismisses an ask without answering. */
814
+ declare const DISMISSED_ANSWER = "Dismissed by user";
815
+ type Logger$1 = (message: string, details?: unknown) => void;
816
+ /** What the evidence assembler consumes: a bounded, lineage-scoped query. */
817
+ interface AskDecisionSource {
818
+ recentFor(sessionIDs: string[], limit?: number): AskDecision[];
819
+ }
820
+ declare class AskDecisionRegistry implements AskDecisionSource {
821
+ private readonly pending;
822
+ private readonly resolved;
823
+ private readonly log;
824
+ private readonly now;
825
+ constructor(logger?: Logger$1, now?: () => number);
826
+ /**
827
+ * Observe one raw event. Total: never throws; anything malformed or
828
+ * unrelated is dropped silently. Must be called synchronously from the event
829
+ * hook so registry mutations are visible to reviews started later.
830
+ */
831
+ observe(event: unknown): void;
832
+ /**
833
+ * Decisions visible to a review running in `sessionIDs` (the requesting
834
+ * session plus its resolved ancestors), oldest first, bounded to the most
835
+ * recent `limit`. Sibling and unrelated sessions are never visible.
836
+ */
837
+ recentFor(sessionIDs: string[], limit?: number): AskDecision[];
838
+ /** Observed-but-unresolved asks (diagnostics only). */
839
+ pendingCount(): number;
840
+ /** Resolved decisions retained (diagnostics only). */
841
+ resolvedCount(): number;
842
+ private onAsked;
843
+ private onReplied;
844
+ private onRejected;
845
+ private store;
846
+ }
847
+
741
848
  type Context = Parameters<Plugin.Plugin["setup"]>[0];
849
+
742
850
  declare function setup(ctx: Context): Promise<() => Promise<void>>;
743
851
 
852
+ declare function resolveConfig(options: Record<string, unknown> | undefined): ReviewerConfig;
853
+
854
+ interface SshAuditSummary {
855
+ destination: string;
856
+ port?: string;
857
+ remoteCommandSha256?: string;
858
+ stdinSource?: string;
859
+ stdinStatus?: string;
860
+ stdinReason?: string;
861
+ }
862
+ interface SshEnrichmentResult {
863
+ text: string;
864
+ audit: SshAuditSummary[];
865
+ preflightDenial?: string;
866
+ }
867
+ declare function enrichSshEvidence(request: PermissionRequest, directory: string, worktree: string, maxChars: number): Promise<SshEnrichmentResult>;
868
+
869
+ /**
870
+ * A single piece of evidence gathered about a permission request. The runtime
871
+ * only consumes `text`, `audit`, and `preflightDenial` today; the remaining
872
+ * fields give future providers room to surface warnings and cost without
873
+ * changing the interface.
874
+ */
875
+ interface EvidenceFragment {
876
+ kind: "ssh" | "local_script" | "git";
877
+ text: string;
878
+ audit?: SshAuditSummary[];
879
+ preflightDenial?: string;
880
+ warnings?: string[];
881
+ durationMs?: number;
882
+ }
883
+ interface EvidenceScope {
884
+ directory: string;
885
+ worktree: string;
886
+ maxChars: number;
887
+ }
888
+ interface EvidenceProviderInput extends EvidenceScope {
889
+ request: PermissionRequest;
890
+ }
891
+ /**
892
+ * Enriches a permission request with one category of evidence (SSH analysis,
893
+ * local script inspection, Git state, …). Providers run concurrently and their
894
+ * fragments are assembled into a single review envelope.
895
+ */
896
+ interface EvidenceProvider {
897
+ readonly id: string;
898
+ collect(input: EvidenceProviderInput): Promise<EvidenceFragment>;
899
+ }
900
+
744
901
  /** What the plugin learned about the host client at startup. */
745
902
  interface OpenCodeCapabilities {
746
903
  /** A public SDK method to answer a permission request exists. */
@@ -763,45 +920,6 @@ interface OpenCodeCapabilities {
763
920
  tuiPublish: boolean;
764
921
  }
765
922
 
766
- type ReviewUiPhase = "reviewing" | "approved" | "denied" | "manual" | "unknown";
767
- interface ReviewUiStatus {
768
- version: 1;
769
- requestID: string;
770
- sessionID: string;
771
- phase: ReviewUiPhase;
772
- permission: string;
773
- action: string;
774
- model: string;
775
- variant: string;
776
- emittedAt: number;
777
- timeoutMs: number;
778
- reason?: string;
779
- decision?: ReviewDecision;
780
- /**
781
- * When phase is `denied` and this is `"deny"`, the block came from fail-closed
782
- * escalation disposition rather than an explicit reviewer/policy deny.
783
- */
784
- escalationDisposition?: EscalationDisposition;
785
- /** Resolved actor (absent on the initial "reviewing" phase, before context
786
- * collection completes). */
787
- actorName?: string;
788
- actorProfile?: ActorProfile;
789
- }
790
- declare function permissionAction(request: PermissionRequest): string;
791
- declare function createUiStatus(request: PermissionRequest, phase: ReviewUiPhase, options: {
792
- model: string;
793
- variant: string;
794
- timeoutMs: number;
795
- reason?: string;
796
- decision?: ReviewDecision;
797
- escalationDisposition?: EscalationDisposition;
798
- emittedAt?: number;
799
- actorName?: string;
800
- actorProfile?: ActorProfile;
801
- }): ReviewUiStatus;
802
- declare function encodeUiStatus(status: ReviewUiStatus): string;
803
- declare function decodeUiStatus(command: string): ReviewUiStatus | undefined;
804
-
805
923
  interface ClientResponse<T> {
806
924
  data?: T;
807
925
  error?: unknown;
@@ -846,114 +964,8 @@ interface RuntimeContext {
846
964
  reviewerDirectoryBase?: string;
847
965
  }
848
966
 
849
- interface SshAuditSummary {
850
- destination: string;
851
- port?: string;
852
- remoteCommandSha256?: string;
853
- stdinSource?: string;
854
- stdinStatus?: string;
855
- stdinReason?: string;
856
- }
857
- interface SshEnrichmentResult {
858
- text: string;
859
- audit: SshAuditSummary[];
860
- preflightDenial?: string;
861
- }
862
- declare function enrichSshEvidence(request: PermissionRequest, directory: string, worktree: string, maxChars: number): Promise<SshEnrichmentResult>;
863
-
864
- /**
865
- * A single piece of evidence gathered about a permission request. The runtime
866
- * only consumes `text`, `audit`, and `preflightDenial` today; the remaining
867
- * fields give future providers room to surface warnings and cost without
868
- * changing the interface.
869
- */
870
- interface EvidenceFragment {
871
- kind: "ssh" | "local_script" | "git";
872
- text: string;
873
- audit?: SshAuditSummary[];
874
- preflightDenial?: string;
875
- warnings?: string[];
876
- durationMs?: number;
877
- }
878
- interface EvidenceProviderInput {
879
- request: PermissionRequest;
880
- directory: string;
881
- worktree: string;
882
- maxChars: number;
883
- }
884
- /**
885
- * Enriches a permission request with one category of evidence (SSH analysis,
886
- * local script inspection, Git state, …). Providers run concurrently and their
887
- * fragments are assembled into a single review envelope.
888
- */
889
- interface EvidenceProvider {
890
- readonly id: string;
891
- collect(input: EvidenceProviderInput): Promise<EvidenceFragment>;
892
- }
893
-
894
- /**
895
- * Captures user answers to agent ask dialogs (the `question` tool) from the
896
- * OpenCode event stream and exposes them as compact, session-scoped
897
- * authorization evidence for the reviewer prompt.
898
- *
899
- * The host runs questions through a dedicated service (`question.asked` /
900
- * `question.replied` / `question.rejected` events) that never touches the
901
- * permission pipeline, so these decisions are invisible to a permission-only
902
- * observer. This registry is the counterpart capture layer: it is
903
- * enrichment-only — question events never trigger, supersede, or enforce
904
- * anything — and it is total (malformed events are dropped, never thrown).
905
- *
906
- * Robustness rules:
907
- * - One logical ask = one record, keyed by the per-ask request ID. The v1 and
908
- * v2 event spellings of the same ask upsert into the same entry, and a
909
- * replayed reply or rejection is ignored.
910
- * - A reply or rejection without a matching pending ask is dropped (the
911
- * question text is unknowable after the fact).
912
- * - Pending asks expire (TTL) so a very late reply cannot pair with a stale
913
- * question from another context.
914
- * - Resolved decisions are FIFO-bounded globally; the per-review limit is
915
- * applied at query time, not storage time.
916
- * - Question and answer text is redacted before storage; a credential pasted
917
- * as a custom answer must never land in the registry, prompt, or audit.
918
- */
919
- /** Marker recorded when the user dismisses an ask without answering. */
920
- declare const DISMISSED_ANSWER = "Dismissed by user";
921
- type Logger$1 = (message: string, details?: unknown) => void;
922
- /** What the evidence assembler consumes: a bounded, lineage-scoped query. */
923
- interface AskDecisionSource {
924
- recentFor(sessionIDs: string[], limit?: number): AskDecision[];
925
- }
926
- declare class AskDecisionRegistry implements AskDecisionSource {
927
- private readonly pending;
928
- private readonly resolved;
929
- private readonly log;
930
- private readonly now;
931
- constructor(logger?: Logger$1, now?: () => number);
932
- /**
933
- * Observe one raw event. Total: never throws; anything malformed or
934
- * unrelated is dropped silently. Must be called synchronously from the event
935
- * hook so registry mutations are visible to reviews started later.
936
- */
937
- observe(event: unknown): void;
938
- /**
939
- * Decisions visible to a review running in `sessionIDs` (the requesting
940
- * session plus its resolved ancestors), oldest first, bounded to the most
941
- * recent `limit`. Sibling and unrelated sessions are never visible.
942
- */
943
- recentFor(sessionIDs: string[], limit?: number): AskDecision[];
944
- /** Observed-but-unresolved asks (diagnostics only). */
945
- pendingCount(): number;
946
- /** Resolved decisions retained (diagnostics only). */
947
- resolvedCount(): number;
948
- private takePending;
949
- private store;
950
- /** Enforce the pending cap and TTL. Map iteration order is insertion
951
- * order, so `keys().next()` is the oldest entry. */
952
- private prunePending;
953
- private pruneExpired;
954
- }
955
-
956
967
  type Logger = (message: string, details?: unknown) => void;
968
+
957
969
  /**
958
970
  * Owns the review lifecycle for permission requests: orchestration, the
959
971
  * supersede state machine, and the model call. The adapter (transport) and the
@@ -961,51 +973,15 @@ type Logger = (message: string, details?: unknown) => void;
961
973
  * races.
962
974
  */
963
975
  declare class ReviewCoordinator {
964
- private readonly ctx;
965
- private readonly config;
966
- private readonly generation;
967
- private readonly attempts;
968
- private stopped;
976
+ private readonly state;
969
977
  private readonly limiter;
970
978
  private readonly pending;
971
- private readonly backend;
972
- /**
973
- * Request IDs that a human (or any other reply source) resolved while the
974
- * automatic review was still in flight. The in-flight review must then give
975
- * up silently: no `emit`, no `reply`. OpenCode resolves a request on a
976
- * first-writer basis, so a late programmatic reply returns 404
977
- * PermissionNotFoundError — we treat that the same way.
978
- */
979
- private readonly resolvedManually;
980
- private readonly log;
981
- private readonly providers;
982
- private readonly scriptRegistry;
983
- /** Live ask-decision capture (enrichment-only; undefined when disabled). */
984
- private readonly askDecisions;
985
- /** Bound for metadata SDK calls (session create, tool listing, replies,
986
- * status publishing): a hung call must never leave a review pending
987
- * forever; the reviewer prompt keeps its own full timeout budget. */
988
- private readonly metadataCallTimeoutMs;
989
979
  constructor(ctx: RuntimeContext, config: ReviewerConfig, logger?: Logger, providers?: EvidenceProvider[], askDecisions?: AskDecisionSource);
990
980
  pendingCount(): number;
991
981
  waitForIdle(): Promise<void>;
992
982
  dispose(): Promise<void>;
993
983
  handle(request: PermissionRequest): void;
994
984
  process(request: PermissionRequest): Promise<ReviewExecutionResult>;
995
- private supersedeResult;
996
- private isSuperseded;
997
- /**
998
- * Reject a request with `reject` while honoring supersede. Returns `undefined`
999
- * when the rejection was applied, or the supersede result when the request had
1000
- * already been answered manually (so the caller returns it unchanged).
1001
- */
1002
- private denyAndReply;
1003
- /**
1004
- * Apply a fully disposed result (allow / deny / escalate) to UI + reply.
1005
- * This is the single side-effect boundary after logical disposition.
1006
- */
1007
- private applyDisposition;
1008
- private processRequest;
1009
985
  handlePermissionReply(event: unknown): void;
1010
986
  /**
1011
987
  * @deprecated No-op. Approvals no longer annotate tool results so they do not
@@ -1017,35 +993,12 @@ declare class ReviewCoordinator {
1017
993
  output?: unknown;
1018
994
  metadata?: unknown;
1019
995
  }): void;
1020
- private collectEnvelope;
1021
- private audit;
1022
- private runReviewer;
1023
- private remember;
1024
- /** Fold the reviewer phase's elapsed time into the request's timing record. */
1025
- private recordReviewerMs;
1026
- /**
1027
- * Send a permission reply. Returns `true` on success, `false` when the
1028
- * request was already resolved by another source (human TUI, a duplicate
1029
- * event, etc.) so the caller can treat itself as superseded. Other errors
1030
- * (transport failure, malformed reply) are still thrown.
1031
- */
1032
- private safeReply;
1033
- private emit;
1034
996
  }
1035
997
 
1036
- /**
1037
- * Normalize a raw OpenCode event into a {@link PermissionRequest}.
1038
- *
1039
- * Returns `undefined` for anything that is not a well-formed
1040
- * `permission.asked` event, so callers can ignore irrelevant events without
1041
- * inspecting their shape.
1042
- */
1043
- declare function extractPermissionRequest(event: unknown): PermissionRequest | undefined;
1044
-
1045
- declare function resolveConfig(options: Record<string, unknown> | undefined): ReviewerConfig;
1046
-
1047
998
  declare function parseDecision(value: unknown): ReviewDecision | undefined;
999
+
1048
1000
  declare function enforceDecision(decision: ReviewDecision, config: ReviewerConfig): ReviewExecutionResult;
1001
+
1049
1002
  declare const DECISION_SCHEMA: {
1050
1003
  readonly type: "object";
1051
1004
  readonly additionalProperties: false;
@@ -1099,6 +1052,8 @@ declare const DECISION_SCHEMA: {
1099
1052
  };
1100
1053
  };
1101
1054
 
1055
+ declare function emergencyBrakeReason(request: PermissionRequest): string | undefined;
1056
+
1102
1057
  /**
1103
1058
  * Categories that can be hardened independently of the global escalation mode
1104
1059
  * via `riskPolicy.onInvalidDecision` / `riskPolicy.onReviewerFailure`.
@@ -1131,7 +1086,26 @@ declare function resolveEscalationDisposition(result: ReviewExecutionResult, con
1131
1086
  */
1132
1087
  declare function applyEscalationDisposition(result: ReviewExecutionResult, config: ReviewerConfig, category?: EscalationCategory): ReviewExecutionResult;
1133
1088
 
1134
- declare function emergencyBrakeReason(request: PermissionRequest): string | undefined;
1089
+ interface GitEnrichmentResult {
1090
+ text: string;
1091
+ }
1092
+ declare function enrichGitEvidence(request: PermissionRequest, directory: string, maxChars: number, worktree?: string): Promise<GitEnrichmentResult>;
1093
+
1094
+ interface LocalScriptEnrichmentResult {
1095
+ text: string;
1096
+ }
1097
+ /** `rootDirectory` is the approved evidence root, which can sit above
1098
+ * `directory` (package-script expansion passes the session directory). */
1099
+ declare function enrichLocalScriptEvidence(request: PermissionRequest, directory: string, worktree: string, maxChars: number, rootDirectory?: string): Promise<LocalScriptEnrichmentResult>;
1100
+
1101
+ /**
1102
+ * Normalize a raw OpenCode event into a {@link PermissionRequest}.
1103
+ *
1104
+ * Returns `undefined` for anything that is not a well-formed
1105
+ * `permission.asked` event, so callers can ignore irrelevant events without
1106
+ * inspecting their shape.
1107
+ */
1108
+ declare function extractPermissionRequest(event: unknown): PermissionRequest | undefined;
1135
1109
 
1136
1110
  declare function redactSecrets(input: string): string;
1137
1111
 
@@ -1156,19 +1130,6 @@ declare class ReviewUiState {
1156
1130
  dismissResults(now?: number): string[];
1157
1131
  }
1158
1132
 
1159
- declare const DEFAULT_AUDIT_PATH = "~/.local/share/opencode/permission-reviewer-audit.jsonl";
1160
- declare function createAuditWriter(config: ReviewerConfig, logger?: (message: string, details?: unknown) => void): ((record: ReviewAuditRecord) => Promise<void>) | undefined;
1161
-
1162
- interface LocalScriptEnrichmentResult {
1163
- text: string;
1164
- }
1165
- declare function enrichLocalScriptEvidence(request: PermissionRequest, directory: string, worktree: string, maxChars: number): Promise<LocalScriptEnrichmentResult>;
1166
-
1167
- interface GitEnrichmentResult {
1168
- text: string;
1169
- }
1170
- declare function enrichGitEvidence(request: PermissionRequest, directory: string, maxChars: number, worktree?: string): Promise<GitEnrichmentResult>;
1171
-
1172
1133
  declare const server: Plugin$1;
1173
1134
  declare const module$1: {
1174
1135
  id: string;