diff --git a/app/lib/features/runs/actions/decision_dialog.dart b/app/lib/features/runs/actions/decision_dialog.dart index 5157097d..ddc8a56e 100644 --- a/app/lib/features/runs/actions/decision_dialog.dart +++ b/app/lib/features/runs/actions/decision_dialog.dart @@ -117,7 +117,7 @@ class _DecisionPromptState extends State<_DecisionPrompt> { RadioListTile( value: option.key, enabled: !_sending, - title: Text(option.key), + title: Text(option.displayLabel), subtitle: _target(option), ), ], @@ -156,6 +156,12 @@ class _DecisionPromptState extends State<_DecisionPrompt> { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text(decisionMeta(widget.decision)), + if (decisionExhaustedText(widget.decision) case final text + when text.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(text, key: decisionExhaustedKey), + ), if (widget.decision.instructions.trim().isNotEmpty) Padding( padding: const EdgeInsets.only(top: 8), diff --git a/app/lib/features/runs/actions/decision_wording.dart b/app/lib/features/runs/actions/decision_wording.dart index a9904946..f74286fa 100644 --- a/app/lib/features/runs/actions/decision_wording.dart +++ b/app/lib/features/runs/actions/decision_wording.dart @@ -14,11 +14,26 @@ const decisionSendingLabel = 'Sending…'; const decisionActionKey = ValueKey('human-decision-action'); const decisionFeedbackKey = ValueKey('human-decision-feedback'); const decisionErrorKey = ValueKey('human-decision-error'); +const decisionExhaustedKey = ValueKey('human-decision-exhausted'); /// `{stage} · run {id} · {label}`, as the web decision card shows it. String decisionMeta(PendingDecision decision) => '${decision.stageKey} · run ${decision.runId} · ${decision.runLabel}'; +/// For a loop that exhausted its visits: `review used visit 3 of 3`, or the +/// part the server recorded; "" for a declared human decision. +String decisionExhaustedText(PendingDecision decision) { + final loop = decision.exhausted; + if (loop == null) return ''; + final stage = loop.stage.isEmpty ? decision.stageKey : loop.stage; + final visit = loop.visit; + final max = loop.maxVisits; + if (visit == null) return '$stage reached its visit limit'; + return max == null + ? '$stage reached its visit limit at visit $visit' + : '$stage reached its visit limit: visit $visit of $max'; +} + /// The option's target line, `→ {target}`, or "" when no target was declared. String decisionTargetText(String target) => target.trim().isEmpty ? '' : '→ $target'; diff --git a/app/lib/features/runs/actions/retry_action.dart b/app/lib/features/runs/actions/retry_action.dart index 1ba6c8c2..6b2495ff 100644 --- a/app/lib/features/runs/actions/retry_action.dart +++ b/app/lib/features/runs/actions/retry_action.dart @@ -4,6 +4,7 @@ import '../../../core/api_gateway.dart'; import '../data/runs_repository.dart'; import 'action_refusal.dart'; import 'retry_dialog.dart'; +import 'retry_extra_visits.dart'; import 'retry_eligibility.dart'; import 'retry_wording.dart'; @@ -106,12 +107,16 @@ Future openRetryRunPrompt( await showRetryRunPrompt( context: context, runId: id, + stages: retryStageKeys(run), + suggestExtraVisits: runExhaustedVisits(run), onSubmit: (intent) async { try { final updated = await repository.retryRun( id, requestKey: intent.requestKey, mode: intent.mode.wireMode, + extraVisits: intent.wireExtraVisits, + extraStage: intent.wireExtraStage, ); if (owns(id)) { onRunChanged(updated); diff --git a/app/lib/features/runs/actions/retry_dialog.dart b/app/lib/features/runs/actions/retry_dialog.dart index 7ce7409c..a8e49809 100644 --- a/app/lib/features/runs/actions/retry_dialog.dart +++ b/app/lib/features/runs/actions/retry_dialog.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'action_refusal.dart'; +import 'retry_extra_visits_field.dart'; import 'retry_intent.dart'; import 'retry_wording.dart'; @@ -19,8 +20,15 @@ Future showRetryRunPrompt({ required BuildContext context, required num runId, required RetrySubmit onSubmit, + List stages = const [], + bool suggestExtraVisits = false, }) { - final prompt = _RetryPrompt(runId: runId, onSubmit: onSubmit); + final prompt = _RetryPrompt( + runId: runId, + onSubmit: onSubmit, + stages: stages, + suggestExtraVisits: suggestExtraVisits, + ); return showDialog( context: context, barrierDismissible: false, @@ -29,17 +37,30 @@ Future showRetryRunPrompt({ } class _RetryPrompt extends StatefulWidget { - const _RetryPrompt({required this.runId, required this.onSubmit}); + const _RetryPrompt({ + required this.runId, + required this.onSubmit, + required this.stages, + required this.suggestExtraVisits, + }); final num runId; final RetrySubmit onSubmit; + /// The run's graph stage keys, offered as the extra visits' stage. + final List stages; + + /// Whether the run failed on an exhausted loop. + final bool suggestExtraVisits; + @override State<_RetryPrompt> createState() => _RetryPromptState(); } class _RetryPromptState extends State<_RetryPrompt> { RetryMode _mode = RetryMode.resume; + int? _extraVisits; + String? _extraStage; String? _requestKey; bool _sending = false; bool _checking = false; @@ -69,6 +90,8 @@ class _RetryPromptState extends State<_RetryPrompt> { final intent = RetryIntent( mode: _mode, requestKey: _requestKey ??= newRetryRequestKey(widget.runId), + extraVisits: _extraVisits, + extraStage: _extraStage, ); final refusal = await widget.onSubmit(intent); if (!mounted) return; @@ -137,6 +160,18 @@ class _RetryPromptState extends State<_RetryPrompt> { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text(_dialogMessage), + // Extra visits extend a resumed run only; once sent, the intent (and + // its idempotency key) is fixed. + if (_mode == RetryMode.resume) + RetryExtraVisitsField( + visits: _extraVisits, + stage: _extraStage, + stages: widget.stages, + suggested: widget.suggestExtraVisits, + enabled: !_attempted, + onVisitsChanged: (value) => setState(() => _extraVisits = value), + onStageChanged: (value) => setState(() => _extraStage = value), + ), if (_error case final error?) Padding( padding: const EdgeInsets.only(top: 8), diff --git a/app/lib/features/runs/actions/retry_extra_visits.dart b/app/lib/features/runs/actions/retry_extra_visits.dart new file mode 100644 index 00000000..d527e75a --- /dev/null +++ b/app/lib/features/runs/actions/retry_extra_visits.dart @@ -0,0 +1,39 @@ +import '../../../core/api_gateway.dart'; + +/// The most extra visits one retry may grant (the server accepts 1-5). +const maxRetryExtraVisits = 5; + +/// The diagnostic phrases with which the server reports an exhausted loop. +const _exhaustedPhrases = [ + 'visit limit reached', + 'visit budget exceeded', + 'total stage budget exceeded', +]; + +/// Whether [run] failed because a loop exhausted its visits: its diagnostic +/// names a visit limit or budget, or a recorded step's control says the limit +/// was reached. Retrying it with extra visits is then worth suggesting. +bool runExhaustedVisits(JsonMap run) { + final diagnostic = '${run['diagnostic'] ?? ''}'.toLowerCase(); + if (_exhaustedPhrases.any(diagnostic.contains)) return true; + final steps = run['steps']; + if (steps is! List) return false; + return steps.whereType().any( + (step) => + step['control'] is Map && step['control']['limit_reached'] == true, + ); +} + +/// The stage keys of the run's graph, in declared order, for the extra +/// visits stage picker. +List retryStageKeys(JsonMap run) { + final graph = run['graph']; + final stages = graph is Map ? graph['stages'] : null; + if (stages is! List) return const []; + final keys = []; + for (final stage in stages.whereType()) { + final key = '${stage['key'] ?? ''}'.trim(); + if (key.isNotEmpty && !keys.contains(key)) keys.add(key); + } + return keys; +} diff --git a/app/lib/features/runs/actions/retry_extra_visits_field.dart b/app/lib/features/runs/actions/retry_extra_visits_field.dart new file mode 100644 index 00000000..876fe8d4 --- /dev/null +++ b/app/lib/features/runs/actions/retry_extra_visits_field.dart @@ -0,0 +1,95 @@ +import 'package:flutter/material.dart'; + +import 'retry_extra_visits.dart'; +import 'retry_wording.dart'; + +/// The resume prompt's optional "Grant extra visits" choice: a checkbox, the +/// number of visits (1-5) and the stage they go to (the exhausted stage by +/// default). Null [visits] means the choice is off. +class RetryExtraVisitsField extends StatelessWidget { + const RetryExtraVisitsField({ + super.key, + required this.visits, + required this.stage, + required this.stages, + required this.suggested, + required this.enabled, + required this.onVisitsChanged, + required this.onStageChanged, + }); + + final int? visits; + final String? stage; + final List stages; + + /// Whether the run failed on an exhausted loop, so the choice is suggested. + final bool suggested; + final bool enabled; + final ValueChanged onVisitsChanged; + final ValueChanged onStageChanged; + + @override + Widget build(BuildContext context) { + final count = visits; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (suggested) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + retryExhaustedHint, + key: retryExhaustedHintKey, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + CheckboxListTile( + key: retryExtraVisitsKey, + contentPadding: EdgeInsets.zero, + controlAffinity: ListTileControlAffinity.leading, + title: const Text(retryExtraVisitsLabel), + value: count != null, + onChanged: enabled + ? (checked) => onVisitsChanged(checked == true ? 1 : null) + : null, + ), + if (count != null) + Wrap( + spacing: 12, + runSpacing: 12, + children: [ + DropdownMenu( + key: retryExtraCountKey, + enabled: enabled, + label: const Text(retryExtraVisitsCountLabel), + initialSelection: count, + onSelected: (value) { + if (value != null) onVisitsChanged(value); + }, + dropdownMenuEntries: [ + for (var n = 1; n <= maxRetryExtraVisits; n++) + DropdownMenuEntry(value: n, label: '+$n'), + ], + ), + DropdownMenu( + key: retryExtraStageKey, + enabled: enabled, + label: const Text(retryExtraStageLabel), + initialSelection: stage, + onSelected: onStageChanged, + dropdownMenuEntries: [ + const DropdownMenuEntry( + value: null, + label: retryExhaustedStageLabel, + ), + for (final key in stages) + DropdownMenuEntry(value: key, label: key), + ], + ), + ], + ), + ], + ); + } +} diff --git a/app/lib/features/runs/actions/retry_intent.dart b/app/lib/features/runs/actions/retry_intent.dart index 4b97bb0e..122fd166 100644 --- a/app/lib/features/runs/actions/retry_intent.dart +++ b/app/lib/features/runs/actions/retry_intent.dart @@ -14,10 +14,35 @@ enum RetryMode { /// belongs to it. Retrying the same uncertain intent reuses [requestKey] so the /// server can dedupe it; a fresh deliberate intent uses a new key. class RetryIntent { - const RetryIntent({required this.mode, required this.requestKey}); + const RetryIntent({ + required this.mode, + required this.requestKey, + this.extraVisits, + this.extraStage, + }); final RetryMode mode; final String requestKey; + + /// Extra visits (1-5) to grant on resume; null grants none. + final int? extraVisits; + + /// The stage the extra visits go to; null lets the server grant them to the + /// exhausted stage(s). + final String? extraStage; + + /// The `retry_extra_visits` value to send: only on resume, within 1-5. + int? get wireExtraVisits { + final visits = extraVisits; + if (mode != RetryMode.resume || visits == null) return null; + return visits >= 1 && visits <= 5 ? visits : null; + } + + /// The `retry_extra_stage` value to send, only alongside extra visits. + String? get wireExtraStage { + final stage = extraStage?.trim() ?? ''; + return wireExtraVisits == null || stage.isEmpty ? null : stage; + } } /// The entropy bound for a fresh key. diff --git a/app/lib/features/runs/actions/retry_wording.dart b/app/lib/features/runs/actions/retry_wording.dart index 97c6616a..873744a8 100644 --- a/app/lib/features/runs/actions/retry_wording.dart +++ b/app/lib/features/runs/actions/retry_wording.dart @@ -14,12 +14,24 @@ const restartDialogMessage = const restartConfirmLabel = 'Restart from start'; const retryKeepLabel = 'Keep'; +const retryExtraVisitsLabel = 'Grant extra visits'; +const retryExtraVisitsCountLabel = 'Extra visits'; +const retryExtraStageLabel = 'Stage'; +const retryExhaustedStageLabel = 'Exhausted stage'; +const retryExhaustedHint = + 'This run stopped because a loop used up its visits. Granting extra ' + 'visits lets it continue when resumed.'; + /// Stable test/semantics keys shared by the action and its prompt. const retryActionKey = ValueKey('retry-run-action'); const retryKeepKey = ValueKey('retry-run-keep'); const retryConfirmKey = ValueKey('retry-run-confirm'); const retryRestartKey = ValueKey('retry-run-restart'); const retryErrorKey = ValueKey('retry-run-error'); +const retryExtraVisitsKey = ValueKey('retry-run-extra-visits'); +const retryExtraCountKey = ValueKey('retry-run-extra-count'); +const retryExtraStageKey = ValueKey('retry-run-extra-stage'); +const retryExhaustedHintKey = ValueKey('retry-run-exhausted-hint'); /// The retry dialog's title: `Retry run {id}?`. String retryDialogTitle(num runId) => 'Retry run $runId?'; diff --git a/app/lib/features/runs/data/runs_repository.dart b/app/lib/features/runs/data/runs_repository.dart index fba12db1..22705b54 100644 --- a/app/lib/features/runs/data/runs_repository.dart +++ b/app/lib/features/runs/data/runs_repository.dart @@ -118,9 +118,18 @@ class RunsRepository { num id, { required String requestKey, String? mode, + int? extraVisits, + String? extraStage, }) async { final fields = {'run_id': id, 'request_key': requestKey}; - if (mode == 'restart') fields['retry_mode'] = mode; + if (mode == 'restart') { + fields['retry_mode'] = mode; + } else if (extraVisits != null && extraVisits >= 1 && extraVisits <= 5) { + // Extra visits only extend a resumed run; a restart replays everything. + fields['retry_extra_visits'] = extraVisits; + final stage = extraStage?.trim() ?? ''; + if (stage.isNotEmpty) fields['retry_extra_stage'] = stage; + } return _required(await _gateway.call('retry_run', fields), 'run_detail'); } diff --git a/app/lib/features/runs/domain/run_decisions.dart b/app/lib/features/runs/domain/run_decisions.dart index 339508e6..1ccb4782 100644 --- a/app/lib/features/runs/domain/run_decisions.dart +++ b/app/lib/features/runs/domain/run_decisions.dart @@ -8,14 +8,58 @@ class PendingDecision { required this.stageKey, required this.instructions, required this.options, + this.exhausted, }); final num runId; final String runLabel; final String stageKey; final String instructions; final List options; + + /// The exhausted loop a server-created decision is about; null for a + /// declared human stage. + final ExhaustedLoop? exhausted; } +/// The loop whose visits ran out, from a waiting step's `exhausted` output: +/// the model stage, the visit it reached and its limit. +class ExhaustedLoop { + const ExhaustedLoop({ + required this.stage, + required this.visit, + required this.maxVisits, + required this.targets, + }); + + final String stage; + final int? visit; + final int? maxVisits; + + /// Where each option leads, by option key. + final Map targets; + + static ExhaustedLoop? parse(dynamic output) { + final value = output is Map ? output['exhausted'] : null; + if (value is! Map) return null; + final targets = value['targets']; + return ExhaustedLoop( + stage: _string(value['stage']).trim(), + visit: _int(value['visit']), + maxVisits: _int(value['max_visits']), + targets: targets is Map + ? {for (final e in targets.entries) '${e.key}': _string(e.value)} + : const {}, + ); + } +} + +/// Readable labels for the options of a server-created exhaustion decision. +const exhaustedOptionLabels = { + 'accept': 'Accept as is', + 'continue': 'One more round', + 'abort': 'Abort', +}; + JsonMap? lastWaitingStep(List steps) { for (final value in steps.reversed) { if (value is Map && value['status'] == 'waiting') { @@ -68,26 +112,37 @@ PendingDecision? pendingDecision(JsonMap? run) { } } } - if (declaration?['type'] != null && declaration!['type'] != 'human') { + final output = step?['output']; + final options = waitingOptions(output); + // A loop that exhausted its visits waits on its own (model) stage with the + // options the server recorded; any other non-human stage is not a decision. + final exhausted = ExhaustedLoop.parse(output); + final declared = exhausted == null || options.isEmpty; + if (declared && + declaration?['type'] != null && + declaration!['type'] != 'human') { return null; } - final edges = declaration?['edges']; - final options = waitingOptions(step?['output']); + final dynamic edges = exhausted != null && !declared + ? exhausted.targets + : declaration?['edges']; final keys = options.isNotEmpty ? options : humanOptions(edges); if (keys.isEmpty) return null; - final instructions = waitingPrompt(step?['output']).trim().isNotEmpty - ? waitingPrompt(step?['output']) + final instructions = waitingPrompt(output).trim().isNotEmpty + ? waitingPrompt(output) : _string(declaration?['prompt']); return PendingDecision( runId: run['id'] is num ? run['id'] as num : 0, runLabel: runIdentity(run['title'], run['name']).label, stageKey: stage, instructions: instructions, + exhausted: declared ? null : exhausted, options: keys .map( (key) => DecisionOption( key, target: _targetLabel(key, edges is Map ? edges[key] : null), + label: declared ? '' : exhaustedOptionLabels[key] ?? '', ), ) .toList(), @@ -108,3 +163,5 @@ String _targetLabel(String option, dynamic target) { bool _positive(dynamic value) => value is num && value > 0; String _string(dynamic value) => value == null ? '' : '$value'; +int? _int(dynamic value) => + value is num ? value.toInt() : int.tryParse(_string(value).trim()); diff --git a/app/lib/features/runs/domain/run_findings.dart b/app/lib/features/runs/domain/run_findings.dart new file mode 100644 index 00000000..bc2c37b8 --- /dev/null +++ b/app/lib/features/runs/domain/run_findings.dart @@ -0,0 +1,151 @@ +import '../../../core/api_gateway.dart'; + +/// A finding's severity, most severe first. Unknown wire values parse as null +/// and are kept visible under the "all" severity filter only. +enum FindingSeverity { + critical, + important, + minor, + nit; + + static FindingSeverity? parse(dynamic value) { + final text = '${value ?? ''}'.trim().toLowerCase(); + for (final severity in values) { + if (severity.name == text) return severity; + } + return null; + } +} + +/// The ledger statuses the server records for a finding. +const findingStatuses = ['open', 'fixed', 'dismissed', 'settled']; + +/// One recorded status change of a finding. +class FindingEvent { + const FindingEvent({ + required this.sequence, + required this.stage, + required this.status, + required this.reason, + }); + + final int? sequence; + final String stage; + final String status; + final String reason; +} + +/// One entry of the run's findings ledger, as the server recorded it. +class RunFinding { + const RunFinding({ + required this.id, + required this.severityText, + required this.origin, + required this.location, + required this.summary, + required this.status, + required this.reason, + required this.raisedBy, + required this.raisedSequence, + required this.updatedBy, + required this.updatedSequence, + required this.events, + }); + + final String id; + + /// The severity exactly as recorded; [severity] is its parsed form. + final String severityText; + final String origin; + final String location; + final String summary; + final String status; + final String reason; + final String raisedBy; + final int? raisedSequence; + final String updatedBy; + final int? updatedSequence; + final List events; + + FindingSeverity? get severity => FindingSeverity.parse(severityText); + bool get isOpen => status == 'open'; +} + +/// The run's findings ledger; empty when the server sent none (older servers). +List runFindings(JsonMap? run) { + final list = run?['findings']; + if (list is! List) return const []; + return [ + for (final item in list.whereType()) + if (_text(item['id']).isNotEmpty || _text(item['summary']).isNotEmpty) + RunFinding( + id: _text(item['id']), + severityText: _text(item['severity']).toLowerCase(), + origin: _text(item['origin']), + location: _text(item['location']), + summary: _text(item['summary']), + status: _text(item['status']).toLowerCase(), + reason: _text(item['reason']), + raisedBy: _text(item['raised_by']), + raisedSequence: _int(item['raised_sequence']), + updatedBy: _text(item['updated_by']), + updatedSequence: _int(item['updated_sequence']), + events: _events(item['events']), + ), + ]; +} + +/// How many findings are still open. +int openFindingCount(Iterable findings) => + findings.where((finding) => finding.isOpen).length; + +/// The status filter a fresh Findings view starts on: open items when any +/// are open, otherwise everything. +String? defaultFindingStatus(Iterable findings) => + openFindingCount(findings) > 0 ? 'open' : null; + +/// The findings matching [status] (null = all) at or above [minSeverity] +/// (null = all), in their recorded order. +List filterFindings( + Iterable findings, { + String? status, + FindingSeverity? minSeverity, +}) => [ + for (final finding in findings) + if ((status == null || finding.status == status) && + (minSeverity == null || + (finding.severity != null && + finding.severity!.index <= minSeverity.index))) + finding, +]; + +/// The run's extra visit grants as `review +1, implement +2`, or null when +/// none were granted. +String? visitGrantsSummary(JsonMap? run) { + final grants = run?['visit_grants']; + if (grants is! Map) return null; + final parts = [ + for (final entry in grants.entries) + if (_int(entry.value) case final count? when count > 0) + '${entry.key} +$count', + ]; + return parts.isEmpty ? null : parts.join(', '); +} + +List _events(dynamic value) { + if (value is! List) return const []; + return [ + for (final item in value.whereType()) + FindingEvent( + sequence: _int(item['sequence']), + stage: _text(item['stage']), + status: _text(item['status']).toLowerCase(), + reason: _text(item['reason']), + ), + ]; +} + +String _text(dynamic value) => value == null ? '' : '$value'.trim(); + +int? _int(dynamic value) => + value is num ? value.toInt() : int.tryParse(_text(value)); diff --git a/app/lib/features/runs/domain/run_models.dart b/app/lib/features/runs/domain/run_models.dart index 365591d7..30ad44ec 100644 --- a/app/lib/features/runs/domain/run_models.dart +++ b/app/lib/features/runs/domain/run_models.dart @@ -329,9 +329,14 @@ class RunListResult { } class DecisionOption { - const DecisionOption(this.key, {this.target = ''}); + const DecisionOption(this.key, {this.target = '', this.label = ''}); final String key; final String target; + + /// A readable label for a server-defined option; empty shows [key]. + final String label; + + String get displayLabel => label.trim().isEmpty ? key : label; } class DecisionDraft { diff --git a/app/lib/features/runs/ui/run_decision_notice.dart b/app/lib/features/runs/ui/run_decision_notice.dart index 1a2f2748..f94de5a8 100644 --- a/app/lib/features/runs/ui/run_decision_notice.dart +++ b/app/lib/features/runs/ui/run_decision_notice.dart @@ -53,6 +53,9 @@ class RunDecisionNotice extends StatelessWidget { maxLines: 1, overflow: TextOverflow.ellipsis, ), + if (decisionExhaustedText(pending) case final text + when text.isNotEmpty) + Text(text, style: metaStyle), ], ), ), diff --git a/app/lib/features/runs/ui/run_detail_summary_fields.dart b/app/lib/features/runs/ui/run_detail_summary_fields.dart index 5e02bd41..52232b39 100644 --- a/app/lib/features/runs/ui/run_detail_summary_fields.dart +++ b/app/lib/features/runs/ui/run_detail_summary_fields.dart @@ -2,6 +2,7 @@ import '../../../core/api_gateway.dart'; import '../../pipelines/pipeline_format.dart'; import '../domain/run_deletion.dart' show formatByteSize, runSizeBytes; import '../domain/run_failure_class.dart' show runBudgetText; +import '../domain/run_findings.dart' show visitGrantsSummary; import '../domain/run_tokens.dart'; import 'run_detail_visit_facts.dart'; @@ -72,6 +73,7 @@ List detailSummaryRows(JsonMap run, {DateTime? now}) { add('Budget', runBudgetText(run)); final retryOf = _number(run['retry_of'])?.toInt() ?? 0; if (retryOf > 0) add('Retry of', 'run $retryOf'); + add('Extra visits', visitGrantsSummary(run)); // A diagnostic is a recorded document: its own whitespace is preserved, but a // blank one is not a row. final diagnostic = '${run['diagnostic'] ?? ''}'; diff --git a/app/lib/features/runs/ui/run_detail_tab.dart b/app/lib/features/runs/ui/run_detail_tab.dart index 2b5eb319..ddf146b4 100644 --- a/app/lib/features/runs/ui/run_detail_tab.dart +++ b/app/lib/features/runs/ui/run_detail_tab.dart @@ -5,7 +5,8 @@ import 'package:flutter/material.dart'; /// /// The stable keys match the web client's `RUN_DETAIL_TABS`; the visible labels /// are the same words. `renderedRunDetailTabs` decides which keys the strip -/// draws, so Input and Output stay addressable without being tabs. +/// draws, so Input and Output stay addressable without being tabs. Findings +/// is appended only for a run whose server recorded a findings ledger. enum RunDetailTab { summary('Summary', Icons.summarize_outlined), graph('Graph', Icons.account_tree_outlined), @@ -13,7 +14,8 @@ enum RunDetailTab { output('Output', Icons.output), timeline('Timeline', Icons.timeline), artifacts('Artifacts', Icons.inventory_2_outlined), - changes('Changes', Icons.difference_outlined); + changes('Changes', Icons.difference_outlined), + findings('Findings', Icons.fact_check_outlined); const RunDetailTab(this.label, this.icon); diff --git a/app/lib/features/runs/ui/run_detail_tab_strip.dart b/app/lib/features/runs/ui/run_detail_tab_strip.dart index a82d2623..fbf14e25 100644 --- a/app/lib/features/runs/ui/run_detail_tab_strip.dart +++ b/app/lib/features/runs/ui/run_detail_tab_strip.dart @@ -41,6 +41,25 @@ class RunArtifactsCount extends StatelessWidget { } } +/// The run's open findings as a badge on the Findings tab; nothing when none +/// are open. +class RunOpenFindingsCount extends StatelessWidget { + const RunOpenFindingsCount({super.key, required this.count, this.child}); + + final int count; + final Widget? child; + + @override + Widget build(BuildContext context) { + if (count <= 0) return child ?? const SizedBox.shrink(); + return Badge( + key: const ValueKey('run-detail-findings-count'), + label: Text('$count'), + child: child, + ); + } +} + /// The run detail's tabs on a phone: the app's floating glass tab bar, full /// width at the bottom of the page (a wide layout puts `RunDetailTopTabs` /// under the run header instead). @@ -59,6 +78,7 @@ class RunDetailTabStrip extends StatelessWidget { this.tabs = renderedRunDetailTabs, this.edge = FloatingBarEdge.bottom, this.artifactCount, + this.openFindingCount, this.disabled = const {}, this.disabledReasons = const {}, }); @@ -77,6 +97,9 @@ class RunDetailTabStrip extends StatelessWidget { /// no badge. final int? artifactCount; + /// The run's open findings, badged on the Findings tab when above zero. + final int? openFindingCount; + /// Tabs shown greyed out that take no taps. final Set disabled; @@ -99,6 +122,11 @@ class RunDetailTabStrip extends StatelessWidget { key: ValueKey('run-detail-tab-${tab.name}'), icon: tab == RunDetailTab.artifacts && count != null ? RunArtifactsCount(count: count, child: Icon(tab.icon)) + : tab == RunDetailTab.findings + ? RunOpenFindingsCount( + count: openFindingCount ?? 0, + child: Icon(tab.icon), + ) : Icon(tab.icon), label: tab.label, enabled: !disabled.contains(tab), diff --git a/app/lib/features/runs/ui/run_detail_tabs.dart b/app/lib/features/runs/ui/run_detail_tabs.dart index 117b5714..c655c0ce 100644 --- a/app/lib/features/runs/ui/run_detail_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_tabs.dart @@ -27,6 +27,8 @@ import 'run_detail_top_tabs.dart'; import 'run_detail_timeline.dart'; import 'run_detail_visit.dart'; import 'run_detail_wide_chrome.dart'; +import 'run_findings_tab.dart'; +import '../domain/run_findings.dart'; import 'run_detail_visit_facts.dart'; import 'run_search_selection.dart'; @@ -398,6 +400,7 @@ class _RunDetailTabsState extends State { List _tabsFor(JsonMap run) => [ for (final tab in renderedRunDetailTabs) if (tab != RunDetailTab.changes || showRunChangesAction(run)) tab, + if (runFindings(run).isNotEmpty) RunDetailTab.findings, ]; /// Artifacts stays in place but disabled while the run recorded none. @@ -414,10 +417,13 @@ class _RunDetailTabsState extends State { final tabs = _tabsFor(widget.run); final disabled = _disabledTabs(widget.run); final artifactCount = runArtifactCount(widget.run); + final findings = runFindings(widget.run); + final openFindings = openFindingCount(findings); // A tab the run no longer offers (or cannot open) falls back to Summary. final shown = (tabs.contains(_tab) && !disabled.contains(_tab)) || - !renderedRunDetailTabs.contains(_tab) + (!renderedRunDetailTabs.contains(_tab) && + _tab != RunDetailTab.findings) ? _tab : RunDetailTab.summary; final edge = PageTabsEdge.of(context); @@ -458,6 +464,7 @@ class _RunDetailTabsState extends State { selected: shown, onSelected: select, artifactCount: artifactCount, + openFindingCount: openFindings, disabled: disabled, disabledReasons: reasons, ), @@ -471,6 +478,7 @@ class _RunDetailTabsState extends State { selected: shown, onSelected: select, artifactCount: artifactCount, + openFindingCount: openFindings, disabled: disabled, disabledReasons: reasons, ); @@ -568,6 +576,11 @@ class _RunDetailTabsState extends State { ); // Its summary heads the tab, so the tab starts below a pane's top tabs. return BelowTopBar(child: viewer); + case RunDetailTab.findings: + return RunFindingsTab( + key: ValueKey('run-detail-findings-${widget.run['id']}'), + findings: runFindings(widget.run), + ); case RunDetailTab.timeline: final visits = detailTimeline(widget.run['steps']); final index = _selectedVisit; diff --git a/app/lib/features/runs/ui/run_detail_top_tabs.dart b/app/lib/features/runs/ui/run_detail_top_tabs.dart index 90e7db85..5030388a 100644 --- a/app/lib/features/runs/ui/run_detail_top_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_top_tabs.dart @@ -18,6 +18,7 @@ class RunDetailTopTabs extends StatelessWidget { required this.selected, required this.onSelected, this.artifactCount, + this.openFindingCount, this.disabled = const {}, this.disabledReasons = const {}, }); @@ -26,6 +27,7 @@ class RunDetailTopTabs extends StatelessWidget { final RunDetailTab selected; final ValueChanged onSelected; final int? artifactCount; + final int? openFindingCount; final Set disabled; /// Why a disabled tab cannot open, as its tooltip. @@ -67,6 +69,11 @@ class RunDetailTopTabs extends StatelessWidget { const SizedBox(width: 6), RunArtifactsCount(count: count), ], + if (tab == RunDetailTab.findings && + (openFindingCount ?? 0) > 0) ...[ + const SizedBox(width: 6), + RunOpenFindingsCount(count: openFindingCount!), + ], ], ), ), diff --git a/app/lib/features/runs/ui/run_findings_tab.dart b/app/lib/features/runs/ui/run_findings_tab.dart new file mode 100644 index 00000000..531158be --- /dev/null +++ b/app/lib/features/runs/ui/run_findings_tab.dart @@ -0,0 +1,172 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/floating_bar_layout.dart'; +import '../../../ui/text/monospace.dart'; +import '../domain/run_findings.dart'; + +/// The Findings tab: the run's recorded findings ledger, filtered by status +/// (open first when any are open) and by minimum severity. Each finding +/// expands to show who raised it and its recorded status changes. +class RunFindingsTab extends StatefulWidget { + const RunFindingsTab({super.key, required this.findings}); + + final List findings; + + @override + State createState() => _RunFindingsTabState(); +} + +class _RunFindingsTabState extends State { + late String? _status = defaultFindingStatus(widget.findings); + FindingSeverity? _minSeverity; + + @override + Widget build(BuildContext context) { + final shown = filterFindings( + widget.findings, + status: _status, + minSeverity: _minSeverity, + ); + return ListView( + key: const Key('run-detail-tab-body-findings'), + padding: withBarClearance(context, const EdgeInsets.all(16)), + children: [ + _filters(context), + const SizedBox(height: 8), + if (shown.isEmpty) + Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: Text( + 'No findings match these filters.', + key: const Key('run-findings-empty'), + style: Theme.of(context).textTheme.bodyMedium, + ), + ), + for (final finding in shown) RunFindingTile(finding: finding), + ], + ); + } + + Widget _filters(BuildContext context) { + int count(String? status) => + filterFindings(widget.findings, status: status).length; + return Wrap( + spacing: 8, + runSpacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + for (final status in [null, ...findingStatuses]) + ChoiceChip( + key: ValueKey('run-findings-status-${status ?? 'all'}'), + label: Text('${_statusLabel(status)} (${count(status)})'), + selected: _status == status, + onSelected: (_) => setState(() => _status = status), + ), + DropdownMenu( + key: const Key('run-findings-severity'), + label: const Text('Minimum severity'), + initialSelection: _minSeverity, + onSelected: (value) => setState(() => _minSeverity = value), + dropdownMenuEntries: [ + const DropdownMenuEntry(value: null, label: 'All severities'), + for (final severity in FindingSeverity.values) + DropdownMenuEntry(value: severity, label: severity.name), + ], + ), + ], + ); + } +} + +String _statusLabel(String? status) => switch (status) { + null => 'All', + final text => '${text[0].toUpperCase()}${text.substring(1)}', +}; + +/// One finding: severity, id and summary, with origin, location, status and +/// the latest reason under it; expanding shows its recorded events. +class RunFindingTile extends StatelessWidget { + const RunFindingTile({super.key, required this.finding}); + + final RunFinding finding; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final meta = [ + if (finding.severityText.isNotEmpty) finding.severityText, + if (finding.origin.isNotEmpty) finding.origin, + if (finding.status.isNotEmpty) finding.status, + ].join(' · '); + final history = [ + if (finding.raisedBy.isNotEmpty) + 'Raised by ${finding.raisedBy}${_visit(finding.raisedSequence)}', + if (finding.updatedBy.isNotEmpty) + 'Updated by ${finding.updatedBy}${_visit(finding.updatedSequence)}', + ]; + return ExpansionTile( + key: ValueKey('run-finding-${finding.id}'), + tilePadding: EdgeInsets.zero, + childrenPadding: const EdgeInsetsDirectional.only(start: 40, bottom: 8), + expandedCrossAxisAlignment: CrossAxisAlignment.start, + leading: Icon( + _severityIcon(finding.severity), + color: _severityColor(theme.colorScheme, finding.severity), + ), + title: Text( + [ + finding.id, + finding.summary, + ].where((part) => part.isNotEmpty).join(' · '), + ), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(meta), + if (finding.location.isNotEmpty) + SelectableText( + finding.location, + style: const TextStyle(fontFamily: appMonospaceFamily), + ), + if (finding.reason.isNotEmpty) Text(finding.reason), + ], + ), + children: [ + for (final line in history) + Text(line, style: theme.textTheme.bodySmall), + for (final event in finding.events) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + [ + if (event.sequence != null) '#${event.sequence}', + if (event.stage.isNotEmpty) event.stage, + if (event.status.isNotEmpty) event.status, + ].join(' · ') + + (event.reason.isEmpty ? '' : ': ${event.reason}'), + style: theme.textTheme.bodySmall, + ), + ), + if (history.isEmpty && finding.events.isEmpty) + Text('No recorded history.', style: theme.textTheme.bodySmall), + ], + ); + } +} + +String _visit(int? sequence) => sequence == null ? '' : ' (visit #$sequence)'; + +IconData _severityIcon(FindingSeverity? severity) => switch (severity) { + FindingSeverity.critical => Icons.error, + FindingSeverity.important => Icons.warning_amber, + FindingSeverity.minor => Icons.info_outline, + FindingSeverity.nit || null => Icons.label_outline, +}; + +Color _severityColor(ColorScheme scheme, FindingSeverity? severity) => + switch (severity) { + FindingSeverity.critical => scheme.error, + FindingSeverity.important => scheme.tertiary, + FindingSeverity.minor => scheme.primary, + FindingSeverity.nit || null => scheme.onSurfaceVariant, + }; diff --git a/app/test/features/runs/actions/decision_exhausted_test.dart b/app/test/features/runs/actions/decision_exhausted_test.dart new file mode 100644 index 00000000..ffcf6501 --- /dev/null +++ b/app/test/features/runs/actions/decision_exhausted_test.dart @@ -0,0 +1,59 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/decision_action.dart'; +import 'package:pipelines_app/features/runs/actions/decision_wording.dart'; + +import '../domain/run_exhausted_decision_fixture.dart'; +import 'retry_test_support.dart' show FakeRetryGateway; + +void main() { + testWidgets('an exhaustion decision shows readable options and the visit ' + 'count, and sends the option key for the exhausted stage', ( + tester, + ) async { + final gateway = FakeRetryGateway( + (type, fields) async => { + 'run_detail': {...exhaustedDecisionRun(), 'status': 'running'}, + }, + ); + final changed = []; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: HumanDecisionAction( + run: exhaustedDecisionRun(), + gateway: gateway, + onRunChanged: changed.add, + ), + ), + ), + ), + ); + + await tester.tap(find.byKey(decisionActionKey)); + await tester.pumpAndSettle(); + expect(find.text('Accept as is'), findsOneWidget); + expect(find.text('One more round'), findsOneWidget); + expect(find.text('Abort'), findsOneWidget); + expect(find.text('→ implement'), findsOneWidget); + expect( + find.text('review reached its visit limit: visit 3 of 3'), + findsOneWidget, + ); + + await tester.tap(find.text('One more round')); + await tester.pump(); + await tester.tap(find.text(decisionConfirmLabel)); + await tester.pumpAndSettle(); + + final decide = gateway.calls.singleWhere((c) => c.type == 'decide_run'); + expect(decide.fields, { + 'run_id': 9, + 'option': 'continue', + 'stage': 'review', + }); + expect(changed, isNotEmpty); + }); +} diff --git a/app/test/features/runs/actions/retry_extra_visits_test.dart b/app/test/features/runs/actions/retry_extra_visits_test.dart new file mode 100644 index 00000000..b77b6bb7 --- /dev/null +++ b/app/test/features/runs/actions/retry_extra_visits_test.dart @@ -0,0 +1,168 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/retry_extra_visits.dart'; +import 'package:pipelines_app/features/runs/actions/retry_intent.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; + +import 'retry_test_support.dart'; + +JsonMap exhaustedRun() => { + ...failedRun(), + 'diagnostic': 'review: visit limit reached (3 of 3)', + 'graph': { + 'stages': [ + {'key': 'implement', 'type': 'model'}, + {'key': 'review', 'type': 'model'}, + ], + }, +}; + +Future pick(WidgetTester tester, Key menu, String label) async { + await tester.tap(find.byKey(menu)); + await tester.pumpAndSettle(); + await tester.tap(find.text(label).last); + await tester.pumpAndSettle(); +} + +void main() { + test('exhausted loops are recognised from the diagnostic or a step', () { + expect(runExhaustedVisits(exhaustedRun()), isTrue); + for (final phrase in [ + 'Visit budget exceeded', + 'total stage budget exceeded', + ]) { + expect(runExhaustedVisits({'diagnostic': phrase}), isTrue); + } + expect( + runExhaustedVisits({ + 'steps': [ + { + 'stage': 'review', + 'control': {'limit_reached': true}, + }, + ], + }), + isTrue, + ); + expect(runExhaustedVisits(failedRun()), isFalse); + expect(retryStageKeys(exhaustedRun()), ['implement', 'review']); + expect(retryStageKeys(failedRun()), isEmpty); + }); + + test('extra visits are only on the wire for a resume within 1-5', () { + RetryIntent intent(RetryMode mode, int? visits, [String? stage]) => + RetryIntent( + mode: mode, + requestKey: 'k', + extraVisits: visits, + extraStage: stage, + ); + expect(intent(RetryMode.resume, 2, 'review').wireExtraVisits, 2); + expect(intent(RetryMode.resume, 2, 'review').wireExtraStage, 'review'); + expect(intent(RetryMode.resume, 2).wireExtraStage, isNull); + expect(intent(RetryMode.resume, 0).wireExtraVisits, isNull); + expect(intent(RetryMode.resume, 6).wireExtraVisits, isNull); + expect(intent(RetryMode.resume, null, 'review').wireExtraStage, isNull); + expect(intent(RetryMode.restart, 2, 'review').wireExtraVisits, isNull); + expect(intent(RetryMode.restart, 2, 'review').wireExtraStage, isNull); + }); + + test('the repository sends extra visits on resume only', () async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + final repo = RunsRepository(gateway); + await repo.retryRun(7, requestKey: 'a', extraVisits: 2); + expect(gateway.calls.last.fields, { + 'run_id': 7, + 'request_key': 'a', + 'retry_extra_visits': 2, + }); + await repo.retryRun(7, requestKey: 'b', extraVisits: 1, extraStage: 'x'); + expect(gateway.calls.last.fields['retry_extra_stage'], 'x'); + await repo.retryRun( + 7, + requestKey: 'c', + mode: 'restart', + extraVisits: 2, + extraStage: 'x', + ); + expect(gateway.calls.last.fields, { + 'run_id': 7, + 'request_key': 'c', + 'retry_mode': 'restart', + }); + await repo.retryRun(7, requestKey: 'd', extraVisits: 9); + expect(gateway.calls.last.fields.containsKey('retry_extra_visits'), false); + }); + + testWidgets('an exhausted run suggests extra visits; chosen ones are sent', ( + tester, + ) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry(tester, gateway: gateway, changed: [], run: exhaustedRun()); + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(retryExhaustedHintKey), findsOneWidget); + // Suggested, but off until the operator chooses it. + expect(find.byKey(retryExtraCountKey), findsNothing); + await tester.tap(find.byKey(retryExtraVisitsKey)); + await tester.pumpAndSettle(); + await pick(tester, retryExtraCountKey, '+3'); + await pick(tester, retryExtraStageKey, 'review'); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + final fields = gateway.retries.single.fields; + expect(fields['retry_extra_visits'], 3); + expect(fields['retry_extra_stage'], 'review'); + expect(fields.containsKey('retry_mode'), isFalse); + }); + + testWidgets('a plain failure offers extra visits without a hint, and the ' + 'default stage is left to the server', (tester) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry(tester, gateway: gateway, changed: []); + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(retryExhaustedHintKey), findsNothing); + await tester.tap(find.byKey(retryExtraVisitsKey)); + await tester.pumpAndSettle(); + expect(find.text(retryExhaustedStageLabel), findsWidgets); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + final fields = gateway.retries.single.fields; + expect(fields['retry_extra_visits'], 1); + expect(fields.containsKey('retry_extra_stage'), isFalse); + }); + + testWidgets('restart hides and never sends extra visits', (tester) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry(tester, gateway: gateway, changed: [], run: exhaustedRun()); + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryExtraVisitsKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + expect(find.byKey(retryExtraVisitsKey), findsNothing); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + final fields = gateway.retries.single.fields; + expect(fields['retry_mode'], 'restart'); + expect(fields.containsKey('retry_extra_visits'), isFalse); + expect(fields.containsKey('retry_extra_stage'), isFalse); + }); +} diff --git a/app/test/features/runs/domain/run_exhausted_decision_fixture.dart b/app/test/features/runs/domain/run_exhausted_decision_fixture.dart new file mode 100644 index 00000000..7a748a71 --- /dev/null +++ b/app/test/features/runs/domain/run_exhausted_decision_fixture.dart @@ -0,0 +1,43 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// A run waiting on the server-created decision of an exhausted review loop: +/// the waiting stage is the model stage, not a human stage in the graph. +JsonMap exhaustedDecisionRun({dynamic output}) => { + 'id': 9, + 'status': 'waiting', + 'current_stage': 'review', + 'name': 'Build', + 'graph': { + 'stages': [ + { + 'key': 'review', + 'type': 'model', + 'edges': {'pass': '#', 'fail': 'implement'}, + }, + {'key': 'implement', 'type': 'model'}, + ], + }, + 'steps': [ + { + 'stage': 'review', + 'sequence': 6, + 'status': 'waiting', + 'output': + output ?? + { + 'prompt': 'Review used all its visits.', + 'options': ['accept', 'continue', 'abort'], + 'exhausted': { + 'stage': 'review', + 'visit': 3, + 'max_visits': 3, + 'targets': { + 'accept': '#success', + 'continue': 'implement', + 'abort': '#failure', + }, + }, + }, + }, + ], +}; diff --git a/app/test/features/runs/domain/run_exhausted_decision_test.dart b/app/test/features/runs/domain/run_exhausted_decision_test.dart new file mode 100644 index 00000000..dae2f7bd --- /dev/null +++ b/app/test/features/runs/domain/run_exhausted_decision_test.dart @@ -0,0 +1,70 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/actions/decision_wording.dart'; +import 'package:pipelines_app/features/runs/domain/run_decisions.dart'; + +import 'run_exhausted_decision_fixture.dart'; + +void main() { + test('an exhaustion decision on a model stage uses the recorded options', () { + final decision = pendingDecision(exhaustedDecisionRun())!; + expect(decision.stageKey, 'review'); + expect(decision.instructions, 'Review used all its visits.'); + expect(decision.options.map((o) => o.key), ['accept', 'continue', 'abort']); + expect(decision.options.map((o) => o.displayLabel), [ + 'Accept as is', + 'One more round', + 'Abort', + ]); + expect(decision.options.map((o) => o.target), [ + 'SUCCESS', + 'implement', + 'FAILURE', + ]); + expect(decision.exhausted?.visit, 3); + expect(decision.exhausted?.maxVisits, 3); + expect( + decisionExhaustedText(decision), + 'review reached its visit limit: visit 3 of 3', + ); + }); + + test('unknown option keys keep their recorded wording', () { + final decision = pendingDecision( + exhaustedDecisionRun( + output: { + 'options': ['accept', 'extend'], + 'exhausted': {'stage': 'review'}, + }, + ), + )!; + expect(decision.options.map((o) => o.displayLabel), [ + 'Accept as is', + 'extend', + ]); + expect(decision.options.last.target, ''); + expect(decisionExhaustedText(decision), 'review reached its visit limit'); + }); + + test('a model stage waiting without an exhaustion record is no decision', () { + expect( + pendingDecision( + exhaustedDecisionRun( + output: { + 'options': ['accept'], + }, + ), + ), + isNull, + ); + expect( + pendingDecision( + exhaustedDecisionRun( + output: { + 'exhausted': {'stage': 'review'}, + }, + ), + ), + isNull, + ); + }); +} diff --git a/app/test/features/runs/domain/run_findings_fixture.dart b/app/test/features/runs/domain/run_findings_fixture.dart new file mode 100644 index 00000000..49a43682 --- /dev/null +++ b/app/test/features/runs/domain/run_findings_fixture.dart @@ -0,0 +1,48 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// A run detail with a small findings ledger: one open, one fixed with its +/// event history, one dismissed, and a malformed entry. +JsonMap findingsRun() => { + 'id': 4, + 'findings': [ + { + 'id': 'F1', + 'severity': 'critical', + 'origin': 'introduced', + 'location': 'internal/cache.go:42', + 'summary': 'Cache never evicts', + 'status': 'open', + 'raised_by': 'review', + 'raised_sequence': 4, + }, + { + 'id': 'F2', + 'severity': 'minor', + 'origin': 'pre-existing', + 'location': '', + 'summary': 'Typo in log', + 'status': 'fixed', + 'reason': 'Corrected', + 'raised_by': 'review', + 'raised_sequence': 4, + 'updated_by': 'implement', + 'updated_sequence': 5, + 'events': [ + { + 'sequence': 5, + 'stage': 'implement', + 'status': 'fixed', + 'reason': 'Corrected', + }, + ], + }, + { + 'id': 'F3', + 'severity': 'nit', + 'origin': 'introduced', + 'summary': 'Naming', + 'status': 'dismissed', + }, + 'not a finding', + ], +}; diff --git a/app/test/features/runs/domain/run_findings_test.dart b/app/test/features/runs/domain/run_findings_test.dart new file mode 100644 index 00000000..7e4ad9e7 --- /dev/null +++ b/app/test/features/runs/domain/run_findings_test.dart @@ -0,0 +1,65 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/domain/run_findings.dart'; + +import 'run_findings_fixture.dart'; + +void main() { + test('parses the recorded ledger and skips malformed items', () { + final findings = runFindings(findingsRun()); + expect(findings.map((f) => f.id), ['F1', 'F2', 'F3']); + final fixed = findings[1]; + expect(fixed.severity, FindingSeverity.minor); + expect(fixed.origin, 'pre-existing'); + expect(fixed.location, ''); + expect(fixed.reason, 'Corrected'); + expect(fixed.updatedBy, 'implement'); + expect(fixed.updatedSequence, 5); + expect(fixed.events.single.stage, 'implement'); + expect(fixed.events.single.sequence, 5); + expect(findings.first.events, isEmpty); + expect(findings.first.raisedSequence, 4); + }); + + test('older servers without findings show nothing', () { + expect(runFindings({'id': 1}), isEmpty); + expect(runFindings({'findings': []}), isEmpty); + expect(runFindings(null), isEmpty); + }); + + test('filters by status and minimum severity', () { + final findings = runFindings(findingsRun()); + expect(openFindingCount(findings), 1); + expect(defaultFindingStatus(findings), 'open'); + expect(defaultFindingStatus(findings.skip(1)), isNull); + ids(List list) => list.map((f) => f.id).toList(); + expect(ids(filterFindings(findings)), ['F1', 'F2', 'F3']); + expect(ids(filterFindings(findings, status: 'fixed')), ['F2']); + expect(ids(filterFindings(findings, minSeverity: FindingSeverity.minor)), [ + 'F1', + 'F2', + ]); + expect( + ids(filterFindings(findings, minSeverity: FindingSeverity.critical)), + ['F1'], + ); + expect( + filterFindings( + findings, + status: 'fixed', + minSeverity: FindingSeverity.important, + ), + isEmpty, + ); + }); + + test('visit grants summarise as stage +n', () { + expect( + visitGrantsSummary({ + 'visit_grants': {'review': 1, 'implement': 2, 'idle': 0}, + }), + 'review +1, implement +2', + ); + expect(visitGrantsSummary({'visit_grants': {}}), isNull); + expect(visitGrantsSummary({}), isNull); + }); +} diff --git a/app/test/features/runs/ui/run_detail_findings_tab_test.dart b/app/test/features/runs/ui/run_detail_findings_tab_test.dart new file mode 100644 index 00000000..c6aae9cd --- /dev/null +++ b/app/test/features/runs/ui/run_detail_findings_tab_test.dart @@ -0,0 +1,43 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_tab.dart'; + +import '../domain/run_findings_fixture.dart'; +import 'run_detail_graph_support.dart'; + +void main() { + testWidgets('a run without findings has no Findings tab', (tester) async { + await pumpRunDetail(tester, RunDetailTestPlatform.material); + expect(runDetailTab(RunDetailTab.findings), findsNothing); + }); + + for (final size in const [Size(900, 1000), Size(390, 844)]) { + testWidgets('a run with findings offers the tab with its open count at ' + '${size.width}', (tester) async { + await pumpRunDetail( + tester, + RunDetailTestPlatform.material, + size: size, + run: { + ...graphRunFixture(), + 'findings': findingsRun()['findings'], + 'visit_grants': {'review': 1}, + }, + ); + expect(runDetailTab(RunDetailTab.findings), findsOneWidget); + expect( + find.byKey(const ValueKey('run-detail-findings-count')), + findsOneWidget, + ); + expect(find.text('review +1'), findsOneWidget); + + await openRunDetailTab(tester, RunDetailTab.findings); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('run-detail-tab-body-findings')), + findsOneWidget, + ); + expect(find.byKey(const ValueKey('run-finding-F1')), findsOneWidget); + }); + } +} diff --git a/app/test/features/runs/ui/run_findings_tab_test.dart b/app/test/features/runs/ui/run_findings_tab_test.dart new file mode 100644 index 00000000..e66601d6 --- /dev/null +++ b/app/test/features/runs/ui/run_findings_tab_test.dart @@ -0,0 +1,64 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/domain/run_findings.dart'; +import 'package:pipelines_app/features/runs/ui/run_findings_tab.dart'; + +import '../domain/run_findings_fixture.dart'; + +Future pumpFindings(WidgetTester tester, List findings) => + tester.pumpWidget( + MaterialApp( + home: Scaffold(body: RunFindingsTab(findings: findings)), + ), + ); + +Finder finding(String id) => find.byKey(ValueKey('run-finding-$id')); + +void main() { + testWidgets('starts on open findings and filters by status', (tester) async { + await pumpFindings(tester, runFindings(findingsRun())); + + expect(finding('F1'), findsOneWidget); + expect(finding('F2'), findsNothing); + expect(find.text('F1 · Cache never evicts'), findsOneWidget); + expect(find.text('critical · introduced · open'), findsOneWidget); + expect(find.text('internal/cache.go:42'), findsOneWidget); + expect(find.text('Open (1)'), findsOneWidget); + + await tester.tap(find.byKey(const ValueKey('run-findings-status-all'))); + await tester.pumpAndSettle(); + for (final id in ['F1', 'F2', 'F3']) { + expect(finding(id), findsOneWidget); + } + + await tester.tap(find.byKey(const ValueKey('run-findings-status-settled'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('run-findings-empty')), findsOneWidget); + }); + + testWidgets('filters by minimum severity and expands events', (tester) async { + await pumpFindings(tester, runFindings(findingsRun())); + await tester.tap(find.byKey(const ValueKey('run-findings-status-all'))); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const Key('run-findings-severity'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('minor').last); + await tester.pumpAndSettle(); + expect(finding('F2'), findsOneWidget); + expect(finding('F3'), findsNothing); + + expect(find.text('Corrected'), findsOneWidget); + await tester.tap(finding('F2')); + await tester.pumpAndSettle(); + expect(find.text('Raised by review (visit #4)'), findsOneWidget); + expect(find.text('Updated by implement (visit #5)'), findsOneWidget); + expect(find.text('#5 · implement · fixed: Corrected'), findsOneWidget); + }); + + testWidgets('with nothing open, all findings show', (tester) async { + await pumpFindings(tester, runFindings(findingsRun()).skip(1).toList()); + expect(finding('F2'), findsOneWidget); + expect(finding('F3'), findsOneWidget); + }); +} diff --git a/docs/cli.md b/docs/cli.md index efb4ca23..24f08313 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -903,6 +903,25 @@ Retry replays the entire workflow; earlier edits or notifications are not undone and may happen again. A missing original directory blocks retry rather than silently using your current directory. +`pipelines retry --extra-visits N [--stage KEY]` (wire fields +`retry_extra_visits` 1-5 and `retry_extra_stage`) continues a run whose loop +exhausted its visits (`max_visits`, the five-visit or 30-step cap) where it +stopped instead of re-running the visit that hit the cap: N extra visits go to +every exhausted stage, or with `--stage` to that stage only. Grants are +recorded on the run (`visit_grants`) and inherited by later retries; each +granted visit also lets the 30-step cap grow by one pass over the graph +(bounded at 120). It cannot be combined with `--mode=restart` or `--visit`. + +A resumed retry also inherits the run's findings ledger as it stood before the +retried visit, and receives the failed visit's `output.md` and `private/` +files (bounded: 200 files, 1 MiB each, 8 MiB total) under +`previous-attempt/` in its turn directory, listed in its `input.md`'s +`# Previous attempt` section. + +`pipelines inspect` lists the run's findings ledger (counts, open findings +most severe first, closed IDs) and its extra-visit grants; `--json` carries the +whole ledger (`findings`, with every status change) and `visit_grants`. + Retry is hidden and rejected while a run is executing or agent cleanup remains active, even if a terminal status was already persisted. Run RPCs report `executing` alongside status so clients can distinguish cleanup from completion. diff --git a/internal/author/skill/SKILL.md b/internal/author/skill/SKILL.md index f33ff419..9b7fe196 100644 --- a/internal/author/skill/SKILL.md +++ b/internal/author/skill/SKILL.md @@ -45,8 +45,10 @@ preserved branch. `failed` and `interrupted` (server stopped mid-run) runs can b retried: resume reruns the failed or interrupted stage, or starts the next stage after the last completed one. `canceled` runs need a new run or direct work on their branch. A retried stage's `input.md` carries a `# Previous attempt` section -(why the last attempt failed) and, with `--input-file`, a `# Operator correction` -section holding only the overridden keys. +(why it failed; partial work under `previous-attempt/`) and, with +`--input-file`, a `# Operator correction`. An exhausted loop continues with +`--extra-visits N [--stage KEY]` (`references/control.md`); `inspect` shows the +findings ledger (`references/format.md`). ## Use an existing pipeline diff --git a/internal/author/skill/references/control.md b/internal/author/skill/references/control.md index e5593310..51314886 100644 --- a/internal/author/skill/references/control.md +++ b/internal/author/skill/references/control.md @@ -33,6 +33,18 @@ Semantics (`internal/server/runner.go`): route normally. Here, `approved` on visit three succeeds; `rejected` fails. - A target with a lower cap than the reviewer stops the loop first, so the reviewer's `on` never fires. +- `on` lists only loop outcomes: validation rejects an outcome whose edge goes + forward (e.g. `success -> write`), since `on` would turn a good result on the + last visit into a failure. Lint also warns when a target's lower cap stops + the loop first and when `limits` sit on a stage no loop re-enters. +- `"on_exhausted":"decide"` (optional `"accept_to":"|#success|#failure"`, + default `#success`): instead of failing, an exhausted loop (the `on` case or + entering beyond the cap) parks the run on an operator decision and notifies: + `accept` (take the work as is, route to `accept_to`), `continue` (one more + round: one more visit for the stage and the loop target) or `abort`. Answer + with `pipelines decide RUN_ID --option accept|continue|abort` or the apps. +- A failed exhausted run continues with `pipelines retry ID --extra-visits N + [--stage KEY]`. - `max_visits` accepts 1–5. Every `on` outcome must have a nonterminal edge. Human stages are exempt from visit caps. The global 30-step and five-visits-per-stage limits always apply. @@ -58,6 +70,10 @@ Claude accounts or parks in `waiting_quota` (`references/debugging.md`). Visit count, limit decision and original target are retained in `inspect --json`. Turn memory is run-local: there is no cross-run memory or hidden replay, and -retries start fresh except for the completed prefix a resume carries. Accumulated +retries start fresh except for the completed prefix, the findings ledger and the +failed visit's partial work (`previous-attempt/`) a resume carries. Reviewers +should reference ledger IDs (`references/format.md`, Findings ledger) rather +than restate earlier findings, and a findings gate (`type=findings`) can +replace a model triage stage. Accumulated turn content is untrusted data; a fresh session does not prove semantic independence. diff --git a/internal/author/skill/references/format.md b/internal/author/skill/references/format.md index 4dc6d371..642ff1f9 100644 --- a/internal/author/skill/references/format.md +++ b/internal/author/skill/references/format.md @@ -54,9 +54,13 @@ Each visit gets `input.md`, `memory.md`, `history.md`, `output.md` and `private/ in `/stages/-/`, plus the run-level shared `public/` addressed by its absolute path. -- `memory.md` (capped at 4 KB, always inlined in the prompt): the run task, the - previous stage's `# handoff` with its outcome and `public/` additions, a - one-line-per-stage outcome ledger and the server-captured changed files. +- `memory.md` (about 20 KB, always inlined in the prompt), in priority order: + the run task (never truncated), the previous stage's `# handoff` with its + outcome and `public/` additions, the open findings ledger, this stage's own + previous handoff, a one-line-per-stage outcome ledger and the server-captured + changed files. Lower-priority sections shrink first. +- `findings.md`: the run's whole findings ledger with every status change + (written when the run has one). - `input.md`: the run task, plus on later turns the previous turn's full output (`internal/turn/render.go`). A stage with `read` reads it on demand; a stage without `read` gets it inlined (up to 32 KB) on every call, so give `read` to @@ -96,6 +100,60 @@ The `{ "outcome": ..., "output": ... }` JSON envelope and its format-repair ladd are retired: never ask for JSON fields or invent server sections. Missing tools or evidence route to `blocked` when declared, else `error`; never fabricate a result. +## Findings ledger + +The runner keeps one findings ledger per run and shows it to every later visit +(open items in `memory.md`, everything in `findings.md`), in `inspect` and in +the app's Findings tab. Any model stage may add an optional `# findings` +section to `output.md`, one item per line: + +````markdown +# findings + +- important introduced internal/cache.go:42: eviction never runs +- nit pre-existing -: helper names are inconsistent +- F3 fixed: evict on write; test added +- F4 dismissed: intended behaviour, documented in README +- F5 settled: operator accepted the trade-off +- F2 open: the fix misses the error path +```` + +A new finding is ` : ` with +severity `critical`, `important`, `minor` or `nit` and origin `introduced` or +`pre-existing`. The runner assigns stable IDs (`F1`, `F2`, ...). A status line +is ` fixed|dismissed|settled|open: `. Dismissed and settled items +are closed for good: re-raising one (same location and summary) or reopening it +is ignored; re-raising a fixed one reopens it. Prompts need not restate this +syntax (the runner explains it); tell reviewers to reference IDs and to raise +only new problems. + +Route on the ledger mechanically with a findings gate instead of a model +triage stage: + +````markdown +# stage triage + +```configs +type=findings +severity=important +origin=introduced +``` + +```limits +{"max_visits":3} +``` + +```edges +open -> implement +clear -> land +``` +```` + +The outcome is `open` when any open finding has at least `severity` (default +`important`) and the given `origin` (default `introduced`; `pre-existing` or +`any`), otherwise `clear`. No model runs. Only `open`, `clear` and `error` +edges are allowed. + ## Configs - `provider`/`model`: exact IDs validated during server setup. Templates @@ -122,6 +180,10 @@ evidence route to `blocked` when declared, else `error`; never fabricate a resul check stage. - `allow_workspace_changes=true`: lets a stage with `shell` but no `edit` leave file changes in the run directory (below). +- `resume_session=true`: on a loop visit, resume this stage's previous harness + session instead of starting a cold one (Claude harness only; others start + fresh; a session Claude Code no longer has starts fresh). Use it for + implementers that re-enter after review; keep reviewers fresh. - `auto_skip=false`: disable the server skip fallback for a stage that declares a `skipped` edge (`references/operations.md`, Server skip fallback). diff --git a/internal/cli/app.go b/internal/cli/app.go index 220ce1f4..e9433a48 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -59,6 +59,7 @@ type options struct { transcripts bool step int version, expected, limit, retryVisit int + extraVisits int timeout, waitTimeout time.Duration stageModels stageModelFlags // quotaNow / quotaDefer choose what run and retry do about a known usage @@ -225,6 +226,7 @@ func (a App) flags(command string) (*flag.FlagSet, *options) { f.StringVar(&o.retryMode, "mode", "resume", "Retry mode: resume failed stage or restart from entry") f.StringVar(&o.retryStage, "stage", "", "Retry this recorded stage (required when it was visited more than once)") f.IntVar(&o.retryVisit, "visit", 0, "1-based occurrence of --stage in the recorded execution") + f.IntVar(&o.extraVisits, "extra-visits", 0, "Grant 1-5 extra visits and continue an exhausted loop; with --stage, only that stage gets them") f.IntVar(&o.version, "version", 0, "Explicit published version of the same pipeline (default: source version)") f.StringVar(&o.retryInputFile, "input-file", "", "JSON object merged into the selected stage input; '-' reads stdin") f.StringVar(&o.notifyMode, "notify", "auto", "Notifications for this retry: auto, on, or off") @@ -1092,7 +1094,19 @@ func (a App) Run(ctx context.Context, args []string) error { if err != nil { return err } - r, err := call(protocol.Message{Type: typeName, RunID: id, RequestKey: key, RetryMode: o.retryMode, RetryStage: o.retryStage, RetryVisit: o.retryVisit, RetryVersion: o.version, RetryInput: retryInput, NotifyMode: o.notifyMode, QuotaPolicy: policy, BudgetUSD: o.budgetUSD}) + message := protocol.Message{Type: typeName, RunID: id, RequestKey: key, RetryMode: o.retryMode, RetryStage: o.retryStage, RetryVisit: o.retryVisit, RetryVersion: o.version, RetryInput: retryInput, NotifyMode: o.notifyMode, QuotaPolicy: policy, BudgetUSD: o.budgetUSD} + if o.extraVisits != 0 { + if o.extraVisits < 1 || o.extraVisits > 5 { + return fmt.Errorf("--extra-visits must be from 1 to 5") + } + if o.retryVisit > 0 { + return fmt.Errorf("--visit cannot be combined with --extra-visits; --stage names the stage that gets the extra visits") + } + // With --extra-visits, --stage names the stage granted the + // visits; the resume point is the exhausted loop itself. + message.RetryExtraVisits, message.RetryExtraStage, message.RetryStage = o.extraVisits, o.retryStage, "" + } + r, err := call(message) if err != nil { return quotaHint(err) } diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 47bbdf2c..8caf7cbd 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -29,7 +29,7 @@ var usage = map[string]string{ "resume": "resume [--yes] [--json]", "run-budget": "run-budget [USD|off] [--json]", "decide": "decide [stage] --option KEY [--feedback TEXT] [--json]", - "retry": "retry [--yes] [--mode resume|restart] [--stage KEY [--visit N]] [--version N] [--input-file FILE|-] [--budget USD] [--now | --defer] [--json [--wait [--wait-timeout DURATION]]]", + "retry": "retry [--yes] [--mode resume|restart] [--stage KEY [--visit N]] [--extra-visits N [--stage KEY]] [--version N] [--input-file FILE|-] [--budget USD] [--now | --defer] [--json [--wait [--wait-timeout DURATION]]]", "title": "title \"\" [--json]", "debug": "debug <run-id> [--json | --no-open]", "chat-adopt": "chat-adopt <session-id> [--harness opencode|claude|codex] [--title TEXT] [--json]", @@ -57,7 +57,7 @@ var notes = map[string]string{ "validate": "Uses the same server parser as submission. Does not persist or activate schedules. Structural validity does not prove runtime/tool availability.", "submit": "Confirm publication at the prompt, or use --yes for explicit automation; schedules activate on acceptance. Managed drafts provide the name and base-version guard. --force never bypasses validation.", "run": "Runs in your current directory after action confirmation (--yes skips it). Select a pipeline and compose a multiline task with Ctrl+S. Stage tools are enabled automatically; no file list or typed RUN confirmation. Cancellation does not undo edits. --title sets an explicit run title; without it the title is derived from the prompt. --model PROVIDER/MODEL overrides the model for every stage of that run; --stage-model STAGE=PROVIDER/MODEL overrides one stage and is repeatable, with a repeated key last-wins. Precedence is per-stage > whole-run > the model pinned in the pipeline version; overrides apply to that run only and never change the pinned definition. An unknown stage key or a malformed provider/model is refused before the run starts, naming the valid stage keys. In JSON mode --wait polls until terminal; --wait-timeout bounds only the client wait after admission and is independent of per-request --timeout. A reached wait limit leaves the run active: inspect read-only with `inspect <run-id> --json`, or reattach with --wait reusing the original --request-key (never an automatic replay or cancel).", - "retry": "Resume a failed or interrupted run's stage by default (an interrupted run resumes its unfinished stage, or the one after its last completed stage), restoring the completed prefix handoff; use --mode=restart to start at entry. --stage selects a recorded stage (use --visit for repeated stages). --input-file accepts a bounded JSON object, merged with replacement at the selected stage and shown to it as an Operator correction; the retried stage also sees why the previous attempt failed; '-' reads stdin. Original history and pinned identity are retained; --version selects an explicit published version of the same pipeline only. --wait-timeout leaves an active retry for later read-only inspection or reattachment with the original --request-key, rather than starting a duplicate retry.", + "retry": "Resume a failed or interrupted run's stage by default (an interrupted run resumes its unfinished stage, or the one after its last completed stage), restoring the completed prefix handoff; use --mode=restart to start at entry. --stage selects a recorded stage (use --visit for repeated stages). --extra-visits N (1-5) continues a loop that exhausted its visits (max_visits, the five-visit or 30-step cap) where it stopped, granting N more visits to the exhausted stage(s), or with --stage to that stage only. --input-file accepts a bounded JSON object, merged with replacement at the selected stage and shown to it as an Operator correction; the retried stage also sees why the previous attempt failed; '-' reads stdin. Original history and pinned identity are retained; --version selects an explicit published version of the same pipeline only. --wait-timeout leaves an active retry for later read-only inspection or reattachment with the original --request-key, rather than starting a duplicate retry.", "list": "Lists active pipelines. Archived pipelines are hidden; --archived lists only them and --all lists both, marking archived ones with their archive time.", "archive": "Retire a pipeline from lists after confirmation (--yes for scripts). Nothing is deleted: versions, runs, artifacts and search history stay and keep its name. An archived pipeline cannot start runs and its name stays reserved (new/submit say so). Archiving is refused while an enabled schedule points at it, naming the schedule; pause or repoint it first. The latest version is sent as a guard, so a publication in between is refused.", "unarchive": "Return an archived pipeline to lists; it can run and take new versions again. Schedules stay paused until you enable them.", diff --git a/internal/cli/inspect.go b/internal/cli/inspect.go index 7f17077f..b5ea58f1 100644 --- a/internal/cli/inspect.go +++ b/internal/cli/inspect.go @@ -3,6 +3,7 @@ package cli import ( "encoding/json" "fmt" + "sort" "strings" "unicode/utf8" @@ -54,6 +55,19 @@ func inspectSummary(d *protocol.RunDetail) string { if next := waitingHint(d); next != "" { b.WriteString("\n" + next + "\n") } + b.WriteString(inspectFindings(d)) + if len(d.VisitGrants) > 0 { + keys := make([]string, 0, len(d.VisitGrants)) + for key := range d.VisitGrants { + keys = append(keys, key) + } + sort.Strings(keys) + parts := make([]string, 0, len(keys)) + for _, key := range keys { + parts = append(parts, fmt.Sprintf("%s +%d", key, d.VisitGrants[key])) + } + b.WriteString("\nextra visits: " + strings.Join(parts, ", ") + "\n") + } if next := quotaWaitLine(d); next != "" { b.WriteString("\n" + next + "\n") } diff --git a/internal/cli/inspect_findings.go b/internal/cli/inspect_findings.go new file mode 100644 index 00000000..f31703f7 --- /dev/null +++ b/internal/cli/inspect_findings.go @@ -0,0 +1,66 @@ +package cli + +import ( + "fmt" + "strings" + + "git.a-wan.net/alan/pipelines/internal/findings" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// inspectFindingsOpenCap bounds the open findings the compact summary lists; +// --json carries the whole ledger with every status change. +const inspectFindingsOpenCap = 20 + +// inspectFindings is the compact summary's findings section: counts per +// status, then the open findings (most severe first) and the closed ones by +// ID. Empty when the run has no ledger. +func inspectFindings(d *protocol.RunDetail) string { + if len(d.Findings) == 0 { + return "" + } + counts := findings.Counts(d.Findings) + var b strings.Builder + fmt.Fprintf(&b, "\nfindings: %d open, %d fixed, %d dismissed, %d settled\n", counts[protocol.FindingOpen], counts[protocol.FindingFixed], counts[protocol.FindingDismissed], counts[protocol.FindingSettled]) + shown := 0 + for _, severity := range append(append([]string(nil), findings.Severities...), "") { + for _, item := range d.Findings { + if item.Status != protocol.FindingOpen || (severity != "" && item.Severity != severity) || (severity == "" && findings.SeverityRank(item.Severity) >= 0) { + continue + } + if shown == inspectFindingsOpenCap { + fmt.Fprintf(&b, " … %d more open (--json)\n", counts[protocol.FindingOpen]-shown) + shown++ + } + if shown > inspectFindingsOpenCap { + continue + } + shown++ + b.WriteString(" " + findingLine(item) + "\n") + } + } + for _, status := range []string{protocol.FindingFixed, protocol.FindingDismissed, protocol.FindingSettled} { + var ids []string + for _, item := range d.Findings { + if item.Status == status { + ids = append(ids, item.ID) + } + } + if len(ids) > 0 { + fmt.Fprintf(&b, " %s: %s\n", status, strings.Join(ids, ", ")) + } + } + return b.String() +} + +func findingLine(item protocol.Finding) string { + line := fmt.Sprintf("%s %s · %s · %s", item.ID, item.Status, item.Severity, item.Origin) + if item.Location != "" { + line += " · " + item.Location + } + line += " — " + item.Summary + if item.Reason != "" { + line += " (" + item.Reason + ")" + } + return line +} diff --git a/internal/cli/inspect_findings_test.go b/internal/cli/inspect_findings_test.go new file mode 100644 index 00000000..1fc32736 --- /dev/null +++ b/internal/cli/inspect_findings_test.go @@ -0,0 +1,33 @@ +package cli + +import ( + "bytes" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func TestInspectShowsFindingsAndVisitGrants(t *testing.T) { + run := sampleRun() + run.Findings = []protocol.Finding{ + {ID: "F1", Severity: "nit", Origin: "introduced", Summary: "naming", Status: "open"}, + {ID: "F2", Severity: "critical", Origin: "introduced", Location: "a.go:3", Summary: "panic", Status: "open"}, + {ID: "F3", Severity: "important", Origin: "pre-existing", Summary: "old", Status: "dismissed", Reason: "not ours"}, + {ID: "F4", Severity: "minor", Origin: "introduced", Summary: "doc", Status: "fixed"}, + } + run.VisitGrants = map[string]int{"review": 1} + var out bytes.Buffer + if err := (App{Out: &out}).inspect(run, &options{}); err != nil { + t.Fatal(err) + } + text := out.String() + for _, want := range []string{"findings: 2 open, 1 fixed, 1 dismissed, 0 settled", " F2 open · critical · introduced · a.go:3 — panic", " fixed: F4", " dismissed: F3", "extra visits: review +1"} { + if !strings.Contains(text, want) { + t.Fatalf("inspect missing %q:\n%s", want, text) + } + } + if strings.Index(text, "F2 open") > strings.Index(text, "F1 open") { + t.Fatalf("open findings not most severe first:\n%s", text) + } +} diff --git a/internal/findings/findings.go b/internal/findings/findings.go new file mode 100644 index 00000000..de418fd5 --- /dev/null +++ b/internal/findings/findings.go @@ -0,0 +1,374 @@ +// Package findings is the run-level findings ledger the runner owns. Stages +// report new findings and status changes in an output.md "# findings" section; +// the runner parses them (Parse), applies them to the ledger (Apply), assigns +// stable IDs, persists the ledger and feeds it to later visits (Render). +// +// Section syntax, one item per line (a leading list marker is optional): +// +// - <severity> <origin> <file:line>: <summary> a new finding +// - <severity> <origin>: <summary> a new finding without a location +// - F3 fixed: <how> status change +// - F3 dismissed: <why> - F3 settled: <why> closed for good +// - F3 open: <why the fix is wrong> reopen a fixed finding +// +// severity is critical, important, minor or nit; origin is introduced or +// pre-existing. Unparseable lines are ignored. +package findings + +import ( + "fmt" + "regexp" + "slices" + "strconv" + "strings" + + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/turn" +) + +// Bounds keep the ledger and each item small: it is persisted on the run and +// rendered into every later visit's memory. +const ( + MaxFindings = 200 + MaxNewPerVisit = 50 + maxSummaryBytes = 300 + maxLocationBytes = 200 + maxReasonBytes = 300 + maxEvents = 20 +) + +// Severities in rank order, most severe first. +var Severities = []string{protocol.SeverityCritical, protocol.SeverityImportant, protocol.SeverityMinor, protocol.SeverityNit} + +var severityAliases = map[string]string{ + "critical": protocol.SeverityCritical, "blocker": protocol.SeverityCritical, + "important": protocol.SeverityImportant, "major": protocol.SeverityImportant, + "minor": protocol.SeverityMinor, + "nit": protocol.SeverityNit, "nitpick": protocol.SeverityNit, "trivial": protocol.SeverityNit, +} + +var originAliases = map[string]string{ + "introduced": protocol.OriginIntroduced, "new": protocol.OriginIntroduced, + "pre-existing": protocol.OriginPreExisting, "preexisting": protocol.OriginPreExisting, + "pre_existing": protocol.OriginPreExisting, "existing": protocol.OriginPreExisting, +} + +var statusWords = map[string]string{ + "fixed": protocol.FindingFixed, "resolved": protocol.FindingFixed, + "dismissed": protocol.FindingDismissed, "rejected": protocol.FindingDismissed, "wontfix": protocol.FindingDismissed, + "settled": protocol.FindingSettled, "accepted": protocol.FindingSettled, + "open": protocol.FindingOpen, "reopen": protocol.FindingOpen, "reopened": protocol.FindingOpen, +} + +// SeverityRank is 0 for critical through 3 for nit, and -1 when unknown. +func SeverityRank(severity string) int { + return slices.Index(Severities, severity) +} + +// NormalizeSeverity returns the canonical severity or "". +func NormalizeSeverity(word string) string { return severityAliases[strings.ToLower(word)] } + +// NormalizeOrigin returns the canonical origin, "any", or "". +func NormalizeOrigin(word string) string { + if strings.EqualFold(word, "any") { + return "any" + } + return originAliases[strings.ToLower(word)] +} + +// New is a finding a stage raised; Change is a status change it reported. +type New struct { + Severity, Origin, Location, Summary string +} + +type Change struct { + ID, Status, Reason string +} + +// Report is one visit's parsed "# findings" section. +type Report struct { + New []New + Changes []Change +} + +var ( + listMarker = regexp.MustCompile(`^\s*(?:[-*+]|\d+[.)])\s+`) + findingID = regexp.MustCompile(`^(?i)F(\d+)$`) +) + +// Parse reads the "# findings" section of a turn's output. It returns an empty +// report when there is none. +func Parse(markdown string) Report { + section, ok := turn.Section(markdown, "findings") + if !ok { + return Report{} + } + var report Report + fence := "" + for _, line := range strings.Split(section, "\n") { + trimmed := strings.TrimSpace(line) + if fence != "" { + if strings.HasPrefix(trimmed, fence) { + fence = "" + } + continue + } + if strings.HasPrefix(trimmed, "```") || strings.HasPrefix(trimmed, "~~~") { + fence = trimmed[:3] + continue + } + line = strings.TrimSpace(listMarker.ReplaceAllString(line, "")) + line = strings.Trim(line, "`") + if line == "" { + continue + } + if change, ok := parseChange(line); ok { + report.Changes = append(report.Changes, change) + continue + } + if item, ok := parseNew(line); ok { + report.New = append(report.New, item) + } + } + return report +} + +// splitReason splits "word: reason", "word — reason" or "word - reason". +func splitReason(text string) (string, string) { + for _, sep := range []string{": ", " — ", " – ", " - "} { + if head, tail, ok := strings.Cut(text, sep); ok { + return strings.TrimSpace(head), strings.TrimSpace(tail) + } + } + return strings.TrimSpace(strings.TrimSuffix(text, ":")), "" +} + +func parseChange(line string) (Change, bool) { + fields := strings.Fields(line) + if len(fields) < 2 { + return Change{}, false + } + id := strings.TrimSuffix(strings.TrimSuffix(fields[0], ":"), ",") + match := findingID.FindStringSubmatch(id) + if match == nil { + return Change{}, false + } + rest := strings.TrimSpace(strings.TrimPrefix(line, fields[0])) + word, reason := splitReason(rest) + status, ok := statusWords[strings.ToLower(strings.Trim(word, "*_`"))] + if !ok { + return Change{}, false + } + return Change{ID: "F" + match[1], Status: status, Reason: capText(reason, maxReasonBytes)}, true +} + +func parseNew(line string) (New, bool) { + fields := strings.Fields(line) + if len(fields) < 2 { + return New{}, false + } + severity := NormalizeSeverity(strings.Trim(fields[0], "*_[]:")) + if severity == "" { + return New{}, false + } + originWord := fields[1] + noLocation := strings.HasSuffix(originWord, ":") + origin := originAliases[strings.ToLower(strings.Trim(originWord, "*_[]:"))] + if origin == "" { + return New{}, false + } + rest := strings.TrimSpace(line[strings.Index(line, originWord)+len(originWord):]) + var location, summary string + if noLocation { + summary = rest + } else { + summary = rest + for _, sep := range []string{": ", " — "} { + // The location is one token (a path, file:line or "-"); a + // multi-word head is prose and stays in the summary. + if head, tail, ok := strings.Cut(rest, sep); ok && !strings.ContainsAny(strings.TrimSpace(head), " \t") { + location, summary = strings.Trim(strings.TrimSpace(head), "`"), strings.TrimSpace(tail) + break + } + } + } + if location == "-" { + location = "" + } + summary = strings.TrimSpace(summary) + if summary == "" { + return New{}, false + } + return New{Severity: severity, Origin: origin, Location: capText(location, maxLocationBytes), Summary: capText(summary, maxSummaryBytes)}, true +} + +func capText(text string, limit int) string { + text = strings.Join(strings.Fields(text), " ") + if len(text) <= limit { + return text + } + cut := limit - len("…") + for cut > 0 && cut < len(text) && (text[cut]&0xC0) == 0x80 { + cut-- + } + return text[:cut] + "…" +} + +// Outcome summarises what Apply did, for logs and tests. +type Outcome struct { + Added []string + Changed []string + Ignored []string +} + +func key(location, summary string) string { + return strings.ToLower(location) + "\x00" + strings.ToLower(summary) +} + +// Apply folds one visit's report into the ledger and returns the new ledger. +// IDs are assigned in order (F1, F2, ...) and never reused. A new finding that +// repeats an open one is ignored, one that repeats a fixed one reopens it, and +// one that repeats a dismissed or settled one is ignored: those are closed for +// good. Reopening a dismissed or settled finding is ignored for the same +// reason. +func Apply(ledger []protocol.Finding, report Report, stageKey string, sequence int) ([]protocol.Finding, Outcome) { + out := append([]protocol.Finding(nil), ledger...) + var result Outcome + byID := map[string]int{} + byKey := map[string]int{} + next := 1 + for i, item := range out { + byID[item.ID] = i + byKey[key(item.Location, item.Summary)] = i + if n, err := strconv.Atoi(strings.TrimPrefix(item.ID, "F")); err == nil && n >= next { + next = n + 1 + } + } + setStatus := func(i int, status, reason string) { + item := out[i] + item.Events = append(append([]protocol.FindingEvent(nil), item.Events...), protocol.FindingEvent{Sequence: sequence, Stage: stageKey, Status: status, Reason: reason}) + if len(item.Events) > maxEvents { + item.Events = item.Events[len(item.Events)-maxEvents:] + } + item.Status, item.Reason = status, reason + item.UpdatedBy, item.UpdatedSequence = stageKey, sequence + out[i] = item + } + for _, change := range report.Changes { + i, ok := byID[change.ID] + if !ok { + result.Ignored = append(result.Ignored, change.ID+": unknown id") + continue + } + current := out[i].Status + if current == change.Status { + continue + } + if change.Status == protocol.FindingOpen && (current == protocol.FindingDismissed || current == protocol.FindingSettled) { + result.Ignored = append(result.Ignored, change.ID+": "+current+" findings are closed") + continue + } + setStatus(i, change.Status, change.Reason) + result.Changed = append(result.Changed, change.ID) + } + added := 0 + for _, item := range report.New { + if i, ok := byKey[key(item.Location, item.Summary)]; ok { + switch out[i].Status { + case protocol.FindingFixed: + setStatus(i, protocol.FindingOpen, "raised again by "+stageKey) + result.Changed = append(result.Changed, out[i].ID) + default: + result.Ignored = append(result.Ignored, out[i].ID+": already "+out[i].Status) + } + continue + } + if added >= MaxNewPerVisit || len(out) >= MaxFindings { + result.Ignored = append(result.Ignored, "over the findings limit: "+item.Summary) + continue + } + added++ + id := fmt.Sprintf("F%d", next) + next++ + out = append(out, protocol.Finding{ + ID: id, Severity: item.Severity, Origin: item.Origin, Location: item.Location, Summary: item.Summary, + Status: protocol.FindingOpen, RaisedBy: stageKey, RaisedSequence: sequence, + Events: []protocol.FindingEvent{{Sequence: sequence, Stage: stageKey, Status: protocol.FindingOpen}}, + }) + byID[id] = len(out) - 1 + byKey[key(item.Location, item.Summary)] = len(out) - 1 + result.Added = append(result.Added, id) + } + return out, result +} + +// Before returns the ledger as it stood before visit sequence: findings raised +// at or after it are dropped and later events are rolled back. A retry resuming +// at sequence starts from this ledger. +func Before(ledger []protocol.Finding, sequence int) []protocol.Finding { + var out []protocol.Finding + for _, item := range ledger { + if item.RaisedSequence >= sequence { + continue + } + var events []protocol.FindingEvent + for _, event := range item.Events { + if event.Sequence < sequence { + events = append(events, event) + } + } + item.Events = events + item.Status, item.Reason, item.UpdatedBy, item.UpdatedSequence = protocol.FindingOpen, "", "", 0 + if n := len(events); n > 0 { + last := events[n-1] + item.Status, item.Reason = last.Status, last.Reason + if n > 1 || last.Status != protocol.FindingOpen || last.Sequence != item.RaisedSequence { + item.UpdatedBy, item.UpdatedSequence = last.Stage, last.Sequence + } + } + out = append(out, item) + } + return out +} + +// Gate is a mechanical routing condition on the ledger: open findings at or +// above MinSeverity whose origin matches (Origin "any" matches both). +type Gate struct { + MinSeverity string + Origin string +} + +// Matching returns the open findings the gate counts. +func (g Gate) Matching(ledger []protocol.Finding) []protocol.Finding { + limit := SeverityRank(g.MinSeverity) + if limit < 0 { + limit = SeverityRank(protocol.SeverityImportant) + } + var out []protocol.Finding + for _, item := range ledger { + if item.Status != protocol.FindingOpen { + continue + } + rank := SeverityRank(item.Severity) + if rank < 0 || rank > limit { + continue + } + if g.Origin != "any" && g.Origin != "" && item.Origin != g.Origin { + continue + } + if g.Origin == "" && item.Origin != protocol.OriginIntroduced { + continue + } + out = append(out, item) + } + return out +} + +// Counts returns the number of findings per status. +func Counts(ledger []protocol.Finding) map[string]int { + counts := map[string]int{} + for _, item := range ledger { + counts[item.Status]++ + } + return counts +} diff --git a/internal/findings/findings_test.go b/internal/findings/findings_test.go new file mode 100644 index 00000000..139bfd0b --- /dev/null +++ b/internal/findings/findings_test.go @@ -0,0 +1,143 @@ +package findings + +import ( + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +const reviewOutput = "# outcome\n\nrejected\n\n# handoff\n\nTwo issues.\n\n# findings\n\n" + + "- important introduced internal/cache.go:42: eviction never runs\n" + + "- nit pre-existing -: odd naming in helpers\n" + + "- minor introduced: missing doc comment\n" + + "* blocker new `cmd/main.go`: panics on empty input\n" + + "- this line is prose and ignored\n" + + "\n```\n- critical introduced x.go:1: inside a fence\n```\n" + + "\n# details\n\n- critical introduced y.go:2: outside the section\n" + +func TestParseNewFindingsAndIgnoresProse(t *testing.T) { + report := Parse(reviewOutput) + if len(report.New) != 4 || len(report.Changes) != 0 { + t.Fatalf("report = %+v", report) + } + want := []New{ + {Severity: "important", Origin: "introduced", Location: "internal/cache.go:42", Summary: "eviction never runs"}, + {Severity: "nit", Origin: "pre-existing", Location: "", Summary: "odd naming in helpers"}, + {Severity: "minor", Origin: "introduced", Location: "", Summary: "missing doc comment"}, + {Severity: "critical", Origin: "introduced", Location: "cmd/main.go", Summary: "panics on empty input"}, + } + for i := range want { + if report.New[i] != want[i] { + t.Errorf("new[%d] = %+v, want %+v", i, report.New[i], want[i]) + } + } + if got := Parse("# outcome\n\nsuccess\n"); len(got.New)+len(got.Changes) != 0 { + t.Fatalf("no section should parse empty: %+v", got) + } +} + +func TestParseStatusChanges(t *testing.T) { + report := Parse("# findings\n\n- F1 fixed: added eviction\n- f2 dismissed — style only\n- F3: settled - agreed with operator\n- F4 open: fix incomplete\n- F5 maybe: unknown word\n") + want := []Change{{"F1", "fixed", "added eviction"}, {"F2", "dismissed", "style only"}, {"F3", "settled", "agreed with operator"}, {"F4", "open", "fix incomplete"}} + if len(report.Changes) != len(want) { + t.Fatalf("changes = %+v", report.Changes) + } + for i := range want { + if report.Changes[i] != want[i] { + t.Errorf("change[%d] = %+v, want %+v", i, report.Changes[i], want[i]) + } + } +} + +func TestApplyAssignsStableIDsAndEnforcesClosedItems(t *testing.T) { + ledger, out := Apply(nil, Parse(reviewOutput), "review", 2) + if strings.Join(out.Added, ",") != "F1,F2,F3,F4" || len(ledger) != 4 { + t.Fatalf("added %v ledger %d", out.Added, len(ledger)) + } + ledger, out = Apply(ledger, Parse("# findings\n- F1 fixed: evicts now\n- F2 dismissed: out of scope\n- F9 fixed: nope\n"), "implement", 3) + if strings.Join(out.Changed, ",") != "F1,F2" || len(out.Ignored) != 1 { + t.Fatalf("outcome %+v", out) + } + // A reviewer re-raising the dismissed F2 is ignored; re-raising the fixed F1 reopens it; + // reopening the dismissed F2 by id is ignored; a genuinely new item gets F5. + ledger, out = Apply(ledger, Parse("# findings\n- nit pre-existing -: odd naming in helpers\n- important introduced internal/cache.go:42: eviction never runs\n- F2 open: still bad\n- minor introduced a.go:1: new thing\n"), "review", 4) + if strings.Join(out.Added, ",") != "F5" || strings.Join(out.Changed, ",") != "F1" || len(out.Ignored) != 2 { + t.Fatalf("outcome %+v", out) + } + byID := map[string]protocol.Finding{} + for _, item := range ledger { + byID[item.ID] = item + } + if byID["F1"].Status != "open" || byID["F2"].Status != "dismissed" || byID["F2"].Reason != "out of scope" || byID["F1"].UpdatedSequence != 4 { + t.Fatalf("ledger %+v", ledger) + } + // Before rolls the ledger back to the state a retry at sequence 4 starts from. + before := Before(ledger, 4) + if len(before) != 4 { + t.Fatalf("before = %d items", len(before)) + } + for _, item := range before { + if item.ID == "F1" && (item.Status != "fixed" || item.UpdatedSequence != 3) { + t.Fatalf("F1 before 4 = %+v", item) + } + if item.ID == "F3" && (item.Status != "open" || item.UpdatedSequence != 0) { + t.Fatalf("F3 before 4 = %+v", item) + } + } + if got := Before(ledger, 2); len(got) != 0 { + t.Fatalf("before 2 = %+v", got) + } + // IDs continue after the highest existing one. + _, out = Apply(before, Parse("# findings\n- minor introduced b.go:1: another\n"), "review", 4) + if strings.Join(out.Added, ",") != "F5" { + t.Fatalf("added %v", out.Added) + } +} + +func TestGateMatching(t *testing.T) { + ledger, _ := Apply(nil, Parse(reviewOutput), "review", 1) + if got := (Gate{MinSeverity: "important", Origin: "introduced"}).Matching(ledger); len(got) != 2 { + t.Fatalf("important introduced = %+v", got) + } + if got := (Gate{}).Matching(ledger); len(got) != 2 { + t.Fatalf("defaults = %+v", got) + } + if got := (Gate{MinSeverity: "nit", Origin: "any"}).Matching(ledger); len(got) != 4 { + t.Fatalf("nit any = %+v", got) + } + if got := (Gate{MinSeverity: "critical", Origin: "pre-existing"}).Matching(ledger); len(got) != 0 { + t.Fatalf("critical pre-existing = %+v", got) + } + ledger, _ = Apply(ledger, Parse("# findings\n- F1 fixed: done\n- F4 settled: accepted\n"), "implement", 2) + if got := (Gate{}).Matching(ledger); len(got) != 0 { + t.Fatalf("after fixes = %+v", got) + } +} + +func TestRenderMemoryIsBoundedAndListsOpenFirst(t *testing.T) { + ledger, _ := Apply(nil, Parse(reviewOutput), "review", 1) + ledger, _ = Apply(ledger, Parse("# findings\n- F2 dismissed: not ours\n"), "implement", 2) + text := RenderMemory(ledger, 4096) + if !strings.Contains(text, "F4 · critical") || strings.Index(text, "F4 · critical") > strings.Index(text, "F1 · important") { + t.Fatalf("open findings not ordered by severity:\n%s", text) + } + if !strings.Contains(text, "Closed (do not re-raise):\n- F2 dismissed") || !strings.Contains(text, "never re-raise") { + t.Fatalf("closed list or instructions missing:\n%s", text) + } + var many []protocol.Finding + for i := 0; i < 150; i++ { + many, _ = Apply(many, Report{New: []New{{Severity: "minor", Origin: "introduced", Location: "f.go:" + strings.Repeat("1", i%7+1), Summary: strings.Repeat("x", 40) + string(rune('a'+i%26)) + strings.Repeat("y", i)}}}, "review", 1) + } + small := RenderMemory(many, 2048) + if len(small) > 2048 || !strings.Contains(small, "more in findings.md") { + t.Fatalf("bounded render is %d bytes:\n%s", len(small), small) + } + if RenderMemory(nil, 4096) != "" { + t.Fatal("empty ledger renders a section") + } + file := RenderFile(ledger) + if !strings.Contains(file, "## Dismissed") || !strings.Contains(file, "#2 implement → dismissed: not ours") { + t.Fatalf("file:\n%s", file) + } +} diff --git a/internal/findings/render.go b/internal/findings/render.go new file mode 100644 index 00000000..b184f20d --- /dev/null +++ b/internal/findings/render.go @@ -0,0 +1,122 @@ +package findings + +import ( + "fmt" + "strings" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// Syntax is the one-paragraph reporting instruction shared by the memory +// section and the model prompt. +const Syntax = "Report findings in an optional `# findings` section of output.md, one per line: a new one as `- <critical|important|minor|nit> <introduced|pre-existing> <file:line or ->: <summary>`; a status change to a ledger item as `- F3 fixed: <how>`, `- F3 dismissed: <why>` or `- F3 settled: <why>` (`- F3 open: <why>` reopens a fixed one). The runner assigns IDs; reference them, and never re-raise a dismissed or settled finding." + +func line(item protocol.Finding) string { + location := "" + if item.Location != "" { + location = " · " + item.Location + } + return fmt.Sprintf("%s · %s · %s%s — %s", item.ID, item.Severity, item.Origin, location, item.Summary) +} + +// RenderMemory is the ledger section of a visit's essential memory: every open +// finding (most severe first) and a short list of closed ones, bounded by +// limit bytes. It is empty when the ledger is. +func RenderMemory(ledger []protocol.Finding, limit int) string { + if len(ledger) == 0 { + return "" + } + counts := Counts(ledger) + var b strings.Builder + fmt.Fprintf(&b, "\n## Findings ledger (runner-owned)\n\n%d open, %d fixed, %d dismissed, %d settled. Full ledger: findings.md beside this file.\n\n", + counts[protocol.FindingOpen], counts[protocol.FindingFixed], counts[protocol.FindingDismissed], counts[protocol.FindingSettled]) + footer := "\n" + Syntax + "\n" + budget := limit - b.Len() - len(footer) + var body strings.Builder + write := func(text string) bool { + if body.Len()+len(text) > budget { + return false + } + body.WriteString(text) + return true + } + omitted := 0 + if counts[protocol.FindingOpen] > 0 { + write("Open:\n") + for _, severity := range append(append([]string(nil), Severities...), "") { + for _, item := range ledger { + if item.Status != protocol.FindingOpen || (severity != "" && item.Severity != severity) || (severity == "" && SeverityRank(item.Severity) >= 0) { + continue + } + if !write("- " + line(item) + "\n") { + omitted++ + } + } + } + } + closed := []string{} + for _, item := range ledger { + if item.Status == protocol.FindingDismissed || item.Status == protocol.FindingSettled { + closed = append(closed, fmt.Sprintf("- %s %s — %s", item.ID, item.Status, capText(item.Summary, 80))) + } + } + if len(closed) > 0 { + write("\nClosed (do not re-raise):\n") + for _, text := range closed { + if !write(text + "\n") { + omitted++ + } + } + } + var fixed []string + for _, item := range ledger { + if item.Status == protocol.FindingFixed { + fixed = append(fixed, item.ID) + } + } + if len(fixed) > 0 { + if !write("\nFixed: " + strings.Join(fixed, ", ") + "\n") { + omitted++ + } + } + if omitted > 0 { + fmt.Fprintf(&body, "- … %d more in findings.md\n", omitted) + } + b.WriteString(body.String()) + b.WriteString(footer) + return b.String() +} + +// RenderFile is findings.md: the whole ledger with every item's history. +func RenderFile(ledger []protocol.Finding) string { + var b strings.Builder + b.WriteString("# Findings ledger\n\nRunner-owned; IDs are stable for the run. " + Syntax + "\n") + if len(ledger) == 0 { + b.WriteString("\nNo findings yet.\n") + return b.String() + } + for _, status := range []string{protocol.FindingOpen, protocol.FindingFixed, protocol.FindingDismissed, protocol.FindingSettled} { + first := true + for _, item := range ledger { + if item.Status != status { + continue + } + if first { + fmt.Fprintf(&b, "\n## %s\n\n", strings.ToUpper(status[:1])+status[1:]) + first = false + } + fmt.Fprintf(&b, "- %s (raised by %s, visit #%d)\n", line(item), item.RaisedBy, item.RaisedSequence) + for _, event := range item.Events { + if event.Sequence == item.RaisedSequence && event.Status == protocol.FindingOpen && event.Reason == "" { + continue + } + reason := "" + if event.Reason != "" { + reason = ": " + event.Reason + } + fmt.Fprintf(&b, " - #%d %s → %s%s\n", event.Sequence, event.Stage, event.Status, reason) + } + } + } + return b.String() +} diff --git a/internal/pipeline/control.go b/internal/pipeline/control.go index 5fb6fb05..3dceee13 100644 --- a/internal/pipeline/control.go +++ b/internal/pipeline/control.go @@ -61,6 +61,14 @@ func parseControl(s *Stage, fields map[string]string) error { } seen[outcome] = true } + switch s.Limits.OnExhausted { + case "", "fail", "decide": + default: + return fmt.Errorf("on_exhausted must be fail or decide") + } + if s.Limits.AcceptTo != "" && s.Limits.OnExhausted != "decide" { + return fmt.Errorf("accept_to needs \"on_exhausted\":\"decide\"") + } delete(fields, "limits") } if text, ok := fields["memory"]; ok { @@ -86,6 +94,9 @@ func validateControl(s Stage, stages map[string]bool) error { return fmt.Errorf("stage %s: limit outcome %q must name a nonterminal edge", s.Key, outcome) } } + if target := s.Limits.AcceptTo; target != "" && !protocol.IsTerminal(target) && !stages[target] { + return fmt.Errorf("stage %s: accept_to %q is not a stage, #success or #failure", s.Key, target) + } } for _, ref := range s.Memory { owner, _, _ := strings.Cut(ref, ".") diff --git a/internal/pipeline/lint.go b/internal/pipeline/lint.go index c2765c80..0177ce73 100644 --- a/internal/pipeline/lint.go +++ b/internal/pipeline/lint.go @@ -90,6 +90,23 @@ func Lint(g Graph) (errs, warnings []LintFinding) { } } } + lintLoops(g, i, index, func(list *[]LintFinding, rule, format string, args ...any) { + if list == nil { + list = &warnings + } + add(list, s, rule, format, args...) + }, &errs) + if model && s.Configs["resume_session"] == "true" { + if !reentered(g, i, index) { + add(&warnings, s, "resume_session", "resume_session=true has no effect: no edge loops back to %s, so it never has a previous session to resume", s.Key) + } + if s.Configs["harness"] != stage.ClaudeBackend { + add(&warnings, s, "resume_session", "resume_session is supported only by harness=claude; this stage starts a fresh session on every visit") + } + if reason := mutatingReason(s); reason == "" { + add(&warnings, s, "resume_session", "resume_session on a read-only stage carries its earlier verdicts into later visits; keep reviewers on fresh sessions and resume only implementers") + } + } if stage.EffectiveType(s.Type) == stage.CheckType { for _, line := range strings.Split(s.Blocks["commands"], "\n") { if guard := silentGuard(line); guard != "" { @@ -113,6 +130,63 @@ func Lint(g Graph) (errs, warnings []LintFinding) { return errs, warnings } +// lintLoops checks a stage's limits block against the graph: an `on` outcome +// must be a loop (back edge or self-loop), because `on` turns that outcome into +// a failure on the last allowed visit; a forward `success` there makes a good +// result fail the run. It also warns when the limits can never apply. +func lintLoops(g Graph, i int, index map[string]int, add func(list *[]LintFinding, rule, format string, args ...any), errs *[]LintFinding) { + s := g.Stages[i] + if s.Limits == nil { + return + } + for _, outcome := range s.Limits.On { + target, ok := s.Edges[outcome] + if !ok || protocol.IsTerminal(target) { + continue + } + if index[target] > i { + add(errs, "limits", "limits.on lists %q, but %s -> %s is a forward edge, not a loop back; on the last allowed visit the runner routes a listed outcome to #failure, so a %s there would fail the run. List only outcomes whose edge returns to %s or an earlier stage (for example \"rejected\"), or drop \"on\"", outcome, outcome, target, outcome, s.Key) + continue + } + if limits := g.Stages[index[target]].Limits; limits != nil && index[target] != i && limits.MaxVisits < s.Limits.MaxVisits { + add(nil, "limits", "%s has max_visits %d, lower than this stage's %d: the loop stops at %s first, so on [%q] never fires; give %s a cap at least %d or leave it unlimited", target, limits.MaxVisits, s.Limits.MaxVisits, target, outcome, target, s.Limits.MaxVisits) + } + } + if !reentered(g, i, index) { + add(nil, "limits", "limits has no effect: no edge loops back to %s, so it is visited once per run; move the limits to the stage that sends the run back, or remove them", s.Key) + } + if s.Limits.OnExhausted == "decide" && stage.EffectiveType(s.Type) == stage.HumanType { + add(nil, "limits", "on_exhausted=decide on a human stage has no effect; human stages are exempt from visit caps") + } +} + +// reentered reports whether stage i lies on a cycle, i.e. whether a run can +// visit it more than once. +func reentered(g Graph, i int, index map[string]int) bool { + key := g.Stages[i].Key + seen := map[string]bool{} + var stack []string + for _, target := range g.Stages[i].Edges { + stack = append(stack, target) + } + for len(stack) > 0 { + next := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if next == key { + return true + } + j, ok := index[next] + if !ok || seen[next] || protocol.IsTerminal(next) { + continue + } + seen[next] = true + for _, target := range g.Stages[j].Edges { + stack = append(stack, target) + } + } + return false +} + // mutatingReason names why a model stage can change the workspace, or "". func mutatingReason(s Stage) string { if s.Configs["delivery"] == "true" { diff --git a/internal/pipeline/lint_loops_test.go b/internal/pipeline/lint_loops_test.go new file mode 100644 index 00000000..75822f53 --- /dev/null +++ b/internal/pipeline/lint_loops_test.go @@ -0,0 +1,109 @@ +package pipeline + +import ( + "strings" + "testing" +) + +func TestLintRejectsForwardLimitOutcomes(t *testing.T) { + // Research runs 100/101: "on" listed the forward success edge, so a good + // result on the last allowed visit failed the run. + source := lintSource( + modelStage("research", "Research.", "read", "success -> write\nretry -> research\nerror -> #failure", "```limits\n{\"max_visits\":3,\"on\":[\"success\",\"retry\"]}\n```"), + modelStage("write", "Write.", "read", "success -> #success\nerror -> #failure", ""), + ) + errs, _ := lintRules(t, source) + if len(errs["limits"]) != 1 || !strings.Contains(errs["limits"][0], `limits.on lists "success", but success -> write is a forward edge`) { + t.Fatalf("limits errors = %v", errs["limits"]) + } +} + +func TestLintWarnsAboutIneffectiveLoopSettings(t *testing.T) { + checks := "```checks\nnone: focused tests only\n```" + source := lintSource( + modelStage("implement", "Implement.", "read\nedit", "success -> review\nerror -> #failure", checks+"\n\n```limits\n{\"max_visits\":2}\n```"), + modelStage("review", "Review.", "read", "approved -> land\nrejected -> implement\nerror -> #failure", "```limits\n{\"max_visits\":3,\"on\":[\"rejected\"],\"on_exhausted\":\"decide\",\"accept_to\":\"land\"}\n```"), + modelStage("land", "Land.", "read", "success -> #success\nerror -> #failure", "```limits\n{\"max_visits\":2}\n```"), + ) + errs, warns := lintRules(t, source) + if len(errs["limits"]) != 0 { + t.Fatalf("unexpected errors %v", errs) + } + joined := strings.Join(warns["limits"], "\n") + for _, want := range []string{"implement has max_visits 2, lower than this stage's 3", "stage land: limits: limits has no effect"} { + if !strings.Contains(joined, want) { + t.Fatalf("warnings missing %q:\n%s", want, joined) + } + } + if strings.Contains(joined, "stage review: limits: limits has no effect") || strings.Contains(joined, "stage implement: limits: limits has no effect") { + t.Fatalf("review and implement are on a loop:\n%s", joined) + } +} + +func TestLintWarnsAboutResumeSession(t *testing.T) { + stageWith := func(key, tools, edges, configs, extra string) string { + return "# stage " + key + "\n\n```prompt\nWork.\n```\n\n```configs\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\n" + configs + "\n```\n\n```tools\n" + tools + "\n```\n\n```edges\n" + edges + "\n```\n\n" + extra + "\n" + } + source := lintSource( + stageWith("implement", "read\nedit", "success -> review\nerror -> #failure", "resume_session=true", "```checks\nnone: focused\n```"), + stageWith("review", "read", "approved -> #success\nrejected -> implement\nerror -> #failure", "resume_session=true", "```limits\n{\"max_visits\":3,\"on\":[\"rejected\"]}\n```"), + ) + _, warns := lintRules(t, source) + joined := strings.Join(warns["resume_session"], "\n") + for _, want := range []string{"stage implement: resume_session: resume_session is supported only by harness=claude", "stage review: resume_session: resume_session on a read-only stage"} { + if !strings.Contains(joined, want) { + t.Fatalf("warnings missing %q:\n%s", want, joined) + } + } + if strings.Contains(joined, "has no effect") { + t.Fatalf("both stages loop:\n%s", joined) + } +} + +func TestParseValidatesExhaustionSettings(t *testing.T) { + base := func(limits string) string { + return lintSource( + modelStage("implement", "Implement.", "read", "success -> review\nerror -> #failure", ""), + modelStage("review", "Review.", "read", "approved -> #success\nrejected -> implement\nerror -> #failure", "```limits\n"+limits+"\n```"), + ) + } + for limits, want := range map[string]string{ + `{"max_visits":3,"on_exhausted":"ask"}`: "on_exhausted must be fail or decide", + `{"max_visits":3,"accept_to":"implement"}`: "accept_to needs", + `{"max_visits":3,"on_exhausted":"decide","accept_to":"nowhere"}`: "accept_to \"nowhere\" is not a stage", + } { + if _, err := Parse(base(limits)); err == nil || !strings.Contains(err.Error(), want) { + t.Fatalf("%s: err = %v, want %q", limits, err, want) + } + } + if _, err := Parse(base(`{"max_visits":3,"on":["rejected"],"on_exhausted":"decide","accept_to":"#success"}`)); err != nil { + t.Fatal(err) + } +} + +func TestParseFindingsGateStage(t *testing.T) { + gate := func(configs, edges string) string { + return lintSource( + modelStage("review", "Review.", "read", "success -> triage\nerror -> #failure", ""), + "# stage triage\n\n```configs\ntype=findings\n"+configs+"\n```\n\n```edges\n"+edges+"\n```\n", + modelStage("fix", "Fix.", "read", "success -> review\nerror -> #failure", ""), + ) + } + g, err := Parse(gate("severity=minor\norigin=any", "open -> fix\nclear -> #success")) + if err != nil { + t.Fatal(err) + } + if g.Stages[1].Type != "findings" { + t.Fatalf("type = %q", g.Stages[1].Type) + } + for _, tc := range []struct{ configs, edges, want string }{ + {"severity=huge", "open -> fix\nclear -> #success", "severity must be"}, + {"origin=old", "open -> fix\nclear -> #success", "origin must be"}, + {"", "open -> fix", "requires an edge for outcome clear"}, + {"", "open -> fix\nclear -> #success\nmaybe -> fix", "outcomes are open and clear"}, + } { + if _, err := Parse(gate(tc.configs, tc.edges)); err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("%+v: err = %v", tc, err) + } + } +} diff --git a/internal/pipeline/retention.go b/internal/pipeline/retention.go index 8fa1df23..d06d9102 100644 --- a/internal/pipeline/retention.go +++ b/internal/pipeline/retention.go @@ -645,6 +645,7 @@ func deleteRunRows(ctx context.Context, tx *sql.Tx, ids []int64) error { {"attention_dismissals", "run_id"}, {"run_schedule_origin", "run_id"}, {"run_stage_skills", "run_id"}, + {"run_loop_state", "run_id"}, {"run_steps", "run_id"}, } { if err := deleteRetentionBatch(ctx, tx, table.name, table.column, ids); err != nil && !missingTable(err) { diff --git a/internal/pipeline/run_loop_state.go b/internal/pipeline/run_loop_state.go new file mode 100644 index 00000000..60177915 --- /dev/null +++ b/internal/pipeline/run_loop_state.go @@ -0,0 +1,91 @@ +package pipeline + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// initRunLoopState records the runner-owned loop state of a run: its findings +// ledger and the extra visits granted to its stages (by a retry with +// --extra-visits or a "continue" exhaustion decision). One row per run, written +// by the runner as the state changes. +func (s *Store) initRunLoopState() error { + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS run_loop_state ( +run_id INTEGER PRIMARY KEY REFERENCES pipeline_runs(id), +findings_json TEXT NOT NULL DEFAULT '[]', +grants_json TEXT NOT NULL DEFAULT '{}')`) + return err +} + +// SetRunFindings replaces a run's findings ledger. +func (s *Store) SetRunFindings(ctx context.Context, runID int64, ledger []protocol.Finding) error { + if ledger == nil { + ledger = []protocol.Finding{} + } + encoded, err := json.Marshal(ledger) + if err != nil { + return err + } + _, err = s.db.ExecContext(ctx, `INSERT INTO run_loop_state(run_id,findings_json) VALUES(?,?) +ON CONFLICT(run_id) DO UPDATE SET findings_json=excluded.findings_json`, runID, string(encoded)) + return err +} + +// SetRunVisitGrants replaces a run's extra-visit grants. +func (s *Store) SetRunVisitGrants(ctx context.Context, runID int64, grants map[string]int) error { + if grants == nil { + grants = map[string]int{} + } + encoded, err := json.Marshal(grants) + if err != nil { + return err + } + _, err = s.db.ExecContext(ctx, `INSERT INTO run_loop_state(run_id,grants_json) VALUES(?,?) +ON CONFLICT(run_id) DO UPDATE SET grants_json=excluded.grants_json`, runID, string(encoded)) + return err +} + +// AddRunVisitGrant adds extra visits for one stage and returns the new grants. +func (s *Store) AddRunVisitGrant(ctx context.Context, runID int64, stageKey string, extra int) (map[string]int, error) { + _, grants, err := runLoopState(ctx, s.db, runID) + if err != nil { + return nil, err + } + if grants == nil { + grants = map[string]int{} + } + grants[stageKey] += extra + return grants, s.SetRunVisitGrants(ctx, runID, grants) +} + +func runLoopState(ctx context.Context, q interface { + QueryRowContext(context.Context, string, ...any) *sql.Row +}, runID int64) ([]protocol.Finding, map[string]int, error) { + var ledgerJSON, grantsJSON string + err := q.QueryRowContext(ctx, `SELECT findings_json,grants_json FROM run_loop_state WHERE run_id=?`, runID).Scan(&ledgerJSON, &grantsJSON) + if errors.Is(err, sql.ErrNoRows) || missingTable(err) { + return nil, nil, nil + } + if err != nil { + return nil, nil, err + } + var ledger []protocol.Finding + if err := json.Unmarshal([]byte(ledgerJSON), &ledger); err != nil { + return nil, nil, err + } + var grants map[string]int + if err := json.Unmarshal([]byte(grantsJSON), &grants); err != nil { + return nil, nil, err + } + if len(ledger) == 0 { + ledger = nil + } + if len(grants) == 0 { + grants = nil + } + return ledger, grants, nil +} diff --git a/internal/pipeline/run_size.go b/internal/pipeline/run_size.go index ea555902..0d0da006 100644 --- a/internal/pipeline/run_size.go +++ b/internal/pipeline/run_size.go @@ -87,6 +87,7 @@ var runDBBytesQuery = func() string { {"retry_checkpoints", "run_id=?1", []string{"mode", "handoff_json", "source_hash"}}, {"run_schedule_origin", "run_id=?1", []string{"name"}}, {"run_stage_skills", "run_id=?1", []string{"skills_json"}}, + {"run_loop_state", "run_id=?1", []string{"findings_json", "grants_json"}}, } terms := make([]string, 0, len(parts)) for _, p := range parts { diff --git a/internal/pipeline/runs.go b/internal/pipeline/runs.go index 3c36cfec..d1982e6f 100644 --- a/internal/pipeline/runs.go +++ b/internal/pipeline/runs.go @@ -323,6 +323,9 @@ strftime('%Y-%m-%dT%H:%M:%SZ',started_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ' return nil, err } stepSkills(r.Steps, r.StageSkills) + if r.Findings, r.VisitGrants, err = runLoopState(ctx, tx, id); err != nil { + return nil, err + } // The run total is one pass over the steps already loaded above: it adds no // query and no transcript parse. r.Usage = protocol.TotalUsage(r.Steps) diff --git a/internal/pipeline/runs_mutate.go b/internal/pipeline/runs_mutate.go index a72a304f..0119ce19 100644 --- a/internal/pipeline/runs_mutate.go +++ b/internal/pipeline/runs_mutate.go @@ -279,7 +279,33 @@ JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version } var edges map[string]string found := false + // A loop that exhausted its visits on a stage with on_exhausted=decide + // parks the run on a decision step under that (non-human) stage's key; its + // evidence carries the option targets. + var exhausted map[string]any + var latestOutput string + if err := tx.QueryRowContext(ctx, `SELECT output_json FROM run_steps WHERE run_id=? AND stage_key=? ORDER BY sequence DESC LIMIT 1`, id, stageKey).Scan(&latestOutput); err == nil { + var evidence map[string]any + if json.Unmarshal([]byte(latestOutput), &evidence) == nil { + if exhausted = protocol.ExhaustedInfo(evidence); exhausted != nil { + edges = map[string]string{} + if targets, ok := exhausted["targets"].(map[string]any); ok { + for option, target := range targets { + if text, ok := target.(string); ok { + edges[option] = text + } + } + } + found = true + } + } + } else if err != sql.ErrNoRows { + return protocol.RunStep{}, false, err + } for _, declared := range graph.Stages { + if exhausted != nil { + break + } if declared.Key == stageKey { if stage.EffectiveType(declared.Type) != stage.HumanType { return protocol.RunStep{}, false, fmt.Errorf("stage %s is not a human decision stage", stageKey) @@ -327,6 +353,11 @@ JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version // successful decision is not presented as a stop or error; the derived // verdict reads the feedback as the step's reason. output := map[string]any{protocol.DecisionOptionKey: option, protocol.DecisionFeedbackKey: feedback} + if exhausted != nil { + // Keep the marker: a decided exhaustion step is a decision, never a + // visit, when the run's state is rebuilt from its steps. + output[protocol.ExhaustedKey] = exhausted + } encoded, err := json.Marshal(output) if err != nil { return protocol.RunStep{}, false, err diff --git a/internal/pipeline/skills.go b/internal/pipeline/skills.go index f1b44f5c..997ac889 100644 --- a/internal/pipeline/skills.go +++ b/internal/pipeline/skills.go @@ -23,6 +23,9 @@ CREATE TABLE IF NOT EXISTS skill_files (name TEXT NOT NULL, version INTEGER NOT if err != nil { return err } + if err := s.initRunLoopState(); err != nil { + return err + } return s.initStageSkills() } diff --git a/internal/protocol/artifact_group.go b/internal/protocol/artifact_group.go index c0556ee2..94c17872 100644 --- a/internal/protocol/artifact_group.go +++ b/internal/protocol/artifact_group.go @@ -13,7 +13,7 @@ const ( // TurnArtifactNames are the files the server itself writes into a model visit's // turn directory. They are always debugging files. -var TurnArtifactNames = []string{"input.md", "memory.md", "history.md", "output.md", "session.html"} +var TurnArtifactNames = []string{"input.md", "memory.md", "history.md", "findings.md", "output.md", "session.html"} // IsDebug reports whether the artifact is a runner-internal debugging file. func (a StageArtifact) IsDebug() bool { return a.Group == ArtifactGroupDebug } diff --git a/internal/protocol/findings.go b/internal/protocol/findings.go new file mode 100644 index 00000000..970a459b --- /dev/null +++ b/internal/protocol/findings.go @@ -0,0 +1,64 @@ +package protocol + +// Finding is one item of a run's findings ledger. The runner owns the ledger: +// stages report new findings and status changes in an output.md "# findings" +// section, and the runner assigns the stable ID (F1, F2, ...), keeps the latest +// status and records every change as an event. +type Finding struct { + ID string `json:"id"` + Severity string `json:"severity"` + Origin string `json:"origin"` + Location string `json:"location,omitempty"` + Summary string `json:"summary"` + Status string `json:"status"` + // Reason is the latest status change's reason. + Reason string `json:"reason,omitempty"` + RaisedBy string `json:"raised_by"` + RaisedSequence int `json:"raised_sequence"` + UpdatedBy string `json:"updated_by,omitempty"` + UpdatedSequence int `json:"updated_sequence,omitempty"` + Events []FindingEvent `json:"events,omitempty"` +} + +// FindingEvent is one status change of a finding, in the visit that made it. +type FindingEvent struct { + Sequence int `json:"sequence"` + Stage string `json:"stage"` + Status string `json:"status"` + Reason string `json:"reason,omitempty"` +} + +// Finding severities (most severe first), statuses and origins. +const ( + SeverityCritical = "critical" + SeverityImportant = "important" + SeverityMinor = "minor" + SeverityNit = "nit" + + FindingOpen = "open" + FindingFixed = "fixed" + FindingDismissed = "dismissed" + FindingSettled = "settled" + + OriginIntroduced = "introduced" + OriginPreExisting = "pre-existing" +) + +// ExhaustedKey marks a waiting (then decided) step the runner created when a +// loop exhausted its visits on a stage with on_exhausted=decide. The value is a +// map with stage, visit, max_visits and targets (option -> target). Such a step +// is a decision, never a stage visit. +const ExhaustedKey = "exhausted" + +// Exhaustion decision options. +const ( + ExhaustedAccept = "accept" + ExhaustedContinue = "continue" + ExhaustedAbort = "abort" +) + +// ExhaustedInfo reads the exhaustion marker from a step output, or nil. +func ExhaustedInfo(output map[string]any) map[string]any { + info, _ := output[ExhaustedKey].(map[string]any) + return info +} diff --git a/internal/protocol/message.go b/internal/protocol/message.go index 9f9196b4..25c105bf 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -50,6 +50,12 @@ type Stage struct { type StageLimits struct { MaxVisits int `json:"max_visits"` On []string `json:"on,omitempty"` + // OnExhausted is "fail" (the default) or "decide": the runner parks the run + // on an operator decision (accept / continue / abort) instead of failing + // when this stage's loop exhausts its visits. + OnExhausted string `json:"on_exhausted,omitempty"` + // AcceptTo is the target of the "accept" decision (default #success). + AcceptTo string `json:"accept_to,omitempty"` } type NotificationPolicy struct { @@ -216,6 +222,11 @@ type Message struct { BudgetUSD float64 `json:"budget_usd,omitempty"` // RunSettings is the get/set_run_settings body and reply. RunSettings *RunSettings `json:"run_settings,omitempty"` + // RetryExtraVisits (1-5) grants extra visits to a resumed loop: to + // RetryExtraStage when set, otherwise to the stage(s) that exhausted their + // visits. The resume continues the exhausted loop instead of failing again. + RetryExtraVisits int `json:"retry_extra_visits,omitempty"` + RetryExtraStage string `json:"retry_extra_stage,omitempty"` // Search is the broad, read-only search traffic over pipelines, versions, // runs, steps, field text and artifacts. See search.go for the per-type // payloads and the ranking/kind/bound vocabulary. diff --git a/internal/protocol/runs.go b/internal/protocol/runs.go index 80997a3d..f83253bd 100644 --- a/internal/protocol/runs.go +++ b/internal/protocol/runs.go @@ -546,6 +546,11 @@ type RunDetail struct { // run's stages, stage services and checks ran with: files and variable // names only, never values. Absent for runs that predate it. Environment *RunEnvironment `json:"environment,omitempty"` + // Findings is the run's runner-owned findings ledger, in ID order. + Findings []Finding `json:"findings,omitempty"` + // VisitGrants are extra visits per stage granted by a retry with + // --extra-visits or a "continue" exhaustion decision. + VisitGrants map[string]int `json:"visit_grants,omitempty"` } // RunEnvironment is the directory environment a run resolved for its diff --git a/internal/server/artifacts.go b/internal/server/artifacts.go index 2f31970a..1e849a1f 100644 --- a/internal/server/artifacts.go +++ b/internal/server/artifacts.go @@ -88,7 +88,7 @@ func (r *runner) scanArtifacts(runID int64, sequence int, directory string, publ } // Mandatory runtime evidence must not disappear behind hundreds of private // captures/public deliverables in the bounded inventory. - for _, name := range []string{"input.md", "memory.md", "history.md", "output.md", "session.html"} { + for _, name := range []string{"input.md", "memory.md", "history.md", "findings.md", "output.md", "session.html"} { full := path.Join(rel, name) if info, err := root.Lstat(full); err == nil && info.Mode().IsRegular() && info.Mode()&fs.ModeSymlink == 0 && info.Size() <= maxArtifactFileBytes { add(full, name, info) diff --git a/internal/server/loop_control_test.go b/internal/server/loop_control_test.go new file mode 100644 index 00000000..309a02ae --- /dev/null +++ b/internal/server/loop_control_test.go @@ -0,0 +1,238 @@ +package server + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" +) + +// loopSource is implement -> review, with review's rejected looping back. +// extraReview is spliced into the review stage (limits etc.). +func loopSource(extraReview string) string { + source := pipeline.Template([]string{"implement", "review"}, true) + source = strings.Replace(source, "# stage review", "# stage review\n\n"+extraReview, 1) + return strings.Replace(source, "success -> #success", "success -> #success\nrejected -> implement", 1) +} + +func loopRunner(t *testing.T, source string) (*runner, *pipeline.Store, int64) { + t.Helper() + ctx := context.Background() + store, err := pipeline.Open(filepath.Join(t.TempDir(), "run.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { store.Close() }) + if _, err := store.Submit(ctx, "loop", source); err != nil { + t.Fatal(err) + } + items, _ := store.List(ctx) + r, err := newRunnerAt(ctx, store, t.TempDir()) + if err != nil { + t.Fatal(err) + } + return r, store, items[0].ID +} + +func markdown(text string) stage.Result { + outcome := strings.TrimSpace(strings.SplitN(strings.TrimPrefix(text, "# outcome\n"), "\n", 2)[0]) + return stage.Result{Outcome: outcome, Output: stage.Values{"markdown": text}} +} + +// TestFindingsLedgerAndGateRouteTheLoop runs implement -> review -> triage +// (a findings gate) and checks the ledger: stable IDs, status changes from a +// later visit, the ledger in memory.md and findings.md, a dismissed finding a +// reviewer re-raises staying dismissed, and the gate routing mechanically. +func TestFindingsLedgerAndGateRouteTheLoop(t *testing.T) { + source := pipeline.Template([]string{"implement", "review"}, true) + source = strings.Replace(source, "success -> #success", "success -> triage", 1) + source += "# stage triage\n\n```limits\n{\"max_visits\":3}\n```\n\n```configs\ntype=findings\nseverity=important\norigin=introduced\n```\n\n```edges\nopen -> implement\nclear -> #success\n```\n" + r, store, pipelineID := loopRunner(t, source) + calls := map[string]int{} + var implementMemory, implementLedgerFile string + r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + calls[def.Key]++ + switch { + case def.Key == "implement" && calls["implement"] == 2: + memory, _ := os.ReadFile(def.Turn.Memory) + implementMemory = string(memory) + ledger, _ := os.ReadFile(filepath.Join(def.Turn.Dir, "findings.md")) + implementLedgerFile = string(ledger) + return markdown("# outcome\nsuccess\n\n# handoff\nFixed F1.\n\n# findings\n- F1 fixed: added the eviction\n- F2 dismissed: style only\n"), nil + case def.Key == "implement": + return markdown("# outcome\nsuccess\n\n# handoff\nDone.\n"), nil + case calls["review"] == 1: + return markdown("# outcome\nsuccess\n\n# handoff\nTwo findings.\n\n# findings\n- important introduced cache.go:42: eviction never runs\n- important pre-existing util.go:7: odd helper\n- nit introduced cache.go:1: naming\n"), nil + default: + // Re-raises the dismissed F2: it must stay dismissed. + return markdown("# outcome\nsuccess\n\n# handoff\nLooks good.\n\n# findings\n- important pre-existing util.go:7: odd helper\n"), nil + } + } + run := startRun(t, r, pipelineID, "findings") + detail, err := store.GetRun(context.Background(), run.ID) + if err != nil { + t.Fatal(err) + } + if detail.Status != "succeeded" || calls["implement"] != 2 || calls["review"] != 2 { + t.Fatalf("status %s calls %v diag %q", detail.Status, calls, detail.Diagnostic) + } + var routes []string + for _, step := range detail.Steps { + if step.Stage == "triage" { + routes = append(routes, step.Outcome+"->"+step.Target) + } + } + if strings.Join(routes, ",") != "open->implement,clear->#success" { + t.Fatalf("gate routes %v", routes) + } + status := map[string]string{} + for _, item := range detail.Findings { + status[item.ID] = item.Status + } + if len(detail.Findings) != 3 || status["F1"] != "fixed" || status["F2"] != "dismissed" || status["F3"] != "open" { + t.Fatalf("ledger %+v", detail.Findings) + } + if !strings.Contains(implementMemory, "## Findings ledger (runner-owned)") || !strings.Contains(implementMemory, "F1 · important · introduced · cache.go:42 — eviction never runs") || !strings.Contains(implementMemory, "never re-raise") { + t.Fatalf("implement memory lacks the ledger:\n%s", implementMemory) + } + if !strings.Contains(implementLedgerFile, "# Findings ledger") || !strings.Contains(implementLedgerFile, "F2 · important · pre-existing") { + t.Fatalf("findings.md:\n%s", implementLedgerFile) + } +} + +// TestExhaustedLoopAsksTheOperator covers on_exhausted=decide: the last allowed +// review asks for another round, the run waits on a decision, "continue" grants +// one more visit and "accept" finishes the run. +func TestExhaustedLoopAsksTheOperator(t *testing.T) { + r, store, pipelineID := loopRunner(t, loopSource("```limits\n{\"max_visits\":2,\"on\":[\"rejected\"],\"on_exhausted\":\"decide\"}\n```")) + calls := map[string]int{} + r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + calls[def.Key]++ + if def.Key == "review" { + return markdown("# outcome\nrejected\n\n# handoff\nStill wrong.\n"), nil + } + return markdown("# outcome\nsuccess\n\n# handoff\nDone.\n"), nil + } + run := startRun(t, r, pipelineID, "exhausted") + ctx := context.Background() + detail, _ := store.GetRun(ctx, run.ID) + last := detail.Steps[len(detail.Steps)-1] + if detail.Status != protocol.RunStatusWaiting || last.Status != protocol.StepStatusWaiting || last.Stage != "review" || protocol.ExhaustedInfo(last.Output) == nil { + t.Fatalf("not waiting on an exhaustion decision: %s %+v", detail.Status, last) + } + if got := strings.Join(protocol.WaitingOptions(last.Output), ","); got != "abort,accept,continue" { + t.Fatalf("options %s", got) + } + if _, err := r.decide(protocol.Message{RunID: run.ID, Option: "continue"}); err != nil { + t.Fatal(err) + } + r.wg.Wait() + detail, _ = store.GetRun(ctx, run.ID) + if detail.Status != protocol.RunStatusWaiting || calls["review"] != 3 || calls["implement"] != 3 { + t.Fatalf("one more round did not run: %s calls %v", detail.Status, calls) + } + if detail.VisitGrants["review"] != 1 || detail.VisitGrants["implement"] != 1 { + t.Fatalf("grants %v", detail.VisitGrants) + } + if _, err := r.decide(protocol.Message{RunID: run.ID, Option: "accept"}); err != nil { + t.Fatal(err) + } + r.wg.Wait() + detail, _ = store.GetRun(ctx, run.ID) + if detail.Status != "succeeded" { + t.Fatalf("accept did not finish the run: %s %q", detail.Status, detail.Diagnostic) + } +} + +// TestRetryWithExtraVisitsContinuesTheLoop retries a run whose review loop was +// exhausted: without extra visits the retry fails again at once; with +// --extra-visits it continues at the implementer and the next review approves. +func TestRetryWithExtraVisitsContinuesTheLoop(t *testing.T) { + r, store, pipelineID := loopRunner(t, loopSource("```limits\n{\"max_visits\":2,\"on\":[\"rejected\"]}\n```")) + calls := map[string]int{} + approve := false + r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + calls[def.Key]++ + if def.Key == "review" { + if approve { + return markdown("# outcome\nsuccess\n\n# handoff\nApproved.\n"), nil + } + return markdown("# outcome\nrejected\n\n# handoff\nStill wrong.\n\n# findings\n- important introduced a.go:1: still wrong\n"), nil + } + return markdown("# outcome\nsuccess\n\n# handoff\nDone.\n"), nil + } + run := startRun(t, r, pipelineID, "extra") + ctx := context.Background() + detail, _ := store.GetRun(ctx, run.ID) + if detail.Status != "failed" || calls["review"] != 2 { + t.Fatalf("source run: %s %v", detail.Status, calls) + } + if _, err := r.retry(protocol.Message{RunID: run.ID, RequestKey: "x", RetryExtraVisits: 9}); err == nil { + t.Fatal("extra visits over the bound accepted") + } + if _, err := r.retry(protocol.Message{RunID: run.ID, RequestKey: "y", RetryExtraVisits: 1, RetryExtraStage: "nope"}); err == nil { + t.Fatal("unknown extra-visits stage accepted") + } + approve = true + retried, err := r.retry(protocol.Message{RunID: run.ID, RequestKey: "retry-extra", RetryExtraVisits: 1}) + if err != nil { + t.Fatal(err) + } + r.wg.Wait() + detail, _ = store.GetRun(ctx, retried.ID) + if detail.Status != "succeeded" || calls["implement"] != 3 || calls["review"] != 3 { + t.Fatalf("retry: %s %q calls %v", detail.Status, detail.Diagnostic, calls) + } + if detail.Steps[0].Stage != "implement" || detail.VisitGrants["review"] != 1 { + t.Fatalf("retry did not continue at the implementer with a review grant: %+v %v", detail.Steps[0], detail.VisitGrants) + } + if len(detail.Findings) != 1 || detail.Findings[0].ID != "F1" { + t.Fatalf("retry did not inherit the ledger: %+v", detail.Findings) + } +} + +// TestRetryCarriesThePartialWorkOfTheFailedVisit checks that the retried +// visit receives the failed visit's private/ files and output.md under +// previous-attempt/ and that its input.md names them. +func TestRetryCarriesThePartialWorkOfTheFailedVisit(t *testing.T) { + r, store, pipelineID := loopRunner(t, pipeline.Template([]string{"implement"}, true)) + fail := true + var retriedInput, carried string + r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + if fail { + _ = os.WriteFile(filepath.Join(def.Turn.Private, "notes.md"), []byte("half done: parser rewritten"), 0o600) + _ = os.WriteFile(def.Turn.Output, []byte("# outcome\nsuccess\n\npartial"), 0o600) + return stage.Result{}, errors.New("timed out") + } + input, _ := os.ReadFile(def.Turn.Input) + retriedInput = string(input) + notes, _ := os.ReadFile(filepath.Join(def.Turn.Dir, "previous-attempt", "private", "notes.md")) + carried = string(notes) + return markdown("# outcome\nsuccess\n\n# handoff\nFinished.\n"), nil + } + run := startRun(t, r, pipelineID, "carry") + fail = false + retried, err := r.retry(protocol.Message{RunID: run.ID, RequestKey: "carry-retry"}) + if err != nil { + t.Fatal(err) + } + r.wg.Wait() + detail, _ := store.GetRun(context.Background(), retried.ID) + if detail.Status != "succeeded" { + t.Fatalf("retry %s %q", detail.Status, detail.Diagnostic) + } + if carried != "half done: parser rewritten" { + t.Fatalf("private notes not carried: %q", carried) + } + for _, want := range []string{"# Previous attempt", "## Partial work from the failed attempt", "- output.md (", "- private/notes.md ("} { + if !strings.Contains(retriedInput, want) { + t.Fatalf("input.md missing %q:\n%s", want, retriedInput) + } + } +} diff --git a/internal/server/loop_state.go b/internal/server/loop_state.go new file mode 100644 index 00000000..6a881f56 --- /dev/null +++ b/internal/server/loop_state.go @@ -0,0 +1,278 @@ +package server + +import ( + "context" + "fmt" + "log" + "os" + "path/filepath" + "strings" + "time" + + "git.a-wan.net/alan/pipelines/internal/findings" + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" + "git.a-wan.net/alan/pipelines/internal/turn" +) + +// Loop control: per-stage visit caps (raised by grants), the findings ledger, +// mechanical findings gates and operator decisions on exhausted loops. + +const ( + // maxStageVisits is the global per-stage visit cap before grants. + maxStageVisits = 5 + // maxRunSteps is the global step cap before grants. + maxRunSteps = 30 + // maxExtraVisits bounds one grant (a retry's --extra-visits). + maxExtraVisits = 5 + // maxRunStepsWithGrants is the absolute step cap however much is granted. + maxRunStepsWithGrants = 120 +) + +func graphHasStage(g protocol.Graph, key string) bool { + for _, s := range g.Stages { + if s.Key == key { + return true + } + } + return false +} + +// visitCaps returns a stage's effective max_visits and hard per-stage cap, +// both raised by the extra visits granted to it. +func (s *runState) visitCaps(selected protocol.Stage) (limit, hard int) { + limit = maxStageVisits + if selected.Limits != nil { + limit = selected.Limits.MaxVisits + } + extra := s.grants[selected.Key] + return limit + extra, maxStageVisits + extra +} + +// stepLimit is the run's total step cap: 30 plus, for every granted visit, +// room for one more pass through the graph, bounded. +func (s *runState) stepLimit(graph protocol.Graph) int { + total := maxRunSteps + for _, extra := range s.grants { + total += extra * max(len(graph.Stages), 1) + } + return min(total, maxRunStepsWithGrants) +} + +// grant adds extra visits to each named stage. +func (s *runState) grant(stages []string, extra int) { + if s.grants == nil { + s.grants = map[string]int{} + } + for _, key := range stages { + s.grants[key] += extra + } +} + +// exhaustedContinuation turns the last step of a run that a visit cap stopped +// into the checkpoint that continues its loop: the stage the routing was +// heading to, with the stopped step's output as its input. ok is false when +// the run did not stop on a cap. +func exhaustedContinuation(last protocol.RunStep) (protocol.RunStep, bool) { + if last.Status != "completed" { + return last, false + } + target := last.Target + if last.Control != nil && last.Control.LimitReached && last.Control.ModelTarget != "" { + target = last.Control.ModelTarget + } + if target == "" || protocol.IsTerminal(target) { + return last, false + } + input := last.Output + if input == nil { + input = map[string]any{} + } + return protocol.RunStep{Sequence: last.Sequence + 1, Stage: target, Status: "failed", Target: protocol.FailureEnd, Input: input}, true +} + +// exhaustedStages are the non-human stages whose next visit their caps refuse, +// plus next (the stage the run continues with) when nothing else is. +func exhaustedStages(graph protocol.Graph, state *runState, next string) []string { + var out []string + for _, declared := range graph.Stages { + if stage.EffectiveType(declared.Type) == stage.HumanType { + continue + } + limit, hard := state.visitCaps(declared) + if visits := state.visits[declared.Key]; visits > 0 && (visits >= limit || visits >= hard) { + out = append(out, declared.Key) + } + } + if len(out) == 0 && next != "" { + out = append(out, next) + } + return out +} + +// applyLimitOn applies a stage's limits.on on its last allowed visit: a listed +// outcome is kept but routed to #failure, or, with on_exhausted=decide, keeps +// its route and the caller parks the run on an operator decision (park true). +func applyLimitOn(step *protocol.RunStep, selected protocol.Stage, visit, maxVisits int) (park bool) { + if selected.Limits == nil || visit < maxVisits || step.Target == "" || protocol.IsTerminal(step.Target) { + return false + } + for _, outcome := range selected.Limits.On { + if outcome != step.Outcome { + continue + } + step.Control.LimitReached = true + step.Control.ModelTarget = step.Target + if decidesOnExhaustion(selected) { + return true + } + step.Target = protocol.FailureEnd + step.Diagnostic = fmt.Sprintf("Pipelines stopped %s after %d visits on outcome %s", selected.Key, maxVisits, step.Outcome) + return false + } + return false +} + +// isExhaustionStep reports whether a recorded step is a runner-created +// exhaustion decision rather than a stage visit. +func isExhaustionStep(step protocol.RunStep) bool { + return protocol.ExhaustedInfo(step.Output) != nil +} + +func decidesOnExhaustion(s protocol.Stage) bool { + return s.Limits != nil && s.Limits.OnExhausted == "decide" +} + +// parkExhausted parks the run on an operator decision because stage selected +// exhausted its visits: accept the work as it is (accept_to, default +// #success), continue for one more round (continueTo, with one more visit +// granted) or abort. It mirrors a human stage's wait: one waiting step and no +// live goroutine; the decision resumes the run through decide. +func (r *runner) parkExhausted(ctx context.Context, id int64, name, workspace string, state *runState, sequence int, selected protocol.Stage, visit, maxVisits int, continueTo string) error { + accept := protocol.SuccessEnd + if selected.Limits != nil && selected.Limits.AcceptTo != "" { + accept = selected.Limits.AcceptTo + } + targets := map[string]any{protocol.ExhaustedAccept: accept, protocol.ExhaustedContinue: continueTo, protocol.ExhaustedAbort: protocol.FailureEnd} + prompt := fmt.Sprintf("Stage %s used its %d allowed visits and the loop is not finished. Choose accept to take the work as it is (continues to %s), continue for one more round (one more visit; continues to %s), or abort to fail the run.", selected.Key, maxVisits, accept, continueTo) + options := []string{protocol.ExhaustedAbort, protocol.ExhaustedAccept, protocol.ExhaustedContinue} + evidence := protocol.NewWaitingEvidence(prompt, options) + evidence[protocol.ExhaustedKey] = map[string]any{"stage": selected.Key, "visit": visit, "max_visits": maxVisits, "targets": targets} + if err := r.store.BeginStep(ctx, id, sequence, selected.Key, state.input); err != nil { + return err + } + state.nextSequence = sequence + 1 + r.mu.Lock() + if err := r.store.MarkWaiting(ctx, id, sequence, selected.Key, evidence); err != nil { + r.mu.Unlock() + return err + } + r.emitRun(protocol.RunEventFrame{ + RunID: id, + Workspace: workspace, + Status: protocol.RunStatusWaiting, + CurrentStage: selected.Key, + CompletedSteps: state.completed, + Step: &protocol.RunStepDelta{Sequence: sequence, Stage: selected.Key, Status: protocol.StepStatusWaiting}, + }, false) + delete(r.active, id) + r.mu.Unlock() + r.deliverRunNotificationBatch(time.Now(), 1) + return nil +} + +// grantForDecision records the extra visit a "continue" exhaustion decision +// allows: one more visit for the exhausted stage and for the stage the loop +// continues with. +func (r *runner) grantForDecision(ctx context.Context, detail *protocol.RunDetail, step protocol.RunStep) { + info := protocol.ExhaustedInfo(step.Output) + if info == nil || step.Outcome != protocol.ExhaustedContinue { + return + } + stages := []string{} + if key, ok := info["stage"].(string); ok && key != "" { + stages = append(stages, key) + } + if step.Target != "" && !protocol.IsTerminal(step.Target) && (len(stages) == 0 || stages[0] != step.Target) { + stages = append(stages, step.Target) + } + for _, key := range stages { + grants, err := r.store.AddRunVisitGrant(ctx, detail.ID, key, 1) + if err != nil { + log.Printf("run %d: grant a visit to %s: %v", detail.ID, key, err) + continue + } + detail.VisitGrants = grants + } +} + +// recordFindings folds a completed visit's "# findings" section into the run's +// ledger and persists it. A ledger write failure is logged, never fatal: the +// stage's own output keeps the findings. +func (r *runner) recordFindings(id int64, state *runState, step protocol.RunStep) { + markdown, _ := step.Output["markdown"].(string) + report := findings.Parse(markdown) + if len(report.New) == 0 && len(report.Changes) == 0 { + return + } + ledger, outcome := findings.Apply(state.findings, report, step.Stage, step.Sequence) + state.findings = ledger + if len(outcome.Ignored) > 0 { + log.Printf("run %d stage %s #%d: findings ignored: %s", id, step.Stage, step.Sequence, strings.Join(outcome.Ignored, "; ")) + } + r.persistFindings(id, ledger) +} + +func (r *runner) persistFindings(id int64, ledger []protocol.Finding) { + save, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := r.store.SetRunFindings(save, id, ledger); err != nil { + log.Printf("run %d: save findings ledger: %v", id, err) + } +} + +func (r *runner) persistGrants(id int64, grants map[string]int) { + save, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := r.store.SetRunVisitGrants(save, id, grants); err != nil { + log.Printf("run %d: save visit grants: %v", id, err) + } +} + +// findingsGateStep evaluates a findings stage against the ledger. +func findingsGateStep(def stage.Definition, state *runState, sequence int) protocol.RunStep { + gate, _ := stage.FindingsGate(def) + matched := gate.Matching(state.findings) + outcome := stage.FindingsClear + reason := fmt.Sprintf("No open findings at %s or above (origin %s).", gate.MinSeverity, gate.Origin) + ids := make([]string, 0, len(matched)) + for _, item := range matched { + ids = append(ids, item.ID) + } + if len(matched) > 0 { + outcome = stage.FindingsOpen + reason = fmt.Sprintf("%d open finding(s) at %s or above (origin %s): %s.", len(matched), gate.MinSeverity, gate.Origin, strings.Join(ids, ", ")) + } + return protocol.RunStep{ + Sequence: sequence, + Stage: def.Key, + Status: "completed", + Outcome: outcome, + Output: stage.Values{"summary": reason, "findings": ids}, + Target: def.Edges[outcome], + Verdict: &protocol.StageVerdict{Reason: reason, ReasonSource: protocol.VerdictReasonFallback}, + } +} + +// writeFindingsFile writes the visit's findings.md (the whole ledger) next to +// memory.md when the run has a ledger. +func writeFindingsFile(paths turn.Paths, ledger []protocol.Finding) error { + if len(ledger) == 0 { + return nil + } + name := filepath.Join(paths.TurnDir, "findings.md") + if err := os.WriteFile(name, []byte(findings.RenderFile(ledger)), 0o600); err != nil { + return fmt.Errorf("write %s: %w", name, err) + } + return nil +} diff --git a/internal/server/retry_carry.go b/internal/server/retry_carry.go new file mode 100644 index 00000000..79561faf --- /dev/null +++ b/internal/server/retry_carry.go @@ -0,0 +1,107 @@ +package server + +import ( + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "sort" + "strings" + "syscall" +) + +// Bounds on the partial work a retried visit inherits from the failed one. +const ( + carryMaxFiles = 200 + carryMaxFileBytes = 1 << 20 + carryMaxTotal = 8 << 20 + carryDir = "previous-attempt" +) + +// carryPartialWork copies a failed visit's output.md and private/ files +// (bounded) into the retried visit's turn directory under previous-attempt/ +// and returns the markdown that tells the stage about them, or "" when there +// was nothing to carry. Symlinks and special files are skipped; the source is +// read through os.Root so nothing outside the failed turn is reachable. +func carryPartialWork(sourceTurn, targetTurn string) string { + source, err := os.OpenRoot(sourceTurn) + if err != nil { + return "" + } + defer source.Close() + var names []string + if info, err := source.Lstat("output.md"); err == nil && info.Mode().IsRegular() { + names = append(names, "output.md") + } + skipped := 0 + _ = fs.WalkDir(source.FS(), "private", func(name string, entry fs.DirEntry, walkErr error) error { + if walkErr != nil { + return nil + } + if entry.Type().IsRegular() { + names = append(names, name) + } + return nil + }) + sort.Strings(names[min(1, len(names)):]) + target := filepath.Join(targetTurn, carryDir) + var copied []string + total := int64(0) + for _, name := range names { + if len(copied) >= carryMaxFiles { + skipped++ + continue + } + info, err := source.Lstat(name) + if err != nil || !info.Mode().IsRegular() || info.Size() > carryMaxFileBytes || total+info.Size() > carryMaxTotal { + skipped++ + continue + } + if err := copyCarried(source, name, filepath.Join(target, filepath.FromSlash(name))); err != nil { + skipped++ + continue + } + total += info.Size() + copied = append(copied, fmt.Sprintf("%s (%d bytes)", name, info.Size())) + } + if len(copied) == 0 { + return "" + } + var b strings.Builder + b.WriteString("\n## Partial work from the failed attempt\n\n") + fmt.Fprintf(&b, "The failed visit's output.md and private/ files are copied, read-only, into %s:\n\n", target) + for _, line := range copied { + b.WriteString("- " + line + "\n") + } + if skipped > 0 { + fmt.Fprintf(&b, "- … %d more not copied (over the size or count bound)\n", skipped) + } + b.WriteString("\nReuse what is still valid instead of redoing it.\n") + return b.String() +} + +func copyCarried(source *os.Root, name, destination string) error { + if path.Clean(name) != name || strings.HasPrefix(name, "../") { + return errors.New("invalid name") + } + src, err := source.OpenFile(name, os.O_RDONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + return err + } + defer src.Close() + if err := os.MkdirAll(filepath.Dir(destination), 0o700); err != nil { + return err + } + dst, err := os.OpenFile(destination, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) + if err != nil { + return err + } + _, copyErr := io.Copy(dst, io.LimitReader(src, carryMaxFileBytes)) + if closeErr := dst.Close(); copyErr == nil { + copyErr = closeErr + } + return copyErr +} diff --git a/internal/server/runner.go b/internal/server/runner.go index da4ee0a4..a52e7569 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -16,6 +16,7 @@ import ( "git.a-wan.net/alan/pipelines/internal/claude" "git.a-wan.net/alan/pipelines/internal/filediff" + "git.a-wan.net/alan/pipelines/internal/findings" "git.a-wan.net/alan/pipelines/internal/harness" "git.a-wan.net/alan/pipelines/internal/opencode" "git.a-wan.net/alan/pipelines/internal/pipeline" @@ -448,7 +449,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc } } if request.RetrySource > 0 && request.RetryMode != "restart" { - checkpoint, checkpointErr := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput) + checkpoint, checkpointErr := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput, request.RetryExtraVisits) if checkpointErr != nil { return nil, checkpointErr } @@ -863,10 +864,10 @@ func retryStageContractEqual(left, right protocol.Stage) bool { } func (r *runner) retrySourceCheckpoint(sourceID int64, pinned *protocol.PipelineDetail) (retryCheckpoint, error) { - return r.retrySourceCheckpointSelected(sourceID, pinned, "", 0, nil) + return r.retrySourceCheckpointSelected(sourceID, pinned, "", 0, nil, 0) } -func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.PipelineDetail, selectedStage string, selectedVisit int, override map[string]any) (retryCheckpoint, error) { +func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.PipelineDetail, selectedStage string, selectedVisit int, override map[string]any, extraVisits int) (retryCheckpoint, error) { source, err := r.store.GetRun(r.ctx, sourceID) if err != nil { return retryCheckpoint{}, err @@ -882,6 +883,13 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol. return retryCheckpoint{}, fmt.Errorf("retry source %d has no failed stage checkpoint", sourceID) } failed := source.Steps[len(source.Steps)-1] + if extraVisits > 0 && selectedStage == "" && !interrupted { + // More visits for an exhausted loop: continue the loop where the cap + // stopped it instead of re-running the visit that hit it. + if next, ok := exhaustedContinuation(failed); ok { + failed = next + } + } if interrupted && selectedStage == "" { // A server stop interrupts a run mid-visit (the visit is recorded as // interrupted, with the input it began with) or between visits (the @@ -951,6 +959,9 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol. // stage's memory bindings must be resolved from the original prefix before // this override is applied at invocation time. handoff = map[string]any{"input": failed.Input, "override": override, "sequence": failed.Sequence, "stage": failed.Stage, "visit": failed.Sequence} + if extraVisits > 0 { + handoff["extra_visits"] = extraVisits + } prefix, prefixRecords, prefixErr := r.retryPrefix(sourceID, source, failed.Sequence) if prefixErr != nil { return retryCheckpoint{}, prefixErr @@ -1076,6 +1087,20 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) { if mode != "resume" && mode != "restart" { return nil, fmt.Errorf("retry mode must be resume or restart") } + if request.RetryExtraVisits < 0 || request.RetryExtraVisits > maxExtraVisits { + return nil, fmt.Errorf("extra visits must be from 1 to %d", maxExtraVisits) + } + if request.RetryExtraVisits > 0 && (mode != "resume" || request.RetryStage != "" || request.RetryVisit > 0) { + return nil, fmt.Errorf("extra visits continue the exhausted loop; they cannot be combined with --mode=restart or a selected stage visit") + } + if request.RetryExtraStage != "" { + if request.RetryExtraVisits == 0 { + return nil, fmt.Errorf("an extra-visits stage needs extra visits") + } + if !graphHasStage(original.Graph, request.RetryExtraStage) { + return nil, fmt.Errorf("stage %q is not part of run %d", request.RetryExtraStage, original.ID) + } + } version := original.Version if request.RetryVersion > 0 { version = request.RetryVersion @@ -1085,7 +1110,7 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) { return nil, err } if mode == "resume" { - if _, err := r.retrySourceCheckpointSelected(original.ID, d, request.RetryStage, request.RetryVisit, request.RetryInput); err != nil { + if _, err := r.retrySourceCheckpointSelected(original.ID, d, request.RetryStage, request.RetryVisit, request.RetryInput, request.RetryExtraVisits); err != nil { return nil, err } } @@ -1098,7 +1123,7 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) { if budgetUSD == 0 && original.Budget != nil && original.Budget.Source == "run" { budgetUSD = original.Budget.LimitUSD } - return r.start(protocol.Message{PipelineID: original.PipelineID, Version: version, RequestKey: request.RequestKey, RetryMode: mode, RetrySource: original.ID, RetryStage: request.RetryStage, RetryVisit: request.RetryVisit, RetryInput: request.RetryInput, Workspace: original.Workspace, Input: original.Input, AllowTools: original.AllowTools, WritePaths: original.WritePaths, Model: original.Model, StageModels: original.StageModels, NotifyMode: notifyMode, OutputFormat: original.OutputFormat, QuotaPolicy: request.QuotaPolicy, BudgetUSD: budgetUSD}, original.ID) + return r.start(protocol.Message{PipelineID: original.PipelineID, Version: version, RequestKey: request.RequestKey, RetryMode: mode, RetrySource: original.ID, RetryStage: request.RetryStage, RetryVisit: request.RetryVisit, RetryInput: request.RetryInput, RetryExtraVisits: request.RetryExtraVisits, RetryExtraStage: request.RetryExtraStage, Workspace: original.Workspace, Input: original.Input, AllowTools: original.AllowTools, WritePaths: original.WritePaths, Model: original.Model, StageModels: original.StageModels, NotifyMode: notifyMode, OutputFormat: original.OutputFormat, QuotaPolicy: request.QuotaPolicy, BudgetUSD: budgetUSD}, original.ID) } func (r *runner) cancel(id int64) error { @@ -1179,6 +1204,8 @@ func (r *runner) decide(request protocol.Message) (*protocol.RunDetail, error) { return nil, err } if applied { + // "continue" on an exhausted loop grants the visit it needs. + r.grantForDecision(r.ctx, detail, step) // Re-seed the identity so the resumed frames (this one and the resumed // loop's) carry it even after a restart, when no creation was observed. r.rememberRunIdentity(detail.ID, identityOfRunSummary(detail.RunSummary)) @@ -1220,7 +1247,7 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail, r.finishRunState(id, d.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil) return } - checkpoint, err := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput) + checkpoint, err := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput, request.RetryExtraVisits) if err != nil { r.finishRunState(id, d.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil) return @@ -1251,6 +1278,30 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail, r.finishRunState(id, d.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil) return } + // The ledger as it stood before the retried visit, the source's grants + // plus any new ones, and the failed visit's partial work. + state.findings = findings.Before(source.Findings, checkpoint.failed.Sequence) + if len(state.findings) > 0 { + r.persistFindings(id, state.findings) + } + for key, extra := range source.VisitGrants { + state.grant([]string{key}, extra) + } + if request.RetryExtraVisits > 0 { + stages := []string{request.RetryExtraStage} + if request.RetryExtraStage == "" { + stages = exhaustedStages(d.Graph, state, state.key) + } + state.grant(stages, request.RetryExtraVisits) + } + if len(state.grants) > 0 { + r.persistGrants(id, state.grants) + } + for _, step := range source.Steps { + if step.Sequence == checkpoint.failed.Sequence && step.Stage == checkpoint.failed.Stage && step.Status != "completed" { + state.carryFrom = r.turnPaths(source.ID, step.Sequence, step.Stage).TurnDir + } + } r.runLoop(ctx, id, d.Graph, d.Name, workspace, request, state) return } @@ -1412,6 +1463,15 @@ type runState struct { // failure, so the same one twice in a row stops the loop. errorLoops map[string]int lastHarness map[string]string + // findings is the run's findings ledger; grants are extra visits per stage + // (loop_state.go). sessions is each stage's latest harness session, which + // a resume_session stage continues on its next visit. + findings []protocol.Finding + grants map[string]int + sessions map[string]string + // carryFrom is the failed source visit's turn directory whose private/ + // and output.md the retried visit receives; prepareTurn consumes it. + carryFrom string } func newRunState(key string, input stage.Values) *runState { @@ -1429,7 +1489,24 @@ func rebuildRunState(detail *protocol.RunDetail, decided protocol.RunStep) *runS } publicSeen := map[string]bool{} state.priorBudgets = map[string]stage.BudgetSnapshot{} + state.findings = append([]protocol.Finding(nil), detail.Findings...) + for key, extra := range detail.VisitGrants { + state.grant([]string{key}, extra) + } for _, step := range detail.Steps { + if isExhaustionStep(step) { + // A runner-created exhaustion decision is not a stage visit. + if step.Sequence >= state.nextSequence { + state.nextSequence = step.Sequence + 1 + } + continue + } + if step.SessionID != "" { + if state.sessions == nil { + state.sessions = map[string]string{} + } + state.sessions[step.Stage] = step.SessionID + } // The runtime stamps this cumulative snapshot on every executed model // visit. Reusing it preserves per-stage limits across export recovery. var audit struct { @@ -1487,6 +1564,9 @@ func rebuildRetryState(detail *protocol.RunDetail, failed protocol.RunStep, hand if step.Sequence >= failed.Sequence { break } + if isExhaustionStep(step) { + continue + } state.visits[step.Stage]++ added := publicArtifacts(step.Artifacts, publicSeen) if step.Status == "completed" { @@ -1561,7 +1641,7 @@ func (r *runner) retryPrefix(sourceID int64, source *protocol.RunDetail, failedS } publicBySequence := retryPublicBySequence(source, failedSequence) for _, step := range source.Steps { - if step.Sequence >= failedSequence || step.Status != "completed" { + if step.Sequence >= failedSequence || step.Status != "completed" || isExhaustionStep(step) { continue } prefix[step.Stage] = step.Output @@ -2057,7 +2137,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na effectiveModels = resolved } runBudget := r.runBudget(ctx, id) - for sequence := state.nextSequence; sequence <= 30; sequence++ { + for sequence := state.nextSequence; sequence <= state.stepLimit(graph); sequence++ { if ctx.Err() != nil { canceled() return @@ -2094,23 +2174,29 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na } } isHuman := stage.EffectiveType(def.Type) == stage.HumanType - maxVisits := 5 - if selected.Limits != nil { - maxVisits = selected.Limits.MaxVisits - } + // Both caps include the extra visits granted to the stage. + maxVisits, hardVisits := state.visitCaps(selected) // Validate the next visit without consuming it. An already-exhausted // stage must not begin work it can never execute. - if !isHuman { - if state.visits[key]+1 > 5 { - state.failureClass = protocol.FailureLoopExhausted + if !isHuman && (state.visits[key]+1 > hardVisits || state.visits[key]+1 > maxVisits) { + if decidesOnExhaustion(selected) { + // on_exhausted=decide: ask the operator instead of failing. + if err := r.parkExhausted(ctx, id, name, workspace, state, sequence, selected, state.visits[key], min(maxVisits, hardVisits), key); err != nil { + if ctx.Err() != nil { + canceled() + return + } + finish("failed", "error", err.Error()) + } + return + } + state.failureClass = protocol.FailureLoopExhausted + if state.visits[key]+1 > hardVisits { finish("failed", "error", "stage visit budget exceeded") return } - if state.visits[key]+1 > maxVisits { - state.failureClass = protocol.FailureLoopExhausted - finish("failed", "error", fmt.Sprintf("stage %s visit limit reached (%d)", key, maxVisits)) - return - } + finish("failed", "error", fmt.Sprintf("stage %s visit limit reached (%d)", key, maxVisits)) + return } // adopted is the visit a previous server process began and left running // across its restart: its step row, turn files and session already exist. @@ -2215,6 +2301,34 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na r.deliverRunNotificationBatch(time.Now(), 1) return } + if stage.EffectiveType(def.Type) == stage.FindingsType { + // A findings gate routes mechanically on the run's ledger: no + // model, no capture, no turn files. + step := findingsGateStep(def, state, sequence) + step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads} + park := applyLimitOn(&step, selected, state.visits[key], maxVisits) + status, outcome, diagnostic, terminal, finishErr := r.finishStage(id, name, workspace, selected, state, step) + if finishErr != nil { + finish("failed", "error", finishErr.Error()) + return + } + state.recordTurn(step, nil) + state.completed++ + r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CurrentStage: key, CompletedSteps: state.completed, + Step: &protocol.RunStepDelta{Sequence: step.Sequence, Stage: step.Stage, Status: step.Status, Outcome: step.Outcome, Target: step.Target, Diagnostic: step.Diagnostic}}, false) + if terminal { + finish(status, outcome, diagnostic) + return + } + if park { + if err := r.parkExhausted(ctx, id, name, workspace, state, state.nextSequence, selected, state.visits[key], maxVisits, step.Target); err != nil { + finish("failed", "error", err.Error()) + } + return + } + state.key = step.Target + continue + } // Server skip fallback: a stage that declares a `skipped` route is // short-circuited only when the run's evidence is complete and empty // (autoSkipEligible, ui_surface.go): every visit recorded a complete @@ -2390,6 +2504,9 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na if adopted != nil { // Follow the CLI the previous process left (see run_reattach.go). claudeClient.Reference = adopted.owner.Reference + } else if def.Configs["resume_session"] == "true" && state.visits[key] > 1 { + // A loop visit continues the stage's previous session. + claudeClient.ResumeSessionID = state.sessions[key] } claudeClient.OnOwnership = func(session, reference string, active bool) error { c, cancel := context.WithTimeout(context.Background(), 10*time.Second) @@ -2642,18 +2759,13 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na if step.Control.OutcomeRepairs > 0 { log.Printf("run %d stage %s #%d: outcome repair follow-up sent %d time(s)", id, key, sequence, step.Control.OutcomeRepairs) } - if err == nil && selected.Limits != nil && state.visits[key] >= maxVisits { - for _, outcome := range selected.Limits.On { - if outcome == step.Outcome { - step.Control.LimitReached = true - step.Control.ModelTarget = step.Target - step.Target = protocol.FailureEnd - step.Diagnostic = fmt.Sprintf("Pipelines stopped %s after %d visits on outcome %s", key, maxVisits, step.Outcome) - } - } + parkExhausted := false + if err == nil { + parkExhausted = applyLimitOn(&step, selected, state.visits[key], maxVisits) } if panicked { step.Target = protocol.FailureEnd + parkExhausted = false } switch { case step.Control.LimitReached: @@ -2734,6 +2846,9 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na if artifactsDir != "" { state.artifactDirs = append(state.artifactDirs, strconv.Itoa(sequence)) } + if stage.EffectiveType(def.Type) == stage.ModelType { + r.recordFindings(id, state, step) + } } else if quota.rerun { // The visit runs again on the switched account with its own // input, told that the limit interrupted it; it does not count. @@ -2768,10 +2883,24 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na canceled() return } + if stageSession != "" { + if state.sessions == nil { + state.sessions = map[string]string{} + } + state.sessions[key] = stageSession + } if terminal { finish(status, outcome, diagnostic) return } + if parkExhausted { + // on_exhausted=decide: the last allowed visit asked for another + // round; the operator decides instead of the run failing. + if err := r.parkExhausted(ctx, id, name, workspace, state, state.nextSequence, selected, state.visits[key], maxVisits, step.Target); err != nil { + finish("failed", "error", err.Error()) + } + return + } r.checkRunBudget(id, name, runBudget) if step.Status == "completed" { delete(state.errorLoops, key) diff --git a/internal/server/turns.go b/internal/server/turns.go index faa84092..f358a1ed 100644 --- a/internal/server/turns.go +++ b/internal/server/turns.go @@ -14,6 +14,7 @@ import ( "strings" "syscall" + "git.a-wan.net/alan/pipelines/internal/findings" "git.a-wan.net/alan/pipelines/internal/protocol" "git.a-wan.net/alan/pipelines/internal/stage" "git.a-wan.net/alan/pipelines/internal/turn" @@ -71,6 +72,15 @@ func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage input += "\n" + state.previousAttempt state.previousAttempt = "" } + if state.carryFrom != "" { + // The failed visit's partial work, copied into this visit's turn. + input += carryPartialWork(state.carryFrom, paths.TurnDir) + state.carryFrom = "" + } + if err := writeFindingsFile(paths, state.findings); err != nil { + return err + } + ledger := state.findings history := turn.RenderHistory(state.turns) memory := turn.RenderEssential(turn.Essential{ Task: state.prompt, @@ -79,6 +89,7 @@ func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage ChangedFiles: state.capturedList(), InputPath: paths.InputPath, HistoryPath: paths.HistoryPath, + Findings: func(limit int) string { return findings.RenderMemory(ledger, limit) }, }) for _, file := range []struct{ path, content string }{ {paths.InputPath, input}, diff --git a/internal/stage/claude_stage.go b/internal/stage/claude_stage.go index 6c8797c7..3645045e 100644 --- a/internal/stage/claude_stage.go +++ b/internal/stage/claude_stage.go @@ -61,6 +61,9 @@ type ClaudeStageClient struct { Policy ToolPolicy OnOwnership func(string, string, bool) error WorkStarted bool + // ResumeSessionID, when set, resumes that earlier session of this stage + // (resume_session=true on a loop visit) instead of starting a new one. + ResumeSessionID string // operatorPlugins are this visit's generated skills-only plugin roots for // the operator's own skills (see OperatorSkills). @@ -275,6 +278,12 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr } } env := claudeStageEnvironment(c.environment(ctx), c.ArtifactsDir) + // resume_session: continue the stage's previous session when Claude Code + // still has it; otherwise this visit starts fresh. + resumeFirst := false + if adopted == nil && c.ResumeSessionID != "" && claudeSessionExists(claudeConfigDir(env), c.ResumeSessionID) { + c.SessionID, resumeFirst = c.ResumeSessionID, true + } // User settings are not loaded, so the operator's skills are offered as // skills-only plugins generated for this visit, never their plugins. A // re-adopted visit keeps the ones its first process generated. @@ -325,7 +334,7 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr return "", err } } - if text, err = c.invoke(ctx, env, c.args(config, tools, effort, false), 0, config.Model, prompt, adopted); err != nil { + if text, err = c.invoke(ctx, env, c.args(config, tools, effort, resumeFirst), 0, config.Model, prompt, adopted); err != nil { return "", err } // One outcome repair follow-up in the same session. @@ -409,6 +418,17 @@ func claudeConfigDir(env []string) string { return "" } +// claudeSessionExists reports whether Claude Code keeps a transcript for the +// session (projects/<project>/<id>.jsonl under its config directory), so a +// resume cannot fail on a session that was cleaned up. +func claudeSessionExists(configDir, id string) bool { + if configDir == "" || id == "" || strings.ContainsAny(id, `/\*?[`) { + return false + } + matches, _ := filepath.Glob(filepath.Join(configDir, "projects", "*", id+".jsonl")) + return len(matches) > 0 +} + func newClaudeSessionID() (string, error) { var b [16]byte if _, err := rand.Read(b[:]); err != nil { diff --git a/internal/stage/findings_gate.go b/internal/stage/findings_gate.go new file mode 100644 index 00000000..c3a33b35 --- /dev/null +++ b/internal/stage/findings_gate.go @@ -0,0 +1,77 @@ +package stage + +import ( + "context" + "fmt" + + "git.a-wan.net/alan/pipelines/internal/findings" +) + +// FindingsType is the mechanical triage stage: it routes on the run's findings +// ledger instead of asking a model. Outcome `open` when any open finding is at +// or above `severity` (default important) with a matching `origin` (default +// introduced; `pre-existing` or `any`), otherwise `clear`. +const FindingsType = "findings" + +// Findings gate outcomes. +const ( + FindingsOpen = "open" + FindingsClear = "clear" +) + +type FindingsStage struct{} + +func (FindingsStage) Validate(def Definition) error { + if EffectiveType(def.Type) != FindingsType { + return fmt.Errorf("expected findings stage") + } + for name := range def.Blocks { + switch name { + case "configs", "edges", "output", "prompt", "limits": + case "skills": + return errSkillsModelOnly("findings") + default: + return fmt.Errorf("unexpected block %q for findings stage", name) + } + } + if _, err := FindingsGate(def); err != nil { + return err + } + for outcome := range def.Edges { + switch outcome { + case FindingsOpen, FindingsClear, "error": + default: + return fmt.Errorf("findings stage outcomes are open and clear, not %q", outcome) + } + } + for _, outcome := range []string{FindingsOpen, FindingsClear} { + if _, ok := def.Edges[outcome]; !ok { + return fmt.Errorf("findings stage requires an edge for outcome %s", outcome) + } + } + return nil +} + +// FindingsGate reads a findings stage's severity and origin configs. +func FindingsGate(def Definition) (findings.Gate, error) { + gate := findings.Gate{MinSeverity: "important", Origin: "introduced"} + for key, value := range def.Configs { + switch key { + case "severity": + if gate.MinSeverity = findings.NormalizeSeverity(value); gate.MinSeverity == "" { + return gate, fmt.Errorf("severity must be critical, important, minor or nit") + } + case "origin": + if gate.Origin = findings.NormalizeOrigin(value); gate.Origin == "" { + return gate, fmt.Errorf("origin must be introduced, pre-existing or any") + } + default: + return gate, fmt.Errorf("unknown findings config %q", key) + } + } + return gate, nil +} + +func (FindingsStage) Run(context.Context, Definition, Values) (Result, error) { + return Result{}, fmt.Errorf("findings stage is resolved by the runner from the run's ledger, not executed") +} diff --git a/internal/stage/model.go b/internal/stage/model.go index 2e15fd2f..a8978d66 100644 --- a/internal/stage/model.go +++ b/internal/stage/model.go @@ -84,7 +84,7 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) { } for key := range def.Configs { switch key { - case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip", "allow_workspace_changes": + case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip", "allow_workspace_changes", "resume_session": default: return ModelSpec{}, fmt.Errorf("unknown config %q", key) } @@ -111,6 +111,11 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) { if value := def.Configs["auto_skip"]; value != "" && value != "true" && value != "false" { return ModelSpec{}, fmt.Errorf("auto_skip must be true or false") } + // resume_session=true resumes the stage's previous harness session on a + // loop visit (Claude only; other harnesses start fresh). The runner reads it. + if value := def.Configs["resume_session"]; value != "" && value != "true" && value != "false" { + return ModelSpec{}, fmt.Errorf("resume_session must be true or false") + } // allow_workspace_changes=true lets a stage with shell but no edit leave file changes // in the run directory; by default the runner fails such a visit. if value := def.Configs["allow_workspace_changes"]; value != "" && value != "true" && value != "false" { diff --git a/internal/stage/model_prompt.go b/internal/stage/model_prompt.go index 1b7ee346..b170856c 100644 --- a/internal/stage/model_prompt.go +++ b/internal/stage/model_prompt.go @@ -10,6 +10,7 @@ import ( "time" "unicode/utf8" + "git.a-wan.net/alan/pipelines/internal/findings" "git.a-wan.net/alan/pipelines/internal/turn" ) @@ -75,7 +76,7 @@ func modelPrompt(def Definition, spec ModelSpec, input Values) (string, error) { case !canRead: b.WriteString("The read tool is not enabled, so the server included the turn files below. Use this supplied context; no extra filesystem access is needed.\n\n") } - writeTurnFile(&b, "memory.md", def.Turn.Memory, capInline(string(memory), turn.EssentialCap, def.Turn.Memory)) + writeTurnFile(&b, "memory.md", def.Turn.Memory, capInline(string(memory), turn.EssentialMax, def.Turn.Memory)) if canRead { b.WriteString("Rely on this essential memory first. Read on demand only, when you need more detail:\n") fmt.Fprintf(&b, "- Input (full run task and previous stage output): %s\n", def.Turn.Input) @@ -110,6 +111,9 @@ func modelPrompt(def Definition, spec ModelSpec, input Values) (string, error) { b.WriteString(" The next stage receives only the handoff as essential memory. For example:\n\n# outcome\n") b.WriteString(preferredOutcome(outcomes)) b.WriteString("\n\n# handoff\nWhat you did, files changed, open issues for the next stage.\n\n# details\n...\n") + b.WriteString("\n") + b.WriteString(findings.Syntax) + b.WriteString("\n") fmt.Fprintf(&b, "\nExecution time: %s. Timezone: %s.\n", time.Now().Format(time.RFC3339), time.Local.String()) if def.Turn.Public != "" { fmt.Fprintf(&b, "\nShared artifacts go to %s; files there are visible to every later stage. That absolute path is the shared folder: a relative public/ inside the workspace is a different, unshared directory. Turn-local work goes to %s and is not handed to later stages.\n", def.Turn.Public, def.Turn.Private) diff --git a/internal/stage/model_prompt_memory_test.go b/internal/stage/model_prompt_memory_test.go index cf3efe81..6e0961c4 100644 --- a/internal/stage/model_prompt_memory_test.go +++ b/internal/stage/model_prompt_memory_test.go @@ -19,7 +19,7 @@ func TestModelPromptInlinesEssentialMemoryAndPointsAtHistory(t *testing.T) { def.Blocks["tools"] = toolset def.Turn.History = filepath.Join(def.Turn.Dir, "history.md") files := map[string]string{ - def.Turn.Memory: "# Essential memory\n\nreviewer finding: lock leak\n" + strings.Repeat("m", 2*turn.EssentialCap), + def.Turn.Memory: "# Essential memory\n\nreviewer finding: lock leak\n" + strings.Repeat("m", 2*turn.EssentialMax), def.Turn.Input: "full previous output\n", def.Turn.History: "FULL HISTORY BODY\n", } @@ -39,7 +39,7 @@ func TestModelPromptInlinesEssentialMemoryAndPointsAtHistory(t *testing.T) { if !strings.Contains(prompt, "reviewer finding: lock leak") || !strings.Contains(prompt, "_[truncated: ") { t.Fatalf("essential memory not inlined with its cap: %q", prompt) } - if strings.Contains(prompt, strings.Repeat("m", turn.EssentialCap+1)) { + if strings.Contains(prompt, strings.Repeat("m", turn.EssentialMax+1)) { t.Fatal("inlined memory exceeded its cap") } if strings.Contains(prompt, "FULL HISTORY BODY") { diff --git a/internal/stage/stage.go b/internal/stage/stage.go index 655f1fbd..d1160ccf 100644 --- a/internal/stage/stage.go +++ b/internal/stage/stage.go @@ -75,7 +75,7 @@ func NewRegistry(types map[string]Stage) *Registry { } func DefaultRegistry() *Registry { - return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}, CheckType: CheckStage{}}) + return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}, CheckType: CheckStage{}, FindingsType: FindingsStage{}}) } func EffectiveType(name string) string { diff --git a/internal/turn/essential.go b/internal/turn/essential.go index 618ebc93..c6c8dffc 100644 --- a/internal/turn/essential.go +++ b/internal/turn/essential.go @@ -6,22 +6,32 @@ import ( "unicode/utf8" ) -// EssentialCap is the hard byte cap on a visit's memory.md (essential memory). -// It is small on purpose: the file is inlined into every model call of the -// visit, so its size is paid once per call. Everything else stays on disk in -// history.md and input.md, read only on demand. -const EssentialCap = 4096 +// EssentialCap is the byte budget of a visit's memory.md (essential memory). +// The file is inlined into every model call of the visit, so it stays bounded; +// everything else stays on disk in history.md and input.md, read on demand. +// +// The run task is never truncated (up to EssentialTaskMax): a task larger than +// the budget grows the file to the task plus essentialMinRest for the other +// sections, so EssentialMax is the absolute bound. +const ( + EssentialCap = 20 << 10 + EssentialTaskMax = 64 << 10 + essentialMinRest = 4 << 10 + EssentialMax = EssentialTaskMax + essentialMinRest + 1024 +) const ( essentialLedgerLines = 10 essentialFileLines = 8 essentialLineCap = 100 - // essentialHandoffMin is the least room a previous stage's handoff gets - // when the task also needs more than half of the remaining budget. - essentialHandoffMin = 1024 // essentialOwnHandoffCap bounds a revisiting stage's own last handoff // (for example a reviewer's earlier must-fix findings it must confirm). - essentialOwnHandoffCap = 768 + essentialOwnHandoffCap = 4 << 10 + // essentialFindingsCap bounds the findings ledger section. + essentialFindingsCap = 8 << 10 + // essentialReserve keeps room for the short trailing sections when the + // previous handoff is long. + essentialReserve = 1536 ) // Essential is everything RenderEssential needs for one visit's memory.md. @@ -38,108 +48,94 @@ type Essential struct { // InputPath and HistoryPath are named as the on-demand detail. InputPath string HistoryPath string + // Findings renders the run's findings ledger section within limit bytes + // (empty when there is no ledger). Nil means no section. + Findings func(limit int) string } -// RenderEssential renders a visit's essential memory: the task, the previous -// stage's handoff, a one-line-per-stage outcome ledger and the changed files. -// The result never exceeds EssentialCap bytes. The previous stage's handoff is -// its "# handoff" section when it wrote one, otherwise the head of its output; -// either is truncated with a pointer to the full text, so the file stays useful -// whether or not a model followed the handoff convention. +// RenderEssential renders a visit's essential memory. Sections in priority +// order: the task (never truncated), the previous stage's handoff, the open +// findings ledger, this stage's own previous handoff, a one-line-per-stage +// outcome ledger and the changed files. Lower-priority sections shrink or are +// dropped first. The result fits EssentialCap unless the task alone needs +// more (see EssentialMax). The previous stage's handoff is its "# handoff" +// section when it wrote one, otherwise the head of its output; either is +// truncated with a pointer to the full text. func RenderEssential(e Essential) string { - var fixed strings.Builder - fixed.WriteString("# Essential memory\n\n") - fixed.WriteString("Short handoff for this visit; enough for most work.") + var b strings.Builder + b.WriteString("# Essential memory\n\n") + b.WriteString("Short handoff for this visit; enough for most work.") if e.InputPath != "" || e.HistoryPath != "" { - fixed.WriteString(" Read on demand only:") + b.WriteString(" Read on demand only:") if e.InputPath != "" { - fmt.Fprintf(&fixed, " %s (full task and previous stage output)", e.InputPath) + fmt.Fprintf(&b, " %s (full task and previous stage output)", e.InputPath) } if e.HistoryPath != "" { if e.InputPath != "" { - fixed.WriteString(";") + b.WriteString(";") } - fmt.Fprintf(&fixed, " %s (every earlier turn in full)", e.HistoryPath) + fmt.Fprintf(&b, " %s (every earlier turn in full)", e.HistoryPath) } - fixed.WriteString(".") + b.WriteString(".") } - fixed.WriteString("\n") + b.WriteString("\n") - var tail strings.Builder - tail.WriteString(renderOwnHandoff(e.Entries, e.StageKey)) - if ledger := renderLedger(e.Entries, e.StageKey); ledger != "" { - tail.WriteString("\n## Stage ledger\n\n") - tail.WriteString(ledger) - } - if files := renderFiles(e.ChangedFiles); files != "" { - tail.WriteString("\n## Changed files (server-captured)\n\n") - tail.WriteString(files) - } - - taskHeading := "\n## Task\n\n" task := strings.TrimSpace(demoteHeadings(strings.TrimSpace(e.Task))) if task == "" { task = "_(no task text)_" } - var handoffHeading, handoff string + if len(task) > EssentialTaskMax { + task = truncateWithNote(task, EssentialTaskMax, "input.md") + } + b.WriteString("\n## Task\n\n") + b.WriteString(task) + b.WriteString("\n") + + limit := EssentialCap + if need := b.Len() + essentialMinRest; need > limit { + limit = need + } + room := func() int { return limit - b.Len() } + if n := len(e.Entries); n > 0 { previous := e.Entries[n-1] title := capLine(fmt.Sprintf("%s · visit %d%s", oneLine(previous.Stage), previous.Visit, outcomeSuffix(previous.Outcome)), 2*essentialLineCap) - handoffHeading = "\n## Previous stage: " + title + "\n\n" - var source string - handoff, source = previousHandoff(previous.Output) - handoffHeading += source + handoff, source := previousHandoff(previous.Output) if public := sortedUnique(previous.PublicFiles); len(public) > 0 { handoff += "\n\nAdded to public/: " + capLine(strings.Join(public, ", "), 2*essentialLineCap) } - } - - // Budget what is left after the fixed parts between the task and the - // handoff. Unused room on either side flows to the other. - reserve := 2 * len(truncationNote(EssentialCap, EssentialCap, "input.md")) - budget := EssentialCap - fixed.Len() - tail.Len() - len(taskHeading) - len(handoffHeading) - 2 - reserve - if budget < 0 { - budget = 0 - } - handoffBudget, taskBudget := 0, budget - if handoffHeading != "" { - half := budget / 2 - if half < essentialHandoffMin { - half = min(essentialHandoffMin, budget) - } - switch { - case len(task) <= budget-half: - handoffBudget = budget - len(task) - case len(handoff) <= half: - handoffBudget = len(handoff) - default: - handoffBudget = half - } - taskBudget = budget - min(handoffBudget, len(handoff)) - } - - var b strings.Builder - b.WriteString(fixed.String()) - b.WriteString(taskHeading) - b.WriteString(truncateWithNote(task, taskBudget, "input.md")) - b.WriteString("\n") - if handoffHeading != "" { - b.WriteString(handoffHeading) - b.WriteString(truncateWithNote(handoff, handoffBudget, "input.md")) + heading := "\n## Previous stage: " + title + "\n\n" + source + budget := room() - len(heading) - 1 - essentialReserve - len(truncationNote(EssentialMax, EssentialMax, "input.md")) + b.WriteString(heading) + b.WriteString(truncateWithNote(handoff, max(budget, 256), "input.md")) b.WriteString("\n") } else { b.WriteString("\nThis is the first stage of the run; there is no earlier turn.\n") } - b.WriteString(tail.String()) - out := b.String() - if len(out) > EssentialCap { - // Pathological input (very long stage keys or paths); never exceed the - // cap even if the section budgets could not absorb it. - out = truncateWithNote(out, EssentialCap-len(truncationNote(len(out), len(out), "history.md")), "history.md") + "\n" - if len(out) > EssentialCap { - out = cutAtRune(out, EssentialCap) + + if e.Findings != nil { + if section := e.Findings(min(essentialFindingsCap, room()-essentialReserve/2)); section != "" && len(section) <= room() { + b.WriteString(section) } } + if own := renderOwnHandoff(e.Entries, e.StageKey, min(essentialOwnHandoffCap, room()-essentialReserve/2)); own != "" && len(own) <= room() { + b.WriteString(own) + } + if ledger := renderLedger(e.Entries, e.StageKey); ledger != "" { + if section := "\n## Stage ledger\n\n" + ledger; len(section) <= room() { + b.WriteString(section) + } + } + if files := renderFiles(e.ChangedFiles); files != "" { + if section := "\n## Changed files (server-captured)\n\n" + files; len(section) <= room() { + b.WriteString(section) + } + } + out := b.String() + if len(out) > EssentialMax { + // Pathological input; never exceed the absolute bound. + out = cutAtRune(out, EssentialMax) + } return out } @@ -147,6 +143,14 @@ func RenderEssential(e Essential) string { // level, outside fenced code) up to the next heading of the same or a higher // level, trimmed. ok is false when there is no such heading or it is empty. func HandoffSection(markdown string) (string, bool) { + return Section(markdown, "handoff") +} + +// Section returns the body of the first heading named name (case-insensitive, +// any ATX level, outside fenced code) up to the next heading of the same or a +// higher level, trimmed. ok is false when there is no such heading or it is +// empty. +func Section(markdown, name string) (string, bool) { lines := markdownLines(markdown) var fence fenceState start, level := -1, 0 @@ -167,7 +171,7 @@ func HandoffSection(markdown string) (string, bool) { continue } if start < 0 { - if strings.EqualFold(text, "handoff") { + if strings.EqualFold(text, name) { start, level = line.next, lvl } continue @@ -189,8 +193,8 @@ func HandoffSection(markdown string) (string, bool) { // previous must-fix findings) sees what it said last time. It is empty on a // first visit and when that visit is the immediately previous turn, which the // "Previous stage" section already shows. -func renderOwnHandoff(entries []MemoryEntry, current string) string { - if current == "" { +func renderOwnHandoff(entries []MemoryEntry, current string, limit int) string { + if current == "" || limit < 256 { return "" } for i := len(entries) - 1; i >= 0; i-- { @@ -203,7 +207,9 @@ func renderOwnHandoff(entries []MemoryEntry, current string) string { own := entries[i] body, source := previousHandoff(own.Output) title := capLine(fmt.Sprintf("%s · visit %d%s", oneLine(own.Stage), own.Visit, outcomeSuffix(own.Outcome)), 2*essentialLineCap) - return "\n## This stage's previous visit: " + title + "\n\n" + source + truncateWithNote(body, essentialOwnHandoffCap, "history.md") + "\n" + heading := "\n## This stage's previous visit: " + title + "\n\n" + source + budget := limit - len(heading) - 1 - len(truncationNote(EssentialMax, EssentialMax, "history.md")) + return heading + truncateWithNote(body, max(budget, 0), "history.md") + "\n" } return "" } diff --git a/internal/turn/essential_test.go b/internal/turn/essential_test.go index f097b082..5b96d79f 100644 --- a/internal/turn/essential_test.go +++ b/internal/turn/essential_test.go @@ -103,7 +103,7 @@ func TestEssentialMemoryCapsEveryPart(t *testing.T) { for i := range 200 { files = append(files, fmt.Sprintf("%03d/%s", i, long)) } - memory := RenderEssential(Essential{Task: paragraph("task", 50000), StageKey: "next", Entries: entries, ChangedFiles: files, InputPath: "/in.md", HistoryPath: "/history.md"}) + memory := RenderEssential(Essential{Task: paragraph("task", 5000), StageKey: "next", Entries: entries, ChangedFiles: files, InputPath: "/in.md", HistoryPath: "/history.md"}) if len(memory) > EssentialCap { t.Fatalf("essential memory is %d bytes, over the %d cap", len(memory), EssentialCap) } @@ -114,6 +114,38 @@ func TestEssentialMemoryCapsEveryPart(t *testing.T) { } } +// TestEssentialMemoryNeverTruncatesTheTask proves a task larger than the +// budget is kept whole and the other sections share a bounded remainder, with +// the previous handoff and the findings ledger ahead of the outcome ledger. +func TestEssentialMemoryNeverTruncatesTheTask(t *testing.T) { + task := paragraph("task", 30000) + "THE END OF THE TASK" + entries := []MemoryEntry{ + {Stage: "implement", Visit: 1, Outcome: "success", Output: "# handoff\n\n" + paragraph("handoff", 9000)}, + {Stage: "review", Visit: 1, Outcome: "rejected", Output: "# handoff\n\nReview handoff: fix F1.\n"}, + } + findings := func(limit int) string { + return "\n## Findings ledger (runner-owned)\n\n- F1 · important · introduced — leak\n" + } + memory := RenderEssential(Essential{Task: task, StageKey: "implement", Entries: entries, Findings: findings, InputPath: "/in.md", HistoryPath: "/history.md"}) + if !strings.Contains(memory, "THE END OF THE TASK") || strings.Contains(memory[:strings.Index(memory, "THE END")], "_[truncated") { + t.Fatalf("task was truncated") + } + if len(memory) > len(task)+essentialMinRest+512 || len(memory) > EssentialMax { + t.Fatalf("memory %d bytes is not bounded by the task (%d) plus the minimum rest", len(memory), len(task)) + } + handoff, ledger, own := strings.Index(memory, "Review handoff: fix F1."), strings.Index(memory, "## Findings ledger"), strings.Index(memory, "## This stage's previous visit") + if handoff < 0 || ledger < handoff { + t.Fatalf("handoff and findings missing or out of order:\n%s", memory[len(task)-200:]) + } + if own >= 0 && own < ledger { + t.Fatalf("own handoff ahead of the findings ledger") + } + small := RenderEssential(Essential{Task: "Small task.", StageKey: "implement", Entries: entries, Findings: findings}) + if len(small) > EssentialCap || !strings.Contains(small, "## Stage ledger") || !strings.Contains(small, "handoff: detail") { + t.Fatalf("small-task memory (%d bytes):\n%s", len(small), small) + } +} + func TestEssentialMemoryFirstVisit(t *testing.T) { memory := RenderEssential(Essential{Task: "Do it.", StageKey: "plan", InputPath: "in.md", HistoryPath: "hist.md"}) for _, want := range []string{"## Task\n\nDo it.", "first stage of the run"} {