@noppu-labs/opencode-permission-reviewer 0.0.0-stage → 2.4.1

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.
@@ -0,0 +1,687 @@
1
+ export type RiskLevel = "low" | "medium" | "high" | "critical"
2
+ export type UserAuthorization = "high" | "medium" | "low" | "unknown"
3
+ export type ReviewOutcome = "allow" | "deny" | "escalate"
4
+ export type ScopeAlignment = "aligned" | "partial" | "misaligned" | "unknown"
5
+ export type EvidenceSufficiency = "sufficient" | "partial" | "insufficient" | "unknown"
6
+ /** How final escalations are disposed after reviewer/policy/fail-safe produce them. */
7
+ export type EscalationMode = "manual" | "deny"
8
+ /** Effective disposition applied to an internal escalate result. */
9
+ export type EscalationDisposition = "manual" | "deny"
10
+
11
+ export interface ReviewDecision {
12
+ /** Structured-decision schema version. Always 2 for the current schema. */
13
+ version: 2
14
+ outcome: ReviewOutcome
15
+ risk_level: RiskLevel
16
+ user_authorization: UserAuthorization
17
+ /** How well the request aligns with the recovered user/delegated intent. */
18
+ scope_alignment: ScopeAlignment
19
+ /** Whether the evidence was sufficient to decide confidently. */
20
+ evidence_completeness: EvidenceSufficiency
21
+ rationale: string
22
+ confidence: number
23
+ /** Optional script-only semantic analysis. Never conveys authorization. */
24
+ script_analysis?: string
25
+ }
26
+
27
+ export interface PermissionToolSource {
28
+ messageID: string
29
+ callID: string
30
+ }
31
+
32
+ export interface PermissionRequest {
33
+ id: string
34
+ sessionID: string
35
+ permission: string
36
+ patterns: string[]
37
+ metadata: Record<string, unknown>
38
+ always: string[]
39
+ tool?: PermissionToolSource
40
+ }
41
+
42
+ export interface MessageWithParts {
43
+ info: Record<string, unknown> & {
44
+ id?: string
45
+ role?: string
46
+ structured?: unknown
47
+ }
48
+ parts: Array<Record<string, unknown>>
49
+ }
50
+
51
+ /** Deterministic risk×authorization matrix that gates reviewer `allow`
52
+ * outcomes. For each risk level, lists the authorization levels that permit an
53
+ * auto-allow. An empty array means no authorization permits auto-allow at that
54
+ * risk (the action is escalated). Only ever RESTRICTS; deny/escalate are always
55
+ * preserved. */
56
+ export interface RiskPolicy {
57
+ allow: {
58
+ low: UserAuthorization[]
59
+ medium: UserAuthorization[]
60
+ high: UserAuthorization[]
61
+ critical: UserAuthorization[]
62
+ }
63
+ minimumConfidence: number
64
+ onInvalidDecision: "manual" | "deny"
65
+ onReviewerFailure: "manual" | "deny"
66
+ }
67
+
68
+ /** Conservative repository trust model. A repository cannot mark itself trusted
69
+ * through project configuration alone — trust comes from global config or an
70
+ * interactive decision stored outside the repo. */
71
+ export type RepositoryTrust = "trusted" | "untrusted" | "unknown"
72
+
73
+ /** A declarative policy condition: matches capability/actor facts. Every field
74
+ * is optional; the rule matches when ALL specified fields match. A missing
75
+ * `when` (or `{ always: true }`) makes the rule universal. */
76
+ export interface PolicyCondition {
77
+ /** Explicit catch-all: valid only as the sole key. */
78
+ always?: true
79
+ actionClass?: CapabilityActionClass[]
80
+ actorProfile?: ActorProfile[]
81
+ writesWorkspace?: boolean
82
+ writesExternal?: boolean
83
+ writesTemporary?: boolean
84
+ deletion?: boolean
85
+ executesCode?: boolean
86
+ createsAdHocCode?: boolean
87
+ packageManagement?: boolean
88
+ gitMutation?: boolean
89
+ networkObserved?: boolean
90
+ credentialRead?: boolean
91
+ privilegeEscalation?: boolean
92
+ remoteEnabled?: boolean
93
+ persistence?: boolean
94
+ repositoryTrust?: RepositoryTrust[]
95
+ }
96
+
97
+ /** A declarative rule that routes a request based on capability+actor facts.
98
+ * `when` is optional: omitting it (or `{ always: true }`) matches every
99
+ * request. An explicitly empty `when: {}` is rejected at load. */
100
+ export interface PolicyRule {
101
+ id: string
102
+ source: "builtin" | "global" | "project" | "inline"
103
+ when?: PolicyCondition
104
+ effect: "review" | "manual" | "deny" | "allow"
105
+ reason: string
106
+ }
107
+
108
+ /** The result of evaluating the declarative policy. */
109
+ export interface PolicyTrace {
110
+ /** Stable hash of the effective rule set (not the matched rules) for audit
111
+ * reproducibility. */
112
+ effectivePolicyHash: string
113
+ matchedRules: Array<{ id: string; source: string; effect: string; reason: string }>
114
+ /** The route the engine computed (counterfactual in observe mode: what enforce
115
+ * mode WOULD have done with the same facts and rules). */
116
+ finalRoute: "review" | "manual" | "deny" | "allow"
117
+ mode: "observe" | "enforce"
118
+ }
119
+
120
+ export type ReviewerOutputFormat = "json_schema" | "text"
121
+
122
+ export interface EscalationReviewerConfig {
123
+ model: string
124
+ variant: string
125
+ outputFormat: ReviewerOutputFormat
126
+ timeoutMs: number
127
+ }
128
+
129
+ export interface ReviewerConfig {
130
+ model: string
131
+ variant: string
132
+ /** How the reviewer model returns its decision. `json_schema` requests
133
+ * OpenCode's structured-output format (requires provider support); `text`
134
+ * asks the model to emit JSON in plain text and parses it locally. */
135
+ outputFormat: ReviewerOutputFormat
136
+ /** Optional reasoning reviewer for valid System One decisions that remain
137
+ * uncertain or conflict with deterministic review gates. */
138
+ escalationReviewer?: EscalationReviewerConfig
139
+ /** Calibrated outcome-confidence floor for System One decisions. */
140
+ systemOneConfidenceThreshold: number
141
+ /** Minimum combined non-escalate probability for routing an explicit
142
+ * System One escalation to the optional reasoning reviewer. */
143
+ systemOneReasoningThreshold: number
144
+ timeoutMs: number
145
+ /** Total review budget, including context, queueing, and retries. */
146
+ reviewBudgetMs?: number
147
+ maxContextChars: number
148
+ maxPartChars: number
149
+ maxEnrichmentChars: number
150
+ maxIntentChars: number
151
+ transcriptMessages: number
152
+ intentMessages: number
153
+ historyMessages: number
154
+ confidenceThreshold: number
155
+ retainReviewSessions: boolean
156
+ audit: boolean
157
+ auditPath?: string
158
+ policy?: string
159
+ debug: boolean
160
+ /** When "observe", actor evidence is collected and audited but never enforces
161
+ * new gates; "enforce" applies declarative policy routes. */
162
+ enforcementMode: "observe" | "enforce"
163
+ /**
164
+ * How internal `escalate` results are disposed before UI/reply.
165
+ * - `manual` (default): leave the request for a human (interactive mode).
166
+ * - `deny`: convert every final escalation into a reject with rationale
167
+ * (non-interactive fail-closed). Never relaxes an explicit deny.
168
+ */
169
+ escalationMode: EscalationMode
170
+ /** Max hops when walking session parents (default 8). */
171
+ maxSessionDepth: number
172
+ /** Max parent sessions fetched during lineage traversal. */
173
+ maxParentSessions: number
174
+ /** Trusted name→profile mappings (empty by default; no mappings shipped). */
175
+ actorProfiles: Record<string, ActorProfile>
176
+ /** Deterministic risk×authorization gate, configurable but defaults reproduce
177
+ * the previous hard-coded matrix exactly. */
178
+ riskPolicy: RiskPolicy
179
+ /** Repository trust level derived from global config (never from project). */
180
+ repositoryTrust: RepositoryTrust
181
+ /** Declarative policy rules (empty by default; observe mode audits the trace
182
+ * without enforcing). Project-sourced allow rules are rejected. */
183
+ policyRules: PolicyRule[]
184
+ /** Capture user answers to agent ask dialogs (question tool) and surface
185
+ * them to the reviewer as scoped authorization evidence. */
186
+ askDecisions: boolean
187
+ /** Non-empty when a TRUSTED config source (global file, inline options)
188
+ * existed but could not be fully honored (malformed file, unreadable file,
189
+ * or rules dropped by validation). Degraded configs block automatic
190
+ * approval: restrictions may have been lost, so requests escalate instead. */
191
+ configDegraded?: string[]
192
+ }
193
+
194
+ export interface ReviewEnvelope {
195
+ request: PermissionRequest
196
+ directory: string
197
+ worktree: string
198
+ transcript: string
199
+ intentHistory: string
200
+ enrichment: string
201
+ verifiedScript?: import("./verified-ssh-script.ts").VerifiedScriptEvidence
202
+ sshAudit: NonNullable<ReviewAuditRecord["ssh"]>
203
+ preflightDenial?: string
204
+ /** Agent-aware context (actor, lineage, intent). Observe-only: flows into the
205
+ * reviewer prompt and audit as evidence, never into enforcement decisions.
206
+ * Optional so older callers/tests still compile. */
207
+ actor?: ActorContext
208
+ lineage?: SessionLineage
209
+ intent?: IntentContext
210
+ evidenceCompleteness?: EvidenceCompleteness
211
+ /** Structured capability facts derived from the bash command. Observe-only:
212
+ * feeds the reviewer prompt and audit, never enforcement. */
213
+ capability?: CapabilityAssessment
214
+ /** The policy trace produced for this request, surfaced to the reviewer prompt
215
+ * as EFFECTIVE_POLICY_SUMMARY and to audit. Observe-only. */
216
+ policyTrace?: PolicyTrace
217
+ /** Per-phase timing captured during evidence assembly (context/enrichment).
218
+ * The reviewer and reply phases are timed in the coordinator. */
219
+ timings?: { contextMs?: number; enrichmentMs?: number; reviewerMs?: number; replyMs?: number }
220
+ /** False when a material part of the action under review (e.g. an elided
221
+ * command segment) never reached the rendered evidence. Blocking: the
222
+ * coordinator must not auto-approve an action the reviewer could not see
223
+ * in full, whatever confidence the model reports. */
224
+ actionEvidenceComplete?: boolean
225
+ /** The parsed command reused across evidence providers. */
226
+ parsedCommand?: ParsedCommand
227
+ /** Operational purpose of the pending action (evidence, never authorization). */
228
+ actionPurpose?: ActionPurpose
229
+ /** User answers to agent ask dialogs in this session or its ancestors,
230
+ * captured live from question events. Observe-only: flows into the reviewer
231
+ * prompt (USER_ASK_DECISIONS) and audit, never into enforcement. */
232
+ askDecisions?: AskDecision[]
233
+ }
234
+
235
+ /** Which layer produced the final decision for a request. Threaded into the
236
+ * audit record so reports can split outcomes by source. */
237
+ export type DecisionSource =
238
+ | "emergency-brake"
239
+ | "deterministic-policy"
240
+ | "llm-reviewer"
241
+ | "system-one-reviewer"
242
+ | "manual-superseded"
243
+ | "failure-safe"
244
+
245
+ export interface ReviewAuditRecord {
246
+ /**
247
+ * Audit schema version. Present on every record; readers default a missing
248
+ * field to `1` (additive — old records are still valid).
249
+ * Bump only on a breaking change to the record shape.
250
+ */
251
+ schemaVersion?: number
252
+ reviewID?: string
253
+ hostRequestID?: string
254
+ hostGeneration?: "v1" | "v2"
255
+ hostVersion?: string
256
+ generation?: string
257
+ nativeAction?: string
258
+ directory?: string
259
+ application?:
260
+ | "evaluation-returned"
261
+ | "reply-accepted"
262
+ | "human-pending"
263
+ | "superseded"
264
+ | "cancelled"
265
+ | "unknown"
266
+ pluginVersion?: string
267
+ effectiveConfigHash?: string
268
+ actionFingerprint?: string
269
+ /** Version of the structured-decision schema the reviewer was asked to emit. */
270
+ decisionSchemaVersion?: number
271
+ /** Version of the reviewer system prompt used for this decision. */
272
+ promptVersion?: string
273
+ /** Which layer produced the outcome (brake, policy, reviewer, supersede,
274
+ * failure-safe). Absent on legacy v1 records. */
275
+ decisionSource?: DecisionSource
276
+ timestamp: string
277
+ durationMs: number
278
+ requestID: string
279
+ sessionID: string
280
+ permission: string
281
+ /** Stable hash of the canonical request (permission, patterns, metadata,
282
+ * tool) for cross-record correlation. Absent on legacy v1 records. */
283
+ actionHash?: string
284
+ outcome: ReviewExecutionResult["kind"]
285
+ reason: string
286
+ riskLevel?: RiskLevel
287
+ userAuthorization?: UserAuthorization
288
+ /** How well the action aligned with the recovered intent (from the reviewer
289
+ * decision). Absent when no reviewer decision was reached. */
290
+ scopeAlignment?: ScopeAlignment
291
+ confidence?: number
292
+ /**
293
+ * Structured outcome emitted by the reviewer LLM before gates/disposition.
294
+ * Absent when no valid structured decision was produced (brake, policy,
295
+ * failure-safe, supersede).
296
+ */
297
+ reviewerOutcome?: ReviewOutcome
298
+ /**
299
+ * How an internal escalate was disposed. Present only when the logical result
300
+ * was escalate (or a gate converted allow→escalate) and enforcement chose
301
+ * manual or deny. Absent for explicit deny, allow, and manual-superseded.
302
+ */
303
+ escalationDisposition?: EscalationDisposition
304
+ /** The model that produced the final reviewer decision. */
305
+ reviewerModel?: string
306
+ /** Present when a System One result was handed to a reasoning reviewer. */
307
+ reviewerEscalatedFrom?: { model: string; reason: string }
308
+ /** Per-phase timings. Absent on legacy v1 records and on deterministic paths
309
+ * that never reach that phase. */
310
+ timings?: { contextMs?: number; enrichmentMs?: number; reviewerMs?: number; replyMs?: number }
311
+ /** Non-fatal warnings accumulated during evidence collection/analysis. */
312
+ warnings?: string[]
313
+ reviewerSessionID?: string
314
+ /** Content identity and inspection mode only; never script text or local path. */
315
+ verifiedScript?: { sha256: string; status: "full" | "reused" | "unavailable"; bytes?: number }
316
+ /** Root session of the request's ancestry (additive; absent when lineage was
317
+ * unavailable). */
318
+ rootSessionID?: string
319
+ /** Overall evidence completeness for the request (additive). */
320
+ evidenceCompleteness?: string
321
+ /** Resolved actor snapshot for audit (additive). Uses identityCompleteness
322
+ * (not the decision's numeric confidence) to avoid field ambiguity; v2 also
323
+ * carries identitySource + confidence. */
324
+ actor?: {
325
+ name?: string
326
+ mode?: string
327
+ profile: ActorProfile
328
+ identityCompleteness: "complete" | "partial" | "unknown"
329
+ /** How the agent identity was established (tool-message, session-api,
330
+ * unavailable, …). Absent on legacy v1 records. */
331
+ identitySource?: string
332
+ /** Reliability of the identity claim. Absent on legacy v1 records. */
333
+ confidence?: EvidenceConfidence
334
+ delegationDepth?: number
335
+ }
336
+ ssh?: Array<{
337
+ destination: string
338
+ port?: string
339
+ remoteCommandSha256?: string
340
+ stdinSource?: string
341
+ stdinStatus?: string
342
+ stdinReason?: string
343
+ }>
344
+ /** Additive capability snapshot for audit (observe-only). */
345
+ capability?: {
346
+ actionClass: string
347
+ summary: string
348
+ parserCompleteness: string
349
+ executesCode?: boolean
350
+ createsAdHocCode?: boolean
351
+ invokesPackageLifecycleScripts?: boolean
352
+ writeEffects?: {
353
+ temporaryWrite?: boolean
354
+ workspaceWrite?: boolean
355
+ externalWrite?: boolean
356
+ deletion?: boolean
357
+ }
358
+ networkObserved?: boolean
359
+ credentialRead?: boolean
360
+ privilegeEscalation?: boolean
361
+ persistence?: boolean
362
+ remoteEnabled?: boolean
363
+ gitMutation?: boolean
364
+ }
365
+ /** Additive policy trace for audit (observe-only). */
366
+ policyTrace?: {
367
+ effectivePolicyHash: string
368
+ matchedRules: Array<{ id: string; source: string; effect: string; reason: string }>
369
+ finalRoute: string
370
+ mode: string
371
+ }
372
+ /** Additive snapshot of the ask decisions surfaced to the reviewer prompt
373
+ * (observe-only; capped to the most recent few). */
374
+ askDecisions?: Array<{ at: number; question: string; answer: string }>
375
+ }
376
+
377
+ export interface ApprovedAnnotation {
378
+ requestID: string
379
+ sessionID: string
380
+ decision: ReviewDecision
381
+ }
382
+
383
+ export interface ReviewExecutionResult {
384
+ kind: "allow" | "deny" | "escalate"
385
+ decision?: ReviewDecision
386
+ reason: string
387
+ reviewSessionID?: string
388
+ /** Which layer produced this result; threaded into the audit record. */
389
+ decisionSource?: DecisionSource
390
+ /** Actual model that produced the final reviewer decision. */
391
+ reviewerModel?: string
392
+ /** Primary model and routing reason when a second reviewer was used. */
393
+ reviewerEscalatedFrom?: { model: string; reason: string }
394
+ /**
395
+ * Structured outcome from the reviewer LLM before gates/disposition.
396
+ * Absent when no valid structured decision was produced.
397
+ */
398
+ reviewerOutcome?: ReviewOutcome
399
+ /**
400
+ * How an internal escalate was disposed at the enforcement boundary.
401
+ * Absent when the result was never an escalate (explicit allow/deny) or when
402
+ * the request was already answered manually (`manual-superseded`).
403
+ */
404
+ escalationDisposition?: EscalationDisposition
405
+ }
406
+
407
+ // ---------------------------------------------------------------------------
408
+ // Agent-aware context data model.
409
+ //
410
+ // These types carry actor/lineage/intent evidence alongside a permission
411
+ // request. They flow into the reviewer prompt (as evidence sections) and the
412
+ // audit record (additive fields) WITHOUT changing enforcement: the v1 decision
413
+ // schema and enforceDecision are untouched (observe-only by default).
414
+ // ---------------------------------------------------------------------------
415
+
416
+ /** Reliability of a derived fact. */
417
+ export type EvidenceConfidence = "confirmed" | "high" | "medium" | "low" | "unknown"
418
+
419
+ /** Every non-trivial derived fact carries provenance so the LLM and audit can
420
+ * weigh claims by how reliably they were established. */
421
+ export interface Provenanced<T> {
422
+ value: T
423
+ source:
424
+ | "permission-event"
425
+ | "tool-message"
426
+ | "session-api"
427
+ | "parent-session"
428
+ | "global-config"
429
+ | "project-config"
430
+ | "effective-permissions"
431
+ | "static-analysis"
432
+ | "heuristic"
433
+ | "unavailable"
434
+ confidence: EvidenceConfidence
435
+ notes?: string[]
436
+ }
437
+
438
+ /** Generic policy templates, NOT automatic trust levels. */
439
+ export type ActorProfile =
440
+ "read-only" | "validation" | "workspace" | "operator" | "reviewer" | "unknown"
441
+
442
+ /** Normalized effective-permission summary when the SDK exposes it.
443
+ * The v1 SDK does not expose effective rules, so this stays `undefined`. */
444
+ export interface EffectivePermissionSummary {
445
+ edit: "allow" | "ask" | "deny" | "mixed" | "unknown"
446
+ bash: "allow" | "ask" | "deny" | "mixed" | "unknown"
447
+ task: "allow" | "ask" | "deny" | "mixed" | "unknown"
448
+ externalDirectory: "allow" | "ask" | "deny" | "mixed" | "unknown"
449
+ source: "session" | "agent-config" | "derived" | "unknown"
450
+ }
451
+
452
+ /** Who is requesting the permission. */
453
+ export interface ActorContext {
454
+ agentName: Provenanced<string | undefined>
455
+ mode: Provenanced<string | undefined>
456
+ profile: Provenanced<ActorProfile>
457
+ sessionID: string
458
+ parentSessionID: Provenanced<string | undefined>
459
+ rootSessionID: Provenanced<string>
460
+ delegationDepth: Provenanced<number>
461
+ effectivePermissions?: EffectivePermissionSummary
462
+ identityCompleteness: "complete" | "partial" | "unknown"
463
+ }
464
+
465
+ /** A node in the session ancestry chain. */
466
+ export interface SessionNode {
467
+ sessionID: string
468
+ parentID?: string
469
+ title?: string
470
+ version?: string
471
+ actorName?: string
472
+ mode?: string
473
+ createdAt?: number
474
+ }
475
+
476
+ /** The resolved session ancestry with failure modes made explicit. */
477
+ export interface SessionLineage {
478
+ origin?: "human-root" | "delegated" | "unknown"
479
+ nodes: SessionNode[]
480
+ rootSessionID: string
481
+ depth: number
482
+ cycleDetected: boolean
483
+ truncated: boolean
484
+ missingParents: string[]
485
+ }
486
+
487
+ /** A single authorization/intent statement. */
488
+ export interface IntentBlock {
489
+ sessionID: string
490
+ messageID: string
491
+ actor: "user" | "assistant" | "system" | "unknown"
492
+ text: string
493
+ synthetic: boolean
494
+ createdAt?: number
495
+ provenance: Provenanced<"intent">
496
+ }
497
+
498
+ /** One user decision on an agent-initiated ask dialog (question tool). The
499
+ * question text is agent-generated and untrusted; only the answer is a user
500
+ * authorization signal, scoped to the subject and time of the ask. */
501
+ export interface AskDecision {
502
+ /** Epoch ms when the reply (or dismissal) was observed. */
503
+ at: number
504
+ /** What the agent asked, already redacted and truncated. */
505
+ question: string
506
+ /** The option labels the user selected, or a dismissal marker. */
507
+ answer: string
508
+ }
509
+
510
+ /** Direct user intent kept separate from delegated task. */
511
+ export interface IntentContext {
512
+ directUserIntent: IntentBlock[]
513
+ delegatedTask: IntentBlock[]
514
+ localSessionIntent: IntentBlock[]
515
+ conflictingInstructions: string[]
516
+ latestExplicitAuthorization?: IntentBlock
517
+ completeness: "complete" | "partial" | "insufficient"
518
+ }
519
+
520
+ /** Meta-summary of what evidence was available. */
521
+ export interface EvidenceCompleteness {
522
+ permission: boolean
523
+ actor: boolean
524
+ lineage: boolean
525
+ directUserIntent: boolean
526
+ delegatedTask: boolean
527
+ /** Whether a non-unavailable ACTION_PURPOSE was recovered. */
528
+ purpose: boolean
529
+ capability: boolean
530
+ repositoryState: boolean
531
+ referencedCode: boolean
532
+ reasons: string[]
533
+ overall: "sufficient" | "partial" | "insufficient"
534
+ }
535
+
536
+ /**
537
+ * Operational purpose of the pending action — what the agent appears to be
538
+ * trying to accomplish. This is untrusted evidence: it never demonstrates
539
+ * user authorization by itself.
540
+ */
541
+ export interface ActionPurpose {
542
+ text?: string
543
+ source: "agent-context" | "intent-derived" | "unavailable"
544
+ confidence: EvidenceConfidence
545
+ }
546
+
547
+ // ---------------------------------------------------------------------------
548
+ // Capability analysis. The analyzer produces these facts from the bash
549
+ // command using the existing shell lexer; each fact is evidence for the reviewer
550
+ // prompt, never a final safety decision. Fields default to "unknown" when no
551
+ // detector covers them yet.
552
+ // ---------------------------------------------------------------------------
553
+
554
+ /** How completely the command could be statically analyzed. */
555
+ export type ParserCompleteness =
556
+ /** Fully parsed: no variables, globs, substitutions, or heredoc bodies. */
557
+ | "complete-for-supported-form"
558
+ /** Some constructs could not be resolved (variables, partial heredoc). */
559
+ | "partial"
560
+ /** Heavy dynamic constructs (command substitution, eval, dynamic heredoc). */
561
+ | "opaque"
562
+
563
+ /** A redirection extracted from a parsed command segment. */
564
+ export interface Redirection {
565
+ /** `>` `>>` `<` `2>` `&>` etc. */
566
+ operator: string
567
+ /** Target path (file descriptor targets normalized to a path when possible). */
568
+ target: string
569
+ /** Whether the target was quoted in the source (affects literal-ness). */
570
+ quoted: boolean
571
+ }
572
+
573
+ /** A heredoc extracted before lexing so its body never reaches the lexer/brake. */
574
+ export interface HeredocRecord {
575
+ /** The literal delimiter token as it appeared (`EOF`, `END`, …). */
576
+ delimiter: string
577
+ /** `<<` (expansion on) or `<<-` (tabs stripped) — normalized form. */
578
+ operator: string
579
+ /** Whether the delimiter was quoted, disabling expansion (`<<'EOF'`). */
580
+ expansionDisabled: boolean
581
+ /** Bounded + redacted body (truncated to a safe length). */
582
+ bodyBounded: string
583
+ /** SHA-256 of the full, unredacted body (stable identity without leaking it). */
584
+ bodySha256: string
585
+ /** Whether the body was truncated for storage. */
586
+ truncated: boolean
587
+ /** Output path associated with the heredoc when a `> path` precedes it. */
588
+ outputTarget?: string
589
+ /** Whether the body is dynamically constructed (unresolvable expansion). */
590
+ dynamic: boolean
591
+ }
592
+
593
+ /** A command parsed into a reusable structure. Wraps the existing lexer output
594
+ * plus pre-extracted redirections and heredocs. */
595
+ export interface ParsedCommand {
596
+ /** The command after heredoc bodies were replaced with placeholders. */
597
+ sanitizedCommand: string
598
+ /** Lexed segments of the sanitized command. */
599
+ segments: import("./shell-lexer.ts").ShellSegment[]
600
+ /** Effective commands (wrappers peeled) per segment. */
601
+ effective: import("./shell-lexer.ts").ShellToken[][]
602
+ /** Redirections grouped by segment index. */
603
+ redirections: Redirection[][]
604
+ /** Heredocs extracted before lexing. */
605
+ heredocs: HeredocRecord[]
606
+ /** Whether the original command contained any dynamic constructs. */
607
+ hasDynamicConstructs: boolean
608
+ /** True when the lexer's depth or expansion budget stopped command-string
609
+ * resolution early; `effective` is then a prefix of the real structure and
610
+ * deterministic facts do not cover the whole command. */
611
+ analysisTruncated: boolean
612
+ }
613
+
614
+ /** High-level classification of what the action does. */
615
+ export type CapabilityActionClass =
616
+ | "read-only"
617
+ | "workspace-write"
618
+ | "temporary-write"
619
+ | "external-write"
620
+ | "destruction"
621
+ | "code-execution"
622
+ | "package-management"
623
+ | "git-mutation"
624
+ | "network"
625
+ | "remote-operation"
626
+ | "service-management"
627
+ | "persistence"
628
+ | "privilege-escalation"
629
+ | "unknown"
630
+
631
+ /** What the action can do, what it appears to do, and analysis confidence. */
632
+ export interface CapabilityAssessment {
633
+ /** Best single-label summary of the dominant capability. */
634
+ actionClass: Provenanced<CapabilityActionClass>
635
+ /** Human-readable summary of the detected surface. */
636
+ summary: string
637
+ /** Executes an interpreter or runtime (sh, python, node, bun, …). */
638
+ executesCode: Provenanced<boolean | "unknown">
639
+ /** Executes code that lives in the repository (scripts, test files). */
640
+ executesRepositoryCode: Provenanced<boolean | "unknown">
641
+ /** Executes ad-hoc code generated by the agent (heredoc/inline). */
642
+ createsAdHocCode: Provenanced<boolean | "unknown">
643
+ /** Invokes a known test runner (pytest, jest, bun test, …). */
644
+ invokesExistingTestRunner: Provenanced<boolean | "unknown">
645
+ /** Runs a package manager that may execute lifecycle scripts. */
646
+ invokesPackageLifecycleScripts: Provenanced<boolean | "unknown">
647
+ /** Reads literal credential material through a known file reader. */
648
+ credentialRead: Provenanced<boolean | "unknown">
649
+ /** Detected file-write surface. */
650
+ writeEffects: {
651
+ temporaryWrite: Provenanced<boolean | "unknown">
652
+ workspaceWrite: Provenanced<boolean | "unknown">
653
+ externalWrite: Provenanced<boolean | "unknown">
654
+ deletion: Provenanced<boolean | "unknown">
655
+ }
656
+ /** Detected network surface. */
657
+ network: {
658
+ observed: Provenanced<boolean | "unknown">
659
+ possible: Provenanced<boolean | "unknown">
660
+ /** Hosts/destinations observed literally in the command. */
661
+ destinations: string[]
662
+ observedAccess: Provenanced<boolean | "unknown">
663
+ possibleAccess: Provenanced<boolean | "unknown">
664
+ }
665
+ /** Detected process side-effects. */
666
+ process: {
667
+ childProcesses: Provenanced<boolean | "unknown">
668
+ persistence: Provenanced<boolean | "unknown">
669
+ privilegeEscalation: Provenanced<boolean | "unknown">
670
+ }
671
+ /** Detected remote-operation surface (ssh, etc.). */
672
+ remote: {
673
+ enabled: Provenanced<boolean | "unknown">
674
+ mutationHint: Provenanced<boolean | "unknown">
675
+ }
676
+ /** Detected git mutation surface. */
677
+ git: {
678
+ observed: Provenanced<boolean | "unknown">
679
+ possible: Provenanced<boolean | "unknown">
680
+ observedAccess: Provenanced<boolean | "unknown">
681
+ possibleAccess: Provenanced<boolean | "unknown">
682
+ }
683
+ /** How completely the command could be analyzed. */
684
+ parserCompleteness: ParserCompleteness
685
+ /** Free-form warnings about analysis limitations. */
686
+ analysisWarnings: string[]
687
+ }