Skip to content

Commit 9efbda5

Browse files
authored
Merge pull request #586 from CWNU-Open-Source-Community/feat/exec-instructions
feat(app): exec --instructions fixes a Thread context pin(对照 Claude Code --append-system-prompt)
2 parents 90d7c17 + fcdcdff commit 9efbda5

4 files changed

Lines changed: 320 additions & 4 deletions

File tree

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# ADR 0203: exec --instructions as a Thread context pin
2+
3+
- Status: Proposed
4+
- Date: 2026-11-10
5+
- Scope: CLI surfaces and per-invocation operator guidance
6+
- Updates: docs/usage.md; extends ADR 0201 (one-shot exec mode); relies on the
7+
Thread context pin contract (operator controls, integrity-checked delivery)
8+
- References: Claude Code `--append-system-prompt` (external parity baseline)
9+
10+
## Problem
11+
12+
`cyberagent exec` (ADR 0201) takes the task prompt but no per-invocation
13+
guidance channel. Operators automating the CLI need to customize agent
14+
behavior for one invocation — output format, commit style, focus constraints —
15+
without writing files into the workspace or editing global configuration.
16+
Claude Code exposes `--append-system-prompt` for exactly this; Codex reaches
17+
for config overrides. Universal-Code has a native equivalent already: Thread
18+
context pins are operator-confirmed fixed task requirements delivered as
19+
protected sections on every turn. The gap is that exec has no way to fix one.
20+
21+
## Decision (proposed)
22+
23+
1. **The Thread context pin is the delivery channel.** `--instructions
24+
"<text>"` adds the text as an operator context pin (`ControlContextPin`,
25+
action `add`, `cli_exec_operator`) on the invocation's Thread before the
26+
first turn. The ordinary pin machinery does the rest: integrity-checked
27+
storage (`ContentSHA256`), protected-section selection, delivery on every
28+
turn including follow-ups, visibility in the Thread's pin state, and
29+
edit/remove through the same operator surface the interactive UI uses. No
30+
new envelope type, Run config field, or delivery rule is introduced.
31+
2. **Validate before any Run exists.** The text is normalized up front
32+
(`normalizeExecInstructions`): an unset flag means no fixed instructions, a
33+
whitespace-only value fails loudly, and otherwise the exact Thread pin
34+
contract applies (nonempty UTF-8, no NUL, at most 8192 characters) plus the
35+
pin storage gate that rejects protected secret content. Failing early
36+
means a rejected text can never strand a created Run.
37+
3. **No authority widening.** Pin text is delivered under the existing pin
38+
semantics — workflow guidance below system policy, never a grant of tools,
39+
permissions, or policy exceptions. The CLI operator's authority comes from
40+
the CLI process itself, not from the instruction text, so exec gains no
41+
capability channel other flags lack.
42+
4. **Output contract unchanged.** The reply and `--json` shape stay exactly
43+
as ADR 0201 defined them; the pin is observable in the Thread's context
44+
pin state rather than in exec output.
45+
46+
## Alternatives considered
47+
48+
- Appending a synthetic source to the discovered project-instruction snapshot
49+
was rejected: the run's instruction state machine compares the pinned
50+
snapshot against live discovery, so a synthetic source would mark every
51+
exec run's instructions stale forever, and a later operator refresh would
52+
silently drop the fixed text.
53+
- A new pinned `RunConfig` channel with a dedicated envelope type was
54+
deferred: it touches domain validation, both supervisor and worker context
55+
assembly, and the system-prompt policy text — a new design surface for a
56+
need the pin channel already covers.
57+
- Prepending the text to the user prompt was rejected: it conflates guidance
58+
with the task message, is not delivered on follow-up turns, and bypasses
59+
the integrity and visibility machinery pins provide.
60+
61+
## Verification
62+
63+
- `TestNormalizeExecInstructions` covers the unset, trimmed, whitespace-only,
64+
rune-cap, NUL, and protected-secret cases.
65+
- `TestExecInstructionsFixesThreadContextPinAndDeliversIt` drives exec through
66+
the offline provider and asserts, on durable state, exactly one active pin
67+
with the fixed text, `cli_exec_operator` provenance, and integrity fields;
68+
and, on the recorded model requests, that the text was actually delivered
69+
into the model context.
70+
- `TestExecInstructionsWhitespaceOnlyFailsBeforeRunCreation` pins the
71+
fail-loud contract before run creation.
72+
- Documentation: docs/usage.md (bilingual) and this ADR.
73+
74+
## Consequences
75+
76+
Scripts gain the parity `--instructions` flag with zero new delivery
77+
machinery: every guarantee (per-turn delivery, integrity, visibility,
78+
editability, no authority widening) is inherited from the Thread pin
79+
contract. Each exec invocation owns a fresh Thread, so its fixed pin is
80+
private to that invocation; any follow-up Thread work (steering, successor
81+
Runs, interactive sends) sees and manages the same pin in the shared pin
82+
state.

