Engine: check stages, harness-agnostic delivery, read-only enforcement, complete captures

- New `type=check` stage: the server runs a `commands` block (sh -c, per
  command_timeout, workspace env) and routes on pass/fail; per-command status,
  exit code, duration and bounded output are recorded and the failing output is
  the handoff. With delivery=true it is the landing gate (commit leftovers,
  merge moved main, checks in a fresh candidate worktree, fast-forward main).
  Parser/registry, lint (silent guards), format docs, CLI inspect, app graph and
  run detail rendering.
- delivery=true is accepted on every harness (and on check stages).
- permissions.shell on claude stages maps to Bash(cmd) / Bash(prefix:*) rules
  instead of a bare Bash allow; stages without edit that change the workspace
  fail the visit with the changed files listed (allow_workspace_changes=true
  opts out; artifacts, public and harness state dirs are ignored).
- File-change capture: symlinks compared by target, untouched protected files no
  longer make captures partial, untracked caches/dependency/build output left
  out, lockfiles listed without patch, huge files compared by metadata, raised
  patch/line limits. Outcome repair follow-ups are logged and counted on the
  step (control.outcome_repairs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 12:52:16 +00:00
parent c4de1de27b
commit 87016ef5dc
47 changed files with 2674 additions and 129 deletions
@@ -111,7 +111,7 @@ String? noPatchReasonMessage(String? reason) => switch (reason) {
'budget' => 'budget' =>
'The workspace snapshot ran out of text budget, so no diff text was ' 'The workspace snapshot ran out of text budget, so no diff text was '
'recorded.', 'recorded.',
'lines' => 'The change is over 5,000 lines, so no diff text was recorded.', 'lines' => 'The change is over 20,000 lines, so no diff text was recorded.',
'evidence_size' => 'evidence_size' =>
"This visit's recorded changes reached their size limit, so this patch " "This visit's recorded changes reached their size limit, so this patch "
'was dropped.', 'was dropped.',
@@ -121,6 +121,15 @@ String? noPatchReasonMessage(String? reason) => switch (reason) {
'baseline' => 'baseline' =>
"The file's content at stage start couldn't be recovered from Git, so no " "The file's content at stage start couldn't be recovered from Git, so no "
'diff was recorded.', 'diff was recorded.',
'symlink' => 'Symbolic link; only the change to its target was recorded.',
'protected' =>
'A protected file (secrets, credentials or a database); its content is '
'never read, only that it changed.',
'generated' =>
'A lockfile, minified or generated file; it is listed without a diff.',
'large' =>
'This file is too large to hash, so it was compared by size and '
'modification time only.',
_ => null, _ => null,
}; };
@@ -36,8 +36,10 @@ class FileChange {
final bool truncated; final bool truncated;
/// Why the server recorded no (complete) patch: `binary`, `file_size`, /// Why the server recorded no (complete) patch: `binary`, `file_size`,
/// `budget`, `lines`, `evidence_size`, `git_status` or `baseline`. Null from /// `budget`, `lines`, `evidence_size`, `git_status`, `baseline`, `symlink`,
/// an older server or when a patch was recorded. /// `protected` (content never read), `generated` (lockfile/minified) or
/// `large` (compared by size and mtime only). Null from an older server or
/// when a patch was recorded; an unknown value gets the generic wording.
final String? noPatchReason; final String? noPatchReason;
final String? beforeMode; final String? beforeMode;
final String? afterMode; final String? afterMode;
@@ -0,0 +1,45 @@
// The `check` stage type: a model-free stage that runs shell commands and
// routes `pass`/`fail` (plus `error`). Its `delivery` config marks the landing
// gate, which runs the commands in a fresh worktree and fast-forwards main on
// pass. Pure data only; an older graph simply has no check stages.
/// The stage type word the server uses for a check stage.
const String checkStageType = 'check';
/// Whether [stage] (a graph stage declaration) is a check stage.
bool isCheckStage(dynamic stage) =>
stage is Map && '${stage['type'] ?? ''}'.trim() == checkStageType;
/// Whether a check [stage] is the delivery (landing) gate.
///
/// Configs are strings on the wire (`"true"`); a JSON boolean is accepted too.
bool isDeliveryGate(dynamic stage) {
if (!isCheckStage(stage)) return false;
final configs = (stage as Map)['configs'];
if (configs is! Map) return false;
final value = configs['delivery'];
return value == true || '${value ?? ''}'.trim().toLowerCase() == 'true';
}
/// The check stage's commands, one per non-blank line of `blocks.commands`
/// (a list of strings is read item by item), in declared order.
List<String> checkCommands(dynamic stage) {
if (stage is! Map) return const <String>[];
final blocks = stage['blocks'];
if (blocks is! Map) return const <String>[];
final raw = blocks['commands'];
final lines = raw is List
? [for (final item in raw) '${item ?? ''}']
: '${raw ?? ''}'.split('\n');
return [
for (final line in lines)
if (line.trim().isNotEmpty) line.trimRight(),
];
}
/// The short kind a graph node shows under its name: `Check` or
/// `Delivery gate`, or null for every other stage type.
String? checkStageCaption({required String type, required bool delivery}) {
if (type.trim() != checkStageType) return null;
return delivery ? 'Delivery gate' : 'Check';
}
@@ -1,3 +1,4 @@
import 'check_stage.dart';
import 'graph_protocol.dart'; import 'graph_protocol.dart';
/// The graph definition: nodes and edges declared by a pipeline, never the /// The graph definition: nodes and edges declared by a pipeline, never the
@@ -70,11 +71,27 @@ class GraphEdge {
/// One graph definition node: a declared stage, or a terminal the definition /// One graph definition node: a declared stage, or a terminal the definition
/// routes to. /// routes to.
class GraphNode { class GraphNode {
const GraphNode({required this.key, required this.terminal, this.stageIndex}); const GraphNode({
required this.key,
required this.terminal,
this.stageIndex,
this.type = '',
this.delivery = false,
});
final String key; final String key;
final bool terminal; final bool terminal;
/// The stage's declared `type` exactly as recorded (blank reads `model`);
/// empty for a terminal.
final String type;
/// Whether this is a check stage marked as the delivery gate.
final bool delivery;
/// `Check` or `Delivery gate` for a check stage, otherwise null.
String? get kindCaption => checkStageCaption(type: type, delivery: delivery);
/// The node's stage declaration index, or null for a terminal. /// The node's stage declaration index, or null for a terminal.
final int? stageIndex; final int? stageIndex;
@@ -142,7 +159,15 @@ List<GraphNode> graphNodes(dynamic graph) {
for (var index = 0; index < stages.length; index += 1) { for (var index = 0; index < stages.length; index += 1) {
final key = _stageKey(stages[index]); final key = _stageKey(stages[index]);
if (key.isEmpty || !seen.add(key)) continue; if (key.isEmpty || !seen.add(key)) continue;
nodes.add(GraphNode(key: key, terminal: false, stageIndex: index)); nodes.add(
GraphNode(
key: key,
terminal: false,
stageIndex: index,
type: '${stages[index]['type'] ?? ''}',
delivery: isDeliveryGate(stages[index]),
),
);
} }
if (graphEdges(graph).any((edge) => edge.isTerminal)) { if (graphEdges(graph).any((edge) => edge.isTerminal)) {
nodes.add(const GraphNode(key: failureEnd, terminal: true)); nodes.add(const GraphNode(key: failureEnd, terminal: true));
@@ -1,3 +1,4 @@
import 'check_stage.dart';
import 'graph_definition.dart'; import 'graph_definition.dart';
import 'graph_protocol.dart'; import 'graph_protocol.dart';
@@ -9,13 +10,22 @@ import 'graph_protocol.dart';
/// reads run visits, so a definition can be inspected without claiming that a /// reads run visits, so a definition can be inspected without claiming that a
/// stage executed. /// stage executed.
class StageDefinitionField { class StageDefinitionField {
const StageDefinitionField(this.label, this.value, {this.block = false}); const StageDefinitionField(
this.label,
this.value, {
this.block = false,
this.monospace = false,
});
final String label; final String label;
final String value; final String value;
/// Multi-line content (prompt, output, outcomes, tools, memory, routes). /// Multi-line content (prompt, output, outcomes, tools, memory, routes).
final bool block; final bool block;
/// Literal code (a check stage's commands): always shown verbatim in a
/// monospace block, never rendered as markdown.
final bool monospace;
} }
/// The one stage declaration [key] names, or null when this version does not /// The one stage declaration [key] names, or null when this version does not
@@ -58,6 +68,12 @@ String stageConfigLabel(String key) {
return 'Budget (tokens)'; return 'Budget (tokens)';
case 'harness': case 'harness':
return 'Harness'; return 'Harness';
case 'command_timeout':
return 'Command timeout';
case 'keep_going':
return 'Keep going';
case 'delivery':
return 'Delivery gate';
default: default:
return key; return key;
} }
@@ -69,10 +85,27 @@ String stageConfigLabel(String key) {
/// interpreted here; the pane keeps the stage's raw JSON so they stay visible. /// interpreted here; the pane keeps the stage's raw JSON so they stay visible.
List<StageDefinitionField> stageDefinitionFields(dynamic stage) { List<StageDefinitionField> stageDefinitionFields(dynamic stage) {
if (stage is! Map) return const <StageDefinitionField>[]; if (stage is! Map) return const <StageDefinitionField>[];
final type = effectiveStageType(stage['type']);
final fields = <StageDefinitionField>[ final fields = <StageDefinitionField>[
StageDefinitionField('Type', effectiveStageType(stage['type'])), StageDefinitionField(
'Type',
isDeliveryGate(stage) ? '$type (delivery gate)' : type,
),
]; ];
// A check stage runs commands where a model stage has its prompt.
final commands = checkCommands(stage);
if (isCheckStage(stage) && commands.isNotEmpty) {
fields.add(
StageDefinitionField(
'Commands',
commands.join('\n'),
block: true,
monospace: true,
),
);
}
final prompt = _text(stage['prompt']); final prompt = _text(stage['prompt']);
if (prompt.trim().isNotEmpty) { if (prompt.trim().isNotEmpty) {
fields.add(StageDefinitionField('Prompt', prompt, block: true)); fields.add(StageDefinitionField('Prompt', prompt, block: true));
@@ -45,10 +45,7 @@ class GraphStageNode extends StatelessWidget {
return status != null && status.trim().isNotEmpty ? status : null; return status != null && status.trim().isNotEmpty ? status : null;
} }
String get _label { String get _label => graphNodeSemanticsLabel(node, _status);
final status = _status;
return status == null ? node.label : '${node.label}\n$status';
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -112,11 +109,13 @@ class GraphStageNode extends StatelessWidget {
graphStatusState(status), graphStatusState(status),
Theme.of(context).colorScheme, Theme.of(context).colorScheme,
); );
final caption = node.kindCaption;
return Column( return Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text(_breakable(node.label), softWrap: true), Text(_breakable(node.label), softWrap: true),
if (caption != null) _kind(context, caption),
if (status != null) if (status != null)
Row( Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
@@ -144,6 +143,29 @@ class GraphStageNode extends StatelessWidget {
); );
} }
/// A check stage's kind under its name: the check icon (a gate icon for the
/// delivery gate) and `Check`/`Delivery gate` in the muted label role.
Widget _kind(BuildContext context, String caption) {
final theme = Theme.of(context);
final color = theme.colorScheme.onSurfaceVariant;
final style = (theme.textTheme.labelSmall ?? const TextStyle()).copyWith(
color: color,
);
return Row(
key: ValueKey('graph-node-kind-${node.key}'),
mainAxisSize: MainAxisSize.min,
children: [
Icon(
checkStageIcon(delivery: node.delivery),
size: (style.fontSize ?? 11) * 1.4,
color: color,
),
const SizedBox(width: 4),
Flexible(child: Text(caption, style: style, softWrap: true)),
],
);
}
/// The web node uses `overflow-wrap: anywhere`; Flutter text does not break a /// The web node uses `overflow-wrap: anywhere`; Flutter text does not break a
/// long unbroken key, so the same invisible break opportunities are added. /// long unbroken key, so the same invisible break opportunities are added.
/// The visible text and the semantics label stay unchanged. /// The visible text and the semantics label stay unchanged.
@@ -265,6 +287,18 @@ class StageActivityHaloPainter extends CustomPainter {
oldDelegate.color != color || oldDelegate.progress != progress; oldDelegate.color != color || oldDelegate.progress != progress;
} }
/// The icon for a check stage; the delivery gate gets the landing icon.
IconData checkStageIcon({required bool delivery}) =>
delivery ? Icons.verified_outlined : Icons.fact_check_outlined;
/// A node's accessible name: its label, a check stage's kind, then the run's
/// recorded status when there is one.
String graphNodeSemanticsLabel(GraphNode node, String? status) => [
node.label,
?node.kindCaption,
if (status != null && status.trim().isNotEmpty) status,
].join('\n');
/// The run state a recorded step status colours as: done is green, an error or /// The run state a recorded step status colours as: done is green, an error or
/// a block is red, running is blue, waiting teal, anything else grey. /// a block is red, running is blue, waiting teal, anything else grey.
String graphStatusState(String status) { String graphStatusState(String status) {
@@ -341,7 +341,7 @@ class RunGraphNode extends StatelessWidget {
} }
return Semantics( return Semantics(
container: true, container: true,
label: status == null ? node.label : '${node.label}\n$status', label: graphNodeSemanticsLabel(node, status),
child: ExcludeSemantics( child: ExcludeSemantics(
child: IgnorePointer( child: IgnorePointer(
child: GraphStageNode( child: GraphStageNode(
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import '../../../ui/adaptive/segmented_bar.dart'; import '../../../ui/adaptive/segmented_bar.dart';
import '../../../ui/text/markdown_source_view.dart'; import '../../../ui/text/markdown_source_view.dart';
import '../../../ui/text/monospace.dart';
import '../../chat/ui/transcript/chat_markdown_view.dart'; import '../../chat/ui/transcript/chat_markdown_view.dart';
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/floating_bar_layout.dart'; import '../../../ui/adaptive/floating_bar_layout.dart';
@@ -190,8 +191,15 @@ class _StageDefinitionFieldView extends StatelessWidget {
children: [ children: [
Text(field.label, style: style.label), Text(field.label, style: style.label),
const SizedBox(height: 4), const SizedBox(height: 4),
// Commands are literal code: verbatim and monospace in either mode.
if (field.monospace)
_SelectableDefinitionText(
key: ValueKey('stage-definition-${field.label}'),
value: field.value,
style: style.value.copyWith(fontFamily: appMonospaceFamily),
)
// An authored text block (a prompt) is markdown: rendered or raw. // An authored text block (a prompt) is markdown: rendered or raw.
if (field.block && raw) else if (field.block && raw)
_SelectableDefinitionText(value: field.value, style: style.value) _SelectableDefinitionText(value: field.value, style: style.value)
else if (field.block) else if (field.block)
ChatMarkdownView(text: field.value) ChatMarkdownView(text: field.value)
@@ -215,7 +223,11 @@ class _StageDefinitionFieldView extends StatelessWidget {
/// fallback font with taller metrics and double-space only that block. It is /// fallback font with taller metrics and double-space only that block. It is
/// the host's own line metrics, not a font override or a fixed height. /// the host's own line metrics, not a font override or a fixed height.
class _SelectableDefinitionText extends StatelessWidget { class _SelectableDefinitionText extends StatelessWidget {
const _SelectableDefinitionText({required this.value, required this.style}); const _SelectableDefinitionText({
super.key,
required this.value,
required this.style,
});
final String value; final String value;
final TextStyle style; final TextStyle style;
@@ -0,0 +1,133 @@
// A check stage visit's recorded output: the per-command results the server
// ran for a `check` stage, read without widget imports.
//
// Only an output map carrying a `checks` list is a check output; older
// servers never send one, so every other step keeps its ordinary rendering.
/// How one command ended. [unknown] keeps a status this client does not know
/// (its raw word stays in [CheckCommandResult.statusWord]).
enum CheckCommandStatus { passed, failed, timedOut, notRun, unknown }
CheckCommandStatus checkCommandStatus(String word) =>
switch (word.trim().toLowerCase()) {
'passed' => CheckCommandStatus.passed,
'failed' => CheckCommandStatus.failed,
'timed_out' => CheckCommandStatus.timedOut,
'not_run' => CheckCommandStatus.notRun,
_ => CheckCommandStatus.unknown,
};
/// The status as the row reads it; an unknown status shows its raw word.
String checkStatusLabel(CheckCommandResult check) => switch (check.status) {
CheckCommandStatus.passed => 'Passed',
CheckCommandStatus.failed => 'Failed',
CheckCommandStatus.timedOut => 'Timed out',
CheckCommandStatus.notRun => 'Not run',
CheckCommandStatus.unknown =>
check.statusWord.isEmpty ? 'Unknown status' : check.statusWord,
};
/// One command's recorded result.
class CheckCommandResult {
const CheckCommandResult({
required this.command,
required this.statusWord,
this.exitCode,
this.durationMs,
this.output = '',
this.truncated = false,
});
final String command;
/// The server's status word verbatim.
final String statusWord;
/// Null when not recorded (a command that never ran has none).
final int? exitCode;
final int? durationMs;
final String output;
/// Whether the server cut [output] at its capture limit.
final bool truncated;
CheckCommandStatus get status => checkCommandStatus(statusWord);
/// `exit 1 · 51s`, leaving out whichever fact was not recorded.
String get meta => [
if (exitCode != null) 'exit $exitCode',
if (durationMs != null) formatCheckDuration(durationMs!),
].join(' · ');
}
/// A check visit's whole recorded output.
class CheckStepOutput {
const CheckStepOutput({
required this.checks,
this.summary,
this.markdown,
this.delivery = false,
});
final List<CheckCommandResult> checks;
/// The server's one-line summary (`1 of 2 checks failed: go test ./...`).
final String? summary;
/// The handoff document the next stage reads.
final String? markdown;
/// Whether this visit was the delivery gate.
final bool delivery;
}
/// The check output recorded in [output], or null when it is not one.
CheckStepOutput? checkStepOutput(dynamic output) {
if (output is! Map) return null;
final checks = output['checks'];
if (checks is! List) return null;
return CheckStepOutput(
checks: [
for (final item in checks)
if (item is Map) _check(item),
],
summary: _text(output['summary']),
markdown: _text(output['markdown']),
delivery: output['delivery'] == true,
);
}
CheckCommandResult _check(Map item) => CheckCommandResult(
command: '${item['command'] ?? ''}',
statusWord: '${item['status'] ?? ''}'.trim(),
exitCode: _int(item['exit_code']),
durationMs: _int(item['duration_ms']),
output: item['output'] is String ? item['output'] as String : '',
truncated: item['truncated'] == true,
);
/// A command duration: `850ms`, `2.1s`, `51s`, `3m 05s`.
String formatCheckDuration(int ms) {
if (ms < 1000) return '${ms}ms';
if (ms < 10000) {
final tenths = (ms / 100).round();
return tenths % 10 == 0 ? '${tenths ~/ 10}s' : '${tenths / 10}s';
}
final seconds = (ms / 1000).round();
if (seconds < 60) return '${seconds}s';
final minutes = seconds ~/ 60;
final rest = (seconds % 60).toString().padLeft(2, '0');
if (minutes < 60) return '${minutes}m ${rest}s';
return '${minutes ~/ 60}h ${(minutes % 60).toString().padLeft(2, '0')}m';
}
int? _int(dynamic value) {
if (value is num) return value.toInt();
if (value is String) return int.tryParse(value.trim());
return null;
}
String? _text(dynamic value) {
if (value is! String) return null;
return value.trim().isEmpty ? null : value;
}
@@ -0,0 +1,136 @@
import 'package:flutter/material.dart';
import '../../../ui/status/run_status_icon.dart';
import '../../../ui/text/monospace.dart';
import '../../chat/ui/transcript/chat_markdown_view.dart';
import '../domain/check_step_output.dart';
/// The note under a command whose recorded output the server cut short.
const String checkOutputTruncated =
'The server truncated this output at its capture limit.';
/// The body of a command that recorded no output.
const String checkOutputEmpty = 'No output recorded.';
/// A check visit's Output: its summary, a delivery-gate marker, one
/// expandable row per command and the handoff document the next stage reads.
class RunCheckOutputView extends StatelessWidget {
const RunCheckOutputView({super.key, required this.output});
final CheckStepOutput output;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final summary = output.summary;
final markdown = output.markdown;
return Column(
key: const Key('run-check-output'),
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (output.delivery)
Align(
alignment: AlignmentDirectional.centerStart,
child: Chip(
key: const Key('run-check-delivery'),
avatar: const Icon(Icons.verified_outlined),
label: const Text('Delivery gate'),
),
),
if (summary != null)
Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: SelectableText(summary, style: theme.textTheme.bodyLarge),
),
if (output.checks.isEmpty)
const Text('No commands were recorded.')
else
for (final (index, check) in output.checks.indexed)
RunCheckCommandRow(
key: ValueKey('run-check-command-$index'),
check: check,
),
if (markdown != null) ...[
const SizedBox(height: 12),
Text('Handoff', style: theme.textTheme.titleSmall),
const SizedBox(height: 4),
ChatMarkdownView(text: markdown),
],
],
);
}
}
/// One command: a status icon, the command, its status, exit code and
/// duration; expanding it shows the recorded output as selectable monospace.
class RunCheckCommandRow extends StatelessWidget {
const RunCheckCommandRow({super.key, required this.check});
final CheckCommandResult check;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final mono = (theme.textTheme.bodyMedium ?? const TextStyle()).copyWith(
fontFamily: appMonospaceFamily,
);
final color = runStatusColor(_state(check.status), theme.colorScheme);
final meta = check.meta;
return ExpansionTile(
tilePadding: EdgeInsets.zero,
childrenPadding: const EdgeInsets.only(bottom: 12),
expandedCrossAxisAlignment: CrossAxisAlignment.stretch,
leading: Icon(
_icon(check.status),
color: color,
semanticLabel: checkStatusLabel(check),
),
title: Text(
check.command.isEmpty ? '(no command)' : check.command,
style: mono,
),
subtitle: Text(
[checkStatusLabel(check), if (meta.isNotEmpty) meta].join(' · '),
),
children: [
if (check.output.isEmpty)
const Text(checkOutputEmpty)
else
DecoratedBox(
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
child: Padding(
padding: const EdgeInsets.all(12),
child: SelectableText(check.output, style: mono),
),
),
if (check.truncated)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
checkOutputTruncated,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
),
],
);
}
static String _state(CheckCommandStatus status) => switch (status) {
CheckCommandStatus.passed => 'succeeded',
CheckCommandStatus.failed || CheckCommandStatus.timedOut => 'failed',
CheckCommandStatus.notRun || CheckCommandStatus.unknown => 'unknown',
};
static IconData _icon(CheckCommandStatus status) => switch (status) {
CheckCommandStatus.passed => Icons.check_circle_outline,
CheckCommandStatus.failed => Icons.cancel_outlined,
CheckCommandStatus.timedOut => Icons.timer_off_outlined,
CheckCommandStatus.notRun => Icons.remove_circle_outline,
CheckCommandStatus.unknown => Icons.help_outline,
};
}
@@ -133,6 +133,22 @@ String? detailVisitSkills(JsonMap step) {
return (option: option, reason: reason); return (option: option, reason: reason);
} }
/// How many times the server sent its one "missing `# outcome`" repair
/// follow-up for this visit (`control.outcome_repairs`); 0 when not recorded,
/// which older servers and unrepaired visits both mean.
int detailVisitOutcomeRepairs(JsonMap step) {
final control = step['control'];
if (control is! Map) return 0;
final value = control['outcome_repairs'];
if (value is num) return value.toInt();
return int.tryParse('${value ?? ''}'.trim()) ?? 0;
}
/// The note a repaired visit shows under its facts.
String outcomeRepairNote(int repairs) => repairs == 1
? 'Outcome repaired by follow-up'
: 'Outcome repaired by follow-up ($repairs times)';
/// The visit's diagnostic exactly as recorded, or null when it is blank. /// The visit's diagnostic exactly as recorded, or null when it is blank.
String? detailVisitDiagnostic(JsonMap step) => _text(step['diagnostic']); String? detailVisitDiagnostic(JsonMap step) => _text(step['diagnostic']);
@@ -21,6 +21,7 @@ class RunVisitFactsView extends StatelessWidget {
final facts = detailVisitFacts(step); final facts = detailVisitFacts(step);
final verdict = detailVisitVerdict(step); final verdict = detailVisitVerdict(step);
final diagnostic = detailVisitDiagnostic(step); final diagnostic = detailVisitDiagnostic(step);
final repairs = detailVisitOutcomeRepairs(step);
return Padding( return Padding(
key: const Key('run-visit-facts'), key: const Key('run-visit-facts'),
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 12), padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 12),
@@ -28,6 +29,23 @@ class RunVisitFactsView extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
_FactGrid(facts: facts, style: style), _FactGrid(facts: facts, style: style),
if (repairs > 0) ...[
const SizedBox(height: 8),
Row(
key: const Key('run-visit-outcome-repaired'),
children: [
Icon(
Icons.build_circle_outlined,
size: 16,
color: style.muted.color,
),
const SizedBox(width: 6),
Flexible(
child: Text(outcomeRepairNote(repairs), style: style.muted),
),
],
),
],
if (verdict != null) ...[ if (verdict != null) ...[
const SizedBox(height: 8), const SizedBox(height: 8),
Text('Verdict', style: style.heading), Text('Verdict', style: style.heading),
@@ -57,10 +75,14 @@ class _FactGrid extends StatelessWidget {
static String _stateOf(VisitFact fact) { static String _stateOf(VisitFact fact) {
final value = fact.value.trim().toLowerCase(); final value = fact.value.trim().toLowerCase();
if (fact.label == 'Outcome') { if (fact.label == 'Outcome') {
if (value == 'error' || value == 'failed' || value == 'blocked') { if (value == 'error' ||
value == 'failed' ||
value == 'fail' ||
value == 'blocked') {
return 'failed'; return 'failed';
} }
if (value == 'success') return 'succeeded'; // A check stage routes `pass`/`fail`.
if (value == 'success' || value == 'pass') return 'succeeded';
return 'running'; return 'running';
} }
return graphStatusState(fact.value); return graphStatusState(fact.value);
@@ -4,6 +4,8 @@ import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/floating_destination_bar.dart'; import '../../../ui/adaptive/floating_destination_bar.dart';
import '../../changes/changes.dart'; import '../../changes/changes.dart';
import '../domain/check_step_output.dart';
import 'run_check_output_view.dart';
import 'run_detail_tab_bodies.dart'; import 'run_detail_tab_bodies.dart';
import 'run_field_body.dart'; import 'run_field_body.dart';
import '../../../ui/layout/sticky_section.dart'; import '../../../ui/layout/sticky_section.dart';
@@ -216,6 +218,9 @@ class _VisitSummaryState extends State<_VisitSummary> {
); );
final open = !_closed.contains(name); final open = !_closed.contains(name);
const padding = EdgeInsets.fromLTRB(16, 0, 16, 16); const padding = EdgeInsets.fromLTRB(16, 0, 16, 16);
// A check visit's Output is its command results, not a field map.
final check = name == 'Output' ? checkStepOutput(value) : null;
final sliver = lazy && check == null;
return StickySection( return StickySection(
key: ValueKey('run-visit-section-$name'), key: ValueKey('run-visit-section-$name'),
title: name, title: name,
@@ -224,13 +229,15 @@ class _VisitSummaryState extends State<_VisitSummary> {
if (!_closed.remove(name)) _closed.add(name); if (!_closed.remove(name)) _closed.add(name);
}), }),
trailing: [copy], trailing: [copy],
body: lazy body: sliver
? null ? null
: Padding( : Padding(
padding: padding, padding: padding,
child: RunFieldBody(value: value, empty: empty), child: check != null
? RunCheckOutputView(output: check)
: RunFieldBody(value: value, empty: empty),
), ),
sliverBody: lazy sliverBody: sliver
? SliverPadding( ? SliverPadding(
padding: padding, padding: padding,
sliver: RunFieldSliver(value: value, empty: empty), sliver: RunFieldSliver(value: value, empty: empty),
@@ -1,4 +1,5 @@
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
import '../domain/check_step_output.dart';
import 'run_detail_visit_export.dart'; import 'run_detail_visit_export.dart';
import 'run_detail_visit_recorded.dart'; import 'run_detail_visit_recorded.dart';
@@ -18,6 +19,10 @@ const String visitSessionNoIdentity =
'Runtime error: this model stage has no recorded session identity.'; 'Runtime error: this model stage has no recorded session identity.';
const String visitSessionNone = 'This visit has no harness session.'; const String visitSessionNone = 'This visit has no harness session.';
/// A check stage runs commands, never a model, so it has no session at all.
const String visitSessionCheck =
'A check stage runs commands without a model; it has no harness session.';
/// An export that exists but cannot be resolved through the configured server. /// An export that exists but cannot be resolved through the configured server.
const String visitSessionEndpointMissing = const String visitSessionEndpointMissing =
'Set the server URL in Settings to open the session.'; 'Set the server URL in Settings to open the session.';
@@ -94,6 +99,7 @@ String _noSessionMessage(JsonMap step) {
if (status == 'canceled' || status == 'interrupted') { if (status == 'canceled' || status == 'interrupted') {
return visitSessionStopped; return visitSessionStopped;
} }
if (checkStepOutput(step['output']) != null) return visitSessionCheck;
final model = final model =
recordedText(step['provider']) != null || recordedText(step['provider']) != null ||
recordedText(step['model']) != null; recordedText(step['model']) != null;
@@ -13,7 +13,7 @@ const _expected = {
'budget': 'budget':
'The workspace snapshot ran out of text budget, so no diff text was ' 'The workspace snapshot ran out of text budget, so no diff text was '
'recorded.', 'recorded.',
'lines': 'The change is over 5,000 lines, so no diff text was recorded.', 'lines': 'The change is over 20,000 lines, so no diff text was recorded.',
'evidence_size': 'evidence_size':
"This visit's recorded changes reached their size limit, so this patch " "This visit's recorded changes reached their size limit, so this patch "
'was dropped.', 'was dropped.',
@@ -24,6 +24,15 @@ const _expected = {
"The file's content at stage start couldn't be recovered from Git, so no " "The file's content at stage start couldn't be recovered from Git, so no "
'diff was recorded.', 'diff was recorded.',
'binary': 'Binary file; only its metadata was recorded.', 'binary': 'Binary file; only its metadata was recorded.',
'symlink': 'Symbolic link; only the change to its target was recorded.',
'protected':
'A protected file (secrets, credentials or a database); its content is '
'never read, only that it changed.',
'generated':
'A lockfile, minified or generated file; it is listed without a diff.',
'large':
'This file is too large to hash, so it was compared by size and '
'modification time only.',
}; };
FileChange _noPatch(Object? reason, {bool binary = false}) => FileChange _noPatch(Object? reason, {bool binary = false}) =>
@@ -0,0 +1,80 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/check_stage.dart';
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
import 'package:pipelines_app/features/graph/domain/stage_definition.dart';
Map<String, dynamic> _verify({Map<String, dynamic>? configs}) => {
'key': 'verify',
'type': 'check',
'configs':
configs ??
{
'command_timeout': '15m',
'timeout': '1h',
'keep_going': 'true',
'delivery': 'true',
},
'edges': {'pass': 'review', 'fail': 'implement', 'error': '#failure'},
'blocks': {'commands': 'go vet ./...\n\ngo test ./...\n'},
'prompt': '',
'output': '',
};
void main() {
test('a check stage reads its commands, one per non-blank line', () {
expect(isCheckStage(_verify()), isTrue);
expect(checkCommands(_verify()), ['go vet ./...', 'go test ./...']);
expect(isCheckStage({'type': 'model'}), isFalse);
expect(isCheckStage({'key': 'x'}), isFalse);
});
test('the delivery config marks the gate, and only on a check stage', () {
expect(isDeliveryGate(_verify()), isTrue);
expect(isDeliveryGate(_verify(configs: {'delivery': 'false'})), isFalse);
expect(isDeliveryGate(_verify(configs: {})), isFalse);
expect(
isDeliveryGate({
'type': 'model',
'configs': {'delivery': 'true'},
}),
isFalse,
);
});
test('graph nodes carry the stage type and the gate caption', () {
final nodes = graphNodes({
'stages': [
_verify(),
{
..._verify(configs: {}),
'key': 'lint',
},
{
'key': 'review',
'edges': {'success': '#'},
},
],
});
final byKey = {for (final node in nodes) node.key: node};
expect(byKey['verify']!.kindCaption, 'Delivery gate');
expect(byKey['lint']!.kindCaption, 'Check');
expect(byKey['review']!.kindCaption, isNull);
expect(byKey['#success']!.kindCaption, isNull);
});
test('a check definition lists its commands in place of a prompt', () {
final fields = stageDefinitionFields(_verify());
final byLabel = {for (final field in fields) field.label: field};
expect(byLabel['Type']!.value, 'check (delivery gate)');
final commands = byLabel['Commands']!;
expect(commands.value, 'go vet ./...\ngo test ./...');
expect(commands.monospace, isTrue);
expect(byLabel.containsKey('Prompt'), isFalse);
expect(byLabel['Command timeout']!.value, '15m');
expect(byLabel['Keep going']!.value, 'true');
expect(byLabel['Delivery gate']!.value, 'true');
expect(byLabel['Outcomes']!.value, contains('pass → review'));
expect(byLabel['Outcomes']!.value, contains('fail → implement'));
});
}
@@ -0,0 +1,81 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart';
import 'package:pipelines_app/features/graph/widgets/stage_definition_view.dart';
import 'package:pipelines_app/ui/text/monospace.dart';
Map<String, dynamic> _graph() => {
'stages': [
{
'key': 'verify',
'type': 'check',
'configs': {'delivery': 'true'},
'edges': {'pass': '#', 'fail': 'fix'},
'blocks': {'commands': 'go vet ./...\ngo test ./...'},
},
{
'key': 'fix',
'type': 'model',
'prompt': 'Fix it.',
'edges': {'success': 'verify'},
},
],
};
Widget _host(Widget child) => MaterialApp(
home: Scaffold(body: Center(child: child)),
);
void main() {
testWidgets('a check node shows its kind under its name', (tester) async {
final nodes = {for (final node in graphNodes(_graph())) node.key: node};
await tester.pumpWidget(
_host(
Column(
mainAxisSize: MainAxisSize.min,
children: [
GraphStageNode(node: nodes['verify']!, onSelected: (_) {}),
GraphStageNode(node: nodes['fix']!, onSelected: (_) {}),
],
),
),
);
expect(find.byKey(const ValueKey('graph-node-kind-verify')), findsOne);
expect(find.byKey(const ValueKey('graph-node-kind-fix')), findsNothing);
expect(find.text('Delivery gate'), findsOne);
expect(find.byIcon(Icons.verified_outlined), findsOne);
expect(find.bySemanticsLabel('verify\nDelivery gate'), findsOne);
expect(find.bySemanticsLabel('fix'), findsOne);
expect(tester.takeException(), isNull);
});
testWidgets('a check definition lists its commands in monospace', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: StageDefinitionView(
graph: _graph(),
stageKey: 'verify',
pipelineId: 1,
pipelineName: 'Demo',
version: 3,
),
),
),
);
final commands = tester.widget<SelectableText>(
find.descendant(
of: find.byKey(const ValueKey('stage-definition-Commands')),
matching: find.byType(SelectableText),
),
);
expect(commands.data, 'go vet ./...\ngo test ./...');
expect(commands.style?.fontFamily, appMonospaceFamily);
expect(find.text('check (delivery gate)'), findsOne);
expect(find.text('Prompt'), findsNothing);
});
}
@@ -0,0 +1,77 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/runs/domain/check_step_output.dart';
void main() {
test('a check output reads each command result', () {
final output = checkStepOutput({
'markdown': '# outcome\n\nfail\n',
'summary': '1 of 2 checks failed: go test ./...',
'delivery': true,
'checks': [
{
'command': 'go vet ./...',
'status': 'passed',
'exit_code': 0,
'duration_ms': 2100,
'output': '',
'truncated': false,
},
{
'command': 'go test ./...',
'status': 'failed',
'exit_code': 1,
'duration_ms': 51000,
'output': '--- FAIL',
'truncated': true,
},
{'command': 'make lint', 'status': 'not_run'},
'not a map',
],
})!;
expect(output.delivery, isTrue);
expect(output.summary, '1 of 2 checks failed: go test ./...');
expect(output.markdown, startsWith('# outcome'));
expect(output.checks, hasLength(3));
final [vet, test, lint] = output.checks;
expect(vet.status, CheckCommandStatus.passed);
expect(vet.meta, 'exit 0 · 2.1s');
expect(test.status, CheckCommandStatus.failed);
expect(test.meta, 'exit 1 · 51s');
expect(test.truncated, isTrue);
expect(lint.status, CheckCommandStatus.notRun);
expect(lint.meta, '');
expect(checkStatusLabel(lint), 'Not run');
});
test('statuses this client does not know keep their own word', () {
final output = checkStepOutput({
'checks': [
{'command': 'x', 'status': 'skipped_by_policy'},
{'command': 'y'},
{'command': 'z', 'status': 'timed_out'},
],
})!;
expect(output.checks[0].status, CheckCommandStatus.unknown);
expect(checkStatusLabel(output.checks[0]), 'skipped_by_policy');
expect(checkStatusLabel(output.checks[1]), 'Unknown status');
expect(checkStatusLabel(output.checks[2]), 'Timed out');
expect(output.delivery, isFalse);
});
test('outputs without a checks list are not check outputs', () {
expect(checkStepOutput(null), isNull);
expect(checkStepOutput('text'), isNull);
expect(checkStepOutput({'markdown': '# outcome'}), isNull);
expect(checkStepOutput({'checks': 'go test'}), isNull);
});
test('durations read compactly', () {
expect(formatCheckDuration(850), '850ms');
expect(formatCheckDuration(2000), '2s');
expect(formatCheckDuration(2100), '2.1s');
expect(formatCheckDuration(51000), '51s');
expect(formatCheckDuration(185000), '3m 05s');
expect(formatCheckDuration(3720000), '1h 02m');
});
}
@@ -0,0 +1,141 @@
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/ui/run_check_output_view.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_facts.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_sections.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_session_state.dart';
import 'package:pipelines_app/ui/text/monospace.dart';
import 'run_detail_graph_support.dart';
import 'run_detail_visit_support.dart';
/// verify (a delivery check) -> review, with one failed check visit.
JsonMap _checkRun({int repairs = 0}) => <String, dynamic>{
'id': 78,
'title': 'Check run',
'name': 'release',
'pipeline_id': 7,
'version': 4,
'status': 'succeeded',
'graph': <String, dynamic>{
'stages': <dynamic>[
<String, dynamic>{
'key': 'verify',
'type': 'check',
'configs': <String, dynamic>{'delivery': 'true'},
'edges': <String, String?>{'pass': '#', 'fail': 'verify'},
'blocks': <String, dynamic>{'commands': 'go vet ./...\ngo test ./...'},
},
],
},
'steps': <dynamic>[
<String, dynamic>{
'stage': 'verify',
'sequence': 1,
'status': 'completed',
'outcome': 'fail',
'target': 'verify',
'started_at': '2026-10-22T00:00:00Z',
'finished_at': '2026-10-22T00:01:00Z',
if (repairs > 0)
'control': <String, dynamic>{'visit': 1, 'outcome_repairs': repairs},
'output': <String, dynamic>{
'markdown': '# outcome\n\nfail\n\n# handoff\n\nFix the test.',
'summary': '1 of 2 checks failed: go test ./...',
'delivery': true,
'checks': <dynamic>[
<String, dynamic>{
'command': 'go vet ./...',
'status': 'passed',
'exit_code': 0,
'duration_ms': 2100,
'output': 'vet ok',
'truncated': false,
},
<String, dynamic>{
'command': 'go test ./...',
'status': 'failed',
'exit_code': 1,
'duration_ms': 51000,
'output': '--- FAIL: TestX',
'truncated': true,
},
],
},
},
],
};
void main() {
const platform = RunDetailTestPlatform.material;
testWidgets('a check visit shows one row per command with its output', (
tester,
) async {
await openVisit(tester, platform, run: _checkRun());
expect(find.byKey(const Key('run-check-output')), findsOneWidget);
expect(find.byKey(const Key('run-check-delivery')), findsOneWidget);
expect(find.text('1 of 2 checks failed: go test ./...'), findsOneWidget);
expect(find.text('go vet ./...'), findsOneWidget);
expect(find.text('Passed · exit 0 · 2.1s'), findsOneWidget);
expect(find.text('Failed · exit 1 · 51s'), findsOneWidget);
// The raw checks list is never shown as a `key=value` field dump.
expect(find.text('checks'), findsNothing);
// Output is collapsed until the row is expanded; then it is selectable
// monospace with the truncation note.
expect(find.text('--- FAIL: TestX'), findsNothing);
final row = find.byKey(const ValueKey('run-check-command-1'));
await tester.ensureVisible(row);
await tester.tap(find.text('go test ./...'));
await tester.pumpAndSettle();
final output = tester.widget<SelectableText>(
find.widgetWithText(SelectableText, '--- FAIL: TestX'),
);
expect(output.style?.fontFamily, appMonospaceFamily);
expect(find.text(checkOutputTruncated), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('a check visit has no model row and an honest session note', (
tester,
) async {
await openVisit(tester, platform, run: _checkRun());
expect(find.text('Provider/model'), findsNothing);
expect(find.text('fail'), findsWidgets);
await openVisitTab(tester, RunVisitSection.session);
expect(find.text(visitSessionCheck), findsOneWidget);
expect(find.text(visitSessionNoIdentity), findsNothing);
});
testWidgets('a repaired outcome is noted on the visit', (tester) async {
await openVisit(tester, platform, run: _checkRun(repairs: 1));
expect(find.byKey(const Key('run-visit-outcome-repaired')), findsOne);
expect(find.text('Outcome repaired by follow-up'), findsOneWidget);
});
testWidgets('an unrepaired visit shows no repair note', (tester) async {
await openVisit(tester, platform, run: _checkRun());
expect(find.byKey(const Key('run-visit-outcome-repaired')), findsNothing);
});
test('outcome repairs read from control, absent meaning none', () {
expect(detailVisitOutcomeRepairs({}), 0);
expect(detailVisitOutcomeRepairs({'control': 'x'}), 0);
expect(
detailVisitOutcomeRepairs({
'control': {'visit': 2},
}),
0,
);
expect(
detailVisitOutcomeRepairs({
'control': {'outcome_repairs': 2},
}),
2,
);
expect(outcomeRepairNote(2), 'Outcome repaired by follow-up (2 times)');
});
}
+27 -12
View File
@@ -30,15 +30,26 @@ includes the same evidence under each step's `file_changes` field.
conversion, `assume-unchanged`) is listed with `no_patch_reason: "baseline"`. conversion, `assume-unchanged`) is listed with `no_patch_reason: "baseline"`.
- Added/deleted files and permission changes are recorded. Renames appear as - Added/deleted files and permission changes are recorded. Renames appear as
deletion/addition. Binary changes retain metadata, not binary contents. deletion/addition. Binary changes retain metadata, not binary contents.
- Symlinks, special files, common credential/environment/key/database paths, - Common credential/environment/key/database paths and `secrets/` are protected:
`secrets/`, Git internals and `node_modules/` are excluded. This is a path-based never opened or listed. They are fingerprinted by metadata (size, mtime, mode)
only, so an untouched `.env` no longer makes a capture partial; a change to one
makes the visit `partial` (counted in `skipped`). This is a path-based
precaution, **not secret-content scanning**; ordinary source patches may contain precaution, **not secret-content scanning**; ordinary source patches may contain
sensitive text and become part of retained history. sensitive text and become part of retained history.
- Limits: 10,000 inventoried entries, 1 MiB per file and 32 MiB per snapshot of - Tool output is not stage work: untracked files below cache and dependency
retained text, 256 MiB per hashed file, five seconds per snapshot, 5,000 directories (`node_modules/`, `.git/`, `__pycache__/`, `.venv/`, `.mypy_cache/`,
combined lines per textual comparison, 64 KiB per patch and 128 KiB serialized `.pytest_cache/`, `.ruff_cache/`, `.next/`, `.dart_tool/`, `.gradle/`, ...),
file evidence per visit. Oversized, unreadable, omitted or truncated evidence untracked `*.pyc`, and untracked files below `build/`, `dist/`, `out/`,
is explicitly flagged partial. `target/` or `coverage/` where Git tracks nothing are left out of the
inventory entirely. Outside Git the cache directories are not walked.
- Symlinks are compared by their target (never followed) and listed with
`no_patch_reason: "symlink"`; a path through a symlinked directory is skipped.
- Limits: 20,000 inventoried entries, 1 MiB per file and 32 MiB per snapshot of
retained text, five seconds per snapshot, 20,000 combined lines per textual
comparison, 128 KiB per patch and 512 KiB serialized file evidence per visit.
Files over 256 MiB are compared by size, mtime and mode
(`no_patch_reason: "large"`). Unreadable, omitted or truncated evidence is
explicitly flagged partial.
- Over-budget content degrades to a listing, not silence: a text file over 1 MiB, - Over-budget content degrades to a listing, not silence: a text file over 1 MiB,
or beyond the 32 MiB snapshot budget, is still compared by SHA-256 and a change or beyond the 32 MiB snapshot budget, is still compared by SHA-256 and a change
is listed with `no_patch: true` (and `truncated`) but no patch. In a Git working is listed with `no_patch: true` (and `truncated`) but no patch. In a Git working
@@ -46,12 +57,16 @@ includes the same evidence under each step's `file_changes` field.
or past the time/file limit) is listed the same way when its or past the time/file limit) is listed the same way when its
`git status --porcelain` entry changed during the visit; a path dirty with the `git status --porcelain` entry changed during the visit; a path dirty with the
same status before and after cannot be proven changed and stays in `skipped`. same status before and after cannot be proven changed and stays in `skipped`.
Git is only read (`--no-optional-locks`); protected paths are never listed. Git is only read (`--no-optional-locks`); protected and excluded paths are
never listed.
- Each content change without a (complete) patch carries `no_patch_reason`: - Each content change without a (complete) patch carries `no_patch_reason`:
`binary`, `file_size` (text over 1 MiB), `budget` (32 MiB snapshot text `binary`, `symlink`, `large`, `generated` (lockfiles such as `go.sum` or
budget), `lines` (over 5,000 combined lines), `evidence_size` (per-visit `package-lock.json`, `*.min.js`, source maps, files below a cache directory),
retained evidence limit), `git_status` (seen only in Git status) or `baseline`. `file_size` (text over 1 MiB), `budget` (32 MiB snapshot text budget), `lines`
Binary changes stay `complete`; the others make the visit `partial`. (over 20,000 combined lines), `evidence_size` (per-visit retained evidence
limit), `git_status` (seen only in Git status) or `baseline`. `binary`,
`symlink`, `large` and `generated` changes are listed completely and stay
`complete`; the others make the visit `partial`.
- `pipelines inspect RUN_ID --json` carries a top-level `warnings` list (also - `pipelines inspect RUN_ID --json` carries a top-level `warnings` list (also
printed to stderr) naming every visit whose capture was partial or unavailable. printed to stderr) naming every visit whose capture was partial or unavailable.
- Failed/canceled stages still retain changes when execution returns. Unconfirmed - Failed/canceled stages still retain changes when execution returns. Unconfirmed
+6 -1
View File
@@ -64,7 +64,12 @@ Start from `pipelines templates` and `pipelines new NAME --template KEY`
(`research`, `task`); these fill in (`research`, `task`); these fill in
the server's provider/model. Read `references/format.md` and the server's provider/model. Read `references/format.md` and
`references/practices.md` before writing prompts. Stage names: `plan` · `references/practices.md` before writing prompts. Stage names: `plan` ·
`implement` · `review` · `ui-review` · `decide` (human) · `land`. `implement` · `verify` (check) · `review` · `ui-review` · `decide` (human) ·
`land`. A `type=check` stage runs listed shell commands on the server, no
model, and routes on `pass`/`fail`: put one before review and use one with
`delivery=true` as the landing gate rather than having a model run the suite.
Stages without `edit` must not change the workspace (the server fails the
visit); give reviewers a `permissions.shell` allow-list.
Keep prompts short and objective: what the stage should produce and any real Keep prompts short and objective: what the stage should produce and any real
constraints. The runner enforces turns, tools and limits and explains the output constraints. The runner enforces turns, tools and limits and explains the output
+3 -3
View File
@@ -9,9 +9,9 @@ request does not authorize publication, execution or deployment.
Inspect actual source and diffs, run relevant tests and record exact results. Inspect actual source and diffs, run relevant tests and record exact results.
A model summary, committed branch or successful merge is not proof of runtime A model summary, committed branch or successful merge is not proof of runtime
behavior. Missing or partial diff capture must be reported as incomplete. behavior. Missing or partial diff capture must be reported as incomplete.
With delivery=true, the stage returns a clean candidate and the server checks and With delivery=true (a model land stage on any harness, or a check stage), the
lands it, first merging a moved main and re-checking the merged tree; only a real server checks and lands the candidate, first merging a moved main and
conflict fails. Direct recovery can complete a reviewed merge without another pipeline. re-checking the merged tree; only a real conflict fails. Direct recovery can complete a reviewed merge without another pipeline.
Keep artifacts under the supplied run/stage artifact directory. Mark unverified Keep artifacts under the supplied run/stage artifact directory. Mark unverified
builds as WIP. Verify any download URL serves the real bytes before reporting it. builds as WIP. Verify any download URL serves the real bytes before reporting it.
+79 -8
View File
@@ -2,8 +2,8 @@
A definition is Markdown made only of `# stage KEY` headings and fenced blocks; A definition is Markdown made only of `# stage KEY` headings and fenced blocks;
no prose outside blocks. Blocks: `prompt`, `configs`, `tools`, `skills`, `edges`, no prose outside blocks. Blocks: `prompt`, `configs`, `tools`, `skills`, `edges`,
`checks`, `limits` (`references/control.md`), `permissions` and `notify` `checks`, `limits` (`references/control.md`), `permissions`, `notify`
(`references/notifications.md`). There are no memory, links, input or output (`references/notifications.md`) and, on check stages, `commands`. There are no memory, links, input or output
blocks; stages communicate through `output.md` (`# handoff`) and `public/`. blocks; stages communicate through `output.md` (`# handoff`) and `public/`.
Schedules are saved run configurations, never definition blocks Schedules are saved run configurations, never definition blocks
(`references/schedules.md`). (`references/schedules.md`).
@@ -102,8 +102,9 @@ evidence route to `blocked` when declared, else `error`; never fabricate a resul
(`pipelines new NAME --template KEY`) fill them in; copy those IDs into a (`pipelines new NAME --template KEY`) fill them in; copy those IDs into a
hand-written draft. Availability needs `pipelines provider-check`. hand-written draft. Availability needs `pipelines provider-check`.
- `harness=opencode|pi|claude`; omission means OpenCode (`references/harnesses.md`). - `harness=opencode|pi|claude`; omission means OpenCode (`references/harnesses.md`).
`claude` needs `provider=anthropic` and a Claude model ID, and accepts no `claude` needs `provider=anthropic` and a Claude model ID; its `permissions`
`permissions` block, `delivery=true` or run write paths. block may hold only a `shell` allow-list (no `edit` patterns or run write
paths).
- `retries` 0–100, default 2 (three attempts). Retries cover transport failures - `retries` 0–100, default 2 (three attempts). Retries cover transport failures
and timeouts; a stage with `edit`/`shell` (or no tools block) never replays and timeouts; a stage with `edit`/`shell` (or no tools block) never replays
admitted work. admitted work.
@@ -114,7 +115,10 @@ evidence route to `blocked` when declared, else `error`; never fabricate a resul
- `budget_usd`, `budget_tokens`: positive caps on reported usage, shared across - `budget_usd`, `budget_tokens`: positive caps on reported usage, shared across
attempts and visits of this stage; totals include cache reads and writes. Set attempts and visits of this stage; totals include cache reads and writes. Set
only when the user asks or a measured visit exists (`references/practices.md`). only when the user asks or a measured visit exists (`references/practices.md`).
- `delivery=true`: the landing stage's gate (below). OpenCode harness only. - `delivery=true`: the landing stage's gate (below), on any harness, or on a
check stage.
- `allow_workspace_changes=true`: lets a stage without `edit` leave file changes
in the run directory (below).
- `auto_skip=false`: disable the server skip fallback for a stage that declares a - `auto_skip=false`: disable the server skip fallback for a stage that declares a
`skipped` edge (`references/operations.md`, Server skip fallback). `skipped` edge (`references/operations.md`, Server skip fallback).
@@ -134,6 +138,20 @@ patterns) and `shell` (exact commands) arrays. It narrows declared tools; it nev
enables a missing one. Empty arrays deny; wildcards, chaining, redirects and enables a missing one. Empty arrays deny; wildcards, chaining, redirects and
traversal are rejected. With restricted edits and shell enabled, list shell too: traversal are rejected. With restricted edits and shell enabled, list shell too:
`{"edit":["README.md","plugin/*.qml"],"shell":["bash -n install.sh"]}`. `{"edit":["README.md","plugin/*.qml"],"shell":["bash -n install.sh"]}`.
On `harness=claude` only `shell` is accepted; each entry becomes a Claude Code
rule (`go test ./...` -> `Bash(go test ./...)`) and an entry ending in ` *` is a
prefix (`git diff *` -> `Bash(git diff:*)`, any arguments; claude only). Claude
Code checks each part of a chained command, and every other command is
refused. A read-only reviewer: `{"shell":["git diff *","git log *","go test ./..."]}`.
A stage whose `tools` block lacks `edit` must leave the run directory as it
found it: the server compares the workspace before and after the visit and
fails the visit (`permission denied: ... changed the workspace (added x, ...)`,
following the `error` edge) when any file changed, outside the run's artifact
directories and a harness state directory inside the workspace. Committing is
not a change; merging or generating files is. Set
`allow_workspace_changes=true` on a stage that legitimately writes (for
example a land stage that merges main itself).
Named MCP entries are an explicit allowlist for unattended Claude stages: Named MCP entries are an explicit allowlist for unattended Claude stages:
`mcp:ai-memory` allows that server's tools, while `mcp:linear/list_issues` `mcp:ai-memory` allows that server's tools, while `mcp:linear/list_issues`
@@ -190,6 +208,56 @@ A check must fail when it cannot run: validation rejects `|| true`, `|| :`,
`|| exit 0`, `|| echo`, negated file tests, `! command -v tool ||`, an `if` with no `|| exit 0`, `|| echo`, negated file tests, `! command -v tool ||`, an `if` with no
failing else, and `set +e`. Cover every language the run can change. failing else, and `set +e`. Cover every language the run can change.
## Check stages
`type=check` runs shell commands on the server, without a model, and routes on
`pass` or `fail`. Use it before review, so a reviewer never sees a red tree, and
as the landing gate instead of a model stage that runs the suite itself.
````markdown
# stage verify
```configs
type=check
command_timeout=15m
```
```commands
uv run ruff check .
uv run ty check
uv run pytest -q
```
```edges
pass -> review
fail -> implement
```
```limits
{"max_visits":3}
```
````
- `commands` (required): 1-20 lines, one `sh -c` command each, run in order
from the run directory with its workspace environment; blank and `#` lines are
ignored. The first failure stops the rest (`not_run`) unless `keep_going=true`.
Lint rejects silent guards (`|| true`) as for `checks`.
- Configs: `command_timeout` (per command, default `30m`), `timeout` (the whole
stage, default `1h`), `keep_going=true|false`, `delivery=true`. No prompt,
tools, model or skills.
- Edges: `pass` and `fail` are required and are the only outcomes besides
`error` (an infrastructure failure). A `fail` loop back needs `limits`.
- Output: the step records each command's status (`passed`, `failed`,
`timed_out`, `not_run`), exit code, duration and output (64 KB per failing
command, head and tail kept), plus a one-line summary as its verdict. Its
`# handoff` names the failing commands with the tail of their output, and the
full outputs follow, so the next stage sees exactly what failed.
- `delivery=true` makes it the landing gate: the server commits what the run
left uncommitted (run worktrees), merges a moved `main`, runs the commands in
a fresh worktree of the commit and fast-forwards `main` on `pass`. A failing
command is `fail` with `main` untouched; a gate problem (dirty checkout,
conflict, refused fast-forward) is `error`.
## Human stages ## Human stages
`type=human` pauses the run until a person picks one of its non-`error` edges `type=human` pauses the run until a person picks one of its non-`error` edges
@@ -201,14 +269,17 @@ wait survives restarts and is never killed by a stage timeout or `max_visits`.
## Land stage and delivery gate ## Land stage and delivery gate
A workflow that commits its change ends in `land`: a model stage with A workflow that commits its change ends in `land`: either a check stage with
`read`/`glob`/`grep`/`shell`, no `edit`, that commits locally. Its prompt states: `delivery=true` (above; no model, the server commits and lands), or a model
stage with `read`/`glob`/`grep`/`shell`, no `edit`, that commits locally. A model
land stage's prompt states:
1. Commit only this run's changes (server list + git status). 1. Commit only this run's changes (server list + git status).
2. Check the staged diff for unrelated work and secrets. 2. Check the staged diff for unrelated work and secrets.
3. No empty commit, push, amend or rebase. Report the hash. 3. No empty commit, push, amend or rebase. Report the hash.
With `delivery=true` and `checks` commands, after `land` succeeds the server: With `delivery=true` and `checks` commands (any harness), after `land` succeeds
the server:
commits whatever the run left uncommitted when the item is the run's own commits whatever the run left uncommitted when the item is the run's own
worktree (see "Run worktrees" below); requires the item checkout to be clean, worktree (see "Run worktrees" below); requires the item checkout to be clean,
untracked files included (the main checkout need not be: the final untracked files included (the main checkout need not be: the final
+19
View File
@@ -119,6 +119,25 @@ func TestInspectStepAndTranscriptsAndJSON(t *testing.T) {
} }
} }
func TestInspectStepListsCheckCommandsAndRepairs(t *testing.T) {
d := &protocol.RunDetail{ID: 7, Steps: []protocol.RunStep{{Sequence: 1, Stage: "verify", Status: "completed", Outcome: "fail",
Control: &protocol.ControlEvidence{OutcomeRepairs: 1},
Output: map[string]any{"markdown": "# outcome\n\nfail\n", "checks": []any{
map[string]any{"command": "go vet ./...", "status": "passed", "exit_code": float64(0), "duration_ms": float64(1200)},
map[string]any{"command": "go test ./...", "status": "failed", "exit_code": float64(1), "duration_ms": float64(51000)},
}}}}}
var out bytes.Buffer
if err := (App{Out: &out}).inspect(d, &options{step: 1}); err != nil {
t.Fatal(err)
}
text := out.String()
for _, want := range []string{"outcome repair follow-ups: 1", "passed exit 0 1.2s go vet ./...", "failed exit 1 51.0s go test ./..."} {
if !strings.Contains(text, want) {
t.Fatalf("missing %q:\n%s", want, text)
}
}
}
func TestWaitLineNamesFailingStageAndDiagnostic(t *testing.T) { func TestWaitLineNamesFailingStageAndDiagnostic(t *testing.T) {
line := waitLine(sampleRun()) line := waitLine(sampleRun())
if !strings.Contains(line, "failed at implement · go test failed") || strings.Contains(line, "long detail line") { if !strings.Contains(line, "failed at implement · go test failed") || strings.Contains(line, "long detail line") {
+14
View File
@@ -93,9 +93,23 @@ func inspectStep(d *protocol.RunDetail, sequence int, transcripts bool) (string,
if step.SessionID != "" { if step.SessionID != "" {
b.WriteString("session: " + step.SessionID + "\n") b.WriteString("session: " + step.SessionID + "\n")
} }
if step.Control != nil && step.Control.OutcomeRepairs > 0 {
fmt.Fprintf(&b, "outcome repair follow-ups: %d\n", step.Control.OutcomeRepairs)
}
if diagnostic := strings.TrimSpace(step.Diagnostic); diagnostic != "" { if diagnostic := strings.TrimSpace(step.Diagnostic); diagnostic != "" {
b.WriteString("\ndiagnostic:\n" + indent(diagnostic) + "\n") b.WriteString("\ndiagnostic:\n" + indent(diagnostic) + "\n")
} }
if checks, ok := step.Output["checks"].([]any); ok && len(checks) > 0 {
b.WriteString("\nchecks:\n")
for _, entry := range checks {
check, _ := entry.(map[string]any)
command, _ := check["command"].(string)
status, _ := check["status"].(string)
exit, _ := check["exit_code"].(float64)
duration, _ := check["duration_ms"].(float64)
fmt.Fprintf(&b, " %-9s exit %-3d %6.1fs %s\n", status, int(exit), duration/1000, command)
}
}
if markdown, ok := step.Output["markdown"].(string); ok && strings.TrimSpace(markdown) != "" { if markdown, ok := step.Output["markdown"].(string); ok && strings.TrimSpace(markdown) != "" {
b.WriteString("\noutput:\n" + indent(strings.TrimSpace(markdown)) + "\n") b.WriteString("\noutput:\n" + indent(strings.TrimSpace(markdown)) + "\n")
} else if len(step.Output) > 0 { } else if len(step.Output) > 0 {
+117
View File
@@ -0,0 +1,117 @@
package filediff
import (
"crypto/sha256"
"fmt"
"io/fs"
"path"
"strings"
)
// Policy no-patch reasons: the change is listed, completely, without a patch
// by design rather than because a capture limit ran out, so it never makes a
// capture partial.
const (
reasonSymlink = "symlink" // a symbolic link; its target is compared
reasonLarge = "large" // over the hash bound; compared by size, mtime and mode
reasonGenerated = "generated" // a lockfile, minified bundle or source map
)
// cacheDirs are tool caches, virtual environments and dependency trees. Their
// untracked files are left out of the inventory entirely (never "skipped"):
// they are regenerated by tools, not authored by a stage. Tracked files below
// them are still compared, without a patch.
var cacheDirs = map[string]bool{
"node_modules": true, "bower_components": true, ".git": true,
"__pycache__": true, ".venv": true, "venv": true, ".tox": true, ".nox": true,
".mypy_cache": true, ".pytest_cache": true, ".ruff_cache": true, ".hypothesis": true, ".eggs": true,
".next": true, ".nuxt": true, ".svelte-kit": true, ".turbo": true, ".parcel-cache": true, ".pnpm-store": true,
".dart_tool": true, ".gradle": true, ".terraform": true,
}
// buildDirs are conventional build output directories. Untracked files below
// one are left out only when Git tracks nothing there, so a new source file
// in a real `build/` source directory is still captured.
var buildDirs = map[string]bool{"build": true, "dist": true, "out": true, "target": true, "coverage": true}
// generatedNames are lockfiles: tool output whose diff is noise.
var generatedNames = map[string]bool{
"package-lock.json": true, "npm-shrinkwrap.json": true, "yarn.lock": true, "pnpm-lock.yaml": true,
"bun.lockb": true, "cargo.lock": true, "go.sum": true, "poetry.lock": true, "uv.lock": true,
"pipfile.lock": true, "gemfile.lock": true, "composer.lock": true, "pubspec.lock": true,
"flake.lock": true, "mix.lock": true, "podfile.lock": true, "packages.lock.json": true,
}
// inCacheDir reports whether any directory component of name is a cache dir.
func inCacheDir(name string) bool {
parts := strings.Split(name, "/")
for _, part := range parts[:len(parts)-1] {
if cacheDirs[part] {
return true
}
}
return false
}
// generatedFile reports a file whose diff is tool output: a lockfile, a
// minified bundle, a source map, compiled Python, or anything below a cache
// directory.
func generatedFile(name string) bool {
base := strings.ToLower(path.Base(name))
if generatedNames[base] || strings.HasSuffix(base, ".min.js") || strings.HasSuffix(base, ".min.css") ||
strings.HasSuffix(base, ".map") || strings.HasSuffix(base, ".pyc") {
return true
}
return inCacheDir(name)
}
// excludedUntracked reports an untracked path that is tool output rather than
// stage work: below a cache directory, compiled Python, or below a build
// directory where Git tracks nothing (trackedDirs holds every directory that
// contains a tracked file).
func excludedUntracked(name string, trackedDirs map[string]bool) bool {
if inCacheDir(name) || strings.HasSuffix(name, ".pyc") {
return true
}
parts := strings.Split(name, "/")
for i, part := range parts[:len(parts)-1] {
if buildDirs[part] && !trackedDirs[strings.Join(parts[:i+1], "/")] {
return true
}
}
return false
}
// trackedDirectories returns every ancestor directory of the tracked names.
func trackedDirectories(names []string) map[string]bool {
dirs := map[string]bool{}
for _, name := range names {
for dir := path.Dir(name); dir != "." && dir != "/" && !dirs[dir]; dir = path.Dir(dir) {
dirs[dir] = true
}
}
return dirs
}
// policyReason is the policy no-patch reason of a changed path, preferring
// the stage-end side (a file that became a symlink is a symlink change).
func policyReason(a file, aOK bool, b file, bOK bool) string {
if bOK && b.reason != "" {
return b.reason
}
if aOK && a.reason != "" {
return a.reason
}
return ""
}
// metaHash fingerprints a file by its metadata alone, without reading it: a
// protected (secret) file is never opened, and a huge file is not hashed.
func metaHash(info fs.FileInfo) [32]byte {
return sha256.Sum256(fmt.Appendf(nil, "meta\x00%d\x00%d\x00%o", info.Size(), info.ModTime().UnixNano(), info.Mode()))
}
// linkHash fingerprints a symbolic link by its target.
func linkHash(target string) [32]byte {
return sha256.Sum256([]byte("symlink\x00" + target))
}
+73
View File
@@ -0,0 +1,73 @@
package filediff
import (
"context"
"os"
"path/filepath"
"testing"
)
// A committed symlink no longer makes every capture partial, and a symlink a
// stage creates (a read-only reviewer's stray link) is listed.
func TestSymlinksAreComparedByTarget(t *testing.T) {
dir, git := gitRepo(t)
put(t, dir, "real.md", "skill\n")
if err := os.Symlink("real.md", filepath.Join(dir, "linked")); err != nil {
t.Fatal(err)
}
git("add", "real.md", "linked")
git("commit", "-qm", "init")
ctx := context.Background()
before := Capture(ctx, dir)
if quiet := Compare(before, Capture(ctx, dir, before)); quiet.Status != "complete" || quiet.Skipped != 0 || len(quiet.Files) != 0 {
t.Fatalf("an untouched symlink: %+v", quiet)
}
if err := os.Symlink("/etc", filepath.Join(dir, "stray")); err != nil {
t.Fatal(err)
}
changes := Compare(before, Capture(ctx, dir, before))
if changes.Status != "complete" || len(changes.Files) != 1 {
t.Fatalf("%+v", changes)
}
if f := changes.Files[0]; f.Path != "stray" || f.Kind != "added" || f.NoPatchReason != reasonSymlink || f.Truncated {
t.Fatalf("%+v", f)
}
}
func TestToolOutputIsExcludedOrListedWithoutPatch(t *testing.T) {
dir, git := gitRepo(t)
for _, name := range []string{"build/keep.sh", "go.sum", "src/a.go"} {
if err := os.MkdirAll(filepath.Join(dir, filepath.Dir(name)), 0o700); err != nil {
t.Fatal(err)
}
put(t, dir, name, "v1\n")
}
git("add", ".")
git("commit", "-qm", "init")
ctx := context.Background()
before := Capture(ctx, dir)
for _, name := range []string{"node_modules/x/index.js", "dist/app.js", "src/__pycache__/a.pyc", "build/new.sh"} {
if err := os.MkdirAll(filepath.Join(dir, filepath.Dir(name)), 0o700); err != nil {
t.Fatal(err)
}
put(t, dir, name, "generated\n")
}
put(t, dir, "go.sum", "v2\n")
put(t, dir, "src/a.go", "v2\n")
changes := Compare(before, Capture(ctx, dir, before))
got := map[string]string{}
for _, f := range changes.Files {
got[f.Path] = f.NoPatchReason
}
// Untracked caches and an untracked build directory are left out; a new
// file in a tracked build directory is stage work; a lockfile has no patch.
want := map[string]string{"build/new.sh": "", "go.sum": reasonGenerated, "src/a.go": ""}
if len(got) != len(want) || changes.Status != "complete" {
t.Fatalf("got %v (%+v)", got, changes)
}
for name, reason := range want {
if r, ok := got[name]; !ok || r != reason {
t.Fatalf("%s: got %q (%v)", name, r, got)
}
}
}
+121 -21
View File
@@ -26,12 +26,12 @@ import (
) )
const ( const (
maxFiles = 10000 maxFiles = 20000
maxFileBytes = 1 << 20 maxFileBytes = 1 << 20
maxSnapshotBytes = 32 << 20 maxSnapshotBytes = 32 << 20
maxPatchBytes = 128 << 10 maxPatchBytes = 512 << 10
maxFilePatchBytes = 64 << 10 maxFilePatchBytes = 128 << 10
maxLines = 5000 maxLines = 20000
binarySniffBytes = 8 << 10 binarySniffBytes = 8 << 10
) )
@@ -82,6 +82,12 @@ type file struct {
// already holds it, and a later capture recovers it only if the file // already holds it, and a later capture recovers it only if the file
// changed. This keeps the text budget for files Git has no baseline for. // changed. This keeps the text budget for files Git has no baseline for.
blob string blob string
// reason is a policy no-patch reason (symlink, large, generated): the
// change is listed completely, without a patch, and no content is kept.
reason string
// secret marks a protected file fingerprinted by metadata only. It is
// never read or listed; a change to it makes the capture partial.
secret bool
} }
// baseline is stage-start content recovered from Git for a changed file whose // baseline is stage-start content recovered from Git for a changed file whose
@@ -108,6 +114,9 @@ type Snapshot struct {
// the previous snapshot; missing records why one could not be recovered. // the previous snapshot; missing records why one could not be recovered.
baselines map[string]baseline baselines map[string]baseline
missing map[string]string missing map[string]string
// excluded holds untracked tool output left out of the inventory, so
// the Git-status pass does not list it either.
excluded map[string]bool
} }
// gitCommand runs git for directory with the run's directory environment // gitCommand runs git for directory with the run's directory environment
@@ -245,7 +254,7 @@ func protected(name string) bool {
if template(part) { if template(part) {
continue continue
} }
if part == ".git" || part == "secrets" || part == ".ssh" || part == ".aws" || part == ".gnupg" || part == ".kube" || part == "node_modules" { if part == ".git" || part == "secrets" || part == ".ssh" || part == ".aws" || part == ".gnupg" || part == ".kube" {
return true return true
} }
if part == ".env" || strings.HasPrefix(part, ".env.") || strings.HasSuffix(part, ".env") || strings.HasSuffix(part, ".pem") || strings.HasSuffix(part, ".key") || strings.HasSuffix(part, ".db") || strings.HasSuffix(part, ".db-wal") || strings.HasSuffix(part, ".db-shm") || strings.HasSuffix(part, ".sqlite") || strings.HasSuffix(part, ".sqlite3") || part == "auth.json" || part == "credentials.json" { if part == ".env" || strings.HasPrefix(part, ".env.") || strings.HasSuffix(part, ".env") || strings.HasSuffix(part, ".pem") || strings.HasSuffix(part, ".key") || strings.HasSuffix(part, ".db") || strings.HasSuffix(part, ".db-wal") || strings.HasSuffix(part, ".db-shm") || strings.HasSuffix(part, ".sqlite") || strings.HasSuffix(part, ".sqlite3") || part == "auth.json" || part == "credentials.json" {
@@ -278,16 +287,43 @@ func (b *boundedOutput) Write(p []byte) (int, error) {
// inventory lists the files to snapshot. Git is only read, never altered; // inventory lists the files to snapshot. Git is only read, never altered;
// the baseline is still stage-start content (see Capture and recoverBaselines). // the baseline is still stage-start content (see Capture and recoverBaselines).
func inventory(ctx context.Context, directory string, root *os.Root) ([]string, bool, error) { func inventory(ctx context.Context, directory string, root *os.Root, excluded map[string]bool) ([]string, bool, error) {
probe := gitCommand(ctx, directory, "-c", "core.fsmonitor=false", "-C", directory, "rev-parse", "--is-inside-work-tree") probe := gitCommand(ctx, directory, "-c", "core.fsmonitor=false", "-C", directory, "rev-parse", "--is-inside-work-tree")
if data, err := probe.Output(); err == nil && strings.TrimSpace(string(data)) == "true" { if data, err := probe.Output(); err == nil && strings.TrimSpace(string(data)) == "true" {
cmd := gitCommand(ctx, directory, "-c", "core.fsmonitor=false", "-C", directory, "ls-files", "--cached", "--others", "--exclude-standard", "--deduplicate", "-z", "--", ".") list := func(args ...string) ([]string, error) {
out := &boundedOutput{limit: 2 << 20} cmd := gitCommand(ctx, directory, append([]string{"-c", "core.fsmonitor=false", "-C", directory, "ls-files"}, append(args, "-z", "--", ".")...)...)
cmd.Stdout = out out := &boundedOutput{limit: 2 << 20}
if err := cmd.Run(); err != nil { cmd.Stdout = out
return nil, true, fmt.Errorf("Git file inventory unavailable") if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("Git file inventory unavailable")
}
text := strings.TrimSuffix(out.String(), "\x00")
if text == "" {
return nil, nil
}
return strings.Split(text, "\x00"), nil
} }
return strings.Split(strings.TrimSuffix(out.String(), "\x00"), "\x00"), true, nil tracked, err := list("--cached", "--deduplicate")
if err != nil {
return nil, true, err
}
untracked, err := list("--others", "--exclude-standard")
if err != nil {
return nil, true, err
}
// Untracked tool output (caches, dependency trees, untracked build
// directories) is not stage work: leave it out instead of letting it
// crowd the inventory and the budgets.
trackedDirs := trackedDirectories(tracked)
names := tracked
for _, name := range untracked {
if excludedUntracked(name, trackedDirs) {
excluded[name] = true
} else {
names = append(names, name)
}
}
return names, true, nil
} }
if ctx.Err() != nil { if ctx.Err() != nil {
return nil, false, ctx.Err() return nil, false, ctx.Err()
@@ -300,6 +336,9 @@ func inventory(ctx context.Context, directory string, root *os.Root) ([]string,
if err != nil { if err != nil {
return err return err
} }
if name != "." && entry.IsDir() && cacheDirs[entry.Name()] {
return fs.SkipDir // tool output, not stage work
}
if name != "." && protected(name) { if name != "." && protected(name) {
names = append(names, name) names = append(names, name)
if entry.IsDir() { if entry.IsDir() {
@@ -319,7 +358,7 @@ func inventory(ctx context.Context, directory string, root *os.Root) ([]string,
} }
func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snapshot { func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snapshot {
s := &Snapshot{files: map[string]file{}, skipped: map[string]bool{}} s := &Snapshot{files: map[string]file{}, skipped: map[string]bool{}, excluded: map[string]bool{}}
root, err := os.OpenRoot(directory) root, err := os.OpenRoot(directory)
if err != nil { if err != nil {
s.diagnostic = "Workspace snapshot unavailable." s.diagnostic = "Workspace snapshot unavailable."
@@ -327,7 +366,7 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
} }
defer root.Close() defer root.Close()
s.available = true s.available = true
names, git, err := inventory(ctx, directory, root) names, git, err := inventory(ctx, directory, root, s.excluded)
s.scope = "Workspace regular files" s.scope = "Workspace regular files"
if git { if git {
s.scope = "Git tracked and nonignored files in the run directory" s.scope = "Git tracked and nonignored files in the run directory"
@@ -379,12 +418,13 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
s.diagnostic = "Workspace capture reached its time/file limit." s.diagnostic = "Workspace capture reached its time/file limit."
break break
} }
if !fs.ValidPath(name) || protected(name) { if !fs.ValidPath(name) {
s.skipped[name] = true s.skipped[name] = true
continue continue
} }
// Reject symlinks in every component, including aliases to sensitive paths. // Never follow a symlink: a path through a symlinked directory is
valid := true // skipped, and a symlink itself is compared by its target only.
valid, link := true, false
parts := strings.Split(name, "/") parts := strings.Split(name, "/")
for j := range parts { for j := range parts {
info, err := root.Lstat(strings.Join(parts[:j+1], "/")) info, err := root.Lstat(strings.Join(parts[:j+1], "/"))
@@ -392,6 +432,10 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
valid = false valid = false
break break
} // tracked deletion } // tracked deletion
if err == nil && info.Mode()&os.ModeSymlink != 0 && j == len(parts)-1 {
link = true
break
}
if err != nil || info.Mode()&os.ModeSymlink != 0 { if err != nil || info.Mode()&os.ModeSymlink != 0 {
s.skipped[name] = true s.skipped[name] = true
valid = false valid = false
@@ -402,10 +446,38 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
continue continue
} }
info, err := root.Lstat(name) info, err := root.Lstat(name)
if err != nil || !info.Mode().IsRegular() || info.Size() > maxHashBytes { if err != nil {
s.skipped[name] = true s.skipped[name] = true
continue continue
} }
if protected(name) {
// A secret is never opened: its metadata shows whether it changed,
// so an untouched .env no longer makes every capture partial.
if info.IsDir() {
s.skipped[name] = true
} else {
s.files[name] = file{hash: metaHash(info), secret: true}
}
continue
}
if link {
target, err := root.Readlink(name)
if err != nil {
s.skipped[name] = true
continue
}
s.files[name] = file{hash: linkHash(target), size: int64(len(target)), mode: info.Mode().Perm(), reason: reasonSymlink}
continue
}
if !info.Mode().IsRegular() {
s.skipped[name] = true
continue
}
if info.Size() > maxHashBytes {
s.files[name] = file{hash: metaHash(info), size: info.Size(), mode: info.Mode().Perm(), reason: reasonLarge}
continue
}
generated := generatedFile(name)
f, err := root.OpenFile(name, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0) f, err := root.OpenFile(name, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0)
if err != nil { if err != nil {
s.skipped[name] = true s.skipped[name] = true
@@ -440,6 +512,9 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
// listed (without a patch) instead of being skipped unseen. // listed (without a patch) instead of being skipped unseen.
switch { switch {
case binary: case binary:
case generated:
// Tool output: compared by hash, listed without a patch.
entry.reason = reasonGenerated
case seen && p.hash == entry.hash && !p.binary: case seen && p.hash == entry.hash && !p.binary:
// Unchanged since the previous snapshot: share its representation // Unchanged since the previous snapshot: share its representation
// without spending this snapshot's budget on it again. // without spending this snapshot's budget on it again.
@@ -463,7 +538,11 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
s.skipped[name] = true s.skipped[name] = true
continue continue
} }
s.files[name] = file{hash: hash, size: opened.Size(), mode: opened.Mode().Perm(), binary: binary, hashOnly: !binary, limit: reasonFileSize} entry := file{hash: hash, size: opened.Size(), mode: opened.Mode().Perm(), binary: binary, hashOnly: !binary, limit: reasonFileSize}
if generated && !binary {
entry.hashOnly, entry.limit, entry.reason = false, "", reasonGenerated
}
s.files[name] = entry
} }
if prev != nil { if prev != nil {
s.recoverBaselines(ctx, directory, prev, used) s.recoverBaselines(ctx, directory, prev, used)
@@ -584,6 +663,14 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
result.Files = append(result.Files, change) result.Files = append(result.Files, change)
} }
listed := 0 listed := 0
secretChanges := 0
defer func() {
if secretChanges > 0 {
result.Skipped += secretChanges
result.Status = "partial"
result.Diagnostic = "A protected file (secrets, credentials, databases) changed; it is never read or listed, so this is not a complete workspace diff."
}
}()
// decided records every path the content comparison settled (changed or // decided records every path the content comparison settled (changed or
// not), so the Git-status pass below only speaks for the rest. // not), so the Git-status pass below only speaks for the rest.
decided := map[string]bool{} decided := map[string]bool{}
@@ -598,7 +685,13 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
continue continue
} }
decided[name] = true decided[name] = true
if aOK && bOK && a.hash == b.hash && a.mode == b.mode { if aOK && bOK && a.hash == b.hash && a.mode == b.mode && a.secret == b.secret {
continue
}
if a.secret || b.secret {
// A protected file changed: never listed, so the capture is honest
// about being incomplete.
secretChanges++
continue continue
} }
kind := "modified" kind := "modified"
@@ -615,6 +708,13 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
if bOK { if bOK {
change.AfterMode = fmt.Sprintf("%04o", b.mode) change.AfterMode = fmt.Sprintf("%04o", b.mode)
} }
if reason := policyReason(a, aOK, b, bOK); reason != "" {
// Listed completely by design (a symlink, a huge or generated
// file), without a patch; not a capture limit.
change.NoPatchReason = reason
add(change)
continue
}
// A clean-at-start file kept only its Git blob id; its start content // A clean-at-start file kept only its Git blob id; its start content
// comes from the after snapshot's verified Git recovery. // comes from the after snapshot's verified Git recovery.
aData, unavailable := a.data, "" aData, unavailable := a.data, ""
@@ -690,7 +790,7 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
} }
ordered := make([]string, 0, len(gitNames)) ordered := make([]string, 0, len(gitNames))
for name := range gitNames { for name := range gitNames {
if !decided[name] && fs.ValidPath(name) && !protected(name) { if !decided[name] && fs.ValidPath(name) && !protected(name) && !before.excluded[name] && !after.excluded[name] {
ordered = append(ordered, name) ordered = append(ordered, name)
} }
} }
+20 -11
View File
@@ -248,10 +248,10 @@ func TestOverBudgetChangeIsListedWithoutPatch(t *testing.T) {
} }
} }
// TestGitStatusListsUncomparableChanges proves a file the content snapshot // TestHugeFilesAreListedByMetadata proves a file above the hash bound is
// skips (here: above the hash bound) is still listed when its Git status // listed completely (by size, mtime and mode, without a patch), while a
// changes during the visit, while a protected path never is. // protected path is never listed and its change marks the capture partial.
func TestGitStatusListsUncomparableChanges(t *testing.T) { func TestHugeFilesAreListedByMetadata(t *testing.T) {
previous := maxHashBytes previous := maxHashBytes
maxHashBytes = 16 maxHashBytes = 16
defer func() { maxHashBytes = previous }() defer func() { maxHashBytes = previous }()
@@ -263,21 +263,30 @@ func TestGitStatusListsUncomparableChanges(t *testing.T) {
git("commit", "-qm", "init") git("commit", "-qm", "init")
ctx := context.Background() ctx := context.Background()
before := Capture(ctx, dir) before := Capture(ctx, dir)
put(t, dir, "big.bin", strings.Repeat("y", 64)) if quiet := Compare(before, Capture(ctx, dir, before)); quiet.Status != "complete" || quiet.Skipped != 0 {
t.Fatalf("an untouched secret and huge file made the capture %+v", quiet)
}
put(t, dir, "big.bin", strings.Repeat("y", 65))
put(t, dir, "fresh.bin", strings.Repeat("z", 64)) put(t, dir, "fresh.bin", strings.Repeat("z", 64))
put(t, dir, ".env", "A=2\n")
changes := Compare(before, Capture(ctx, dir, before)) changes := Compare(before, Capture(ctx, dir, before))
got := map[string]string{} got := map[string]string{}
for _, f := range changes.Files { for _, f := range changes.Files {
if !f.NoPatch { if f.Patch != "" || f.NoPatchReason != reasonLarge || f.Truncated {
t.Fatalf("git-listed change carries a patch: %+v", f) t.Fatalf("huge-file change: %+v", f)
} }
got[f.Path] = f.Kind got[f.Path] = f.Kind
} }
if len(got) != 2 || got["big.bin"] != "modified" || got["fresh.bin"] != "added" { if len(got) != 2 || got["big.bin"] != "modified" || got["fresh.bin"] != "added" || changes.Status != "complete" {
t.Fatalf("git status listing = %v (%+v)", got, changes) t.Fatalf("listing = %v (%+v)", got, changes)
} }
if changes.Status != "partial" || !strings.Contains(changes.Diagnostic, "without patches") { put(t, dir, ".env", "A=2\n")
changes = Compare(before, Capture(ctx, dir, before))
for _, f := range changes.Files {
if f.Path == ".env" {
t.Fatal("a protected path was listed")
}
}
if changes.Status != "partial" || !strings.Contains(changes.Diagnostic, "protected") {
t.Fatalf("status/diagnostic = %q/%q", changes.Status, changes.Diagnostic) t.Fatalf("status/diagnostic = %q/%q", changes.Status, changes.Diagnostic)
} }
} }
+89
View File
@@ -0,0 +1,89 @@
package pipeline
import (
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func checkStageSource(key, commands, configs, edges string) string {
return "# stage " + key + "\n\n```configs\ntype=check\n" + configs + "\n```\n\n```commands\n" + commands + "\n```\n\n```edges\n" + edges + "\n```\n"
}
// A check stage sits between implement and review: a red tree goes back to
// the implementer with the failing output, never to the reviewer.
func TestParseCheckStageBeforeReview(t *testing.T) {
source := lintSource(
modelStage("implement", "Make the change.", "read\nedit\nshell", "success -> verify\nerror -> #failure", "```checks\nnone: the verify stage runs the suite\n```"),
checkStageSource("verify", "go vet ./...\ngo test ./...", "command_timeout=15m", "pass -> review\nfail -> implement"),
modelStage("review", "Review the diff.", "read\nglob\ngrep", "success -> #success\nerror -> #failure", ""),
)
g, err := ParseDefinition(source)
if err != nil {
t.Fatal(err)
}
verify := g.Stages[1]
if verify.Type != stage.CheckType || verify.Blocks["commands"] != "go vet ./...\ngo test ./..." || verify.Configs["command_timeout"] != "15m" {
t.Fatalf("parsed %+v", verify)
}
if verify.Edges["error"] != "#failure" || !verify.FallbackError {
t.Fatal("check stage error edge", verify.Edges)
}
def := StageDefinition(verify)
if _, err := stage.CheckStageSpec(def); err != nil {
t.Fatal("stored definition no longer validates:", err)
}
errs, _ := Lint(g)
var rules []string
for _, finding := range errs {
rules = append(rules, finding.String())
}
// fail -> implement loops back: the existing loop rule asks for a limit.
if len(errs) != 1 || errs[0].Rule != "limits" {
t.Fatalf("lint %v", rules)
}
limited := strings.Replace(source, "```configs\ntype=check", "```limits\n{\"max_visits\":3}\n```\n\n```configs\ntype=check", 1)
if g, err = ParseDefinition(limited); err != nil {
t.Fatal(err)
}
if errs, _ := Lint(g); len(errs) != 0 {
t.Fatal(errs)
}
}
func TestCheckStageRejectsModelBlocksAndSilentGuards(t *testing.T) {
if _, err := ParseDefinition(checkStageSource("verify", "go test ./...", "model=x", "pass -> #success\nfail -> #failure")); err == nil {
t.Fatal("model config accepted on a check stage")
}
if _, err := ParseDefinition(checkStageSource("verify", "", "", "pass -> #success\nfail -> #failure")); err == nil {
t.Fatal("empty commands accepted")
}
g, err := ParseDefinition(checkStageSource("verify", "ruff check . || true", "", "pass -> #success\nfail -> #failure"))
if err != nil {
t.Fatal(err)
}
errs, _ := Lint(g)
if len(errs) != 1 || errs[0].Rule != "commands" {
t.Fatal(errs)
}
}
// A delivery check stage is the landing gate: its commands are the checks the
// server runs on the committed candidate before fast-forwarding main.
func TestCheckStageAsLandingGateSatisfiesDeliveryLint(t *testing.T) {
source := lintSource(
modelStage("implement", "Make the change; the delivery gate lands it.", "read\nedit\nshell", "success -> land\nerror -> #failure", "```checks\nnone: the land gate runs the suite\n```"),
checkStageSource("land", "go test ./...", "delivery=true", "pass -> #success\nfail -> #failure"),
)
g, err := ParseDefinition(source)
if err != nil {
t.Fatal(err)
}
if errs, _ := Lint(g); len(errs) != 0 {
t.Fatal(errs)
}
if enabled, err := stage.DeliveryEnabled(StageDefinition(g.Stages[1])); err != nil || !enabled {
t.Fatal(enabled, err)
}
}
+7
View File
@@ -90,6 +90,13 @@ func Lint(g Graph) (errs, warnings []LintFinding) {
} }
} }
} }
if stage.EffectiveType(s.Type) == stage.CheckType {
for _, line := range strings.Split(s.Blocks["commands"], "\n") {
if guard := silentGuard(line); guard != "" {
add(&errs, s, "commands", "command %q can pass without running anything (%s); a missing tool must fail the check, so remove the guard", strings.TrimSpace(line), guard)
}
}
}
if stage.EffectiveType(s.Type) == stage.HumanType { if stage.EffectiveType(s.Type) == stage.HumanType {
continue // a person bounds a human stage's loop continue // a person bounds a human stage's loop
} }
+9 -2
View File
@@ -458,6 +458,9 @@ type ControlEvidence struct {
LimitReached bool `json:"limit_reached,omitempty"` LimitReached bool `json:"limit_reached,omitempty"`
ModelTarget string `json:"model_target,omitempty"` ModelTarget string `json:"model_target,omitempty"`
Memory map[string]MemoryRead `json:"memory,omitempty"` Memory map[string]MemoryRead `json:"memory,omitempty"`
// OutcomeRepairs counts the "missing # outcome" repair follow-ups the
// server sent during this visit (0 when the first answer was valid).
OutcomeRepairs int `json:"outcome_repairs,omitempty"`
} }
// StageFileChanges is observed workspace evidence, not a model's claim of authorship. // StageFileChanges is observed workspace evidence, not a model's claim of authorship.
@@ -483,9 +486,13 @@ type FileChange struct {
NoPatch bool `json:"no_patch,omitempty"` NoPatch bool `json:"no_patch,omitempty"`
// NoPatchReason says why a content change has no (complete) patch: // NoPatchReason says why a content change has no (complete) patch:
// "binary", "file_size" (text over 1 MiB), "budget" (snapshot text budget), // "binary", "file_size" (text over 1 MiB), "budget" (snapshot text budget),
// "lines" (over 5,000 combined lines), "evidence_size" (per-visit retained // "lines" (over 20,000 combined lines), "evidence_size" (per-visit retained
// evidence limit), "git_status" (seen only in Git status) or "baseline" // evidence limit), "git_status" (seen only in Git status) or "baseline"
// (stage-start content unrecoverable). Empty when a patch was recorded. // (stage-start content unrecoverable). Policy reasons, which list the
// change completely and leave Truncated unset: "symlink" (target
// compared), "large" (over the hash bound; size/mtime/mode compared) and
// "generated" (lockfile, minified bundle, source map, cache file).
// Empty when a patch was recorded.
NoPatchReason string `json:"no_patch_reason,omitempty"` NoPatchReason string `json:"no_patch_reason,omitempty"`
BeforeMode string `json:"before_mode,omitempty"` BeforeMode string `json:"before_mode,omitempty"`
AfterMode string `json:"after_mode,omitempty"` AfterMode string `json:"after_mode,omitempty"`
+139
View File
@@ -0,0 +1,139 @@
package server
import (
"context"
"errors"
"fmt"
"os"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// errDeliveryChecksFailed marks a delivery check stage whose commands ran and
// failed on the candidate: that is the stage's fail outcome, not an error.
var errDeliveryChecksFailed = errors.New("delivery checks failed")
// runCheckStage executes a check stage. Without delivery its commands run in
// place in the run workspace. With delivery=true it is the landing gate: the
// server commits the run's leftovers, merges a moved main, runs the commands
// in a fresh candidate worktree of the commit and fast-forwards main only when
// every command passes. A failing command is the fail outcome (main is not
// touched); a gate failure (dirty checkout, conflict, refused fast-forward) is
// an error.
func (r *runner) runCheckStage(ctx context.Context, def stage.Definition, workspace string, delivery bool, landing stage.LandingAccess, runID int64) (stage.Result, error) {
spec, err := stage.CheckStageSpec(def)
if err != nil {
return stage.Result{}, err
}
if !delivery {
def.Workspace = workspace
return stage.CheckStage{}.Run(ctx, def, nil)
}
ctx, cancel := context.WithTimeout(ctx, spec.Timeout)
defer cancel()
var report stage.CheckReport
note, err := verifyDeliveryWith(ctx, workspace, landing, r.deliveryCommitMessage(runID), func(ctx context.Context, candidate string) error {
report = stage.RunCheckCommands(ctx, candidate, spec)
if report.Failed() {
return errDeliveryChecksFailed
}
return nil
})
if err != nil && !errors.Is(err, errDeliveryChecksFailed) {
return stage.Result{}, err
}
result := stage.CheckResult(def.Key, spec, report)
markdown, _ := result.Output["markdown"].(string)
gate := "Delivery gate: the checks ran on a fresh worktree of the committed item; main was not changed."
if err == nil {
gate = "Delivery gate: the checks passed on a fresh worktree of the committed item and main was fast-forwarded to it."
}
if note != "" {
gate += " " + strings.TrimPrefix(note, "delivery gate: ") + "."
}
result.Output["markdown"] = strings.Replace(markdown, "\n## Commands\n", "\n"+gate+"\n\n## Commands\n", 1)
return result, nil
}
// checkVerdict is the check stage's one-line verdict: its own summary, never
// a model's paraphrase of the command output.
func checkVerdict(output stage.Values) *protocol.StageVerdict {
summary, _ := output["summary"].(string)
if strings.TrimSpace(summary) == "" {
return nil
}
return &protocol.StageVerdict{Reason: summary, ReasonSource: protocol.VerdictReasonFallback}
}
// readOnlyViolation reports the files a stage without edit left changed in
// the run directory. Paths under the stage's artifacts directory, the run's
// shared public directory and a harness state directory that lives inside the
// workspace (for example CLAUDE_CONFIG_DIR) are the harness's or the run's own
// and are not counted. It returns "" when the stage may change files or none
// changed.
func readOnlyViolation(def stage.Definition, tools []string, explicitTools bool, changes *protocol.StageFileChanges, workspace string, ignored []string) string {
if stage.EffectiveType(def.Type) != stage.ModelType || !explicitTools || def.Configs["allow_workspace_changes"] == "true" || changes == nil {
return ""
}
for _, tool := range tools {
if tool == "edit" {
return ""
}
}
var prefixes []string
for _, dir := range ignored {
if rel, ok := workspaceRelative(workspace, dir); ok {
prefixes = append(prefixes, rel+"/")
}
}
var changed []string
for _, file := range changes.Files {
skip := false
for _, prefix := range prefixes {
if prefix == "./" || strings.HasPrefix(file.Path+"/", prefix) {
skip = true
break
}
}
if !skip {
changed = append(changed, file.Kind+" "+file.Path)
}
}
if len(changed) == 0 && changes.Omitted == 0 {
return ""
}
listed := changed
if len(listed) > 20 {
listed = append(append([]string(nil), listed[:20]...), fmt.Sprintf("and %d more", len(changed)-20))
}
if changes.Omitted > 0 {
listed = append(listed, fmt.Sprintf("%d more omitted from the capture", changes.Omitted))
}
return fmt.Sprintf("permission denied: stage %s has no edit tool but changed the workspace (%s); the visit fails. If this stage is meant to change files, add edit to its tools or set allow_workspace_changes=true", def.Key, strings.Join(listed, ", "))
}
// workspaceEnv is the environment a command in workspace runs with: the run's
// directory environment when one applies, else the server's.
func workspaceEnv(ctx context.Context, workspace string) []string {
if env := workenv.CommandEnv(ctx, workspace); env != nil {
return env
}
return os.Environ()
}
// workspaceRelative returns dir relative to workspace when dir is inside it.
func workspaceRelative(workspace, dir string) (string, bool) {
workspace = strings.TrimSuffix(workspace, "/")
dir = strings.TrimSuffix(dir, "/")
if workspace == "" || dir == "" {
return "", false
}
if dir == workspace {
return ".", true
}
rel, ok := strings.CutPrefix(dir, workspace+"/")
return rel, ok && rel != ""
}
+205
View File
@@ -0,0 +1,205 @@
package server
import (
"context"
"os"
"path/filepath"
"strings"
"sync/atomic"
"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"
)
func checkModelStage(key, tools, edges, configs string) string {
return "# stage " + key + "\n\n```prompt\nDo the work.\n```\n\n```tools\n" + tools + "\n```\n\n```edges\n" + edges + "\n```\n\n```configs\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n" + configs + "\n```\n\n"
}
func checkTypeStage(key, commands, edges, configs string) string {
return "# stage " + key + "\n\n```limits\n{\"max_visits\":3}\n```\n\n```configs\ntype=check\n" + configs + "\n```\n\n```commands\n" + commands + "\n```\n\n```edges\n" + edges + "\n```\n\n"
}
func startSource(t *testing.T, ctx context.Context, source, workspace string, execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error)) (*protocol.RunDetail, *pipeline.Store) {
t.Helper()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "runner.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { store.Close() })
if _, err := store.Submit(ctx, "check", source); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
r.execute = execute
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: t.Name(), Workspace: workspace, Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, err := store.GetRun(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
return detail, store
}
// A failing check sends the run back to the implementer with the failing
// output in its input; the reviewer only runs once the tree is green.
func TestCheckStageRoutesFailureOutputBackToTheImplementer(t *testing.T) {
ctx := context.Background()
workspace := t.TempDir()
source := checkModelStage("implement", "read\nedit\nshell", "success -> verify\nerror -> #failure", "") +
checkTypeStage("verify", "echo checking\ntest -f fixed || { echo 'FAIL: fixed is missing' >&2; exit 4; }", "pass -> review\nfail -> implement", "") +
checkModelStage("review", "read\nglob\ngrep", "success -> #success\nerror -> #failure", "")
var visits atomic.Int32
var secondInput string
detail, _ := startSource(t, ctx, source, workspace, func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == "implement" {
if visits.Add(1) == 2 {
data, _ := os.ReadFile(def.Turn.Input)
secondInput = string(data)
if err := os.WriteFile(filepath.Join(workspace, "fixed"), []byte("yes\n"), 0o600); err != nil {
return stage.Result{}, err
}
}
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "done"}}, nil
})
if detail.Status != "succeeded" {
t.Fatalf("run %s: %s %+v", detail.Status, detail.Diagnostic, detail.Steps)
}
var stages []string
for _, step := range detail.Steps {
stages = append(stages, step.Stage+":"+step.Outcome)
}
if got := strings.Join(stages, " "); got != "implement:success verify:fail implement:success verify:pass review:success" {
t.Fatal(got)
}
for _, want := range []string{"1 of 2 checks failed", "exit code 4", "FAIL: fixed is missing"} {
if !strings.Contains(secondInput, want) {
t.Fatalf("implementer input lacks %q:\n%s", want, secondInput)
}
}
failed := detail.Steps[1]
if failed.Verdict == nil || !strings.HasPrefix(failed.Verdict.Reason, "1 of 2 checks failed") {
t.Fatalf("verdict %+v", failed.Verdict)
}
checks, _ := failed.Output["checks"].([]any)
if len(checks) != 2 || failed.Provider != "" || failed.SessionID != "" {
t.Fatalf("check step %+v", failed)
}
}
// A delivery check stage is the landing gate: the run's uncommitted work is
// committed, the commands run on a fresh candidate and main fast-forwards;
// a failing command is the fail outcome and leaves main alone.
func TestDeliveryCheckStageLandsOnlyAGreenCandidate(t *testing.T) {
for _, test := range []struct {
name, command, status string
landed bool
}{
{"pass", "test -f work", "succeeded", true},
{"fail", "test -f absent", "failed", false},
} {
t.Run(test.name, func(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
main := filepath.Join(root, "main")
runGit(t, root, "init", "-b", "main", main)
runGit(t, main, "config", "user.email", "test@example.invalid")
runGit(t, main, "config", "user.name", "test")
if err := os.WriteFile(filepath.Join(main, "README"), []byte("base\n"), 0o600); err != nil {
t.Fatal(err)
}
runGit(t, main, "add", "README")
runGit(t, main, "commit", "-m", "base")
item := filepath.Join(root, "item")
runGit(t, main, "worktree", "add", "-b", "item", item)
if err := os.WriteFile(filepath.Join(item, "work"), []byte("change\n"), 0o600); err != nil {
t.Fatal(err)
}
runGit(t, item, "add", "work")
runGit(t, item, "commit", "-m", "work")
before := runGitOutput(t, main, "rev-parse", "HEAD")
source := checkTypeStage("land", test.command, "pass -> #success\nfail -> #failure", "delivery=true")
detail, _ := startSource(t, ctx, source, item, nil)
if detail.Status != test.status || len(detail.Steps) != 1 {
t.Fatalf("run %s %q %+v", detail.Status, detail.Diagnostic, detail.Steps)
}
step := detail.Steps[0]
markdown, _ := step.Output["markdown"].(string)
if !strings.Contains(markdown, "Delivery gate") || step.Output["delivery"] != true {
t.Fatalf("gate evidence missing: %q", markdown)
}
landed := runGitOutput(t, main, "rev-parse", "HEAD") == runGitOutput(t, item, "rev-parse", "HEAD")
if landed != test.landed || (!test.landed && runGitOutput(t, main, "rev-parse", "HEAD") != before) {
t.Fatalf("landed = %v, want %v", landed, test.landed)
}
})
}
}
// A stage without edit that changes the workspace fails its visit and names
// the files; allow_workspace_changes=true opts a stage out.
func TestReadOnlyStageThatChangesFilesFails(t *testing.T) {
ctx := context.Background()
for _, test := range []struct {
name, configs, status string
}{
{"enforced", "", "failed"},
{"allowed", "allow_workspace_changes=true", "succeeded"},
} {
t.Run(test.name, func(t *testing.T) {
workspace := t.TempDir()
if err := os.WriteFile(filepath.Join(workspace, "main.go"), []byte("package main\n"), 0o600); err != nil {
t.Fatal(err)
}
source := checkModelStage("review", "read\nglob\ngrep\nshell", "success -> #success\nerror -> #failure", test.configs)
detail, _ := startSource(t, ctx, source, workspace, func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
if err := os.Symlink("/etc", filepath.Join(workspace, "stray-link")); err != nil {
return stage.Result{}, err
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "looks fine"}}, nil
})
if detail.Status != test.status {
t.Fatalf("run %s %q", detail.Status, detail.Diagnostic)
}
if test.status == "failed" {
diagnostic := detail.Steps[0].Diagnostic
if !strings.Contains(diagnostic, "permission denied") || !strings.Contains(diagnostic, "added stray-link") || !strings.Contains(diagnostic, "allow_workspace_changes") {
t.Fatal(diagnostic)
}
}
})
}
}
func TestReadOnlyViolationIgnoresHarnessAndRunDirectories(t *testing.T) {
def := stage.Definition{Key: "review", Type: stage.ModelType, Configs: map[string]string{}}
changes := &protocol.StageFileChanges{Files: []protocol.FileChange{
{Path: ".claude-profile/.claude.json", Kind: "modified"},
{Path: "artifacts/x/out.md", Kind: "added"},
}}
ignored := []string{"/w/.claude-profile", "/w/artifacts/x"}
if v := readOnlyViolation(def, []string{"read", "shell"}, true, changes, "/w", ignored); v != "" {
t.Fatal(v)
}
changes.Files = append(changes.Files, protocol.FileChange{Path: "src/a.go", Kind: "modified"})
if v := readOnlyViolation(def, []string{"read", "shell"}, true, changes, "/w", ignored); !strings.Contains(v, "modified src/a.go") || strings.Contains(v, ".claude.json") {
t.Fatal(v)
}
for name, ok := range map[string]bool{
"edit tool": readOnlyViolation(def, []string{"edit"}, true, changes, "/w", nil) == "",
"no tools block (legacy bundle)": readOnlyViolation(def, nil, false, changes, "/w", nil) == "",
} {
if !ok {
t.Fatal(name, "was enforced")
}
}
}
+17 -8
View File
@@ -43,6 +43,20 @@ const deliveryCleanupTimeout = 10 * time.Second
// own `merge --ff-only`, which refuses without touching anything when a local // own `merge --ff-only`, which refuses without touching anything when a local
// change or untracked file would be overwritten. // change or untracked file would be overwritten.
func verifyDelivery(ctx context.Context, workspace string, access stage.LandingAccess, checks []string, commitMessage string) (string, error) { func verifyDelivery(ctx context.Context, workspace string, access stage.LandingAccess, checks []string, commitMessage string) (string, error) {
return verifyDeliveryWith(ctx, workspace, access, commitMessage, func(ctx context.Context, candidate string) error {
for _, check := range checks {
if err := runDeliveryCheck(ctx, candidate, check); err != nil {
return err
}
}
return nil
})
}
// verifyDeliveryWith is verifyDelivery with the candidate checks supplied as
// a function of the fresh candidate worktree: a check stage records each
// command's result there instead of stopping at the first error.
func verifyDeliveryWith(ctx context.Context, workspace string, access stage.LandingAccess, commitMessage string, check func(context.Context, string) error) (string, error) {
lock, err := acquireDeliveryLock(ctx, access.LockPath) lock, err := acquireDeliveryLock(ctx, access.LockPath)
if err != nil { if err != nil {
return "", err return "", err
@@ -82,7 +96,7 @@ func verifyDelivery(ctx context.Context, workspace string, access stage.LandingA
note = fmt.Sprintf("delivery gate: canonical main moved to %s; merged it into item %s as %s and re-ran checks on the merged tree", shortCommit(mainHead), shortCommit(itemHead), shortCommit(merged)) note = fmt.Sprintf("delivery gate: canonical main moved to %s; merged it into item %s as %s and re-ran checks on the merged tree", shortCommit(mainHead), shortCommit(itemHead), shortCommit(merged))
itemHead = merged itemHead = merged
} }
if err := runDeliveryCandidate(ctx, workspace, itemHead, checks); err != nil { if err := runDeliveryCandidate(ctx, workspace, itemHead, check); err != nil {
if note != "" { if note != "" {
return note, fmt.Errorf("%s; %w", note, err) return note, fmt.Errorf("%s; %w", note, err)
} }
@@ -199,7 +213,7 @@ func acquireDeliveryLock(ctx context.Context, path string) (*os.File, error) {
} }
} }
func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, checks []string) error { func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, check func(context.Context, string) error) error {
candidate, err := os.MkdirTemp(filepath.Dir(workspace), ".pipelines-delivery-") candidate, err := os.MkdirTemp(filepath.Dir(workspace), ".pipelines-delivery-")
if err != nil { if err != nil {
return fmt.Errorf("create delivery candidate: %w", err) return fmt.Errorf("create delivery candidate: %w", err)
@@ -212,12 +226,7 @@ func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, check
return fmt.Errorf("create delivery candidate: %w: %s", err, strings.TrimSpace(string(output))) return fmt.Errorf("create delivery candidate: %w: %s", err, strings.TrimSpace(string(output)))
} }
defer cleanupDeliveryCandidate(workspace, candidate) defer cleanupDeliveryCandidate(workspace, candidate)
for _, check := range checks { return check(ctx, candidate)
if err := runDeliveryCheck(ctx, candidate, check); err != nil {
return err
}
}
return nil
} }
// cleanupDeliveryCandidate always uses its own bounded context: the stage context // cleanupDeliveryCandidate always uses its own bounded context: the stage context
+5 -2
View File
@@ -597,7 +597,10 @@ esac
runStage := func(name, tools string) (status, sessions, diagnostic string) { runStage := func(name, tools string) (status, sessions, diagnostic string) {
t.Helper() t.Helper()
workspace := t.TempDir() workspace := t.TempDir()
script := strings.ReplaceAll(scriptTemplate, "@STATE@", workspace) // The fake harness keeps its counters outside the workspace: a read-only
// stage must leave the run directory unchanged.
state := t.TempDir()
script := strings.ReplaceAll(scriptTemplate, "@STATE@", state)
if err := os.WriteFile(executable, []byte(script), 0700); err != nil { if err := os.WriteFile(executable, []byte(script), 0700); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -623,7 +626,7 @@ esac
if len(detail.Steps) > 0 { if len(detail.Steps) > 0 {
diagnostic = detail.Steps[0].Diagnostic diagnostic = detail.Steps[0].Diagnostic
} }
if data, err := os.ReadFile(filepath.Join(workspace, "sessions")); err == nil { if data, err := os.ReadFile(filepath.Join(state, "sessions")); err == nil {
sessions = strings.TrimSpace(string(data)) sessions = strings.TrimSpace(string(data))
} }
return detail.Status, sessions, diagnostic return detail.Status, sessions, diagnostic
+32 -4
View File
@@ -2193,6 +2193,8 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
budgetBefore = budgets[key].Snapshot() budgetBefore = budgets[key].Snapshot()
stageCtx = stage.WithBudget(stageCtx, budgets[key]) stageCtx = stage.WithBudget(stageCtx, budgets[key])
} }
repairs := &stage.RepairCounter{}
stageCtx = stage.WithRepairCounter(stageCtx, repairs)
snapshotCtx, snapshotCancel := context.WithTimeout(ctx, 5*time.Second) snapshotCtx, snapshotCancel := context.WithTimeout(ctx, 5*time.Second)
before := filediff.Capture(snapshotCtx, workspace) before := filediff.Capture(snapshotCtx, workspace)
snapshotCancel() snapshotCancel()
@@ -2209,7 +2211,11 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
err = ctx.Err() err = ctx.Err()
return return
} }
if r.execute != nil { if stage.EffectiveType(def.Type) == stage.CheckType {
// The server runs a check stage's commands itself, in the run
// workspace or, for delivery, in a fresh candidate worktree.
result, err = r.runCheckStage(stageCtx, def, workspace, delivery, landing, id)
} else if r.execute != nil {
timeout, _ := stage.StageTimeout(def) timeout, _ := stage.StageTimeout(def)
executeCtx, cancel := context.WithTimeout(stageCtx, timeout) executeCtx, cancel := context.WithTimeout(stageCtx, timeout)
defer cancel() defer cancel()
@@ -2383,7 +2389,26 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
step.Output = stage.Values{"error": err.Error(), "stage": key, "input": input} step.Output = stage.Values{"error": err.Error(), "stage": key, "input": input}
} }
} }
if err == nil && delivery && result.Outcome == "success" { if err == nil {
// A stage without edit must leave the run directory as it found it;
// a shell is not a licence to write (allow_workspace_changes opts out).
ignored := append([]string{artifactsDir, visitTurn.PublicDir}, stage.HarnessStateDirs(workspaceEnv(stageCtx, workspace))...)
if violation := readOnlyViolation(def, tools, explicitTools, changes, workspace, ignored); violation != "" {
err = errors.New(violation)
log.Printf("run %d stage %s #%d: %s", id, key, sequence, violation)
step.Status = "failed"
step.Diagnostic = violation
step.Outcome = "error"
step.Output = stage.Values{"error": violation, "stage": key, "input": input}
if len(result.Output) > 0 {
step.Output["salvage"] = result.Output
}
}
}
if err == nil && stage.EffectiveType(def.Type) == stage.CheckType {
step.Verdict = checkVerdict(result.Output)
}
if err == nil && delivery && stage.EffectiveType(def.Type) == stage.ModelType && result.Outcome == "success" {
checks, checksErr := stage.DeliveryChecks(def) checks, checksErr := stage.DeliveryChecks(def)
if checksErr != nil { if checksErr != nil {
err = checksErr err = checksErr
@@ -2427,7 +2452,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CleanupUnconfirmed: true}, false) r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CleanupUnconfirmed: true}, false)
return return
} }
step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads} step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads, OutcomeRepairs: repairs.Count()}
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 { if err == nil && selected.Limits != nil && state.visits[key] >= maxVisits {
for _, outcome := range selected.Limits.On { for _, outcome := range selected.Limits.On {
if outcome == step.Outcome { if outcome == step.Outcome {
@@ -2474,7 +2502,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
// markdown body, which the field-map summariser reads as untrusted data and // markdown body, which the field-map summariser reads as untrusted data and
// answers with an invented rationale; those steps get the honest read-time // answers with an invented rationale; those steps get the honest read-time
// fallback instead. // fallback instead.
if r.verdict != nil && !turnOutputOnly(step.Output) { if r.verdict != nil && !turnOutputOnly(step.Output) && step.Verdict == nil {
reasonCtx, reasonCancel := context.WithTimeout(context.Background(), summarise.DefaultTimeout) reasonCtx, reasonCancel := context.WithTimeout(context.Background(), summarise.DefaultTimeout)
if line := r.verdict(reasonCtx, step.Output); line != "" && line != summarise.NoSummary { if line := r.verdict(reasonCtx, step.Output); line != "" && line != summarise.NoSummary {
step.Verdict = &protocol.StageVerdict{Reason: line, ReasonSource: protocol.VerdictReasonModel} step.Verdict = &protocol.StageVerdict{Reason: line, ReasonSource: protocol.VerdictReasonModel}
+413
View File
@@ -0,0 +1,413 @@
package stage
import (
"bytes"
"context"
"errors"
"fmt"
"os/exec"
"strconv"
"strings"
"syscall"
"time"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// CheckType is a stage the server runs itself: a list of shell commands in the
// run's workspace, no model. Its outcome is pass or fail, so a red tree can be
// routed back to the implementer (with the failing output as the handoff)
// before a reviewer or a landing stage ever sees it.
const CheckType = "check"
// Check outcomes. error stays the infrastructure-failure route, as for every
// stage type.
const (
CheckPass = "pass"
CheckFail = "fail"
)
// Per-command check statuses recorded on the step output.
const (
CheckStatusPassed = "passed"
CheckStatusFailed = "failed"
CheckStatusTimedOut = "timed_out"
CheckStatusNotRun = "not_run"
)
const (
maxCheckCommands = 20
maxCheckCommandBytes = 4096
defaultCommandTimeout = 30 * time.Minute
maxCheckOutputBytes = 64 << 10 // retained per failed command (head and tail)
maxPassedOutputBytes = 2 << 10 // retained per passing command (tail)
checkHandoffTailBytes = 1500 // per failed command in the handoff
checkOutputHeadBytes = 16 << 10
checkProcessWaitDelay = 5 * time.Second
checkFailureHandoffMax = 3
)
// CheckSpec is a validated check stage.
type CheckSpec struct {
Commands []string
CommandTimeout time.Duration
Timeout time.Duration
KeepGoing bool
Delivery bool
}
// CheckCommandResult is one command's recorded result (step output "checks").
type CheckCommandResult struct {
Command string `json:"command"`
Status string `json:"status"`
ExitCode int `json:"exit_code"`
DurationMS int64 `json:"duration_ms"`
Output string `json:"output,omitempty"`
Truncated bool `json:"truncated,omitempty"`
}
// CheckReport is the result of running a check stage's commands once.
type CheckReport struct {
Commands []CheckCommandResult
}
// Failed reports whether any command did not pass.
func (r CheckReport) Failed() bool {
for _, c := range r.Commands {
if c.Status != CheckStatusPassed {
return true
}
}
return false
}
type CheckStage struct{}
var _ Stage = CheckStage{}
func (CheckStage) Validate(def Definition) error {
_, err := CheckStageSpec(def)
return err
}
// CheckStageSpec validates a check stage definition and returns its settings.
func CheckStageSpec(def Definition) (CheckSpec, error) {
if EffectiveType(def.Type) != CheckType {
return CheckSpec{}, fmt.Errorf("expected check stage")
}
for name := range def.Blocks {
switch name {
case "configs", "edges", "output", "commands":
case "skills":
return CheckSpec{}, errSkillsModelOnly("check")
case "prompt", "tools", "permissions", "checks":
return CheckSpec{}, fmt.Errorf("check stages run their commands block on the server, without a model; remove the %s block", name)
default:
return CheckSpec{}, fmt.Errorf("unexpected block %q for check stage", name)
}
}
commands, err := CheckCommands(def.Blocks["commands"])
if err != nil {
return CheckSpec{}, err
}
spec := CheckSpec{Commands: commands, CommandTimeout: defaultCommandTimeout}
for key, value := range def.Configs {
switch key {
case "timeout":
case "command_timeout":
duration, err := time.ParseDuration(value)
if err != nil || duration <= 0 {
return CheckSpec{}, fmt.Errorf("command_timeout must be a positive duration, such as 10m")
}
spec.CommandTimeout = duration
case "keep_going":
if value != "true" && value != "false" {
return CheckSpec{}, fmt.Errorf("keep_going must be true or false")
}
spec.KeepGoing = value == "true"
case "delivery":
if value != "true" {
return CheckSpec{}, fmt.Errorf("delivery must be true when set")
}
spec.Delivery = true
default:
return CheckSpec{}, fmt.Errorf("unknown check config %q (use timeout, command_timeout, keep_going or delivery)", key)
}
}
if spec.Timeout, err = StageTimeout(def); err != nil {
return CheckSpec{}, err
}
for _, outcome := range []string{CheckPass, CheckFail} {
if def.Edges[outcome] == "" {
return CheckSpec{}, fmt.Errorf("check stage requires %s and %s edges", CheckPass, CheckFail)
}
}
for outcome := range def.Edges {
if outcome != CheckPass && outcome != CheckFail && outcome != "error" {
return CheckSpec{}, fmt.Errorf("check stage outcomes are %s, %s and error; remove the %s edge", CheckPass, CheckFail, outcome)
}
}
return spec, nil
}
// CheckCommands parses a commands block: one shell command per line; blank
// lines and lines starting with # are ignored.
func CheckCommands(text string) ([]string, error) {
var commands []string
for _, line := range strings.Split(text, "\n") {
command := strings.TrimSpace(line)
if command == "" || strings.HasPrefix(command, "#") {
continue
}
if len(command) > maxCheckCommandBytes {
return nil, fmt.Errorf("check command exceeds %d bytes", maxCheckCommandBytes)
}
if !utf8.ValidString(command) || strings.ContainsRune(command, 0) {
return nil, fmt.Errorf("check commands must be UTF-8 text")
}
commands = append(commands, command)
}
if len(commands) == 0 || len(commands) > maxCheckCommands {
return nil, fmt.Errorf("check stage requires a commands block with 1 to %d commands, one per line", maxCheckCommands)
}
return commands, nil
}
// Run executes the commands in place in def.Workspace. The runner calls
// RunCheckCommands directly for a delivery check (in a fresh candidate
// worktree); this is the in-place path.
func (CheckStage) Run(ctx context.Context, def Definition, _ Values) (Result, error) {
spec, err := CheckStageSpec(def)
if err != nil {
return Result{}, err
}
if strings.TrimSpace(def.Workspace) == "" {
return Result{}, fmt.Errorf("check stage has no workspace")
}
ctx, cancel := context.WithTimeout(ctx, spec.Timeout)
defer cancel()
report := RunCheckCommands(ctx, def.Workspace, spec)
if err := ctx.Err(); err != nil && !report.Failed() {
return Result{}, err
}
return CheckResult(def.Key, spec, report), nil
}
// RunCheckCommands runs every command with `sh -c` from directory, in order,
// with the directory's workspace environment. It stops at the first failure
// unless KeepGoing; later commands are recorded as not_run.
func RunCheckCommands(ctx context.Context, directory string, spec CheckSpec) CheckReport {
report := CheckReport{}
stop := false
for _, command := range spec.Commands {
if stop || ctx.Err() != nil {
report.Commands = append(report.Commands, CheckCommandResult{Command: command, Status: CheckStatusNotRun, ExitCode: -1})
continue
}
result := runCheckCommand(ctx, directory, command, spec.CommandTimeout)
report.Commands = append(report.Commands, result)
if result.Status != CheckStatusPassed && !spec.KeepGoing {
stop = true
}
}
return report
}
func runCheckCommand(ctx context.Context, directory, command string, timeout time.Duration) CheckCommandResult {
commandCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
cmd := exec.CommandContext(commandCtx, "sh", "-c", command)
cmd.Dir = directory
cmd.Env = workenv.CommandEnv(ctx, directory)
// A test suite starts children; a timeout kills the whole process group,
// and WaitDelay bounds a child that keeps the output pipes open.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
if cmd.Process != nil {
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
return nil
}
cmd.WaitDelay = checkProcessWaitDelay
output := &headTailBuffer{head: checkOutputHeadBytes, limit: maxCheckOutputBytes}
cmd.Stdout = output
cmd.Stderr = output
started := time.Now()
err := cmd.Run()
result := CheckCommandResult{Command: command, DurationMS: time.Since(started).Milliseconds()}
result.Output, result.Truncated = output.String()
var exit *exec.ExitError
switch {
case err == nil:
result.Status = CheckStatusPassed
case commandCtx.Err() != nil:
result.Status = CheckStatusTimedOut
result.ExitCode = -1
if ctx.Err() != nil {
result.Output = strings.TrimRight(result.Output+"\n[stopped: the stage timeout or cancellation ended the command]", "\n")
} else {
result.Output = strings.TrimRight(result.Output+"\n[stopped: command_timeout "+timeout.String()+" reached]", "\n")
}
case errors.As(err, &exit):
result.Status = CheckStatusFailed
result.ExitCode = exit.ExitCode()
default:
result.Status = CheckStatusFailed
result.ExitCode = -1
result.Output = strings.TrimSpace(result.Output + "\n" + err.Error())
}
if result.Status == CheckStatusPassed && len(result.Output) > maxPassedOutputBytes {
cut := len(result.Output) - maxPassedOutputBytes
for cut < len(result.Output) && !utf8.RuneStart(result.Output[cut]) {
cut++
}
result.Output = "[... earlier output omitted ...]\n" + result.Output[cut:]
result.Truncated = true
}
return result
}
// CheckResult renders a report as the stage result: outcome pass or fail, the
// output.md-style markdown later stages read (handoff first, then every
// command's output), a one-line summary and the structured per-command list.
func CheckResult(key string, spec CheckSpec, report CheckReport) Result {
outcome := CheckPass
if report.Failed() {
outcome = CheckFail
}
summary := CheckSummary(report)
var b strings.Builder
b.WriteString("# outcome\n\n" + outcome + "\n\n# handoff\n\n" + summary + "\n")
failures := 0
for _, c := range report.Commands {
if c.Status != CheckStatusFailed && c.Status != CheckStatusTimedOut {
continue
}
failures++
if failures > checkFailureHandoffMax {
b.WriteString("\nMore failures are listed below.\n")
break
}
fmt.Fprintf(&b, "\n`%s` %s:\n\n~~~\n%s\n~~~\n", c.Command, checkStatusPhrase(c), tailText(c.Output, checkHandoffTailBytes))
}
if outcome == CheckFail {
b.WriteString("\nFix the cause; the server reruns these checks.\n")
}
b.WriteString("\n## Commands\n")
for _, c := range report.Commands {
fmt.Fprintf(&b, "\n### `%s`: %s\n", c.Command, checkStatusPhrase(c))
if c.Status == CheckStatusNotRun {
continue
}
if strings.TrimSpace(c.Output) == "" {
b.WriteString("\n(no output)\n")
continue
}
fmt.Fprintf(&b, "\n~~~\n%s\n~~~\n", c.Output)
}
checks := make([]any, 0, len(report.Commands))
for _, c := range report.Commands {
checks = append(checks, map[string]any{
"command": c.Command, "status": c.Status, "exit_code": c.ExitCode,
"duration_ms": c.DurationMS, "output": c.Output, "truncated": c.Truncated,
})
}
output := Values{"markdown": b.String(), "summary": summary, "checks": checks}
if spec.Delivery {
output["delivery"] = true
}
return Result{Outcome: outcome, Output: output}
}
// CheckSummary is the one-line verdict for a report.
func CheckSummary(report CheckReport) string {
total := len(report.Commands)
var failed []string
for _, c := range report.Commands {
if c.Status == CheckStatusFailed || c.Status == CheckStatusTimedOut {
failed = append(failed, c.Command)
}
}
if len(failed) == 0 {
if total == 1 {
return "1 check passed."
}
return strconv.Itoa(total) + " checks passed."
}
line := fmt.Sprintf("%d of %d checks failed: %s", len(failed), total, strings.Join(failed, "; "))
if len(line) > 180 {
line = strings.ToValidUTF8(line[:180], "") + "…"
}
return line
}
func checkStatusPhrase(c CheckCommandResult) string {
duration := (time.Duration(c.DurationMS) * time.Millisecond).Round(100 * time.Millisecond)
switch c.Status {
case CheckStatusPassed:
return "passed (" + duration.String() + ")"
case CheckStatusTimedOut:
return "timed out (" + duration.String() + ")"
case CheckStatusNotRun:
return "not run (an earlier check failed)"
default:
return fmt.Sprintf("failed with exit code %d (%s)", c.ExitCode, duration)
}
}
func tailText(text string, limit int) string {
text = strings.TrimSpace(text)
if len(text) <= limit {
if text == "" {
return "(no output)"
}
return text
}
cut := len(text) - limit
for cut < len(text) && !utf8.RuneStart(text[cut]) {
cut++
}
return "[...]\n" + text[cut:]
}
// headTailBuffer keeps the first head bytes and the last limit-head bytes of a
// stream: compiler errors come first, test summaries last.
type headTailBuffer struct {
head, limit int
first bytes.Buffer
tail []byte
dropped int64
}
func (b *headTailBuffer) Write(p []byte) (int, error) {
n := len(p)
if room := b.head - b.first.Len(); room > 0 {
take := min(room, len(p))
b.first.Write(p[:take])
p = p[take:]
}
if len(p) == 0 {
return n, nil
}
keep := b.limit - b.head
b.tail = append(b.tail, p...)
if over := len(b.tail) - keep; over > 0 {
b.dropped += int64(over)
b.tail = append(b.tail[:0], b.tail[over:]...)
}
return n, nil
}
// String returns the retained text and whether anything was dropped.
func (b *headTailBuffer) String() (string, bool) {
if b.dropped == 0 {
return strings.ToValidUTF8(strings.TrimRight(b.first.String()+string(b.tail), "\n"), "\uFFFD"), false
}
tail := b.tail
for len(tail) > 0 && !utf8.RuneStart(tail[0]) {
tail = tail[1:]
}
text := b.first.String() + fmt.Sprintf("\n[... %d bytes omitted ...]\n", b.dropped) + string(tail)
return strings.ToValidUTF8(strings.TrimRight(text, "\n"), "\uFFFD"), true
}
+159
View File
@@ -0,0 +1,159 @@
package stage
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func checkDefinition(t *testing.T, commands string, configs map[string]string) Definition {
t.Helper()
if configs == nil {
configs = map[string]string{}
}
return Definition{Key: "verify", Type: CheckType, Workspace: t.TempDir(),
Blocks: map[string]string{"commands": commands, "configs": "type=check", "edges": "x"},
Configs: configs,
Edges: map[string]string{"pass": "review", "fail": "implement", "error": "#failure"}}
}
func TestCheckStageValidation(t *testing.T) {
def := checkDefinition(t, "# lint first\ngo vet ./...\n\ngo test ./...", map[string]string{"command_timeout": "5m", "keep_going": "true", "timeout": "20m", "delivery": "true"})
spec, err := CheckStageSpec(def)
if err != nil {
t.Fatal(err)
}
if len(spec.Commands) != 2 || spec.CommandTimeout != 5*time.Minute || spec.Timeout != 20*time.Minute || !spec.KeepGoing || !spec.Delivery {
t.Fatalf("spec %+v", spec)
}
if err := DefaultRegistry().Validate(def); err != nil {
t.Fatal("registry:", err)
}
if enabled, err := DeliveryEnabled(def); err != nil || !enabled {
t.Fatal("delivery check", enabled, err)
}
for name, change := range map[string]func(*Definition){
"no commands": func(d *Definition) { d.Blocks["commands"] = "# only a comment\n" },
"too many": func(d *Definition) { d.Blocks["commands"] = strings.Repeat("true\n", 21) },
"prompt block": func(d *Definition) { d.Blocks["prompt"] = "Run the tests." },
"tools block": func(d *Definition) { d.Blocks["tools"] = "shell" },
"skills block": func(d *Definition) { d.Blocks["skills"] = "x" },
"unknown config": func(d *Definition) { d.Configs["model"] = "x" },
"bad timeout": func(d *Definition) { d.Configs["command_timeout"] = "soon" },
"bad keep_going": func(d *Definition) { d.Configs["keep_going"] = "yes" },
"bad delivery": func(d *Definition) { d.Configs["delivery"] = "false" },
"missing fail": func(d *Definition) { delete(d.Edges, "fail") },
"missing pass": func(d *Definition) { delete(d.Edges, "pass") },
"success outcome": func(d *Definition) { d.Edges["success"] = "#success" },
} {
t.Run(name, func(t *testing.T) {
copy := def
copy.Blocks, copy.Configs, copy.Edges = map[string]string{}, map[string]string{}, map[string]string{}
for k, v := range def.Blocks {
copy.Blocks[k] = v
}
for k, v := range def.Configs {
copy.Configs[k] = v
}
for k, v := range def.Edges {
copy.Edges[k] = v
}
change(&copy)
if err := (CheckStage{}).Validate(copy); err == nil {
t.Fatal("accepted")
}
})
}
}
func TestCheckStageRunsCommandsInTheWorkspace(t *testing.T) {
def := checkDefinition(t, "pwd > where.txt\necho all good", nil)
result, err := DefaultRegistry().Run(context.Background(), def, Values{})
if err != nil {
t.Fatal(err)
}
if result.Outcome != CheckPass {
t.Fatalf("outcome %q: %v", result.Outcome, result.Output)
}
where, _ := os.ReadFile(filepath.Join(def.Workspace, "where.txt"))
real, _ := filepath.EvalSymlinks(def.Workspace)
if got := strings.TrimSpace(string(where)); got != def.Workspace && got != real {
t.Fatalf("ran in %q, want %q", got, def.Workspace)
}
if result.Output["summary"] != "2 checks passed." {
t.Fatal("summary", result.Output["summary"])
}
checks := result.Output["checks"].([]any)
if len(checks) != 2 || checks[1].(map[string]any)["output"] != "all good" {
t.Fatalf("checks %v", checks)
}
}
func TestCheckStageFailureIsTheHandoff(t *testing.T) {
def := checkDefinition(t, "echo compiling\necho 'FAIL: TestParse expected 2' >&2; exit 3\necho never", nil)
result, err := (CheckStage{}).Run(context.Background(), def, nil)
if err != nil {
t.Fatal(err)
}
if result.Outcome != CheckFail {
t.Fatalf("outcome %q", result.Outcome)
}
markdown := result.Output["markdown"].(string)
handoff := markdown[strings.Index(markdown, "# handoff"):strings.Index(markdown, "## Commands")]
for _, want := range []string{"1 of 3 checks failed", "exit code 3", "FAIL: TestParse expected 2"} {
if !strings.Contains(handoff, want) {
t.Fatalf("handoff lacks %q:\n%s", want, handoff)
}
}
if !strings.HasPrefix(markdown, "# outcome\n\nfail\n") {
t.Fatalf("markdown does not start with the outcome:\n%s", markdown)
}
checks := result.Output["checks"].([]any)
if checks[2].(map[string]any)["status"] != CheckStatusNotRun {
t.Fatal("a later check ran after a failure", checks[2])
}
// keep_going runs every command and reports each failure.
def.Configs["keep_going"] = "true"
def.Blocks["commands"] = "exit 1\nexit 2\ntrue"
result, _ = (CheckStage{}).Run(context.Background(), def, nil)
if result.Output["summary"] != "2 of 3 checks failed: exit 1; exit 2" {
t.Fatal(result.Output["summary"])
}
}
func TestCheckStageCommandTimeoutKillsTheProcessGroup(t *testing.T) {
def := checkDefinition(t, "sleep 30 & echo started; wait", map[string]string{"command_timeout": "300ms"})
started := time.Now()
result, err := (CheckStage{}).Run(context.Background(), def, nil)
if err != nil {
t.Fatal(err)
}
if time.Since(started) > 10*time.Second {
t.Fatal("timeout did not stop the command", time.Since(started))
}
check := result.Output["checks"].([]any)[0].(map[string]any)
if result.Outcome != CheckFail || check["status"] != CheckStatusTimedOut || !strings.Contains(check["output"].(string), "command_timeout") {
t.Fatalf("result %v", check)
}
}
func TestCheckOutputIsBoundedHeadAndTail(t *testing.T) {
buffer := &headTailBuffer{head: 10, limit: 30}
for i := 0; i < 100; i++ {
_, _ = buffer.Write([]byte("0123456789"))
}
_, _ = buffer.Write([]byte("THE-END"))
text, truncated := buffer.String()
if !truncated || !strings.HasPrefix(text, "0123456789") || !strings.HasSuffix(text, "THE-END") || len(text) > 80 {
t.Fatalf("%v %q", truncated, text)
}
def := checkDefinition(t, "head -c 300000 /dev/zero | tr '\\0' x; echo; echo TAIL; exit 1", nil)
result, _ := (CheckStage{}).Run(context.Background(), def, nil)
check := result.Output["checks"].([]any)[0].(map[string]any)
if output := check["output"].(string); len(output) > maxCheckOutputBytes+200 || !strings.HasSuffix(output, "TAIL") || check["truncated"] != true {
t.Fatalf("output %d bytes, truncated %v", len(output), check["truncated"])
}
}
+31 -5
View File
@@ -131,7 +131,10 @@ func claudeMCPAllowRules(tools []string) ([]string, error) {
// approved only below the run directory and the stage's artifacts directory; // approved only below the run directory and the stage's artifacts directory;
// everything else a declared tool does not need approval for stays denied by // everything else a declared tool does not need approval for stays denied by
// dontAsk. // dontAsk.
func claudeAllowRules(tools []string, directory, artifactsDir string) []string { //
// A non-nil shell allow-list replaces the bare Bash rule with one Bash(...)
// rule per permitted command, so any other command is refused.
func claudeAllowRules(tools []string, directory, artifactsDir string, shell []string) []string {
rules := []string{} rules := []string{}
edit := false edit := false
for _, tool := range tools { for _, tool := range tools {
@@ -139,6 +142,12 @@ func claudeAllowRules(tools []string, directory, artifactsDir string) []string {
case "Edit": case "Edit":
edit = true edit = true
case "Write": case "Write":
case "Bash":
if shell != nil {
rules = append(rules, claudeShellRules(shell)...)
} else {
rules = append(rules, tool)
}
default: default:
rules = append(rules, tool) rules = append(rules, tool)
} }
@@ -160,7 +169,7 @@ func (c *ClaudeStageClient) args(config ModelConfig, tools []string, effort stri
// skills block) may be loaded. A skill only adds instructions; the declared // skills block) may be loaded. A skill only adds instructions; the declared
// tools and their rules still bound what the session can do. // tools and their rules still bound what the session can do.
tools = append(append([]string(nil), tools...), "Skill") tools = append(append([]string(nil), tools...), "Skill")
rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir) rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir, c.Policy.Shell)
args := []string{"-p", "--output-format", "stream-json", "--verbose", args := []string{"-p", "--output-format", "stream-json", "--verbose",
"--model", config.Model, "--model", config.Model,
"--permission-mode", "dontAsk", "--permission-mode", "dontAsk",
@@ -212,10 +221,11 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
if effort == "none" || effort == "minimal" { if effort == "none" || effort == "minimal" {
return "", fmt.Errorf("the claude harness supports reasoning_effort low, medium, high, xhigh or max") return "", fmt.Errorf("the claude harness supports reasoning_effort low, medium, high, xhigh or max")
} }
if len(c.WritePaths) > 0 || c.Policy.Edit != nil || c.Policy.Shell != nil { if len(c.WritePaths) > 0 || c.Policy.Edit != nil {
// The other harnesses enforce these narrower scopes themselves. Claude // The other harnesses enforce these narrower scopes themselves. Claude
// Code's rule syntax is not audited for them, so refuse, never widen. // Code's edit-path rules are not audited for them, so refuse, never
return "", fmt.Errorf("the claude harness cannot enforce a permissions block or a narrowed write scope; use the opencode harness for this stage") // widen. A shell allow-list is enforced with Bash(...) rules.
return "", fmt.Errorf("the claude harness cannot enforce permissions.edit or a narrowed write scope; use the opencode harness for this stage")
} }
tools, err := claudeTools(c.Tools) tools, err := claudeTools(c.Tools)
if err != nil { if err != nil {
@@ -272,6 +282,11 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
} }
owned = true owned = true
} }
if c.Policy.Shell != nil {
// The allow-list is enforced by Bash(...) rules; say it up front so the
// session does not spend turns on refused commands.
prompt += "\nPermitted shell commands (a trailing * allows any arguments; anything else is refused): " + strings.Join(c.Policy.Shell, "; ")
}
if text, err = c.run(ctx, env, c.args(config, tools, effort, false), config.Model, prompt); err != nil { if text, err = c.run(ctx, env, c.args(config, tools, effort, false), config.Model, prompt); err != nil {
return "", err return "", err
} }
@@ -327,6 +342,17 @@ func claudeStageEnvironment(inherited []string, artifactsDir string) []string {
// claudeConfigDir is the Claude Code configuration directory the stage's CLI // claudeConfigDir is the Claude Code configuration directory the stage's CLI
// will use: the environment's CLAUDE_CONFIG_DIR, else $HOME/.claude. // will use: the environment's CLAUDE_CONFIG_DIR, else $HOME/.claude.
// HarnessStateDirs are directories a harness itself writes during a visit
// (Claude Code's config directory: session state, caches) for the given
// environment. When one lives inside the run directory its changes are the
// harness's, not the stage's.
func HarnessStateDirs(env []string) []string {
if dir := claudeConfigDir(env); dir != "" {
return []string{filepath.Clean(dir)}
}
return nil
}
func claudeConfigDir(env []string) string { func claudeConfigDir(env []string) string {
lookup := func(name string) string { lookup := func(name string) string {
for i := len(env) - 1; i >= 0; i-- { for i := len(env) - 1; i >= 0; i-- {
+78 -8
View File
@@ -228,6 +228,74 @@ func TestClaudeStageDeclaredToolsAreTheOnlyTools(t *testing.T) {
} }
} }
// A shell allow-list replaces the bare Bash rule: only the listed commands
// (exact, or a prefix with any arguments) are approved under dontAsk.
func TestClaudeStageShellAllowListMapsToBashRules(t *testing.T) {
client, root, _ := fakeClaudeClient(t, "success")
client.Tools = []string{"read", "shell"}
client.Policy.Shell = []string{"go test ./...", "git diff *"}
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
t.Fatal(err)
}
calls := fakeClaudeArgs(t, root)
if len(calls) != 1 {
t.Fatal(calls)
}
args := calls[0]
for _, want := range []string{"Read,Bash,Skill", "Bash(go test ./...)", "Bash(git diff:*)"} {
if !slices.Contains(args, want) {
t.Fatalf("missing %q in args %q", want, args)
}
}
if slices.Contains(args, "Bash") {
t.Fatalf("a bare Bash rule approves every command: %q", args)
}
prompt, _ := os.ReadFile(filepath.Join(root, "prompt"))
if !strings.Contains(string(prompt), "Permitted shell commands") || !strings.Contains(string(prompt), "git diff *") {
t.Fatalf("prompt does not name the allow-list: %q", prompt)
}
// An empty list approves no command at all.
client2, root2, _ := fakeClaudeClient(t, "success")
client2.Tools = []string{"shell"}
client2.Policy.Shell = []string{}
if _, err := client2.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
t.Fatal(err)
}
for _, arg := range fakeClaudeArgs(t, root2)[0] {
if strings.HasPrefix(arg, "Bash") && arg != "Bash,Skill" {
t.Fatalf("empty allow-list approved %q", arg)
}
}
}
func TestClaudeStagePermissionsValidation(t *testing.T) {
def := func(permissions string) Definition {
return Definition{Key: "review", Type: ModelType,
Blocks: map[string]string{"prompt": "Review.", "configs": "x", "tools": "read\nshell", "permissions": permissions},
Configs: map[string]string{"harness": "claude", "provider": "anthropic", "model": "claude-haiku-5-5"},
Edges: map[string]string{"success": "#success"}}
}
if _, err := (ModelStage{}).Spec(def(`{"shell":["git diff *","go test ./..."]}`)); err != nil {
t.Fatal("shell allow-list rejected:", err)
}
for name, permissions := range map[string]string{
"edit": `{"edit":["a.go"],"shell":[]}`,
"chaining": `{"shell":["go test && rm x"]}`,
"mid star": `{"shell":["git * diff"]}`,
"parentheses": `{"shell":["echo (x)"]}`,
} {
if _, err := (ModelStage{}).Spec(def(permissions)); err == nil {
t.Fatal(name, "accepted")
}
}
// Prefix entries are claude-only: other harnesses enforce exact commands.
opencode := def(`{"shell":["git diff *"]}`)
opencode.Configs = map[string]string{"provider": "opencode-go", "model": "deepseek-v4.1-flash"}
if _, err := (ModelStage{}).Spec(opencode); err == nil || !strings.Contains(err.Error(), "claude harness") {
t.Fatal("opencode prefix permission:", err)
}
}
func TestClaudeStageNamedMCPToolsAreAllowlistedSeparately(t *testing.T) { func TestClaudeStageNamedMCPToolsAreAllowlistedSeparately(t *testing.T) {
client, root, _ := fakeClaudeClient(t, "success") client, root, _ := fakeClaudeClient(t, "success")
client.Tools = []string{"read", "mcp:ai-memory", "mcp:linear/list_issues"} client.Tools = []string{"read", "mcp:ai-memory", "mcp:linear/list_issues"}
@@ -254,12 +322,11 @@ func TestClaudeStageNamedMCPToolsAreAllowlistedSeparately(t *testing.T) {
func TestClaudeStageRefusesWhatItCannotEnforce(t *testing.T) { func TestClaudeStageRefusesWhatItCannotEnforce(t *testing.T) {
for name, change := range map[string]func(*ClaudeStageClient, *ModelConfig){ for name, change := range map[string]func(*ClaudeStageClient, *ModelConfig){
"write paths": func(c *ClaudeStageClient, _ *ModelConfig) { c.WritePaths = []string{"app"} }, "write paths": func(c *ClaudeStageClient, _ *ModelConfig) { c.WritePaths = []string{"app"} },
"edit permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Edit = []string{"app/**"} }, "edit permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Edit = []string{"app/**"} },
"shell permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Shell = []string{"go test"} }, "unknown tool": func(c *ClaudeStageClient, _ *ModelConfig) { c.Tools = []string{"browser"} },
"unknown tool": func(c *ClaudeStageClient, _ *ModelConfig) { c.Tools = []string{"browser"} }, "other provider": func(_ *ClaudeStageClient, m *ModelConfig) { m.Provider = "opencode-go" },
"other provider": func(_ *ClaudeStageClient, m *ModelConfig) { m.Provider = "opencode-go" }, "no reasoning": func(_ *ClaudeStageClient, m *ModelConfig) { m.ReasoningEffort = "none" },
"no reasoning": func(_ *ClaudeStageClient, m *ModelConfig) { m.ReasoningEffort = "none" },
} { } {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
client, root, active := fakeClaudeClient(t, "success") client, root, active := fakeClaudeClient(t, "success")
@@ -326,7 +393,8 @@ func TestClaudeStageBudgetAccounting(t *testing.T) {
func TestClaudeStageOutcomeRepairResumesTheSameSession(t *testing.T) { func TestClaudeStageOutcomeRepairResumesTheSameSession(t *testing.T) {
client, root, _ := fakeClaudeClient(t, "repair") client, root, _ := fakeClaudeClient(t, "repair")
budget := NewBudget(0, 1000) budget := NewBudget(0, 1000)
ctx := withOutputRepair(context.Background(), []string{"error", "success"}) counter := &RepairCounter{}
ctx := withOutputRepair(WithRepairCounter(context.Background(), counter), []string{"error", "success"})
text, err := client.Generate(ctx, claudeConfig(budget), "task") text, err := client.Generate(ctx, claudeConfig(budget), "task")
if err != nil || !strings.HasPrefix(text, "# outcome\nsuccess\n") || !strings.Contains(text, "Report kept.") { if err != nil || !strings.HasPrefix(text, "# outcome\nsuccess\n") || !strings.Contains(text, "Report kept.") {
t.Fatalf("%q %v", text, err) t.Fatalf("%q %v", text, err)
@@ -339,6 +407,9 @@ func TestClaudeStageOutcomeRepairResumesTheSameSession(t *testing.T) {
if budget.Snapshot().UsedTokens != 34 { if budget.Snapshot().UsedTokens != 34 {
t.Fatalf("usage %+v", budget.Snapshot()) t.Fatalf("usage %+v", budget.Snapshot())
} }
if counter.Count() != 1 {
t.Fatalf("repair follow-ups counted %d, want 1", counter.Count())
}
} }
func TestClaudeStageTimeoutStopsTheProcessGroup(t *testing.T) { func TestClaudeStageTimeoutStopsTheProcessGroup(t *testing.T) {
@@ -395,7 +466,6 @@ func TestClaudeHarnessValidation(t *testing.T) {
"unknown harness": definition(map[string]string{"harness": "codex", "provider": "anthropic", "model": "claude-haiku-5-5"}, nil), "unknown harness": definition(map[string]string{"harness": "codex", "provider": "anthropic", "model": "claude-haiku-5-5"}, nil),
"capitalised": definition(map[string]string{"harness": "Claude", "provider": "anthropic", "model": "claude-haiku-5-5"}, nil), "capitalised": definition(map[string]string{"harness": "Claude", "provider": "anthropic", "model": "claude-haiku-5-5"}, nil),
"other provider": definition(claude(map[string]string{"provider": "opencode-go"}), nil), "other provider": definition(claude(map[string]string{"provider": "opencode-go"}), nil),
"delivery": definition(claude(map[string]string{"delivery": "true"}), nil),
"permissions block": definition(claude(nil), map[string]string{"permissions": `{"edit":["app/**"]}`}), "permissions block": definition(claude(nil), map[string]string{"permissions": `{"edit":["app/**"]}`}),
"no reasoning": definition(claude(map[string]string{"reasoning_effort": "none"}), nil), "no reasoning": definition(claude(map[string]string{"reasoning_effort": "none"}), nil),
} { } {
+7 -5
View File
@@ -84,7 +84,7 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
} }
for key := range def.Configs { for key := range def.Configs {
switch key { switch key {
case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip": case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip", "allow_workspace_changes":
default: default:
return ModelSpec{}, fmt.Errorf("unknown config %q", key) return ModelSpec{}, fmt.Errorf("unknown config %q", key)
} }
@@ -111,8 +111,10 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
if value := def.Configs["auto_skip"]; value != "" && value != "true" && value != "false" { if value := def.Configs["auto_skip"]; value != "" && value != "true" && value != "false" {
return ModelSpec{}, fmt.Errorf("auto_skip must be true or false") return ModelSpec{}, fmt.Errorf("auto_skip must be true or false")
} }
if def.Configs["delivery"] == "true" && backend != "opencode" { // allow_workspace_changes=true lets a stage without edit leave file changes
return ModelSpec{}, fmt.Errorf("delivery is supported only by the opencode harness") // in the run directory; by default the runner fails such a visit.
if value := def.Configs["allow_workspace_changes"]; value != "" && value != "true" && value != "false" {
return ModelSpec{}, fmt.Errorf("allow_workspace_changes must be true or false")
} }
if err := ValidateChecksBlock(def); err != nil { if err := ValidateChecksBlock(def); err != nil {
return ModelSpec{}, err return ModelSpec{}, err
@@ -143,8 +145,8 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
if _, err := claudeTools(tools); err != nil { if _, err := claudeTools(tools); err != nil {
return ModelSpec{}, err return ModelSpec{}, err
} }
if _, present := def.Blocks["permissions"]; present { if err := claudePermissionsSupported(def); err != nil {
return ModelSpec{}, fmt.Errorf("the claude harness cannot enforce a permissions block; use the opencode harness for this stage") return ModelSpec{}, err
} }
if effort == "none" || effort == "minimal" { if effort == "none" || effort == "minimal" {
return ModelSpec{}, fmt.Errorf("the claude harness supports reasoning_effort low, medium, high, xhigh or max") return ModelSpec{}, fmt.Errorf("the claude harness supports reasoning_effort low, medium, high, xhigh or max")
+30 -2
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"errors" "errors"
"strings" "strings"
"sync/atomic"
"git.a-wan.net/alan/pipelines/internal/turn" "git.a-wan.net/alan/pipelines/internal/turn"
) )
@@ -13,14 +14,38 @@ import (
// message in the same session asking only for the outcome, instead of failing // message in the same session asking only for the outcome, instead of failing
// a stage whose admitted work a full retry would repeat. The outcome is always // a stage whose admitted work a full retry would repeat. The outcome is always
// stated by the model; the server never infers one from prose. // stated by the model; the server never infers one from prose.
type outputRepair struct{ outcomes []string } type outputRepair struct {
outcomes []string
counter *RepairCounter
}
type outputRepairKey struct{} type outputRepairKey struct{}
type repairCounterKey struct{}
// RepairCounter counts the outcome repair follow-ups sent during one visit
// (across its attempts). The runner records the count on the step.
type RepairCounter struct{ n atomic.Int32 }
// Count is the number of follow-ups sent so far.
func (c *RepairCounter) Count() int {
if c == nil {
return 0
}
return int(c.n.Load())
}
// WithRepairCounter makes every outcome repair follow-up under ctx increment
// counter.
func WithRepairCounter(ctx context.Context, counter *RepairCounter) context.Context {
return context.WithValue(ctx, repairCounterKey{}, counter)
}
// withOutputRepair lets a model client repair a missing or invalid outcome // withOutputRepair lets a model client repair a missing or invalid outcome
// for the given declared outcomes while its session is still open. // for the given declared outcomes while its session is still open.
func withOutputRepair(ctx context.Context, outcomes []string) context.Context { func withOutputRepair(ctx context.Context, outcomes []string) context.Context {
return context.WithValue(ctx, outputRepairKey{}, &outputRepair{outcomes: outcomes}) counter, _ := ctx.Value(repairCounterKey{}).(*RepairCounter)
return context.WithValue(ctx, outputRepairKey{}, &outputRepair{outcomes: outcomes, counter: counter})
} }
// outputRepairFrom returns the attempt's repair, or nil when none applies. // outputRepairFrom returns the attempt's repair, or nil when none applies.
@@ -40,6 +65,9 @@ func (r *outputRepair) followUp(text string) (string, bool) {
if !errors.Is(err, turn.ErrMissingOutcome) && !errors.Is(err, turn.ErrOutcomeNotAllowed) && !errors.Is(err, turn.ErrDuplicateOutcome) { if !errors.Is(err, turn.ErrMissingOutcome) && !errors.Is(err, turn.ErrOutcomeNotAllowed) && !errors.Is(err, turn.ErrDuplicateOutcome) {
return "", false return "", false
} }
if r.counter != nil {
r.counter.n.Add(1)
}
allowed := strings.Join(r.outcomes, ", ") allowed := strings.Join(r.outcomes, ", ")
return "Your final message has no valid `# outcome` section. Do not redo any work or repeat your report; the server keeps it. " + return "Your final message has no valid `# outcome` section. Do not redo any work or repeat your report; the server keeps it. " +
outputShape(r.outcomes) + " Reply with only these two lines:\n\n# outcome\n<one of: " + allowed + ">\n", true outputShape(r.outcomes) + " Reply with only these two lines:\n\n# outcome\n<one of: " + allowed + ">\n", true
+52 -2
View File
@@ -77,9 +77,17 @@ func StagePermissions(def Definition) (ToolPolicy, error) {
seen[pattern] = true seen[pattern] = true
} }
seen = map[string]bool{} seen = map[string]bool{}
claude := def.Configs["harness"] == ClaudeBackend
for _, command := range policy.Shell { for _, command := range policy.Shell {
if command == "" || strings.TrimSpace(command) != command || strings.ContainsAny(command, "*?;|&<>`$\r\n\\") { exact, prefix := ShellPermissionPrefix(command)
return ToolPolicy{}, fmt.Errorf("shell permissions must be exact commands without wildcards, chaining, redirects, or expansion") if prefix && !claude {
return ToolPolicy{}, fmt.Errorf("shell prefix permissions (%q) are supported only by the claude harness; list exact commands", command)
}
if exact == "" || strings.TrimSpace(exact) != exact || strings.ContainsAny(exact, "*?;|&<>`$\r\n\\") {
return ToolPolicy{}, fmt.Errorf("shell permissions must be exact commands (or, on the claude harness, a command prefix ending in \" *\") without other wildcards, chaining, redirects, or expansion")
}
if claude && strings.ContainsAny(exact, "()") {
return ToolPolicy{}, fmt.Errorf("claude shell permissions cannot contain parentheses")
} }
if seen[command] { if seen[command] {
return ToolPolicy{}, fmt.Errorf("duplicate shell permission") return ToolPolicy{}, fmt.Errorf("duplicate shell permission")
@@ -92,3 +100,45 @@ func StagePermissions(def Definition) (ToolPolicy, error) {
} }
return *policy, nil return *policy, nil
} }
// ShellPermissionPrefix splits a permissions.shell entry. "go test *" is a
// prefix entry (the command with any arguments; claude harness only) and
// returns ("go test", true); any other entry is an exact command.
func ShellPermissionPrefix(entry string) (string, bool) {
if base, ok := strings.CutSuffix(entry, " *"); ok {
return base, true
}
return entry, false
}
// claudePermissionsSupported limits a claude stage's permissions block to a
// shell allow-list (mapped to Bash(...) rules). Claude Code's edit-path rules
// are not audited, so restricted edits stay with the other harnesses.
func claudePermissionsSupported(def Definition) error {
if _, present := def.Blocks["permissions"]; !present {
return nil
}
policy, err := StagePermissions(def)
if err != nil {
return err
}
if policy.Edit != nil {
return fmt.Errorf("the claude harness enforces only permissions.shell; remove permissions.edit or use the opencode harness for this stage")
}
return nil
}
// claudeShellRules maps a shell allow-list to Claude Code permission rules:
// an exact command to Bash(command) and a prefix entry to Bash(prefix:*).
// Claude Code checks each part of a chained command against the rules.
func claudeShellRules(shell []string) []string {
rules := make([]string, 0, len(shell))
for _, entry := range shell {
if base, prefix := ShellPermissionPrefix(entry); prefix {
rules = append(rules, "Bash("+base+":*)")
} else {
rules = append(rules, "Bash("+base+")")
}
}
return rules
}
+5 -2
View File
@@ -33,7 +33,10 @@ type Definition struct {
// ArtifactsDir is the per-run/step directory the runtime created for this // ArtifactsDir is the per-run/step directory the runtime created for this
// visit; empty when the runner did not provide one (for example in tests). // visit; empty when the runner did not provide one (for example in tests).
ArtifactsDir string ArtifactsDir string
Turn TurnPaths // Workspace is the run directory (runtime-provided); a check stage runs
// its commands there.
Workspace string
Turn TurnPaths
// Skills is the visit's materialised skills block (runtime-provided, like // Skills is the visit's materialised skills block (runtime-provided, like
// ArtifactsDir); nil when the stage configures none or in tests. // ArtifactsDir); nil when the stage configures none or in tests.
Skills *SkillSet Skills *SkillSet
@@ -72,7 +75,7 @@ func NewRegistry(types map[string]Stage) *Registry {
} }
func DefaultRegistry() *Registry { func DefaultRegistry() *Registry {
return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}}) return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}, CheckType: CheckStage{}})
} }
func EffectiveType(name string) string { func EffectiveType(name string) string {
+10 -3
View File
@@ -40,8 +40,9 @@ func (a LandingAccess) valid() bool {
} }
// DeliveryEnabled is the narrow, declarative capability check used before the // DeliveryEnabled is the narrow, declarative capability check used before the
// runner supplies any landing paths. Only a validated model definition can ask // runner supplies any landing paths. Only a validated model or check
// for it; runtime paths are still derived by the server. // definition can ask for it, whatever its harness; runtime paths are still
// derived by the server.
func DeliveryEnabled(def Definition) (bool, error) { func DeliveryEnabled(def Definition) (bool, error) {
delivery := def.Configs["delivery"] delivery := def.Configs["delivery"]
if delivery == "" { if delivery == "" {
@@ -50,8 +51,14 @@ func DeliveryEnabled(def Definition) (bool, error) {
if delivery != "true" { if delivery != "true" {
return false, fmt.Errorf("delivery must be true when set") return false, fmt.Errorf("delivery must be true when set")
} }
if EffectiveType(def.Type) == CheckType {
if _, err := CheckStageSpec(def); err != nil {
return false, fmt.Errorf("invalid delivery check stage: %w", err)
}
return true, nil
}
if EffectiveType(def.Type) != ModelType { if EffectiveType(def.Type) != ModelType {
return false, fmt.Errorf("delivery is supported only by model stages") return false, fmt.Errorf("delivery is supported only by model and check stages")
} }
if _, err := (ModelStage{}).Spec(def); err != nil { if _, err := (ModelStage{}).Spec(def); err != nil {
return false, fmt.Errorf("invalid delivery model stage: %w", err) return false, fmt.Errorf("invalid delivery model stage: %w", err)
+19 -10
View File
@@ -246,18 +246,27 @@ func TestDeliveryEnabledRequiresValidatedModelStage(t *testing.T) {
} }
} }
func TestDeliveryRejectsPiBeforeAgentExecution(t *testing.T) { func TestDeliveryIsHarnessAgnostic(t *testing.T) {
for _, harness := range []string{"opencode", "pi"} {
def := modelDefinition()
def.Configs["delivery"] = "true"
def.Configs["harness"] = harness
def.Blocks["checks"] = "go test ./..."
if err := (ModelStage{}).Validate(def); err != nil {
t.Fatalf("%s delivery was rejected: %v", harness, err)
}
if enabled, err := DeliveryEnabled(def); err != nil || !enabled {
t.Fatalf("%s delivery = %v, %v", harness, enabled, err)
}
}
def := modelDefinition() def := modelDefinition()
def.Configs["delivery"] = "true" def.Configs["delivery"] = "true"
def.Configs["harness"] = "pi" def.Configs["harness"] = ClaudeBackend
def.Blocks["checks"] = "true" def.Configs["provider"] = ClaudeProvider
if err := (ModelStage{}).Validate(def); err == nil || !strings.Contains(err.Error(), "opencode harness") { def.Configs["model"] = "claude-sonnet-4-5"
t.Fatal("Pi delivery was accepted", err) def.Blocks["checks"] = "go test ./..."
} if enabled, err := DeliveryEnabled(def); err != nil || !enabled {
delete(def.Configs, "delivery") t.Fatalf("claude delivery = %v, %v", enabled, err)
delete(def.Blocks, "checks")
if err := (ModelStage{}).Validate(def); err != nil {
t.Fatal("Pi non-delivery was changed", err)
} }
} }