Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion docs/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2739,7 +2739,7 @@ paths:
tags: [Runs]
operationId: passFailedRunNode
summary: Pass a failed script node
description: Marks a failed script or command node as succeeded and continues downstream without re-executing it. Agent nodes must use retry with optional human context instead.
description: Marks a failed script or command node as succeeded and continues downstream without re-executing it. Agent nodes must use retry with optional human context instead. A node marked verificationStep:true returns 409 unless the request carries override=true; pass, rejection and override are all audited.
requestBody:
$ref: "#/components/requestBodies/NodeAction"
responses:
Expand Down Expand Up @@ -3803,6 +3803,22 @@ components:
properties:
nodeId:
type: string
reason:
type: string
context:
type: string
override:
type: boolean
description: Required to pass a node marked verificationStep; the request is audited with its operator.
expected:
type: object
description: Binds the decision to the attempt (and optionally the artifact) the operator reviewed. Honoured by approve, reject, retry, decline-retry and resume; a mismatch returns 409 and leaves the node waiting. artifactName and artifactSha256 must be supplied together (400 otherwise) and bind to the newest artifact of that name by creation time.
properties:
status: {type: string}
attempt: {type: integer}
reworkCount: {type: integer}
artifactName: {type: string}
artifactSha256: {type: string}
SyncConfig:
required: true
content:
Expand Down Expand Up @@ -4905,6 +4921,14 @@ components:
type: integer
maxReworks:
type: integer
requires:
type: array
description: "Preconditions checked before the node executes: artifact:<name>@<sha256> or verdict:<PASS|FAIL>@<diffHash>. Values are trimmed and the verdict is case-insensitive. An unmet precondition fails the node with the expected and actual values when no sibling is still running; a parallel producer must be an upstream edge."
items:
type: string
verificationStep:
type: boolean
description: Marks a verification step. /pass refuses it unless the request carries override=true; both outcomes are audited.
position:
$ref: "#/components/schemas/OpenObject"
WorkflowEdge:
Expand Down
27 changes: 26 additions & 1 deletion docs/api/orchestration.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" -OJ \

## 人工动作

以下接口成功均返回 `200 {"ok":true}`;run/node/状态错误通常 `400`。与 Issue 关联且执行被关闭/交付锁定的 run,在 approve、pass、reject、retry 时返回 `409`。
以下接口成功均返回 `200 {"ok":true}`;run/node/状态错误通常 `400`。与 Issue 关联且执行被关闭/交付锁定的 run,以及 `expected` 中的节点尝试或产物哈希已变化、`verificationStep` 节点未带 `override` 的 pass,在 approve、pass、reject、retry 时返回 `409`。

### `POST /api/runs/{runId}/approve`

Expand All @@ -223,6 +223,23 @@ curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" -OJ \

批准等待中的节点。

`expected` 可把批准绑定到操作者看到的那个节点尝试和产物上:

```json
{
"nodeId":"approval",
"expected":{
"status":"waiting_approval",
"attempt":2,
"reworkCount":0,
"artifactName":"verify",
"artifactSha256":"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
}
}
```

`artifactName`/`artifactSha256` 必须同时提供,校验当前 run 中该名字的**最新**产物(按创建时间)仍带这个内容哈希;只给其中一半返回 `400`(避免看起来绑定了实际没有)。节点状态或产物哈希任一不匹配时返回 `409`,节点保持 `waiting_approval`,run 追加 `gate.approval_rejected` 审计事件(写明期望值与实际值)。同一 `expected` 校验也作用于 `/reject`、`/retry`、`/decline-retry`、`/resume`。不带 `expected` 时行为不变。

### `POST /api/runs/{runId}/pass`

```json
Expand All @@ -231,6 +248,14 @@ curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" -OJ \

将已失败的**脚本**节点视为通过并继续下游,不重新执行该节点。用于 `onFailure=fail` 停下来之后,或打回返工到达最大轮次后,避免硬脚本一直卡住。Agent / AI 节点不能手动通过,应走 `/retry` 并附带补充上下文。

节点带 `verificationStep: true` 时,`/pass` 默认返回 `409`(节点保持失败,run 追加 `node.pass_rejected` 审计事件)。确需人工放行时显式带 `override`:

```json
{"nodeId":"phpunit-full","override":true,"context":"环境问题,验证本身已人工复核"}
```

放行仍会写 `node.passed_override` 审计事件,并记录请求的操作者(登录用户,未登录记为「未记录操作者」)。

### `POST /api/runs/{runId}/reject`

```json
Expand Down
83 changes: 83 additions & 0 deletions docs/enhancements/approval-binding.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Approval binding and engine-enforced verification gates

