1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Pre-spawn intent/method-conformance FRONT gate (DOC-15 C3, #1360).
//!
//! # Spec References
//!
//! - [`SPEC-CONFORMANCE-02~draft`](docs/specs/intent-conformance.md#SPEC-CONFORMANCE-02~draft) (§5.1 FRONT gate)
//! - [`SPEC-CONFORMANCE-01~draft`](docs/specs/intent-conformance.md#SPEC-CONFORMANCE-01~draft) (§4 decision matrix)
//!
//! Why: a managed session begins *coding a ticket* the moment
//! [`crate::daemon::managed_routes::spawn_managed`] calls `adapter.spawn`. The
//! FRONT gate is the only seam that owns BOTH the task text (the intent) and the
//! spawn trigger, so it is where we can check the planned method against the
//! ticket+spec intent *before* any code is written — when redirection is
//! cheapest (spec §5.1 Rationale). The gate realises the ~80% auto / ~20%
//! escalate operating model: the default is auto-proceed; escalation is the
//! exception, reserved for a genuine method divergence (spec G2).
//!
//! What: this module is the pure, testable core of the gate. It exposes
//! - [`ConformanceGate`] — the seam over the shared ISR
//! (`trusty_common::intent_source`), so the spawn path can resolve a
//! `ResolvedIntent` without coupling to a live GitHub client (mocked in tests);
//! - [`HeadlessApproval`] — the #1269 capability flag that selects the headless
//! auto-spawn path vs. the degraded operator-confirm path;
//! - [`front_gate_disposition`] — the pure matrix→`Disposition` mapping, composed
//! STRICTER-WINS with `evaluate_autonomy_tier` so conformance can never *lower*
//! a tier escalation (spec §5.1, AC-16);
//! - [`run_front_gate`] — the async orchestration the spawn path calls.
//!
//! Fail-open everywhere (spec §4.2, AC-17): non-ticketed work, an unresolved
//! ISR, or an empty planned/prescribed method all yield `AutoAccept` — the gate
//! must NEVER be the reason work stalls.
//!
//! Test: `super::front_gate::tests` covers the matrix rows (agree/gap/divergence),
//! fail-open (non-ticketed + ISR failure), the stricter-wins composition, and the
//! #1269 degraded branch — all without network access (AC-13..AC-17).
use async_trait;
use ;
use ;
use crate;
use crate;
use crate;
/// The fail-open reason used when the gate has no intent to conform to.
///
/// Why: non-ticketed work, an unresolved ISR, and a clean gap all collapse to
/// the same outcome — auto-proceed — and the spec fixes the reason text
/// ("no intent source", §5.1). Centralising the literal keeps every call site
/// and every test asserting on one string.
/// What: the canonical `AutoAccept` reason for the fail-open / no-intent path.
/// Test: `tests::non_ticketed_auto_accepts`, `tests::isr_failure_auto_accepts`.
pub const NO_INTENT_SOURCE: &str = "no intent source";
/// Whether the fully-headless auto-spawn approval path is available (#1269).
///
/// Why: spec §5.1 — the fully-headless auto-spawn path is **soft-blocked by
/// #1269**. The gate must still land and function: on an escalation it degrades
/// to the CLI-owned launch / operator-confirm path rather than blocking the
/// whole gate on #1269. Modelling the capability as an explicit two-state value
/// (rather than a bare `bool`) keeps the degradation branch self-documenting at
/// every call site.
/// What: `Headless` — the headless approval channel is live (post-#1269);
/// `OperatorConfirm` — degrade an escalation to operator confirmation (the
/// `pending_decision` is written and surfaced through the CLI/activity channels,
/// and a human resolves it via `POST …/answer`).
/// Test: `tests::degraded_branch_marks_operator_confirm`.
/// The outcome of running the FRONT gate against a spawn.
///
/// Why: the spawn path needs more than a yes/no — on an escalation it must write
/// the `pending_decision`/`proposed_default` and withhold the spawn, and it must
/// know whether it is on the headless or the degraded operator-confirm path so it
/// can log/surface accordingly (spec §5.1).
/// What: carries the composed [`Disposition`], plus — when the disposition is
/// `Escalate` — the `proposed_default` (the conformant method to surface to the
/// human) and the approval mode in force.
/// Test: `tests::*` assert on the disposition and the escalation fields.
/// Seam over the shared intent-source resolver (ISR).
///
/// Why: `run_front_gate` must resolve a `ResolvedIntent` from a ticket-id, but
/// the production resolver fetches a GitHub issue over the network. Modelling the
/// resolution as a trait lets the spawn path run the real ISR while unit tests
/// inject a deterministic mock — no network, fully offline (spec §5.1 inputs,
/// CLAUDE.md no-network-in-tests).
/// What: one async method mapping `(ticket_id, owner, repo, task)` to a
/// `ResolvedIntent`. Implementors MUST be fail-open: any failure resolves to
/// [`ResolvedIntent::unresolved`], never an `Err` (the trait is infallible by
/// design so the gate can never block on resolver failure — spec §4.2).
/// Test: `tests` use a `MockGate`; the production impl is [`IsrConformanceGate`].
/// Production [`ConformanceGate`] backed by the shared ISR.
///
/// Why: the real gate must reuse `trusty_common::intent_source` — the single
/// shared resolver both conformance gates call (spec G4) — rather than
/// re-implement ticket fetch + precedence. This wraps it behind the
/// `BackendTicketFetcher` (PAT/App-token via the pluggable resolver) and a
/// filesystem spec lookup rooted at the session's workspace.
/// What: holds the repo root used for SLD spec resolution; `resolve` builds an
/// `IntentQuery::Ticket` (pre-work `changed_files` is empty, so the spec axis is
/// keyed off the ticket body's links only — spec §6.1) and calls
/// `resolve_default`, which is itself fail-open.
/// Test: covered by `tests::production_gate_*` (offline: a non-fetchable ticket
/// resolves to `unresolved`, the fail-open contract — no network is exercised).
/// The method the resolved intent prescribes, under precedence (ticket > spec).
///
/// Why: the FRONT gate compares the planned method against the *winning* method,
/// not against both axes — precedence has already been applied centrally by the
/// ISR (spec §6.1). A small accessor keeps [`front_gate_disposition`] declarative.
/// What: returns the ticket method when the ticket won, the spec method when the
/// spec won, and `None` for a gap.
/// Test: `tests::prescribed_method_follows_precedence`.
/// Lowercase + collapse whitespace, for method-text comparison.
///
/// Why: trivial formatting differences between the planned method (from the task
/// prose) and the prescribed method (from the ticket/spec) must not register as a
/// divergence — that would manufacture a false escalation (spec §4.3 fail-open
/// bias). Mirrors the ISR's own `normalise` so FRONT and the resolver agree on
/// what "the same method" means.
/// What: lowercases, splits on whitespace, and rejoins single-spaced.
/// Test: `tests::planned_matching_prescribed_auto_accepts`.
/// Map the resolved intent + planned method onto a conformance `Disposition`.
///
/// Why: this is the FRONT half of the normative decision matrix (spec §4.1),
/// pre-work. It is a pure function of `(intent, planned_method)` so it is fully
/// unit-testable offline.
/// What: implements the matrix rows for FRONT —
/// - `unresolved` / non-ticketed / gap (no prescribed method) → `AutoAccept`
/// (M3, fail-open §4.2);
/// - a prescribed method exists and the planned method is absent OR agrees with
/// it → `AutoAccept` (M1/M2 agree). Pre-work the plan is implicit, so an absent
/// planned method is treated as conformant (escalate-only-on-divergence, §5.1);
/// - a prescribed method exists and the planned method *diverges* from it →
/// `Escalate` (M1/M2/M5 divergence). The reason names both methods so a human
/// can triage instantly (`first_failing_signal` style, §5.1).
///
/// Note (M4): a ticket/spec **conflict** is NOT an escalation here — the ISR has
/// already applied ticket > spec, so the prescribed method is the *ticket*
/// method and the gate conforms to it; the stale spec is advisory only (spec
/// §4.1 M4, §5.1). The conflict therefore only matters insofar as the planned
/// method diverges from the *ticket* method.
/// Test: `tests::gap_auto_accepts`, `tests::planned_matching_prescribed_auto_accepts`,
/// `tests::divergence_escalates`, `tests::conflict_follows_ticket`.
/// Which input won the stricter-wins composition (the escalation source).
///
/// Why: the FRONT gate's `proposed_default` is only meaningful when the
/// *conformance* path is what escalated — it names the conformant method to
/// adopt. When the *autonomy* tier is the escalation source (e.g. a T4
/// destructive task), surfacing the conformance-derived method is misleading: the
/// reason reads "T4: destructive" while `proposed_default` says "use cursor
/// pagination", which has nothing to do with why we stopped (#1360 review). The
/// composition must therefore report which side won so the caller can scope
/// `proposed_default` to the conformance case only.
/// What: `Conformance` — the conformance disposition is the (sole) escalation
/// source; `Autonomy` — the autonomy tier escalated (it wins outright when both
/// escalate, since the tier engine is the authoritative safety floor); `Neither`
/// — both auto-accepted, no escalation.
/// Test: `tests::stricter_wins_*`.
/// Compose two dispositions STRICTER-WINS, reporting the escalation source.
///
/// Why: spec §5.1 / AC-16 — the conformance disposition is *combined* with the
/// standard `evaluate_autonomy_tier` decision by taking the stricter outcome. The
/// gate must NEVER *lower* a tier escalation to auto-accept (a T4/destructive
/// action still escalates regardless of conformance). Equally, a conformance
/// divergence must escalate even when the autonomy tier would auto-accept.
/// Beyond the disposition, the caller needs to know WHICH side escalated so it can
/// scope `proposed_default` to the conformance-only case (#1360 review): a
/// `proposed_default` derived from conformance is meaningless when the autonomy
/// tier is the reason we stopped.
/// What: returns the stricter `Disposition` plus an [`EscalationSource`] tag —
/// `Escalate` if EITHER input escalates (preferring the autonomy reason when both
/// escalate, since the tier engine is the established safety authority, and
/// tagging the source `Autonomy` in that case); `AutoAccept` (tagged `Neither`)
/// only when BOTH auto-accept.
/// Test: `tests::stricter_wins_*`, `tests::run_*_proposes_default`.
/// Compose two dispositions STRICTER-WINS (escalate beats auto-accept).
///
/// Why: the disposition-only projection of [`stricter_of_with_source`], for call
/// sites and tests that do not need the escalation-source tag.
/// What: returns the stricter `Disposition`, discarding the source tag.
/// Test: `tests::stricter_wins_*`.
/// Run the FRONT gate for a spawn, producing a [`FrontGateOutcome`].
///
/// Why: the single entry point [`crate::daemon::managed_routes::spawn_managed`]
/// calls between record-creation and `adapter.spawn`. It ties together ticket
/// extraction, ISR resolution, the conformance disposition, and the stricter-wins
/// composition with autonomy — and selects the headless vs. degraded path.
/// What: in order — (1) extract a ticket-id from `task`; non-ticketed →
/// `AutoAccept` fail-open (AC-17); (2) resolve the intent via `gate` (fail-open);
/// (3) derive the planned method from `task` (heuristic, no network); (4) map to a
/// conformance `Disposition` ([`front_gate_disposition`]); (5) compose
/// stricter-wins with `autonomy` ([`stricter_of`]); (6) wrap with the
/// `proposed_default` (the prescribed method) and the `approval` mode. The gate
/// is infallible by design (every failure is fail-open) so it can never block.
/// Test: `tests::run_*` (AC-13, AC-14, AC-16, AC-17).
pub async
/// Build the autonomy [`Disposition`] the FRONT gate composes against.
///
/// Why: the gate must compose with `evaluate_autonomy_tier` (spec §5.1), but
/// pre-work most guardrail signals (review, CI) are not yet available — the work
/// has not been done. The honest pre-work signal set is "unknown", which the
/// autonomy engine already treats conservatively. This helper builds an
/// `ActionContext`/`GuardrailSignals` pair from what IS known pre-work (the task
/// text as the decision, the caller-supplied change class) and runs the engine,
/// so the FRONT gate gives `evaluate_autonomy_tier` its FIRST production caller
/// (spec §2.2 — the engine was built+tested with zero callers).
/// What: runs `evaluate_autonomy_tier` with an unavailable/unknown guardrail set
/// and the supplied [`ActionContext`]; maps the inevitable `EmptyDecision` error
/// (empty task) to a fail-open `AutoAccept` so the gate never blocks on its own
/// composition step.
/// Test: `tests::autonomy_disposition_*`.
/// Build the PRE-WORK autonomy disposition for a task about to be spawned.
///
/// Why: the FRONT gate runs *before* any code exists, so the post-work guardrails
/// (`review`, `ci`) are not yet meaningful — the work has not been done. The only
/// autonomy dimension that applies pre-spawn is the tier/destructive classifier:
/// a task that names an irreversible operation (`delete`, `drop table`,
/// `decommission`, …) must escalate before the agent is even launched (T4),
/// while ordinary work proceeds. Feeding the engine `StyleOnly` + a pre-work
/// signal set (review `Unavailable`, CI `Unknown` — NOT `Reject`/`Red`) yields
/// exactly that: auto-accept normally, escalate on destructive text. This is the
/// engine's FIRST production caller (spec §2.2).
/// What: constructs an [`ActionContext`] from the task text (the `pending_decision`
/// the destructive-keyword scan reads) under `ChangeClass::StyleOnly`, plus a
/// neutral pre-work [`GuardrailSignals`], and runs `evaluate_autonomy_tier`. Maps
/// the empty-task error to a fail-open `AutoAccept`.
///
/// Why `ChangeClass::StyleOnly` is the safe pre-work default: the destructive
/// scan is NOT gated by the change class. `classify_tier` first derives a base
/// tier from the class (StyleOnly → T1) and then *unconditionally* bumps to T4 if
/// `ActionContext::mentions_destructive_op()` matches a destructive keyword —
/// `if ctx.mentions_destructive_op() { base.max(T4) }` runs independently of
/// `change_class`. So picking the *lowest* base tier (StyleOnly/T1) cannot
/// suppress a destructive escalation: a "drop table" task is forced to T4
/// regardless. This is exactly the pre-work intent — ordinary work auto-accepts
/// (T1), destructive text escalates (T4). The passing test
/// `tests::prework_autonomy_destructive_task_escalates` ("drop table sessions …")
/// pins this behaviour; if the keyword scan were ever gated on `change_class`,
/// switch this default to `ChangeClass::Standard` as the conservative floor.
/// Test: `tests::prework_autonomy_*` (esp. `prework_autonomy_destructive_task_escalates`).
/// Project an [`AutonomyDecision`] onto its [`Disposition`].
///
/// Why: [`stricter_of`] composes two `Disposition`s; the autonomy engine returns
/// the richer `AutonomyDecision` (tier + disposition). This narrows it to the
/// disposition the composition needs.
/// What: returns `decision.disposition`.
/// Test: `tests::autonomy_disposition_*`.