‎docs/usage.md‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,15 @@ committed assistant reply on stdout, and exits non-zero unless the supervisor
149149
finished the task (`turn_finish`; approval waits, continuation stops, and
150150
budget exhaustion report their stop reason). `--json` emits `{run_id, thread_id, status, reply}` instead of the
151151
bare reply. Unattended runs cannot widen permissions: pre-arrange execution
152-
grants the same way you would for any Run.
152+
grants the same way you would for any Run. `--instructions "<text>"` fixes
153+
extra operator guidance for the invocation: the text is validated against the
154+
Thread context pin contract (nonempty UTF-8, no NUL, at most 8192 characters,
155+
no protected secret content), stored as an operator context pin on the
156+
invocation's Thread, and delivered as a protected fixed-requirement section on
157+
every turn — including follow-up turns on the same Thread. It never widens
158+
authority: pin text stays below system policy and can never grant tools,
159+
permissions, or policy exceptions. The pin is visible in the Thread's context
160+
pin state and can be edited or removed there like any operator pin.
153161

154162
`cyberagent exec` 对已注册 Workspace 执行一条非交互 prompt 并打印最终助手
155163
回复——与交互会话完全相同的 Thread turn 机制在本进程内驱动,底层 Run 的全部
@@ -160,7 +168,13 @@ agent 循环、把最后一条已提交的助手回复打印到 stdout,除非
160168
`turn_finish` 结束任务(等待审批、继续等待与预算耗尽都会报告其停止原因)
161169
否则以非零码退出。`--json` 输出
162170
`{run_id, thread_id, status, reply}` 取代纯回复文本。无人值守运行不能放宽
163-
权限:执行授权需要与任何 Run 一样预先安排。
171+
权限:执行授权需要与任何 Run 一样预先安排。`--instructions "<文本>"` 为本次
172+
调用固定额外的操作者指令:文本先按 Thread context pin 契约校验(非空 UTF-8、
173+
无 NUL、最多 8192 字符、不含受保护的密钥内容),以操作者 context pin 的形式
174+
存入本次调用的 Thread,并在每个 turn 作为受保护的固定要求小节交付——包括同一
175+
Thread 上的后续 turn。它不放宽任何权限:pin 文本始终低于系统策略,永远不能
176+
授予工具、权限或策略例外。pin 在 Thread 的 context pin 状态中可见,可以像
177+
其他操作者 pin 一样在那里编辑或移除。
164178

165179
### 补充消息与排队 / Follow-up messages and queue
166180