This change upgrades two conventions into engine guarantees:

1. A human approval can be bound to the exact artifact the operator reviewed, so an approval aimed at a stale run state is rejected instead of silently approving something else.
2. A verification node cannot be bypassed with `POST /api/runs/{id}/pass`; an explicit, audited override is required. `POST /api/runs/{id}/approve` on such a node (parked by a pause or the rework-budget human gate) remains an explicit human decision: it still writes `gate.approved` and the `decision` artifact, but it is not the `/pass` bypass and is out of P4's scope.

It follows the enhancement plan in `plan.md` (P2–P4). P5 (sidecar integration with AegisOS) is not part of this change.

## Baseline facts (P1, read from source)

- A run freezes its workflow at start: `internal/engine/run_start.go:156` stores `WorkflowSnapshot`, and a later publish does not change it. `RefreshRunSOP` (`internal/engine/run_ops.go`) is the only explicit snapshot update.
- Every artifact, including engine-written `decision.md`, gets a SHA-256 in `newArtifact` (`internal/engine/artifacts.go`), so binding needs no new table.
- Before this change, `/pass` accepted any failed script/command node on a failed run (or a script parked by a pause) and had no type-level restriction, so a verification script could be bypassed.

The live smoke test (`./start.sh dev`, first admin, minimal SOP run) was not run in the development session that produced this change: the dev image build failed inside Docker at `npm --prefix chatbot ci` with a network error. That is an environment failure, not a regression from this change.

## P2 — binding an approval to an artifact

`engine.NodeExpectation` and the HTTP `expected` object gained:

- `artifactName`: logical artifact name, e.g. `verify`;
- `artifactSha256`: expected content hash.

`checkNodeExpectation` compares against the **newest** artifact with that name (newest attempt, then newest creation time). Approving against an older attempt is exactly the stale decision this check exists to reject.

On mismatch the engine returns an `apperr.Conflict` (HTTP `409`), appends `gate.approval_rejected` with the expected and actual values, and leaves the node in `waiting_approval`. Status/attempt/rework mismatches use the same `409` now, since they mean the same thing: the card the operator acted on is stale.

```json
{
"nodeId": "approval",
"expected": {
"status": "waiting_approval",
"attempt": 2,
"artifactName": "verify",
"artifactSha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
}
}
```

The lookup is run-global by artifact name: if two nodes publish the same name, the newest creation wins for both binding and `requires`. Artifact names are only unique within a node by validation, so a workflow that needs two distinct `verify` artifacts must give them distinct names.

Omitting `expected` keeps the old behavior.

## P3 — node preconditions with `requires`

`WorkflowNode.requires` accepts:

- `artifact:<name>@<sha256>`: the run must carry that artifact with that hash;
- `verdict:<PASS|FAIL>@<diffHash>`: the newest verdict artifact (named `verdict`, or whose path basename is `verify.json`) must be JSON with `verdict` and `diffHash` matching (case-insensitive).

Malformed values are rejected at workflow validation, which runs when a run starts (and on `RefreshRunSOP`); the save path does not call it, so a typo is reported at start. At execution the scheduler checks the preconditions before spawning the node. An unmet precondition fails the node with the expected and actual values; the failure bypasses `onFailure`, `MaxReworks` and the retry policy because a deterministic precondition will not change on retry. If a sibling node is still in flight, the check is deferred until it settles — a parallel producer must still be wired as an upstream edge, otherwise the consumer can be failed before that producer becomes ready.

```json
{
"id": "ship",
"type": "agent",
"agentId": "releaser",
"requires": ["verdict:PASS@c0ffee"]
}
```

## P4 — closing the `/pass` bypass for verification nodes

`WorkflowNode.verificationStep: true` marks a verification step. The JSON name avoids `verification` because that is the removed legacy gate-array field the API strips on save.

- `POST /api/runs/{id}/pass` without `override` returns `409`, leaves the node failed, and appends `node.pass_rejected`.
- `{"nodeId":"...","override":true}` passes the node and appends `node.passed_override` naming the operator (the signed-in user; anonymous requests are recorded as `未记录操作者`).

Non-verification script nodes keep the previous behavior, so the environment-problem workflow that `/pass` exists for still works.

## Tests

- `internal/engine/gate_binding_test.go`: matching hash approves, mismatched/missing artifact rejects and audits, half-filled binding returns an error, the newest artifact by creation time wins over a higher attempt number on an older artifact, omitted `expected` unchanged.
- `internal/engine/node_requires_test.go`: artifact hash mismatch stops the consumer with expected+actual, matching hash runs it, verdict mismatch names both, malformed verdict JSON names the artifact, malformed `requires` fails validation.
- `internal/engine/pass_override_test.go`: verification node rejects `/pass` and audits — on a failed run and on a paused script — override passes and records the actor; plain script node unchanged.
- `internal/httpapi/gate_binding_http_test.go`: HTTP `409` for a stale approval and for `/pass` without override, `200` with override.

Run with `GOFLAGS=-buildvcs=false go test ./internal/engine ./internal/httpapi` when the checkout sits under a directory tree that also contains an `.svn` directory (Go's VCS stamping refuses the nested build otherwise).

## P5 — not implemented

The sidecar interface (verify / critique / delivery-check) and its SOP integration are the next step. The deployment shape (same-host process, MCP, or container) must be confirmed before writing that adapter.
16 changes: 13 additions & 3 deletions internal/domain/issue.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,11 +384,21 @@ type HumanDecision struct {
NodeID string `json:"nodeId"`
Reason string `json:"reason,omitempty"`
Context string `json:"context,omitempty"`
// Override lets /pass through a node marked verificationStep:true. The
// request is still audited with its operator; without it the pass is
// refused. The field is shared with approve/retry/resume bodies, which
// ignore it.
Override bool `json:"override,omitempty"`
}

// NodeDecisionExpectation binds a workbench action to the attempt being viewed.
// artifactName/artifactSha256 additionally bind an approval to the artifact the
// operator reviewed: the action is rejected with 409 when the newest artifact
// of that name no longer carries that hash.
type NodeDecisionExpectation struct {
Status string `json:"status"`
Attempt int `json:"attempt"`
ReworkCount int `json:"reworkCount"`
Status string `json:"status"`
Attempt int `json:"attempt"`
ReworkCount int `json:"reworkCount"`
ArtifactName string `json:"artifactName,omitempty"`
ArtifactSHA256 string `json:"artifactSha256,omitempty"`
}
28 changes: 20 additions & 8 deletions internal/domain/workflow.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,26 @@ type WorkflowNode struct {
ExecutionScope string `json:"executionScope,omitempty"` // run, repositories; empty = run
Command string `json:"command,omitempty"` // legacy command-node payload
ArtifactOutputs []ArtifactContract `json:"artifactOutputs,omitempty"`
RejectTo string `json:"rejectTo,omitempty"`
OnFailure string `json:"onFailure,omitempty"` // fail, reject
RetryStrategy string `json:"retryStrategy,omitempty"` // targeted_fix, full_redo
CarryOver []string `json:"carryOver,omitempty"`
MaxAttempts int `json:"maxAttempts"`
MaxReworks int `json:"maxReworks"`
Notifications []NodeNotification `json:"notifications,omitempty"`
Position Position `json:"position"`
// Requires lists preconditions checked before the node executes. Supported
// forms: "artifact:<name>@<sha256>" (the run must carry that artifact with
// that content hash) and "verdict:<PASS|FAIL>@<diffHash>" (the verdict
// artifact must carry that verdict bound to that diff). An unmet
// precondition fails the node with the expected and actual values instead
// of silently skipping it.
Requires []string `json:"requires,omitempty"`
// VerificationStep marks the node as a verification step: /pass refuses it
// by default and only an explicit override, recorded with its operator, may
// let the run continue past it. The JSON name avoids `verification`, which
// is the removed legacy gate-array field the API strips on save.
VerificationStep bool `json:"verificationStep,omitempty"`
RejectTo string `json:"rejectTo,omitempty"`
OnFailure string `json:"onFailure,omitempty"` // fail, reject
RetryStrategy string `json:"retryStrategy,omitempty"` // targeted_fix, full_redo
CarryOver []string `json:"carryOver,omitempty"`
MaxAttempts int `json:"maxAttempts"`
MaxReworks int `json:"maxReworks"`
Notifications []NodeNotification `json:"notifications,omitempty"`
Position Position `json:"position"`
}

// ValidateWorkflowMetricStages prevents silently dropping a mistyped stage.
Expand Down
77 changes: 75 additions & 2 deletions internal/engine/bot_control.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
package engine

import (
"agentflow/internal/apperr"
"agentflow/internal/domain"
"fmt"
"strings"
)

// NodeExpectation binds chat-card actions to the exact attempt displayed. The
// existing engine state lock and persistence conflict checks still apply.
// ArtifactName/ArtifactSHA256 additionally bind a human gate decision to the
// artifact the operator reviewed: the run must still carry that artifact with
// that content hash, or the decision is rejected as stale.
type NodeExpectation struct {
NodeID, Status string
Attempt, ReworkCount int
ArtifactName string
ArtifactSHA256 string
}

func checkNodeExpectation(run domain.Run, expected []NodeExpectation) error {
Expand All @@ -18,8 +25,74 @@ func checkNodeExpectation(run domain.Run, expected []NodeExpectation) error {
}
want := expected[0]
node := run.Nodes[want.NodeID]
if node == nil || node.Status != want.Status || node.Attempt != want.Attempt || node.ReworkCount != want.ReworkCount {
return fmt.Errorf("通知对应的节点状态已变化,请查看最新消息")
if node == nil {
return apperr.Newf(apperr.Conflict, "通知对应的节点 %q 已不存在,请查看最新消息", want.NodeID)
}
if node.Status != want.Status || node.Attempt != want.Attempt || node.ReworkCount != want.ReworkCount {
return apperr.Newf(apperr.Conflict, "通知对应的节点状态已变化:期望 status=%s attempt=%d rework=%d,实际 status=%s attempt=%d rework=%d",
want.Status, want.Attempt, want.ReworkCount, node.Status, node.Attempt, node.ReworkCount)
}
name, sha := strings.TrimSpace(want.ArtifactName), strings.TrimSpace(want.ArtifactSHA256)
if name == "" && sha == "" {
return nil
}
if name == "" || sha == "" {
// Half a binding is a caller bug, not an unbound approval: accepting it
// would let a client believe its approval is artifact-bound when it is not.
return apperr.New(apperr.Invalid, "expected.artifactName 与 expected.artifactSha256 必须同时提供")
}
artifact := latestRunArtifact(run, name)
if artifact == nil {
return apperr.Newf(apperr.Conflict, "批准绑定的产物 %q 不在当前 run 中,请查看最新消息", name).
With("expectedArtifact", name).
With("expectedSha256", sha)
}
if !strings.EqualFold(artifact.SHA256, sha) {
return apperr.Newf(apperr.Conflict, "批准绑定的产物 %q 内容已变化:期望 sha256 %s,实际 %s", name, sha, artifact.SHA256).
With("expectedArtifact", name).
With("expectedSha256", sha).
With("actualSha256", artifact.SHA256)
}
return nil
}

// latestRunArtifact returns the newest artifact with this logical name. Old
// attempts stay in the run for audit, and a decision must bind to the newest
// one — binding an older attempt is exactly the stale approval this check
// exists to reject. Newest means creation time, not attempt number: attempts
// are per node, so comparing them across nodes is meaningless.
func latestRunArtifact(run domain.Run, name string) *domain.Artifact {
var best *domain.Artifact
for i := range run.Artifacts {
artifact := &run.Artifacts[i]
if artifact.Name != name {
continue
}
if best == nil || artifact.CreatedAt.After(best.CreatedAt) ||
artifact.CreatedAt.Equal(best.CreatedAt) && artifact.Attempt > best.Attempt {
best = artifact
}
}
return best
}

// auditActor names the operator in control events; an anonymous request is
// still recorded, so the audit trail never reads as if nobody made the call.
func auditActor(actor string) string {
if trimmed := strings.TrimSpace(actor); trimmed != "" {
return trimmed
}
return "未记录操作者"
}

func describeExpectation(expected []NodeExpectation) string {
if len(expected) == 0 {
return ""
}
want := expected[0]
parts := []string{fmt.Sprintf("status=%s attempt=%d rework=%d", want.Status, want.Attempt, want.ReworkCount)}
if want.ArtifactName != "" {
parts = append(parts, fmt.Sprintf("artifact=%s sha256=%s", want.ArtifactName, want.ArtifactSHA256))
}
return strings.Join(parts, " ")
}
Loading