‎internal/app/exec_command.go‎

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@ import (
88
"io"
99
"os"
1010
"strings"
11+
"time"
1112
"unicode/utf8"
1213

1314
"cyberagent-workbench/internal/application"
1415
"cyberagent-workbench/internal/domain"
1516
"cyberagent-workbench/internal/idgen"
1617
"cyberagent-workbench/internal/projectconfig"
18+
"cyberagent-workbench/internal/redact"
1719
"cyberagent-workbench/internal/toolgateway"
1820
"cyberagent-workbench/internal/workspace"
1921
)
@@ -39,6 +41,8 @@ func (a *App) execCommand(ctx context.Context, args []string) error {
3941
timeout := fs.Duration("timeout", 0, "whole-execution deadline; zero means no deadline")
4042
stdin := fs.Bool("stdin", false, "read the prompt from stdin instead of the positional argument")
4143
jsonOutput := fs.Bool("json", false, "emit a structured JSON result")
44+
instructions := fs.String("instructions", "",
45+
"fix extra operator instructions as a Thread context pin for this invocation")
4246
enablePermissionControl := fs.Bool("enable-permission-control", false,
4347
"enable the operator-approval runtime for this process")
4448
enableFullAccess := fs.Bool("enable-danger-full-access", false,
@@ -49,6 +53,7 @@ func (a *App) execCommand(ctx context.Context, args []string) error {
4953
"workspace": true, "profile": true, "route": true,
5054
"max-turns": true, "max-tokens": true, "max-tool-calls": true,
5155
"max-cost-usd": true, "timeout": true, "stdin": false, "json": false,
56+
"instructions": true,
5257
"enable-permission-control": false, "enable-danger-full-access": false,
5358
"confirm-full": false,
5459
})); err != nil {
@@ -64,11 +69,19 @@ func (a *App) execCommand(ctx context.Context, args []string) error {
6469
}
6570
prompt = strings.TrimSpace(prompt)
6671
if prompt == "" {
67-
return errors.New(`usage: cyberagent exec --workspace <name> "prompt" [--profile code|review|learn|script] [--route <route>] [--timeout 30m] [--json]`)
72+
return errors.New(`usage: cyberagent exec --workspace <name> "prompt" [--profile code|review|learn|script] [--route <route>] [--instructions <text>] [--timeout 30m] [--json]`)
6873
}
6974
if strings.TrimSpace(*workspaceName) == "" {
7075
return errors.New("exec requires --workspace <name>")
7176
}
77+
// Validate the fixed instructions before any Run exists: a late pin
78+
// failure would otherwise strand a created Run, and the operator gets the
79+
// same text contract (UTF-8, no NUL, 8192-rune cap, no redacted secrets)
80+
// the interactive Thread pin surface enforces.
81+
fixedInstructions, err := normalizeExecInstructions(*instructions)
82+
if err != nil {
83+
return err
84+
}
7285
if *timeout > 0 {
7386
var cancel context.CancelFunc
7487
ctx, cancel = context.WithTimeout(ctx, *timeout)
@@ -151,6 +164,21 @@ func (a *App) execCommand(ctx context.Context, args []string) error {
151164
turns := application.NewThreadTurnService(a.store,
152165
application.NewRunLifecycleControlService(a.store).WithLifecycleHooks(a.newLifecycleHookEngine()),
153166
application.NewRunExecutionHandoffWithRuntime(a.store, a.router, a.checker, dependencies))
167+
if fixedInstructions != "" {
168+
if err := pinExecInstructions(ctx, turns, domain.InitialThreadID(run.ID),
169+
fixedInstructions); err != nil {
170+
// A created Run with a failed pin would sit idle until its budget
171+
// expires. Cancel it on a bounded detached context so the
172+
// operator gets a terminal Run, and report the Run ID if even
173+
// the cancellation fails. The pin error stays primary.
174+
cancelCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
175+
if _, cancelErr := application.NewRunService(a.store).Cancel(cancelCtx, run.ID); cancelErr != nil {
176+
err = fmt.Errorf("%w (run %s could not be cancelled: %v)", err, run.ID, cancelErr)
177+
}
178+
cancel()
179+
return err
180+
}
181+
}
154182
oneShot := application.NewOneShotService(a.store, turns)
155183
result, err := oneShot.Run(ctx, application.OneShotRequest{
156184
Version: domain.ThreadMessageProtocolVersion,
@@ -196,3 +224,51 @@ func clipExecGoal(prompt string) string {
196224
}
197225
return clipped
198226
}
227+
228+
// normalizeExecInstructions validates the exec --instructions value before any
229+
// Run is created. An unset flag means no fixed instructions; a whitespace-only
230+
// value is an operator mistake and fails loudly. Otherwise the text must
231+
// satisfy the Thread context pin contract and carry no protected secret
232+
// content, mirroring the interactive pin surface's storage gate.
233+
func normalizeExecInstructions(raw string) (string, error) {
234+
if raw == "" {
235+
return "", nil
236+
}
237+
text := strings.TrimSpace(raw)
238+
if text == "" {
239+
return "", errors.New("exec --instructions requires nonempty text")
240+
}
241+
if err := domain.ValidateContextPinText(text); err != nil {
242+
return "", fmt.Errorf("exec --instructions: %w", err)
243+
}
244+
if text != redact.String(text) {
245+
return "", errors.New("exec --instructions: remove protected secrets before fixing them as context guidance")
246+
}
247+
return text, nil
248+
}
249+
250+
// pinExecInstructions fixes the invocation's extra operator instructions as a
251+
// Thread context pin before the first turn. The ordinary pin delivery — an
252+
// integrity-checked, operator-confirmed fixed requirement selected as a
253+
// protected section every turn — carries them for this Run and any successor
254+
// the Thread creates, with the same authority ceiling as every other pin: the
255+
// text never grants tools, permissions, or policy exceptions.
256+
func pinExecInstructions(ctx context.Context, turns *application.ThreadTurnService,
257+
threadID, text string) error {
258+
state, err := turns.InspectContextPins(ctx, threadID)
259+
if err != nil {
260+
return fmt.Errorf("exec instructions pin inspect: %w", err)
261+
}
262+
if _, err := turns.ControlContextPin(ctx, domain.ThreadContextPinControl{
263+
Version: domain.ThreadContextPinsVersion,
264+
ThreadID: threadID,
265+
Action: "add",
266+
ExpectedRevision: state.Revision,
267+
Text: text,
268+
OperationKey: idgen.New("cli-exec-pin"),
269+
RequestedBy: "cli_exec_operator",
270+
}); err != nil {
271+
return fmt.Errorf("exec instructions pin: %w", err)
272+
}
273+
return nil
274+
}

0 commit comments

Comments
 (0)