orchestrator

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 29, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Overview

Package orchestrator's state-machine layer is split into TWO machines — NewExecutionMachine and NewCardMachine (machine_execution.go / machine_card.go) — rather than the single unified NewMachine this package used to export (PR-B, docs/plans/suggestion-as-state-transition-impl.md §2, purely a refactor: rule content/names/behavior are unchanged, only which machine object each rule lives on).

Why split at all (docs/plans/suggestion-as-state-transition.md §2.5): walking the old unified rule table by reachability showed it was always two disconnected islands wearing one name. The pending/executing/awaiting island and the captured/triaged/parked/ready/working island share only their terminal statuses (done/aborted) — a task born in "captured" never reaches "executing", and one born in "pending" never reaches "triaged". That separation was never a property of the machine itself; it only held because FOUR pieces of discipline living entirely outside machine.go enforced it by hand:

  • api.ApplyAction peeking at whether a task carries a task_triage sidecar row to route `reopen` (ordinary done/aborted → executing) away from `reopen_triaged` (triage done/aborted → triaged) — the unified machine could not tell a done triage card apart from a done ordinary task by status alone.
  • the `triage_done` rule being named that instead of plain `done`, purely because IsManualAction shared one namespace across every rule: reusing "done" would have let `boid action send --type done` push a triage card straight to done from a Manual:true rule, letting khi assert completion the daemon never actually evaluated.
  • the preExecutionStatuses enumeration discipline (論点6-3): every triage-vocabulary rule (attrs_set/child_added/.../answered) had to spell out its FromStatus set by hand instead of using "*", or it would have reached across the island boundary into executing/done/etc on an ordinary task.
  • abort and drop's scopes being manually kept from overlapping — abort pinned to the execution-lifecycle statuses, drop to the four pre-execution ones — inside the same rule table.

The deeper reason the split holds is not implementation accident: an ordinary task is a session-bearing subject (its status tracks whether a sandboxed process is running and how it exited); a card is an object khi and nose read and annotate (its status is a judgment ledger — whose turn it is, whether it needs attention). A card never runs an agent session of its own — khi's judgment happens in a separate triggering task, and even the Shape button only ever writes back into the card from a workspace-side session. That asymmetry is why the exported constructor is NewCardMachine, not some execution-flavored name: the card is a note board, not a lesser task.

The entity itself is NOT split (docs/plans/suggestion-as-state-transition.md §3.8 considered a dedicated `card` table and rejected it): a card's children are ordinary tasks whose parent_id crosses whatever boundary a second table would draw, and action log / timeline / Web UI / notify all already share one representation profitably. Only the StateMachine each task is evaluated against is chosen per task — see internal/api's machineFor, which selects NewCardMachine when the task carries a task_triage sidecar row and NewExecutionMachine otherwise (the same sidecar-existence judgment api.resolveReopenVariant already made before the split, now shared by both).

Splitting the machine object collapses three of the four bypass disciplines above into the type system itself: reopen_triaged can go back to being named `done` inside NewCardMachine's own namespace (kept `triage_done` regardless in this PR — action HISTORY rows already say `triage_done` and are not renamed; only a later PR may switch new writes to `done`), the FromStatus-enumeration discipline stops mattering once executing/pending/etc. simply do not exist as reachable statuses in NewCardMachine's own rule table, and abort/drop's scopes no longer share a table to overlap in (abort exists only in NewExecutionMachine; drop only in NewCardMachine). The `reopen` sidecar-lookup routing itself (决定17) is NOT one of the things the split removes — a done card and a done ordinary task are still indistinguishable by status alone, so api still has to look at the sidecar to decide whether "reopen" should apply NewExecutionMachine's rule or NewCardMachine's; what changes is that this same lookup now ALSO selects which machine object governs the whole request (machineFor), not just which of two same-named-but-differently- scoped rules to fire within one shared table.

"Rule content/names/behavior are unchanged" is deliberately not "behavior never changes by one millimeter" (docs/plans/suggestion-as-state-transition.md §3.8's own caveat): splitting the machine object means IsManualAction's "is this action name known anywhere" check now runs against a SMALLER rule table per call site, which moves an error some callers used to get from api.ApplyAction's own IsManualAction gate onto whatever happens next once the task itself is loaded (e.g. task-not-found now surfaces as 404 before an unknown/wrong-machine action name would have 400'd) — see workflow_action.go's ApplyAction and this PR's own PR description for the specific call sites this touches.

Index

Constants

View Source
const (
	DefaultActionListLimit = 200
	MaxActionListLimit     = 1000
)

DefaultActionListLimit / MaxActionListLimit bound a single BoidOpActionList call's ROW COUNT — not its response size. This is the direct response to the PR-1/PR-2 review finding "wire レベルにサイズ上限がない…返り値側にも limit が要る — 一括読み は大量のデータを返しうる": since action_list is a brand-new read surface added BY this PR, its own default/max limit is where that concern is closed for THIS op (see the PR's report for the separate judgment call on the pre-existing, broker-wide input-side gap, which this PR does not touch).

MaxActionListLimit (1000) × each action's own payload cap (MaxContentBytes = 64KiB, content_size.go) puts the mathematical worst case at ~64MB — nowhere near "bounded" in an absolute sense. This is deliberately NOT a tight response-size bound; it is a row-count cap chosen against real payload sizes (khi's actual attrs blobs measured max 22,572B, nowhere close to the 64KiB cap — 実測, 2026-08-19), which keep a 1000-row response small in practice today. Neither constant is a measured constant the way MaxContentBytes itself is — there is no equivalent real-workspace measurement of "how many actions land per tick" yet (khi does not call this op today; it is this PR's own new consumer). Revisit (tighten the row cap, or add a real response-byte budget) once a workspace is actually driving this op in production and the gap between "small in practice" and "bounded in the worst case" starts to matter — 12 節 B-3's own framing ("問題になったら…決める") applies here too.

View Source
const (
	// ActorHuman は Web UI / CLI からの人間操作 (nose 本人)。
	ActorHuman = "human"
	// ActorDaemon は daemon 自身の自動処理 (dispatch loop の auto_advance、
	// dispatch_error、daemon shutdown による abort、fired event 記録、
	// 起動時の auto-reopen など) — どの task/human にも帰属しない機械的記録。
	ActorDaemon = "daemon"
)

Actor 値の3系統。docs/plans/cross-project-issue-triage.md 論点11「代行Goタスク」の 前提条件: nose (人間操作) が押した action と代行タスクが押した action を actions ログ上で 区別できないと、事故ったときに「人間の判断ミスか代行タスクの誤判定か」が復元不能になる。

View Source
const (
	TaskTriageChildStatusOpen       = "open"
	TaskTriageChildStatusSpecced    = "specced"
	TaskTriageChildStatusDispatched = "dispatched"
	TaskTriageChildStatusClosed     = "closed"
)

Child status vocabulary for task_triage.detail.children (逆輸入1: task_spec/task_ref/open_items were unified into this single list). Status progresses open → specced → dispatched → closed; PR-2 only acts on "specced" (task-ifying it into "dispatched" — see TaskWorkflowService.Dispatch).

View Source
const (
	CardMachineName      = "card"
	ExecutionMachineName = "execution"
)

CardMachineName / ExecutionMachineName are the StateMachine.Name values NewCardMachine/NewExecutionMachine stamp. PR-1 (docs/plans/ suggestion-as-state-transition-impl.md §3.2) needs a way to tell, from api.ApplyAction, which machine a task resolved to WITHOUT re-deriving the sidecar-row judgment machineFor already made — comparing sm.Name against this constant is that check (see the push-down defense discussion in machine_card.go's own doc comment).

View Source
const (
	OpBoidJobDone    = "job_done"
	OpBoidJobList    = "job_list"
	OpBoidJobShow    = "job_show"
	OpBoidJobLog     = "job_log"
	OpBoidActionSend = "action_send"
	OpBoidAgentStop  = "agent_stop"
	OpBoidTaskCreate = "task_create"
	OpBoidTaskGet    = "task_get"
	OpBoidTaskUpdate = "task_update"
	OpBoidTaskImport = "task_import"
	OpBoidTaskReopen = "task.reopen"
	OpBoidTaskList   = "task_list"
	OpBoidTaskNotify = "task_notify"
	OpBoidTaskAnswer = "task_answer"
	OpBoidTaskAsk    = "task_ask"
	OpBoidTaskDelete = "task_delete"
	OpBoidTaskWait   = "task_wait"

	// Phase 5b PR1 task-context RPCs (docs/plans/phase5-shim-and-task-context.md).
	OpBoidTaskCurrent      = "task_current"
	OpBoidTaskInstructions = "task_instructions"
	OpBoidTaskEnv          = "task_env"
	OpBoidTaskPayload      = "task_payload"

	// Phase 5b PR2 attachments RPCs (docs/plans/phase5-shim-and-task-context.md).
	OpBoidTaskAttachmentsList = "task_attachments_list"
	OpBoidTaskAttachmentsGet  = "task_attachments_get"

	// Phase 5b PR7 job_done payload_patch direct-pass RPC
	// (docs/plans/phase5-shim-and-task-context.md).
	OpBoidTaskUpdatePayloadPatch = "task_update_payload_patch"

	// OpBoidProjectBehaviors backs `boid project behaviors` from inside the
	// sandbox (docs/plans/workspace-default-project.md follow-up).
	OpBoidProjectBehaviors = "project_behaviors"
	// OpBoidProjectList backs `boid project list` from inside the sandbox —
	// discovery companion to OpBoidProjectBehaviors, scoped to the caller's
	// own workspace (see sandbox.BoidOpProjectList's doc comment).
	OpBoidProjectList = "project_list"

	// OpBoidCardGet / OpBoidCardList back `boid card get` / `boid card list`
	// from inside the sandbox (docs/plans/cross-project-issue-triage.md Phase
	// 1 PR-5a 決定14, renamed from task_triage_get/list by
	// docs/plans/card-model-cleanup.md PR-3 §4): the read half of "daemon が
	// state の唯一の正".
	OpBoidCardGet  = "card_get"
	OpBoidCardList = "card_list"

	// OpBoidTaskIdentityLink / OpBoidTaskIdentityUnlink / OpBoidTaskIdentityResolve
	// back `boid task identity link/unlink/resolve` from inside the sandbox
	// (docs/plans/ingestion-identity.md PR-1, B-1): the identity index's
	// only external surface. No HTTP route exists for these (the sandbox
	// shim is the sole caller today).
	OpBoidTaskIdentityLink    = "task_identity_link"
	OpBoidTaskIdentityUnlink  = "task_identity_unlink"
	OpBoidTaskIdentityResolve = "task_identity_resolve"

	// OpBoidTaskResolveOrCapture backs `boid task resolve-or-capture` from
	// inside the sandbox (docs/plans/ingestion-identity.md PR-2, B-2): the
	// destination-resolution op — resolve Identity to an existing task, or
	// atomically create a new `captured` triage task and link it when
	// unresolved. Same "no HTTP route" scoping as the PR-1 identity ops
	// above (sandbox shim is the sole caller).
	OpBoidTaskResolveOrCapture = "task_resolve_or_capture"

	// OpBoidActionList backs `boid action list` from inside the sandbox
	// (docs/plans/ingestion-identity.md PR-3, B-3): the workspace-scoped
	// since-cursor read over actions — the missing read half of
	// OpBoidActionSend.
	OpBoidActionList = "action_list"

	// OpBoidSignalList / OpBoidSignalAck back `boid signal list` / `boid
	// signal ack` from inside the sandbox (docs/plans/
	// signal-ingest-detailed-design.md §3.2, PR-3) — part of the general
	// boidPolicy (see boidPolicy's own doc comment in policy.go).
	OpBoidSignalList = "signal_list"
	OpBoidSignalAck  = "signal_ack"
	// OpBoidSignalClaim backs `boid signal claim <id>...` — the explicit
	// "these are the rows I handed to a judgment" half of the read/claim
	// split (2026-08-29). Granted by the same general boidPolicy as
	// signal_list/signal_ack: a job that may read its workspace's inbox and
	// ack a row may also say which rows it took.
	OpBoidSignalClaim = "signal_claim"

	// OpBoidSignalIngest / OpBoidSignalCursorGet mirror
	// sandbox.BoidOpSignalIngest / BoidOpSignalCursorGet — declared here for
	// mirror-table / drift-check completeness only. DELIBERATELY NOT added
	// to boidPolicy's AllowedOps (policy.go): design doc §3.2 grants these
	// only via PR-5's connector-scoped reduced policy.
	OpBoidSignalIngest    = "signal_ingest"
	OpBoidSignalCursorGet = "signal_cursor_get"

	OpFetchGet = "get"
)

Mirror of sandbox layer's op constants. orchestrator cannot import sandbox (that would reverse the layer direction), so these are kept as string literals that must stay in lock-step with internal/sandbox/protocol.go. Drift is detected by internal/dispatcher/policy_translate_test.go — the only layer allowed to see both sides.

View Source
const (
	// StatusReady means project.yaml loaded successfully and no
	// fetch/load failure has been observed since (the zero value / default
	// for any project with no statuses entry).
	StatusReady = "ready"
	// StatusDegraded means the project's row is preserved (per the
	// on-startup-auto-prune-retirement invariant, docs/plans/
	// volume-only-daemon.md §論点a) but its project.yaml/bare-repo could not
	// be loaded — see ProjectStatus.Message for why.
	StatusDegraded = "degraded"
)
View Source
const (
	InternalSignalPack      = "boid"
	InternalSignalConnector = "actions"
)

InternalSignalPack / InternalSignalConnector are the reserved "<pack>/ <connector>" identity boid's own action-derived signals ingest under (§4.6's envelope table: source.pack="boid", source.connector="actions"). InternalSignalPack is a reserved Pack name — internal/integrationpack's LoadPacks refuses to ever load a real installed Pack claiming it, so an external connector's rows can never collide with these under the same signals PRIMARY KEY (workspace_id, service, connector, id).

View Source
const (
	DefaultSignalListLimit = 200
	MaxSignalListLimit     = 1000
)

DefaultSignalListLimit / MaxSignalListLimit bound ListSignals/ClaimSignals row counts, mirroring action_list.go's DefaultActionListLimit/ MaxActionListLimit (same "row-count cap, not response-size cap" posture — see that file's doc comment for the full rationale, which applies identically here since this is also a brand-new read surface).

View Source
const (
	// WorkspaceEnvelopeAPIVersion is the only apiVersion value this binary
	// accepts. A future incompatible schema change bumps this (e.g.
	// boid.dev/v2) rather than silently reinterpreting an old document.
	WorkspaceEnvelopeAPIVersion = "boid.dev/v1"
	// WorkspaceEnvelopeKind is the only kind value this binary accepts.
	WorkspaceEnvelopeKind = "Workspace"
)
View Source
const BaseBranchSnapshotNote = "" /* 240-byte string literal not displayed */

BaseBranchSnapshotNote documents 決定2's tradeoff for --explain output: BaseBranch is resolved and snapshotted onto the task row at task-creation time (task_create.go), so changing the workspace default's base_branch (or project.yaml's) after a task already exists does NOT retroactively change that task's branch — only tasks created AFTER the change see the new value. task_behaviors / hooks are evaluated at dispatch time and are NOT snapshotted, so they DO pick up workspace default changes immediately for every existing task too.

View Source
const DefaultBehavior = "supervisor"

DefaultBehavior is the hardcoded fallback behavior name used when a CreateTaskRequest omits both behavior and behavior_spec, the project meta is nil, and no default_task_behavior is configured. When meta is non-nil, the default resolution consults meta.DefaultTaskBehavior first, then falls back to "supervisor" with a deprecation warning if that behavior exists.

View Source
const DefaultWorkspaceSlug = "default"

DefaultWorkspaceSlug is the reserved slug for the implicit "default" workspace that every project belongs to when no explicit assignment is chosen. It is auto-created at daemon startup, used as the fallback target for `project add` / `project migrate` when --workspace is omitted, and guarded against deletion by WorkspaceStore.Remove.

View Source
const MaxContentBytes = 64 * 1024 // 65,536 bytes

docs/plans/ingestion-identity.md PR-2 (B-2), 決定 J-10 / A-5: `description` と action payload に上限を置き、超えたら「切り詰めずにエラー」にする。

根拠 (決定 3 改訂の帰結): 原文が daemon 側の description として載るように なった以上、daemon が機械的に効かせられる開示の枠はサイズとフィールド粒度 だけになった (逆輸入 3 — 中身は解釈しない)。黙って切ると head/agent 発の source (外部に正本が無い) は復元できなくなるため、エラーにして workspace 側が要約に落とすか分割するかを選べるようにする。

上限の値 (2026-08-19、この PR で実測): khi の note (取り込み済み 32 枚: jira 23 枚 / slack 8 枚 / frontmatter 無しの手動メモ 1 枚。実データ上 source.type は jira と slack のみで、bitbucket/mail/head/agent は 0 件) の 本文 (frontmatter を除いた markdown 部分) バイト数分布は次のとおり:

jira  (n=23): max 15,584B / median 1,259B / min   213B
slack (n= 8): max 13,283B / median 6,302B / min 1,298B

観測された最大は jira の 15,584B (ES image registry 起票の課題本文)。 MaxContentBytes は 64 KiB (65,536B) — description 側の実測最大に対して 約 4.2 倍のマージンを取り (この「4.2 倍」は description 側限定の数字— action payload 側のマージンは下記の別実測を参照)、frontmatter を含めた 同ノートのファイル全体サイズの最大 (31,761B) の 2 倍以上をカバーする。 実測 32 件は一度も 16KB を超えていないため、64KiB は「日常的な Jira 課題 本文 / Slack スレッド全文が絶対に切られない」ための十分な余裕でありながら、 1 record が無制限に肥大化するのは防ぐ値として選んだ。

action payload 側の実測 (2026-08-19、この PR で追加実測): 上の分布は description (本文) 側だけの実測であり、同じ MaxContentBytes が適用される action payload (attrs_set 等) は書き込まれる内容の性質が違うため、 「description で妥当だったから payload でも妥当」とは言えない。そのため khi 側の claims / attrs データで別途実測した:

claims JSONL の 1 レコード          (n=109): max  5,537B / p95 2,571B / median   251B
畳んだ attrs 全体 (frontmatter 相当) (n= 31): max 22,572B /  —        / median 1,039B

khi の daemon_sync.py:497 (`send_action(task_id, "attrs_set", diff)`) は 初回 push 時に desired_attrs 全体を 1 発の attrs_set payload として送る ため、単発 attrs_set payload の現実的な最大は「畳んだ attrs 全体」の実測 最大 22,572B — MaxContentBytes 64 KiB に対して約 2.9 倍のマージン。

description 側 (4.2 倍) と payload 側 (2.9 倍) でマージン倍率が異なるが、 同じ MaxContentBytes を両方に適用しているのは意図的な判断であり、値を 分ける根拠が無いという放置ではない:

  • どちらも「1 回の書き込みで daemon に渡る自由記述/構造化データの塊」 という同じ形をしている (description はタスク本文、attrs_set の payload は note の frontmatter 相当の属性群) — フィールド粒度で 別々の上限を持つほどの構造的な違いは無い。
  • 64 KiB は payload 側の実測最大 22,572B に対しても 2.9 倍の余裕があり、 description 側と同じく「日常的な書き込みが絶対に切られない」を満たす。
  • 上限は「日常値を精密に予測する」ためのものではなく「無制限な肥大化を 防ぐ安全弁」なので、2 つの実測がどちらも同じオーダー (10 の 4 乗 B オーダー) に収まっている以上、値を分けて管理するコストに見合わない と判断した。将来どちらかの分布が大きく変わったら (khi 側 doc の mail 対応リスクと同様) この判断ごと見直すこと。

未確定のまま残るリスク (doc 12 節・このコメントに明記): khi 側 doc は 「mail を足したときに本文 + 添付テキストが載ることは未確定」と書いている。 添付テキストの抽出結果は jira/slack の会話ログよりずっと大きくなり得るため、 mail 対応時にこの実測前提が破れる可能性がある。そのときは新たに mail の 本文分布を実測し、この定数を見直すこと — 黙って追認しない。

適用箇所は 1 箇所ではない (J-10): description の入口である task_create / task_update / BoidOpTaskResolveOrCapture の新規作成パスと、action payload の入口である action_send (= TaskWorkflowService.ApplyAction) の 4 箇所 すべてがこの ValidateContentSize を通る。どれか 1 つでも抜けると迂回路に なるため、新しい書き込み経路を足すときは必ずここを通すこと。

この 4 箇所の外にも actions.payload を直接書く経路がある (task_notify.go の progress / done_request / fail_request) — これらは 2026-08-19 時点で 同じ ValidateContentSize("action payload", ...) を通すよう追加対応済み。 詳細は task_notify.go 側のコメントを参照。

View Source
const MaxSignalAttempts = 5

MaxSignalAttempts is the v0 constant retry ceiling before a signal is considered dead (design doc §2: "無限再配送の防止...v0 は定数 5"). Store functions take maxAttempts as an explicit parameter rather than baking this in directly, so tests can exercise the dead-letter boundary without waiting through 5 real claims — but every non-test caller should pass this constant.

View Source
const ParentIDSentinelRoot = "-"

ParentIDSentinelRoot is a sentinel value for CreateTaskRequest.ParentID that explicitly requests root-task creation. When this value is detected at an entry point (sandbox, CLI, HTTP API), auto-populate is skipped and the stored parent_id is left empty. Use this when a root task must be created from inside a child context where auto-populate would otherwise attach the current task as parent.

View Source
const TriggerSweepResolution = time.Minute

TriggerSweepResolution is the effective lower bound on `every` (N-6, Opus review): the daemon only ever evaluates triggerIsDue once per TriggerLoop sweep tick (internal/server/wire.go wires TriggerLoop.Interval to this SAME constant, so they cannot drift apart), so an `every` below this value does not mean "run more often than once per sweep tick" — it silently collapses to "once per sweep tick", which is not what a project.yaml author who wrote e.g. `every: 1s` would expect (1 sweep tick = 1 minute here, not 1 second — ~1,440 containers/day, not ~86,400). ValidateTriggers rejects anything below this at project.yaml load time rather than let that surprise happen silently at runtime.

View Source
const URLDerivedProjectIDPrefix = "url-"

URLDerivedProjectIDPrefix marks a project id derived from a git URL rather than read from a committed project.yaml's `id:` field (docs/plans/ workspace-default-project.md 決定3/論点g — see internal/api's deriveProjectIDFromURL, the only producer of an id with this prefix).

Exported so ProjectStore.LoadAll and ProjectAppService.FetchProject (the reload paths) can gate their GitHeadReadFailurePathAbsent fallback on it (Codex review, PR5 round 2 Major): that failure kind alone does not distinguish "this project was registered without a project.yaml on purpose" from "this is an ordinary project.yaml-bearing project whose .boid/project.yaml was deleted upstream by mistake" — both read back identically from gitShowHEAD. Silently switching the latter over to the workspace default on next reload/fetch would hide the deletion and swap its task_behaviors out from under it without any degraded signal. Gating on this prefix limits the fallback to projects this daemon itself registered via the no-project.yaml path; every other project keeps degrading exactly as before.

Variables

View Source
var ErrActionListUnscoped = errors.New("action list: no project or workspace scope given")

ErrActionListUnscoped is returned by ListActionsSince when the filter names neither a project scope (ProjectIDs) nor a WorkspaceID. Broker + executor scoping (mirroring BoidOpTaskList/BoidOpCardList exactly) is the primary enforcement point — this is defense in depth at the query itself, cheap to add and directly closes the "brokered scoping bug" class PR-4/PR-5 review flagged three separate times (executor-only scoping with the broker passing a request through unscoped).

View Source
var ErrDetachedHead = fmt.Errorf("project is in detached HEAD state")

ErrDetachedHead is returned by ClassifyBaseBranch when the project working directory is in detached-HEAD state. Wrapped so callers can use errors.Is.

View Source
var ErrIdentityConflict = errors.New("identity already linked to a different task")

ErrIdentityConflict is returned by LinkIdentity when the given (projectID, identity) pair is already bound to a DIFFERENT task. Linking the SAME task again is idempotent (not a conflict) — see LinkIdentity's doc comment.

View Source
var ErrTaskNotFound = errors.New("task not found")

ErrTaskNotFound is returned by scanTask (and propagated by GetTask, FindTaskByRemote, FindTaskByRef) when no matching task row exists. Callers should check for it with errors.Is rather than matching on error strings.

View Source
var ErrTriggerRunAlreadyFinished = errors.New("trigger run is already finished")

ErrTriggerRunAlreadyFinished is returned by CompleteTriggerRun when the row was already closed (or does not exist) — a lost race against the other closer, not a failure to talk to the database.

View Source
var ErrTriggerRunInFlight = errors.New("trigger run: already in flight (single-flight)")

ErrTriggerRunInFlight is CreateTriggerRun's sentinel for "single-flight already holds this (project_id, trigger_name)" — surfaced when the INSERT is rejected by idx_trigger_runs_inflight_unique (migration 0043, Opus review Blocker 1), the partial UNIQUE index on trigger_runs(project_id, trigger_name) WHERE finished_at IS NULL. Callers (internal/api/trigger_loop.go's fireTrigger, and everything that calls it) treat this exactly like an in-memory single-flight "busy" skip — the difference is this one is enforced by the DB itself, so it also catches races the caller's own read-then-check missed (concurrent goroutines, concurrent daemon processes sharing one DB file).

View Source
var ErrTriggerRunNotFound = errors.New("trigger run: not found")

ErrTriggerRunNotFound is LatestTriggerRun's sentinel for "this (project_id, trigger_name) has never run" — same ErrXxxNotFound convention as ErrTaskNotFound (task_identity.go's ResolveIdentity uses the same shape).

Functions

func AckSignals added in v0.4.0

func AckSignals(dbtx db.DBTX, workspaceID string, ids []string) error

AckSignals marks each id acked within workspaceID (acked_at = now WHERE acked_at IS NULL — already-acked rows are left untouched, making re-ack a no-op success rather than an error). Matching is by (workspace_id, id) ONLY (§2: id is not workspace-unique across service/connector) — every row sharing that id, regardless of service/connector, is acked.

Returns an error naming every id that has no matching signal row in workspaceID (typo detection, §2) — the call fails entirely in that case; none of the given ids (known or unknown) are acked, so a caller can retry after fixing the typo without wondering what partially applied.

func ActorFromContext added in v0.2.4

func ActorFromContext(ctx context.Context) string

ActorFromContext は WithActor で設定された actor を返す。未設定なら空文字。

func ActorTask added in v0.2.4

func ActorTask(taskID string) string

ActorTask はサンドボックス内から boid task/action 経由で送られた operation (brokered) の actor 値を返す。taskID はその operation を送った側のタスク自身の ID — 自己申告 (boid task notify 等) では対象タスクと同一、khi 等 workspace push や将来の 代行タスクでは対象タスクと異なりうる。

func AddDetailChild added in v0.2.4

func AddDetailChild(detail json.RawMessage, child TaskTriageChild) (json.RawMessage, error)

AddDetailChild appends child to detail's "children" list, defaulting Status to TaskTriageChildStatusOpen when unset. Idempotent by ID: if a child with the same ID already exists, detail is returned unchanged (a resend after a crash between khi recording the push and receiving the ack must not duplicate the child entry — same dedup posture as the Ref-based task-create get-or-create, 論点7).

func AssignDefaultWorkspaceToUnlinked added in v0.0.8

func AssignDefaultWorkspaceToUnlinked(dbtx db.DBTX, workspaceID string) (int, error)

AssignDefaultWorkspaceToUnlinked inserts a project_workspaces row pointing at workspaceID for every project that does not yet have one. Used at daemon startup to migrate legacy unlinked projects to the default workspace. The INSERT ... SELECT pattern keeps the operation idempotent and atomic in a single statement.

Returns (number of rows inserted, error). Pass the DefaultWorkspaceSlug to land projects in the implicit default workspace.

func AssignWorkspaceIfExists added in v0.0.13

func AssignWorkspaceIfExists(conn *sql.DB, projectID, workspaceID string) error

AssignWorkspaceIfExists atomically checks that workspaceID has a corresponding workspaces row and, if so, assigns projectID to it — all in a single transaction (docs/plans/workspace-db-consolidation.md MAJOR 3, codex review). This replaces the previous WorkspaceExists+ SetProjectWorkspace two-step, which ran as two separate statements: a DELETE landing between them could remove the workspaces row after the existence check passed but before the assign committed, leaving a dangling project_workspaces reference the same MAJOR-5 fix this supersedes was meant to prevent. dbtx must be a *sql.DB (a fresh transaction is opened internally) — passing an existing *sql.Tx would attempt a nested BEGIN, which SQLite does not support the way this function needs.

workspaceID == "" clears the assignment (bypassing the existence check — there is no slug to check), and DefaultWorkspaceSlug is exempt from the check (WorkspaceRepository.EnsureDefault guarantees it always exists), mirroring SetProjectWorkspace's own exemptions.

func BareRepoPath added in v0.1.0

func BareRepoPath(dataDir, workspaceSlug, projectName string) string

BareRepoPath returns the daemon-managed bare repository path for a project named projectName registered into workspaceSlug (docs/plans/ volume-only-daemon.md §論点b layout: "<data_dir>/repos/<workspace-slug>/ <project-name>.git/"). dataDir is the daemon's data-home (~/.local/share/boid equivalent — container-side /home/boid/.local/share/boid in the eventual volume-only deploy).

This is a plain filepath.Join with no validation of its own — a projectName such as "../../../../tmp/owned" cleans straight through it and moves the result outside dataDir/repos/workspaceSlug entirely (PR-2a codex round-1 Blocker 2). Callers that accept projectName from an external caller (an API request body's --name override, ultimately) MUST use SafeBareRepoPath below instead, not this function directly.

func ClaimSignalIDs added in v0.4.0

func ClaimSignalIDs(dbtx db.DBTX, workspaceID string, ids []string) error

ClaimSignalIDs charges one attempt against exactly the ids named. It is the EXPLICIT half of the read/claim split (2026-08-29): `boid signal list` reads with no side effect, `boid signal claim <id>...` says which of those rows were actually handed to a judgment.

ClaimSignals above answers both questions in one step, and that is the problem it exists to fix. `attempts` is the dead-letter counter — five increments and MaxSignalAttempts retires the row — so what it counts had better be "handed to a judgment". ClaimSignals can only count "returned by the read", and a consumer whose read is deliberately WIDER than its judgment charges every row it merely looked at: khi lists MAX_TARGETS*4 rows so that several signals collapsing onto one card still fill its target slots, then judges at most MAX_TARGETS of them, and the remainder it explicitly deferred to the next round has already been charged. Five such rounds retire a signal nobody ever judged, silently.

Deliberately NOT replaced by a time-based expiry, which is the other obvious way to stop a signal nobody can process. A clock cannot tell "this signal is unprocessable" from "the consumer was not running" — the whole khi workspace being down for a week would retire every signal that arrived meanwhile. GCSignals below already encodes that ruling: it refuses to delete a pending row on age alone, no matter what olderThan says, after exactly that shape turned out to be a data-loss bug (its own [H1] note). attempts has the property a clock does not: no consumer, no decay.

Same typo guard and all-or-nothing failure as AckSignals — see its doc comment. An already-acked row is NOT charged (there is nothing left to hand to a judgment) but is not an error either: the row exists, so the caller named something real.

func ClampActionListLimit added in v0.4.0

func ClampActionListLimit(requested int) int

ClampActionListLimit resolves a caller-requested limit (<=0 meaning "use the default") against the two constants above. Always returns a value in [1, MaxActionListLimit] — a caller can request fewer, but never more.

func ClampSignalListLimit added in v0.4.0

func ClampSignalListLimit(requested int) int

ClampSignalListLimit resolves a caller-requested limit (<=0 meaning "use the default") the same way action_list.go's ClampActionListLimit does.

func ClearPendingAnswer

func ClearPendingAnswer(payload json.RawMessage) json.RawMessage

ClearPendingAnswer removes the pending_answer field from the awaiting trait while preserving session_id, question, and question_id. This is called after a hook is spawned so the answer is not consumed again on the next resume. Returns payload unchanged when the awaiting trait is absent or has no answer.

func CloneHostCommandsMap added in v0.0.13

func CloneHostCommandsMap(m map[string]HostCommandSpec) map[string]HostCommandSpec

CloneHostCommandsMap returns a deep copy of m: a new top-level map, plus independent copies of every HostCommandSpec's slice/map fields. Callers such as Server.HostCommands() use this to hand out a snapshot rather than the live internal map, so a caller mutating the returned value (or a slice/map nested inside one of its entries) can never perturb daemon state. A nil input returns nil.

func CompleteTriggerRun added in v0.4.0

func CompleteTriggerRun(dbtx db.DBTX, id string, finishedAt time.Time, exitCode int) error

CompleteTriggerRun records a run's terminal outcome, exactly once per row.

It is NOT idempotent, deliberately: a second call on an already-finished row is refused with ErrTriggerRunAlreadyFinished rather than overwriting finished_at/exit_code. It used to overwrite, on the stated grounds that a fail-open retry path must not error on a second call — but no caller double-calls (selfHealStaleTriggerRun, reconcileInFlight and finishTimeOutTriggerRun each close a row once), and overwriting hid a real race between the two independent closers. See the guard's own comment below.

func ConnectorBuiltinPolicies added in v0.4.0

func ConnectorBuiltinPolicies(pctx PolicyContext) map[string]BuiltinPolicy

ConnectorBuiltinPolicies returns the reduced, connector-scoped builtin policy map a signal-derived trigger's exec job gets INSTEAD OF DefaultBuiltinPolicies(RoleHook, []string{"boid","fetch"}, pctx) (docs/plans/signal-ingest-detailed-design.md §5.2, Q27):

  • "boid" -> connectorPolicy(pctx): ONLY OpBoidSignalIngest / OpBoidSignalCursorGet / OpBoidJobDone are allowed. Nothing else from the general boidPolicy set (task_create, card/action reads, ...) is reachable — a connector job cannot touch boid state beyond its own source's ingest/cursor. OpBoidJobDone is included alongside those two (rather than excluded like every other general op) because it is not a "touch boid state" capability the §5.2 reduction is meant to deny — handleBoidBuiltin (internal/sandbox/broker.go) restricts it to the caller's OWN job id (entry.Context.JobID) regardless of policy, so granting it cannot reach another job/project. Omitting it was a real bug (found during shadow-a's 2026-08-27 2-hour observation): every connector job's in-container runner posts `boid job done` to report its own completion (internal/sandbox/runner/runner.go's postJobDone, the same mechanism every other non-foreground job relies on) — with job_done missing from AllowedOps, the broker rejected that call, and the daemon's "runtime exited without boid job done" fallback then forced every connector run's real (successful) exit_code=0 into a recorded exit_code=1/JobStatusFailed, which trigger_loop.go's trackFailStreak counted as a real failure on every single run.
  • NO "fetch" entry at all (§5.2: "fetch builtin も渡さない — connector の外部到達は gateway で足りる"): a connector job's only network path is the API gateway (already reached via $BOID_API_BASE/$BOID_SIGNAL_SERVICE), not the general-purpose fetch builtin every other hook/exec job gets.

Called only by dispatcher.BuildSessionJobSpec when SessionJobInput.ConnectorPolicy is true — every other job keeps calling DefaultBuiltinPolicies unchanged.

func CreateAction

func CreateAction(ctx context.Context, dbtx db.DBTX, a *Action, resolver MetaProjectResolver) error

CreateAction inserts a, then — within the SAME statement's transaction — ingests it into its target card's workspace inbox when eligible (docs/plans/boid-internal-signal-inbox.md §4.5). resolver may be nil (no metaproject lookup wired — e.g. most existing tests that don't care about signals at all): IngestActionSignal treats that identically to "this workspace declares no metaproject", a quiet no-op that leaves every other behavior of this function untouched (Q5's "1 ビットも変わらない").

ctx carries the write's origin project via WriterProjectIDFromContext (signal_ingest_bridge.go) when this write came from inside a sandbox (internal/server/boid_executor.go's ExecuteBoidBuiltin is the sole place that ever sets it) — used only for the actor-axis self-reference check, never for anything this function itself does with a.

func CreateProject

func CreateProject(dbtx db.DBTX, project *Project) error

CreateProject inserts a new project record.

func CreateTask

func CreateTask(dbtx db.DBTX, t *Task) error

func CreateTriggerRun added in v0.4.0

func CreateTriggerRun(dbtx db.DBTX, run *TriggerRun) error

CreateTriggerRun inserts a new in-flight run (FinishedAt/ExitCode unset). run.ID is generated when empty, mirroring CreateTask/CreateAction (store.go).

run.JobID may be empty (Opus review Blocker 1): the row is created FIRST, BEFORE dispatch, so single-flight is claimed via this INSERT succeeding — not via a later read. There is no job id yet at that point (StartExec hasn't been called); SetTriggerRunJobID fills it in once dispatch succeeds. See internal/api/trigger_loop.go's fireTrigger for the full insert → dispatch → fill-in-job-id sequence, and this PR's report ("single-flight の直し方") for why this ordering, not the reverse, is required to close the race.

Returns ErrTriggerRunInFlight (not a generic error) when idx_trigger_runs_inflight_unique rejects the insert — i.e. some other row for the same (project_id, trigger_name) is already in flight.

func DecodeActionCursor added in v0.4.0

func DecodeActionCursor(cursor string) (createdAt time.Time, id string, err error)

DecodeActionCursor parses EncodeActionCursor's output. An empty string decodes to the zero Time and empty id ("from the beginning") without error. A non-empty but malformed cursor is a hard error — J-10's general posture (machine-readable contracts error loudly on bad input rather than silently reinterpreting it) applies here too: silently treating a corrupted cursor as "from the beginning" would quietly re-deliver a script's entire history instead of surfacing the mistake.

func DefaultBehaviorResolvable added in v0.1.0

func DefaultBehaviorResolvable(meta *ProjectMeta) bool

DefaultBehaviorResolvable reports whether ResolveBehavior would succeed for a task creation request that specifies neither behavior nor behavior_spec, given meta — mirroring the exact resolution order ResolveBehavior's own default-resolution branch below uses (docs/plans/ workspace-default-project.md 論点d, fable 2巡目 m2): meta.DefaultTaskBehavior must be both set AND actually resolve via LookupBehavior, else a behavior literally named "supervisor" must exist in meta.TaskBehaviors, else it is not resolvable.

Used at project-registration time (CreateProjectFromGitURL's project.yaml-less path) to decide whether the workspace default alone is sufficient before allowing registration to succeed. Deliberately NOT "does a default project definition exist" — a workspace default that defines task_behaviors but sets neither default_task_behavior nor a "supervisor" entry must still be rejected here, exactly as a behavior-unspecified task creation against it would 400 later.

func DefaultBranch added in v0.1.0

func DefaultBranch(bareRepoPath string) (string, error)

DefaultBranch returns a bare repo's default branch — its HEAD symbolic ref, short form (docs/plans/volume-only-daemon.md §論点a: "Default branch determined by bare repo's HEAD symbolic ref (`git symbolic-ref HEAD`)").

func DefaultBuiltinPolicies

func DefaultBuiltinPolicies(role Role, names []string, pctx PolicyContext) map[string]BuiltinPolicy

DefaultBuiltinPolicies creates per-command BuiltinPolicy values for the given role and command names. "boid" is always available as a builtin; pass it explicitly via names.

func DefaultHostCommandsPath added in v0.0.13

func DefaultHostCommandsPath() (string, error)

DefaultHostCommandsPath returns the default path for the aggregated host_commands.yaml config: $XDG_CONFIG_HOME/boid/host_commands.yaml, or ~/.config/boid/host_commands.yaml when XDG_CONFIG_HOME is unset (matching the behaviour of os.UserConfigDir on Linux). Mirrors DefaultWorkspaceDir's resolution strategy (workspace_store.go).

func DefaultWorkspaceDir added in v0.0.8

func DefaultWorkspaceDir() (string, error)

DefaultWorkspaceDir returns the default directory for workspace YAML files: $XDG_CONFIG_HOME/boid/workspaces, or ~/.config/boid/workspaces when XDG_CONFIG_HOME is unset (matching the behaviour of os.UserConfigDir on Linux).

func DeleteProject

func DeleteProject(dbtx db.DBTX, id string) error

DeleteProject removes a project by ID. All tasks (and their dependent records) belonging to the project are deleted first. Standalone jobs (task_id NULL session / hook) are also swept by project_id so the jobs.project_id FK constraint does not refuse the project delete.

func DeleteTask

func DeleteTask(dbtx db.DBTX, id string) error

func DeleteTaskTriage added in v0.2.4

func DeleteTaskTriage(dbtx db.DBTX, taskID string) error

DeleteTaskTriage resets a card's CardAttrs columns back to their empty defaults without deleting the task row itself. Before card-model-cleanup PR-2 (migration 0045) this deleted a separate task_triage sidecar row — deleting the parent task row already cascaded that via ON DELETE CASCADE (0035_add_task_triage.sql), so the only real use was explicit cleanup of the sidecar's CONTENT without touching the task. Now that the content lives on the tasks row itself, "delete the sidecar" can only mean resetting those columns; the task row (and its type='card') is untouched. Has no production caller as of this PR (grep confirms) — kept for interface/test-double compatibility, same posture as its predecessor.

func DeleteTriggerRun added in v0.4.0

func DeleteTriggerRun(dbtx db.DBTX, id string) error

DeleteTriggerRun removes a trigger_runs row outright — the dispatch- failure cleanup path (Opus review Blocker 1): fireTrigger claims single-flight by inserting a row BEFORE calling StartExec, so a dispatch failure must undo that claim to preserve the pre-existing "fail-open, retry the very same instant" contract (TestSweepTriggers_DispatchFailure_FailsOpenAndRetriesImmediately) — CLOSING the row instead (CompleteTriggerRun) would leave a real started_at behind, making the immediately-following retry see `every` as not yet elapsed. Deleting, not closing, is what keeps that test's behavior byte-for-byte unchanged.

func DeriveProjectNameFromURL added in v0.1.0

func DeriveProjectNameFromURL(rawURL string) (string, error)

DeriveProjectNameFromURL derives a project name from a git remote URL's last path component, stripping a trailing ".git" (docs/plans/ volume-only-daemon.md §論点a: "project-name は URL から derive"). Handles both slash-delimited forms (https://host/owner/repo(.git)?, ssh://host/owner/repo(.git)?) and the scp-like form (git@host:owner/repo(.git)?) since both end in a '/'-delimited path segment.

func DetailSuggestionRaw added in v0.4.0

func DetailSuggestionRaw(detail json.RawMessage) (json.RawMessage, bool)

DetailSuggestionRaw returns the raw JSON bytes of task_triage.detail's current suggestion (same top-level-then-attrs precedence as DetailSuggestion above — see its own doc comment), for a caller that needs MORE than the fixed Suggestion struct's four fields expose. accept(verb) (docs/plans/suggestion-as-state-transition-impl.md §3, internal/api/suggestion_accept.go) is the concrete reason this exists: park's params.wake_at/wake_task_id are a WRITE-side addition Suggestion itself does not carry (Suggestion is the stable read/display-side projection this PR does not otherwise touch). Reuses decodeSuggestion purely as the "is this candidate non-empty and well-formed" check, so the two functions can never disagree about WHICH candidate wins.

func DropDetailChild added in v0.4.0

func DropDetailChild(detail json.RawMessage, id string) (out json.RawMessage, changed bool, err error)

DropDetailChild closes the child with the given id because khi decided not to pursue it — a wrong project baked into the spec, a duplicate of another child, or a stray left behind while the subagent was exploring the write CLI. Idempotent: an already-closed child returns changed=false so a resend after a lost ack does not append a duplicate action.

This is the counterpart MarkDetailChildClosed cannot be: that one matches on TaskRef, which only exists once a child has been task-ified, so a child still sitting at "open" or "specced" can never reach "closed" through it. Without this function such a child is unclosable, and since ShouldAutoDone requires EVERY child closed, one stray entry keeps its whole card from ever finishing (the failure mode task_triage's child docs already warn about, hit in production 2026-08-21).

A "dispatched" child is refused. That status is the daemon's own mechanical fact (論点9) and its task is still running: closing it here would let ShouldAutoDone fire while real work is in flight. Withdrawing live work is an abort of the child's task, not a triage-detail edit.

func EncodeActionCursor added in v0.4.0

func EncodeActionCursor(createdAt time.Time, id string) string

EncodeActionCursor renders a (created_at, id) pair as the opaque cursor string BoidOpActionList's wire contract carries.

id is part of the cursor — not just created_at — because actions.id is a random UUID (migration 0001_initial.sql), not a creation-ordered sequence: two actions created in the same instant would otherwise be indistinguishable by created_at alone, and a cursor that cannot tell them apart risks silently skipping or re-delivering one of the pair. Ordering by (created_at, id) together, consistently on both the SELECT's ORDER BY and the cursor's WHERE threshold, is the standard keyset-pagination technique for exactly this "ties on the primary sort key" case.

The real-world source of same-instant ties is internal/dispatcher/store.go's markStaleTasksAborted: it takes ONE now := time.Now().UTC() OUTSIDE its per-task loop and inserts N action rows sharing that exact value (the daemon-restart bulk-abort path) — NOT TaskWorkflowService.persistFiredEvents (internal/api/workflow_action.go), which calls CreateAction once per event inside the loop and so gets a fresh time.Now() per row (measured: three rows in one transaction landed with distinct nanosecond timestamps, never tied). Getting this citation right matters: if a future reader "verifies" that ties don't happen by checking persistFiredEvents alone, they will conclude id is unnecessary and drop it — see TestListActionsSince_TiedCreatedAt_PageBoundary_NoDuplicatesNoGaps (action_list_test.go) for the reproduction against the actual tie source.

func ExpandBaseBranch

func ExpandBaseBranch(value, workDir string) (string, error)

ExpandBaseBranch expands ${current_branch} (or $current_branch) in value by reading the HEAD branch of the git repo at workDir. Unknown variables are left as-is for backward compatibility. Returns an error if the git command fails or the repo is in detached HEAD state.

func ExpandHostCommandsForDispatch added in v0.0.13

func ExpandHostCommandsForDispatch(raw map[string]HostCommandSpec) map[string]HostCommandSpec

ExpandHostCommandsForDispatch returns a clone of raw with each entry's Path and Env values expanded via interpolateHostCommands against the daemon process's own environment (MAJOR 2 codex review finding). The aggregated host_commands.yaml config on disk — and the map this function receives when called with the value LoadHostCommandsConfig just parsed — stores raw/unexpanded definitions by design (see readKitHostCommandsRaw's doc comment: expanding at aggregation time would bake resolved values, possibly secret-shaped, into that file, and would let two kits using differently-named placeholders that happen to resolve to the same value silently evade collision detection). But a raw `path: ${HOME}/bin/gh` is useless to exec.LookPath at dispatch time — something has to expand it before ProjectStore ever hands a HostCommandSpec to the sandbox.

Call this once at daemon startup on the freshly loaded raw config and wire the *expanded* result into ProjectStore.SetHostCommands (the dispatch-time read path), while Server.HostCommands() keeps handing out the raw CloneHostCommandsMap snapshot unchanged (the PR2 contract: the on-disk file and the API-visible snapshot both stay raw/inspectable).

raw is never mutated: the returned map (and every HostCommandSpec.Env value map inside it) is an independent deep copy (CloneHostCommandsMap) before interpolateHostCommands runs in place on that copy.

func ExpandTaskBaseBranch

func ExpandTaskBaseBranch(template, remoteID string) (string, error)

ExpandTaskBaseBranch expands the ${TASK_REMOTE_ID} template variable in template against the supplied remoteID. Other template variables are rejected with one specific carve-out: ${current_branch} (the variable owned by ExpandBaseBranch) is preserved as-is so callers can compose the two expanders without ordering surprises.

Contract:

  • Static values (no ${...} or $... markers, or only ${current_branch}) pass through unchanged. An empty remoteID is fine in that case.
  • If the template references ${TASK_REMOTE_ID} but remoteID is empty, expansion fails: task creation must not silently produce a broken branch name. Callers are expected to surface this as a 400.
  • Any other ${VAR} or $VAR reference is rejected. This intentionally restricts the surface; the longer-term plan is to keep template variables to an explicit allow-list rather than letting arbitrary env vars leak into task state.

func FilterPayloadByTraits

func FilterPayloadByTraits(payload json.RawMessage, consumes []TraitType) json.RawMessage

FilterPayloadByTraits returns a payload containing only the top-level keys matching the listed traits. If consumes is empty, an empty payload is returned.

func FoldDetailAttrs added in v0.2.4

func FoldDetailAttrs(detail json.RawMessage, patch map[string]json.RawMessage) (json.RawMessage, error)

FoldDetailAttrs merges patch into detail's top-level "attrs" object, last-write-wins per key, leaving every other top-level key (children, summary, ...) untouched. This backs the "attrs_set" action vocabulary entry (docs/plans/cross-project-issue-triage.md PR-4 設計メモ 論点4/6).

Deliberately a PURE fold with zero policy: it does not know or care what keys mean (urgency, summary, ...) and does not enforce monotonicity or any other invariant on a key's value across writes. That kind of policy (e.g. "urgency only ever increases") is khi's responsibility on the evaluate side, per 論点6's closing note — encoding it here would be a boundary violation the same way `applyParkSideEffect` does not decide whether a wake_at is "reasonable".

func FormatMigrationIssue added in v0.0.8

func FormatMigrationIssue(p ProjectMigrationIssue) string

FormatMigrationIssue renders a single ProjectMigrationIssue using the canonical multi-line format. When ProjectID is non-empty the output is prefixed with `project "<ID>": ` to mirror the wrapping previously done by project_store.LoadAll via fmt.Errorf("project %q: %w", id, err).

Exported so that callers building aggregate messages (server/wire.go, boid start parent) can reuse the same canonical format for each issue.

func GCSignals added in v0.4.0

func GCSignals(dbtx db.DBTX, olderThan time.Duration, dryRun bool) (int64, error)

GCSignals deletes signals rows that are STRUCTURALLY eligible — acked (judgment complete) or dead-lettered (retries exhausted, attempts >= MaxSignalAttempts) — and, when olderThan > 0, additionally old enough (acked_at, respectively received_at, before the cutoff). olderThan=0 disables the AGE filter only, matching GCTasks (status IN (...)) / GCTriggerRuns (finished_at IS NOT NULL): those siblings keep a non-time STATE predicate that protects live rows even when the caller asks for an unbounded sweep, and GCSignals now does the same — a still-pending signal (unacked, attempts < MaxSignalAttempts) is NEVER eligible for deletion, regardless of olderThan.

[H1, Opus review 2026-08-26, CONFIRMED data-loss bug]: an earlier version of this function had no structural gate — at olderThan<=0 its WHERE clause degenerated to `1 = 1`, deleting EVERY signal in the table, including brand-new pending (attempts=0) rows that had never even been claimed once. Worse, signal_cursors was left pointing PAST the deleted rows (IngestSignals had already advanced it), so the connector's own "occurred_at <= cursor, drop it" self-filter (§5.3) would never let those rows be re-ingested — permanent, silent loss. Reachable via `boid gc --older-than 0`, `POST /api/gc {"older_than":"0s"}`, or the 24h auto-GC loop if `gc.older_than` were ever configured to 0. The structural gate below closes this: a pending row can never match, so it survives every combination of olderThan and dryRun.

Intended to run inside the SAME transaction as GCTasks/GCTriggerRuns (TaskGCStore.GC, repository.go) — a single statement, so it needs no tx guarantee of its own the way IngestSignals/ClaimSignals do.

func GCTriggerRuns added in v0.4.0

func GCTriggerRuns(dbtx db.DBTX, olderThan time.Duration, dryRun bool) (int64, error)

GCTriggerRuns deletes FINISHED trigger_runs rows older than olderThan (N-2, Opus review): with no retention at all, this table grows unbounded (`every: 10m` × 1 trigger = 144 rows/day = ~52,560 rows/year; khi's 2 triggers alone project to ~105,000 rows/year). olderThan=0 disables the time filter, matching GCTasks' own convention (every finished row is eligible). In-flight rows (finished_at IS NULL) are NEVER touched regardless of age — they are single-flight's own source of truth, not stale history (the same reason GCTasks never deletes a non-terminal task).

Called from TaskGCStore.GC in the SAME transaction as GCTasks, so `boid gc` / POST /api/gc purges trigger_runs on the existing 30-day schedule without a separate GC pass.

func GetSignalCursor added in v0.4.0

func GetSignalCursor(dbtx db.DBTX, workspaceID, service, connector string) (string, error)

GetSignalCursor returns (workspaceID, service, connector)'s stored cursor, or "" if the source has never ingested (design doc §2: "無ければ空文字 (= 最初から)").

Contract (design doc §5.3): the cursor is EXCLUSIVE of itself from the connector's point of view — a conformant connector drops anything with `occurred_at <= cursor` before ever calling `boid signal ingest`, and treats `occurred_at > cursor` as new. This store does not enforce or interpret that filtering itself (PK-based dedup in IngestSignals is a second, independent safety net for exact-duplicate re-sends; a well-behaved connector's own `<= cursor` filtering is what keeps fetch volume down) — GetSignalCursor just returns the opaque stored value.

[L8, Opus review 2026-08-26] KNOWN RISK inherited from this exclusive-boundary design (same bug family as khi's pre-rewrite ts-based bookmarks — see the boid-project memory note "khi-source-bookmark-must-be-exclusive"): if two sibling events share the EXACT SAME occurred_at and the cursor advances to that timestamp after only one of them has been ingested (the other arriving from the source in a later page/fetch), the connector's own `occurred_at <= cursor` self-filter will silently drop the sibling FOREVER — it never reaches IngestSignals, so PK-based dedup never even sees it to no-op it. This is not something the store layer can fix (a cursor here is a single scalar, not a set of "ids already seen at this timestamp"). Pack authors (§7.2) working with sub-second or tie-prone sources should add a secondary tiebreaker (e.g. sort by id too) in their own fetch logic rather than relying on occurred_at alone to be unique.

func HasPendingSignals added in v0.4.0

func HasPendingSignals(dbtx db.DBTX, workspaceID string, maxAttempts int) (bool, error)

HasPendingSignals reports whether workspaceID has at least one pending (unacked, attempts < maxAttempts) signal — the `on: signals` trigger predicate (design doc §4.2). Dead signals never count: a workspace with only dead-lettered signals must not fire its trigger forever (signal-driven-review.md §8.1).

func IngestActionSignal added in v0.4.0

func IngestActionSignal(ctx context.Context, dbtx db.DBTX, a *Action, resolver MetaProjectResolver) error

IngestActionSignal is CreateAction's internal-signal ingest step (design doc §4). Exported — rather than a private helper only CreateAction calls — so tests can exercise the ingest DECISION in isolation from the actions table's own id PRIMARY KEY (a real action id can only ever be INSERTed once, so a test proving re-ingest of the SAME action id is a no-op, Q10, has to call this directly with a repeated Action value rather than through CreateAction twice).

Best-effort by design (§6.2: "ingest 失敗で action の書き込みを巻き戻さな い"). CreateAction calls this AFTER its own INSERT has already run (as one statement within the caller's transaction) and only logs whatever error this returns: a failed ingest means the workspace misses ONE signal for this action, which is recoverable — the same card's next action carries its own signal (§6.2's "取りこぼした signal は次に同じ card が動いたとき の signal でカバーされる"). It must never fail the caller's transaction: the action is the fact, the signal is a side effect of it, and undoing the fact because the side effect failed would invert that causality (§6.2).

func IngestSignals added in v0.4.0

func IngestSignals(dbtx db.DBTX, workspaceID, service, connector string, rows []SignalIngestRow) error

IngestSignals is a connector's single entry point into the inbox: for each row it INSERT OR IGNOREs into signals (PK-based dedup, Q10) and then advances (workspace, service, connector)'s cursor to max(rows.OccurredAt) — but ONLY forward, never backward (a batch that is entirely older than the current cursor leaves it untouched).

Callers MUST invoke this within a single transaction (dbtx must be a db.DBTX backed by an open *sql.Tx, or the whole call must itself be the only statement running against a *sql.DB) — the INSERTs and the cursor UPDATE/INSERT are only atomic as a unit if dbtx guarantees it. See TaskRepository.IngestSignals (repository.go) for the wrapper that provides this guarantee when given a raw *sql.DB, and this file's own package doc comment for why (Q13: crash between the inserts and the cursor advance must not lose signals OR leave the cursor pointing past unsaved rows).

func IsBareRepoDir added in v0.1.0

func IsBareRepoDir(dir string) bool

IsBareRepoDir reports whether dir looks like a daemon-managed bare git repository (docs/plans/volume-only-daemon.md §論点b layout: "<data_dir>/repos/<workspace-slug>/<project-name>.git/") rather than a filesystem project checkout (which has its .git as a *subdirectory*, not visible at this level, and a .boid/project.yaml directly on disk). ProjectStore.LoadAll uses this to decide whether a registered project's WorkDir should be loaded via ReadProjectMetaFromBareRepo (this file) or ReadProjectMetaWithKits (spec_loader.go, the pre-existing filesystem path) — both project models coexist post-PR-2a (see that migration path's own doc comment in project_store.go).

Detection: a bare repo has HEAD (a file, not a directory) and objects/ (a directory) directly under dir. This is deliberately cheap (two os.Stat calls, no git subprocess) since LoadAll runs it once per registered project on every daemon startup/reload.

func IsCardTransitionAction added in v0.4.0

func IsCardTransitionAction(actionType string) bool

IsCardTransitionAction reports whether actionType is one of the six card-lifecycle transition verbs the push-down defense (穴11) restricts to actor==human requests. Non-transitioning card actions (attrs_set and friends) and wake_due are excluded: khi may still send those directly.

func IsInstructionsEditable

func IsInstructionsEditable(taskType TaskType, status TaskStatus) bool

IsInstructionsEditable reports whether a task's instructions can be edited, given its type and current status. Instructions are an execution-only concept (ExecAttrs.Instructions — a Card has no instructions field at all, design doc §3.2's field attribution table), so this is only ever true for an execution task sitting in "pending" (avoiding races with in-flight handlers / post-execution mutations).

Before card-model-cleanup PR-2 this delegated to IsPreDispatchEditableStatus, which — once card machine v2 folded captured/triaged into parked — also returned true for a parked card; that was already dead-end behavior (task_service.go's caller had nowhere meaningful to write a parked card's "instructions" even then), not an intentional editing surface. The ExecAttrs split now makes writing instructions onto a card structurally impossible, so this predicate is narrowed to match.

func IsPreDispatchEditableStatus added in v0.2.4

func IsPreDispatchEditableStatus(taskType TaskType, status TaskStatus) bool

IsPreDispatchEditableStatus reports whether title/project/instructions can still be edited, given the task's type and current status. card-model- cleanup PR-2 (docs/plans/card-model-cleanup.md §3.3) retired the old status-only predicate (which leaned on now-deleted legacy statuses to answer "is this a pre-dispatch card") in favor of a direct type switch:

  • Card: editable only in "parked", the card's resting/undecided state (a 整形セッション, UC-3, needs to edit these).
  • Execution: editable only in "pending" (execution not yet started).

parked WAS deliberately excluded pre-card-machine-v2 ("a parked task is set aside and not the target of active editing") — that premise broke when card machine v2 folded captured/triaged into parked: parked is now a card's INITIAL state (not just a later "set aside" one), so excluding it made every fresh card permanently uneditable (title/project/instructions), with only description slipping through (PR #987 review, HIGH 7). working is unchanged: once a card has specced/dispatched children or manual work underway, re-editing its title/project out from under that is still the wrong default.

func IsReadonly

func IsReadonly(task *Task) bool

IsReadonly returns true if the task's working directory should be mounted read-only. Driven solely by the task's Exec.Readonly flag (e.g. plan tasks) — Readonly is execution-only (design doc §3.2); a card (Exec == nil) never mounts a sandbox at all, so false is the only sensible answer.

func IsTerminalStatus added in v0.2.4

func IsTerminalStatus(status TaskStatus) bool

IsTerminalStatus は task がこれ以上遷移しない終端状態かを返す (done/aborted/dropped)。 GC 対象判定・open/closed フィルタ・boid task watch の終了判定はすべてここを経由する。

func IsURLDerivedProjectID added in v0.1.0

func IsURLDerivedProjectID(id string) bool

IsURLDerivedProjectID reports whether id was derived from a git URL (project.yaml-less registration, PR5) rather than read from a committed project.yaml's `id:` field.

func LinkIdentity added in v0.4.0

func LinkIdentity(dbtx db.DBTX, projectID, identity, taskID string) error

LinkIdentity binds identity (scoped to projectID, I-3) to taskID. Linking an identity that already points at taskID is a no-op success (idempotent — a workspace resend of the same push must not fail). Linking an identity that already points at a DIFFERENT task returns ErrIdentityConflict; the existing binding is left untouched (this store never does silent newest-wins — see match_card.py's build_key_index() note in the design doc for the bug class this replaces).

func ListIdentitiesByTask added in v0.4.0

func ListIdentitiesByTask(dbtx db.DBTX, taskID string) ([]string, error)

ListIdentitiesByTask returns every identity string bound to taskID (empty, not nil, when the task has none), ordered for determinism.

func ListTaskTriageByTaskIDs added in v0.3.11

func ListTaskTriageByTaskIDs(dbtx db.DBTX, taskIDs []string) (map[string]*CardAttrs, error)

ListTaskTriageByTaskIDs batch-fetches task_triage sidecar rows for a set of task IDs in O(chunks) queries instead of O(len(taskIDs)) — the Parked/Queue Web UI views used to call GetTaskTriage once per row (internal/api/web.go's triageByTaskID), and #task-list polls every 5s (tasks.templ's hx-trigger), so that N+1 scaled linearly with poll frequency × view size (BD-8 残件1). A taskID with no sidecar row is simply absent from the returned map — same "missing means no enrichment" contract callers already read off GetTaskTriage's sql.ErrNoRows today, just expressed as map absence instead of a per-call error.

Best-effort across BOTH axes, same posture as the old per-task GetTaskTriage loop it replaces (Opus review finding, 2026-08-18: an earlier version of this function aborted the entire call — discarding rows already scanned from prior chunks — on a single row's Scan error, which is a real, if narrow, possibility independent of the chunk/query succeeding: e.g. a wake_at value written by something other than UpsertTaskTriage's own nullableTime path, in a format sql.NullTime can't parse. That would have turned exactly one malformed row into "every card on the Parked/Queue tab loses its badge" — the class of silent whole-view failure 決定9 exists to prevent):

  • a single row's Scan error is skipped, not fatal — every other row in that chunk, and every other chunk, still gets processed
  • a whole chunk's Query failing (or a mid-stream rows.Err()) does not discard rows already gathered from earlier chunks; remaining chunks still run

The first error encountered (if any) is still returned alongside whatever partial map was gathered, so a caller that wants to log/surface it can — but the map itself, not the error, is the thing to check for "did I get anything useful" (see triageByTaskID's doc comment, internal/api/web.go, for how the actual call site uses this).

func LoadHostCommandsConfig added in v0.0.13

func LoadHostCommandsConfig(path string) (map[string]HostCommandSpec, error)

LoadHostCommandsConfig reads and parses the aggregated host_commands.yaml config at path. A missing or empty file is not an error — it returns an empty map — since the file may not have been written yet (fresh install, before the first daemon-startup preflight runs). Parsing is strict at every level (top-level keys and each command's fields, including nested reject rules — see hostCommandSpecStrict) so a typo in the hand-edited file (docs/plans/workspace-db-consolidation.md's documented edit path) surfaces as a load error rather than being silently ignored.

func LoadHostCommandsFromKits added in v0.0.13

func LoadHostCommandsFromKits(kitsDir string) (map[string]HostCommandSpec, error)

LoadHostCommandsFromKits scans kitsDir for installed kits — each a subdirectory containing a kit.yaml — and aggregates their host_commands sections into a single map keyed by command name. Definitions are read raw (readKitHostCommandsRaw): no env-var interpolation and no other kit.yaml validation runs on this path (see readKitHostCommandsRaw's doc comment).

A missing kitsDir (no kits installed yet, or KitsDir unconfigured) is not an error: it returns an empty map, matching the "空扱い" decision in docs/plans/workspace-db-consolidation.md (host_commands 実定義の集約先).

Two kits may declare the same command name only when the definitions are identical after normalizeHostCommandSpec (nil/empty slice-and-map fields unified) and reflect.DeepEqual — that case is silently deduped into one entry. If two kits declare the same name with different definitions, this returns an error naming both kit directories and the conflicting command; callers are expected to treat this as fatal (daemon startup abort per decision 9 in the plan doc — "host_command 名前衝突は migration fail").

func MarkDetailChildClosed added in v0.2.4

func MarkDetailChildClosed(detail json.RawMessage, childTaskID string) (out json.RawMessage, changed bool, err error)

MarkDetailChildClosed marks the child entry whose TaskRef equals childTaskID as closed. This is the daemon's own self-record of the "child_closed" vocabulary entry (論点9) — khi never calls this; the TaskWorkflowService hooks it directly into the child task's own done/aborted finalization path. changed=false means no matching, not-already-closed child was found (already closed by an earlier call, or this task was never linked via TaskRef) — callers use this to skip appending a duplicate action.

func MarshalWorkspaceEnvelope added in v0.1.0

func MarshalWorkspaceEnvelope(e *WorkspaceEnvelope) ([]byte, error)

MarshalWorkspaceEnvelope renders one envelope as the bytes of a single yaml document, and verifies that those bytes parse back into the same values.

The verification is what turns D13-b from arithmetic into a property. Every caller that WRITES an export goes through here, so a string this file's rule does not anticipate — a yaml.v3 upgrade changing a style choice, a spec field of some shape nobody considered — fails the export loudly, naming the key, instead of producing a file that is discovered to be unrestorable at restore time. It cannot produce a false alarm on a document that is in fact fine: the comparison is against the emitter's own node tree, value for value.

The size half of "applicable" lives with the caller (api.checkWorkspaceEnvelopeIsApplicable): it is a property of the daemon's request cap, which this package knows nothing about.

func MaterializeWorkspaceKitsForPersist added in v0.0.13

func MaterializeWorkspaceKitsForPersist(kitsDir string, kitRefs []string, meta *WorkspaceMeta) error

MaterializeWorkspaceKitsForPersist resolves kitRefs (a legacy `kits:` reference list, sourced by the caller — see below) against the kits installed under kitsDir, merging their host_commands (folded in as reference names) and env into meta in place — the exact same expansion MigrateWorkspaceYAMLToDB performs once at cutover (a kit's additional_bindings is read too, but no longer materialized into anything — see materializeKitRuntimeIntoWorkspace's doc comment, Phase 4 PR4).

Phase 2.5 PR7 (docs/plans/workspace-db-consolidation.md, decision 12) removed WorkspaceMeta.Kits outright: this function used to read meta.Kits and clear it after resolving. There is no longer a Kits field to read, so kitRefs is now an explicit parameter the caller must source itself. The only remaining caller is cmd/workspace.go's ensureWorkspaceExistsForAssign (`boid workspace assign`'s auto-create convenience path), which extracts a legacy `kits:` key straight out of the raw on-disk shadow yaml before this call — the wire-level POST/PUT/import bodies no longer accept a kits: key at all (workspaceMetaStrict has no such field any more), so no server-side caller needs this any longer. cmd/project_migrate.go no longer calls this either: its own auto-generated legacy kit's host_commands are folded directly into the workspace meta from the legacy project.yaml's own fields (mergeLegacyFieldsIntoWorkspace), with no kit-directory round trip needed at all — only a *pre-existing, externally referenced* kit (like ensureWorkspaceExistsForAssign's case) needs this function's disk lookup.

This was discovered as a real e2e regression (docker-proxy-* scenarios failing with "$DOCKER_PROXY_TEST_ROOT/docker-proxy-test.sh: not found", exit 127) when `boid workspace assign`'s auto-create path (introduced in PR4) funneled a legacy `kits: [docker-proxy-test]` yaml straight into WorkspaceRepository.Create without this expansion step — the workspaces table has no kits column at all (decision 「kits カラム無し」), so an unmaterialized kit reference would silently vanish on save.

len(kitRefs) == 0 is a fast path: the overwhelming majority of calls (any workspace that never referenced a kit) never touch the filesystem at all.

func MergePayload

func MergePayload(base, update json.RawMessage) (json.RawMessage, error)

func MergePayloadPatch

func MergePayloadPatch(base, patch json.RawMessage, handlerID string, allowedTraits []TraitType) (json.RawMessage, error)

func MigrateWorkspaceYAMLToDB added in v0.0.13

func MigrateWorkspaceYAMLToDB(conn *sql.DB, workspaceDir, kitsDir string, projectRepo *ProjectRepository) error

MigrateWorkspaceYAMLToDB performs the one-time cutover (docs/plans/workspace-db-consolidation.md マイグレーション節 PR3) from yaml-file-authority workspaces (DefaultWorkspaceDir()/*.yaml + kit yaml under kitsDir) to DB-authority workspaces (the `workspaces` table). Call this once at daemon startup, after internal/db/migrate.Apply(conn) has already added the schema_migrations.state/input_hash columns (migration 0031) and the workspaces table (migration 0030).

Idempotent: once schema_migrations records workspace_db_consolidation as state=committed, every subsequent call returns nil immediately without touching the filesystem or the DB.

Crash recovery: if a previous call was interrupted between recording state=staging and reaching state=committed, the next call recomputes the preflight input_hash and compares it against the recorded one — a match rolls forward (safe: every step from here on is an idempotent upsert/atomic-rename), a mismatch aborts with an error (the on-disk inputs changed since the interrupted attempt; automatic reconciliation would risk silently mixing old and new state, so this requires manual intervention).

The old workspace yaml files and kitsDir are never modified or deleted by this function (decision 16: downgrade-by-restoring-the-prior-binary relies on them still being present on disk).

func PathIsUnder added in v0.1.0

func PathIsUnder(root, path string) bool

PathIsUnder reports whether path is root itself or a descendant of it. Exported (PR-2a codex round-1 Blocker 2/Major 2) so internal/api's ProjectAppService can reuse the exact same containment check degradedMessageFor already relies on, both to defend BareRepoPath's computed destination against a traversal-capable projectName (SafeBareRepoPath below) and to classify a project's WorkDir as daemon-managed vs. legacy without duplicating this logic.

This is a purely LEXICAL check (filepath.Rel on the two strings as given) — it does not resolve symlinks, so a symlinked ANCESTOR directory can make an out-of-tree location appear to be "under root" (PR-2a codex round-2 Blocker 2: replacing <dataDir>/repos/<workspace> with a symlink to /srv/shared still lexically joins under the right prefix, even though os.RemoveAll on the resulting path actually recurses into wherever the symlink points). Callers that go on to WRITE or DELETE at path based on this answer — SafeBareRepoPath below and internal/api's isManagedBareRepoPath (rm-time/fetch-time classification) — MUST use PathIsUnderResolved instead; this lexical-only form remains appropriate for degradedMessageFor's cosmetic (no side effect) message-wording decision below.

func PathIsUnderResolved added in v0.1.0

func PathIsUnderResolved(root, path string) (bool, error)

PathIsUnderResolved is PathIsUnder with symlink resolution applied to BOTH root and path before the lexical comparison (PR-2a codex round-2 Blocker 2), so a symlinked ancestor directory cannot make an escaped location appear contained. Two different resolution strategies are needed depending on whether root/path already exist on disk:

  • Already exists (the common rm-time/fetch-time case: an already-registered project's bare repo, or the daemon's own <dataDir>/repos root): filepath.EvalSymlinks resolves every symlink along the way.
  • Does not exist yet (the register-time case: SafeBareRepoPath is called BEFORE the clone that will create the bare repo directory — there is nothing there yet that COULD be a symlink): resolves the deepest EXISTING ancestor via EvalSymlinks and rejoins the not-yet-created suffix unresolved (nothing below an ancestor that does not exist could itself be a symlink).

Returns an error only for a resolution failure unrelated to "the path does not exist yet" (e.g. a permission error, or a symlink loop) — callers should treat that as "could not verify containment" and fail closed (refuse the write/delete), not silently fall back to the lexical-only check.

func RejectPayloadInstructions

func RejectPayloadInstructions(payload json.RawMessage) error

RejectPayloadInstructions returns an error if payload contains an "instructions" top-level key. instructions moved out of payload into Task.Instructions; accepting it here would silently drop it.

func RejectReservedPayloadKeys

func RejectReservedPayloadKeys(payload json.RawMessage) error

RejectReservedPayloadKeys returns an error if the payload contains writes to the artifact.children.* namespace (which is managed by virtual evaluation only).

func RejectTrailingYAMLDocument added in v0.0.13

func RejectTrailingYAMLDocument(dec *yaml.Decoder) error

RejectTrailingYAMLDocument guards against MINOR 2 (codex review round 2, docs/plans/workspace-db-consolidation.md): yaml.Decoder.Decode only ever consumes a single "---"-delimited document per call and silently ignores everything after it — a caller who hand-authors a multi-document workspace yaml (e.g. by copy-pasting a second workspace's fields below a `---` separator, perhaps intending some other tool to consume it) would have the second document silently dropped with no error, and only the first document's fields would ever reach the DB. This calls dec on the same Decoder immediately after the real decode succeeded, expecting io.EOF (nothing left); any other outcome — a second document decoding cleanly, or even a malformed one — is reported as an error rather than silently discarded.

Exported (MAJOR 3, codex review round 1) so cmd/workspace.go's extractLegacyWorkspaceKitRefs can reuse the exact same trailing-document check on the raw local workspace.yaml bytes it reads directly, instead of re-implementing it — see that function's doc comment for why a plain yaml.Unmarshal-into-map there would otherwise defeat this same guard.

func ReposRoot added in v0.1.0

func ReposRoot(dataDir string) string

ReposRoot returns the daemon's bare-repo storage root (<dataDir>/repos) — the prefix every BareRepoPath result shares, used by ProjectStore.SetReposRoot to distinguish a legacy (pre-cutover, host-filesystem) project registration from a git-URL one when neither loader can read its project.yaml (see LoadAll's migration-path handling).

func RequireUpstreamURL added in v0.0.10

func RequireUpstreamURL(project *Project) error

RequireUpstreamURL returns an error when project has no upstream_url captured. This is the "既存 project の...欠落 project は...dispatch 時エラー" building block described in docs/plans/git-gateway-cutover.md's "本計画で確定する設計 § 1" — it is intentionally NOT wired into any dispatch path yet. Wiring it in now would reject every current e2e project fixture (none has a real git remote until PR7a's fixture-upstream-server harness lands) ahead of the plan's own PR ordering (PR2 → ... → PR7a → PR6). It is exposed and tested here so PR6 (cutover, where dispatch starts needing upstream_url to build the gateway clone URL) has a ready-made, already covered building block to call.

func ResolveAllowedDomains added in v0.0.8

func ResolveAllowedDomains(globalFloor []string, workspace *WorkspaceMeta) []string

func ResolveEnabledServices added in v0.1.0

func ResolveEnabledServices(floor []string, workspace *WorkspaceMeta) []string

ResolveEnabledServices returns the effective API gateway service allowlist for a job dispatched under workspace: the additive union of the daemon-wide floor (config.yaml services_floor) and the workspace's own Services list (docs/plans/api-gateway.md §3). The workspace cannot remove entries from the floor.

Unlike ResolveAllowedDomains, matching is case-SENSITIVE: a service name is an arbitrary config.yaml map key (an identifier), not a domain name, so there is no DNS-style case-insensitivity convention to honor here. Duplicate entries are de-duplicated while preserving first-seen order, same as ResolveAllowedDomains. workspace may be nil (no workspace overrides).

func SafeBareRepoPath added in v0.1.0

func SafeBareRepoPath(dataDir, workspaceSlug, projectName string) (string, error)

SafeBareRepoPath is BareRepoPath with defense-in-depth validation applied (PR-2a codex round-1 Blocker 2): projectName must satisfy ValidProjectName AND the resulting join must still resolve beneath <dataDir>/repos/<workspaceSlug> — the latter check protects against both a bug in ValidProjectName's character-level allowlist and any future change to BareRepoPath's own Join call that reintroduces a traversal (belt-and-suspenders: input validation at the edge, output validation at the boundary it is meant to protect). Every caller that accepts projectName from outside the daemon process (currently just ProjectAppService.CreateProjectFromGitURL's --name / URL-derived name) must go through this, not the raw BareRepoPath.

The containment check runs through PathIsUnderResolved against ReposRoot(dataDir) — <dataDir>/repos, WITHOUT the workspaceSlug segment — not the plain (lexical-only) PathIsUnder against the per-workspace directory round-1 used (PR-2a codex round-2 Blocker 2). Two things follow from that choice:

  • Symlink defense: <dataDir>/repos/<workspaceSlug> ITSELF being replaced with a symlink to somewhere outside dataDir entirely (codex's concrete scenario) is only detectable by resolving through it and comparing against a boundary that sits ABOVE the symlink — comparing the resolved bareRepoPath against the resolved <dataDir>/repos/<workspaceSlug> itself is circular (path is always lexically a child of root by construction, so resolving both through the SAME symlink trivially keeps that child/parent relationship no matter where the symlink points). ReposRoot(dataDir) is workspace-slug scoping, but is the boundary an attacker would actually need to escape and matches isManagedBareRepoPath's own convention below.
  • No loss of protection for the original round-1 traversal-name scenario: projectName is already constrained by ValidProjectName to a single clean path segment with no separators and no ".." anywhere — BareRepoPath's Join always places it immediately after workspaceSlug, so a validated projectName can never affect which workspace's directory the result lands in regardless of which boundary this checks against; only an escape past dataDir/repos entirely is actually reachable, and every ".."-based escape used to get there starts by leaving <dataDir>/repos/<workspaceSlug> anyway.

Safe to call even though neither root nor path exists yet at register time (the case this function always runs in, BEFORE any clone) — see PathIsUnderResolved's own doc comment.

func SetDetailChildren added in v0.2.4

func SetDetailChildren(detail json.RawMessage, children []TaskTriageChild) (json.RawMessage, error)

SetDetailChildren returns a new detail blob with the "children" key replaced by children, leaving every other top-level key of detail untouched (summary/source/content_ref/suggestion/observed etc — 逆輸入1/3). detail's shape is a schema-light JSON blob by design (実測c), so this round-trips through a map rather than a fixed Go struct to avoid silently dropping fields PR-2's code doesn't know about.

func SetPendingAnswer added in v0.0.7

func SetPendingAnswer(payload json.RawMessage, answer, actor string) json.RawMessage

SetPendingAnswer writes answer into the awaiting trait's pending_answer field while preserving question/question_id and any sibling traits. It is the durable counterpart to the in-memory BlockingAskRegistry delivery: when the answering agent has disconnected (its `boid task ask` foreground command was killed by a harness command-timeout), the answer is parked here so the agent picks it up on its next ask. If the awaiting trait is absent, one is created holding just the answer so it is never silently dropped.

func SetProjectUpstreamURL added in v0.0.10

func SetProjectUpstreamURL(dbtx db.DBTX, id, upstreamURL string) error

SetProjectUpstreamURL updates a project's captured upstream_url (see docs/plans/git-gateway-cutover.md PR2: project → upstream URL mapping). Used by `project add` / `project reload` capture and the daemon-startup backfill for projects registered before this column existed.

func SetProjectWorkspace

func SetProjectWorkspace(dbtx db.DBTX, projectID, workspaceID string) error

SetProjectWorkspace updates a project's local workspace membership.

Domain-layer validation per plan (3-layer defense, last line before DB INSERT). Empty workspaceID clears the membership and bypasses slug validation; any non-empty slug must satisfy ValidWorkspaceSlug so we never persist a malformed identifier even if an upstream layer forgets to check.

func SetTriggerRunJobID added in v0.4.0

func SetTriggerRunJobID(dbtx db.DBTX, id, jobID string) error

SetTriggerRunJobID records the job id StartExec returned, once dispatch succeeds (Opus review Blocker 1's insert-then-dispatch split — CreateTriggerRun's own doc comment). Errors (including "no such row") are returned as-is rather than swallowed; the caller (fireTrigger) treats a failure here as a residual, logged gap — see its own doc comment.

func ShouldWake added in v0.2.4

func ShouldWake(now time.Time, tt *CardAttrs, wakeTaskFound bool, wakeTaskStatus TaskStatus) bool

docs/plans/webui-detail-list-redesign.md PR-4 (§3.6, §5 論点2) removed this file's urgency vocabulary consts (UrgencyNow/Today/Week/Someday) and UrgencyRank: urgency dropped from every display surface (list row, task_tree.templ badge, queue_next ORDER BY — all gone), and UrgencyRank itself had zero production callers left (comments and its own test only — confirmed by grep before deletion). The closed vocabulary khi still WRITES against (attrs_set's urgency key) lives independently as a literal list in internal/api/workflow_card.go's promotedAttrVocabulary — that map does NOT reference these consts (never did), so it is unaffected by this deletion.

ShouldWake evaluates queue 節 rule 1 (wake 評価) for a parked task: wake if wake_at has passed, OR the task referenced by wake_task_id has reached a terminal status. Both are decided purely from tt's fields plus facts the caller supplies about "now" and the referenced task — no agent judgment is involved (決定12).

wakeTaskFound=false (the referenced task no longer exists — deleted or GC'd) is treated the same as "terminal": a vanished reference must not permanently strand a parked task (fail-open, ストレージ節 原則2's same direction — daemon-side state loss/drift resolves toward re-surfacing, never toward silently hiding something forever).

func SourceClosed added in v0.3.0

func SourceClosed(detail json.RawMessage) bool

SourceClosed reports whether khi has affirmatively observed the card's source as finished. Absent and false are both "not closed" — only an explicit true counts. The only production reader left after 決定15's removal is logAttrsSetOnDoneTriage (internal/api/attrs_set_done.go, I-5c) — a visibility log, not a gate on any transition.

func SpecDetailChild added in v0.2.4

func SpecDetailChild(detail json.RawMessage, id string, spec TaskTriageChildSpec, title string) (json.RawMessage, error)

SpecDetailChild finds the child with the given id and sets its Spec/Title, advancing its status to TaskTriageChildStatusSpecced. Returns an error if no child with that id exists — unlike AddDetailChild this is not create-or-update: "specced" only ever applies to a child khi already announced via child_added (or one seeded directly in the child's own detail at task-create time).

If the child has already progressed past "specced" — i.e. it is dispatched or closed — this is an idempotent no-op (detail returned unchanged, found=true, no error): those two statuses are daemon-recorded MECHANICAL FACTS (child_dispatched/child_closed, 論点9), and a khi resend of child_specced after an uncertain ack (crash/timeout before receiving the response) must never regress one of them back to "specced" — that would let a stale duplicate action send erase "this child already ran and finished" (codex review Major fix). Re-specc'ing a child that is still "open" or already "specced" (re-editing the spec before Go) both apply normally.

func SplitWorkspaceEnvelopeDocuments added in v0.1.0

func SplitWorkspaceEnvelopeDocuments(data []byte) ([][]byte, error)

SplitWorkspaceEnvelopeDocuments splits data (one or more "---"-separated yaml documents) into the raw bytes of each individual document, WITHOUT going through WorkspaceEnvelope's Go struct representation. `boid workspace apply` uses this (rather than re-marshaling the *WorkspaceEnvelopeApply values DecodeWorkspaceEnvelopeDocuments returns) to forward each document's original field-presence exactly as written to POST /api/workspaces/apply, one request per document: since WorkspaceEnvelopeSpec's fields no longer carry `omitempty` (Blocker 1), every zero-value Go field — including one that was never present in the source at all — marshals identically to an explicit empty value, so re-marshaling the decoded struct would erase exactly the missing-vs-empty distinction the fix exists to preserve. Round-tripping through yaml.Node instead doesn't have that problem: a mapping key that was absent from the source has no corresponding child node at all, so re-marshaling the node reproduces the source's exact key set, not a struct's zero-value view of it.

func StripAwaitingTrait

func StripAwaitingTrait(payload json.RawMessage) json.RawMessage

StripAwaitingTrait removes the entire awaiting trait from a payload. The awaiting trait is owned exclusively by ApplyAction("ask"/"answer") and the lifecycle, so any value carried in a coordinator's FinalPayload (which snapshots task.Payload before the hook runs) is necessarily stale and must not be merged back over the freshly-persisted DB state on hook completion. Returns the payload unchanged when the awaiting trait is absent.

func StripDetailAttrs added in v0.3.0

func StripDetailAttrs(detail json.RawMessage, keys ...string) (json.RawMessage, error)

StripDetailAttrs removes keys from detail's top-level "attrs" object, leaving every other top-level key untouched. It backs the promotion of urgency/kind out of the opaque blob and into their real columns (Phase 1 PR-5a): those two are queue predicates, and keeping a second copy in the blob would let the value the queue SQL reads drift from the value a workspace-side reader sees. Migration 0040 converges existing rows; this keeps the invariant self-healing for any row that somehow still carries a stale copy, without depending on the migration having run.

func TouchTaskUpdatedAt added in v0.4.0

func TouchTaskUpdatedAt(dbtx db.DBTX, id string) error

TouchTaskUpdatedAt bumps id's updated_at column to now — a single-column statement that carries NO status, deliberately narrower than UpdateTask's blanket rewrite (docs/plans/webui-detail-list-redesign.md §3.2, PR-3). It exists so a non-transitioning side effect (attrs_set's suggestion attachment, child_closed's parent self-record) can record "something worth surfacing changed here" in the SAME transaction as its own write, without reintroducing the stale-snapshot race UpdateTask(t) risks for those actions — see workflow_action.go's skipTaskUpdate doc comment for why those actions never call UpdateTask with a caller-held Task value.

func TouchWorkspaceIngestSuccess added in v0.2.4

func TouchWorkspaceIngestSuccess(dbtx db.DBTX, workspaceID string, at time.Time) error

TouchWorkspaceIngestSuccess records "最終 ingestion 成功" for workspaceID, preserving any existing last_triage_review_at. PR-4's ingestion task is the intended (not-yet-existing) caller.

func TouchWorkspaceTriageReview added in v0.2.4

func TouchWorkspaceTriageReview(dbtx db.DBTX, workspaceID string, at time.Time) error

TouchWorkspaceTriageReview records "最終棚卸し実施" for workspaceID (UC-5's periodic テーマセッション棚卸し), preserving any existing last_ingest_success_at.

func TraitBool

func TraitBool(payload json.RawMessage, trait string) bool

TraitBool returns true if the given trait key exists and its value is the JSON literal true. The key may be a dot-separated path (e.g. "lifecycle.executed") for nested object access.

func TraitExists

func TraitExists(payload json.RawMessage, trait string) bool

TraitExists reports whether the dotted-path key resolves to a present, non-null JSON value in payload. Unlike TraitBool it does not require the value to be the JSON literal true; any concrete value (object, array, string, number, true) counts as "exists". Used by state-machine condition rules that gate on the presence of a sibling trait (e.g. `lifecycle.done` set by `done_request`) regardless of its body shape.

func TraitGetString

func TraitGetString(payload json.RawMessage, trait string) (string, bool)

TraitGetString reads the string value at a dotted path. Returns ("", false) if the path is missing or the value is not a JSON string. Used by auto-rule ActionPayloadFns to extract user-facing message text from lifecycle traits.

func UnlinkAllForTask added in v0.4.0

func UnlinkAllForTask(dbtx db.DBTX, taskID string) error

UnlinkAllForTask releases every identity bound to taskID (I-6: drop releases the task's identities so the same external keys can be re-linked to a fresh task later). Called from the service layer immediately after a `drop` transition commits — never from done (I-5: done holds identities).

func UnlinkIdentity added in v0.4.0

func UnlinkIdentity(dbtx db.DBTX, projectID, identity string) error

UnlinkIdentity removes the binding for (projectID, identity), if any. Not finding one is not an error (idempotent, matching UnlinkAllForTask).

func UpdateTask

func UpdateTask(dbtx db.DBTX, t *Task) error

UpdateTask persists every mutable Task column. Compare against CreateTask's INSERT column list before adding a new field to Task: a column missing here while present there is a silent no-op — the caller gets a nil error (and, if it copies the request field onto the in-memory *Task first, a response that *looks* updated) while the row underneath keeps its old value. This exact class of bug shipped for remote_id/project_id/ auto_start (fixed together; see update_task_columns_test.go / task_update_persist_test.go) — found via khi-task-collector's self-heal loop patching remote_id every cycle forever without it ever sticking.

Two INSERT columns are deliberately absent from this UPDATE, not dropped:

  • ref: an immutable dedup key by design (docs/plans/ ingestion-identity.md 決定16 — "後から変えられない dedup キー"). CreateTask is the only writer; there is no UpdateTaskRequest.Ref field at all (internal/apiwire/task.go), so there is no API-level "口" that could even attempt to change it.
  • behavior: set once at CreateTask time and never exposed on UpdateTaskRequest either (only CreateTaskRequest has Behavior) — no update port exists, so there is nothing to silently drop.

remote_id and auto_start have no status guard here — callers rely on being able to set them regardless of task status (khi patches remote_id on working/parked tasks; a caller may flip auto_start after the task already left pending). project_id, by contrast, IS gated by IsPreDispatchEditableStatus one layer up in api.TaskAppService.UpdateTask — this function has no status of its own to check, it just persists whatever the caller decided was valid to set.

card-model-cleanup PR-2 (migration 0045): this SET clause deliberately does NOT touch kind/urgency/wake_at/wake_task_id/suggestion_verb/detail (the CardAttrs columns) even though they now live on this same tasks row. Those are UpsertTaskTriage's exclusive write path (workflow_card.go's park/attrs_set/child_* side effects), which does its own read-modify-write scoped to exactly those columns; folding them into this function's blanket rewrite would introduce a lost-update race that did NOT exist before the STI merge (task_triage was a genuinely separate table/row with its own writer before this PR — a concurrent GetTask-then-UpdateTask on the core columns could never clobber a concurrent attrs_set). The exec columns (traits/readonly/branch_prefix/base_branch/payload/instructions/ auto_start) keep the SAME blanket-rewrite treatment they always had (UpdateTask was already their sole non-locked writer pre-refactor); for a card, t.Exec is nil so execInsertValues binds SQL NULL to all of them — already their permanent value on a card row (CHECK-enforced), so this is a no-op, not a new write path.

func UpsertTaskTriage added in v0.2.4

func UpsertTaskTriage(dbtx db.DBTX, tt *CardAttrs) error

UpsertTaskTriage writes CardAttrs' columns onto the tasks row identified by tt.TaskID. Despite the name (kept for call-site compatibility across PR-2 — see this file's own package doc comment), this is no longer an upsert against a separate sidecar table: every card row already has these columns (defaulted to their zero value) from the moment CreateTask makes it type='card', so there is nothing to insert — only UPDATE. The affected- row check turns "taskID doesn't exist or isn't a card" into a clear error instead of a silent no-op (a bare UPDATE with no matching WHERE row returns no error from database/sql).

func ValidKitName added in v0.0.8

func ValidKitName(s string) error

ValidKitName checks that s is a valid kit name. A valid name consists of lowercase ASCII letters, digits, and hyphens, is between 1 and 64 characters long, and contains no other characters.

func ValidProjectName added in v0.1.0

func ValidProjectName(name string) error

ValidProjectName checks that name is safe to use as the last path segment of a daemon-managed bare-repo path (BareRepoPath's projectName argument) — PR-2a codex round-1 Blocker 2. Rejects:

  • empty, or longer than 128 chars;
  • any path separator ('/' or '\'), which would let projectName escape its intended single path segment entirely (e.g. "sub/dir");
  • a name that is exactly "." or ".." or starts with '.' (a leading dot is never meaningful for a project name and ".."-prefixed forms are exactly the traversal shape the concrete failure scenario uses: "../../../../tmp/owned" cleans through filepath.Join and moves CreateProjectFromGitURL's clone destination outside <data_dir>/repos/<workspace>, persisting that external path as work_dir and potentially handing it to os.RemoveAll during rollback);
  • a ".." component anywhere else in the name (defense in depth: even a non-leading "foo..bar" is rejected, since there is no legitimate project name that needs it and it costs nothing to disallow);
  • any character outside [a-zA-Z0-9._-].

Applies to BOTH an explicit --name override and a URL-derived name (DeriveProjectNameFromURL only strips a trailing ".git" and takes the last '/'- or ':'-delimited segment of whatever URL string it was given — it does not itself guarantee the result is traversal-safe against an adversarial URL, so CreateProjectFromGitURL must validate the derived name too, not just an explicit override).

func ValidWorkspaceSlug added in v0.0.8

func ValidWorkspaceSlug(s string) error

ValidWorkspaceSlug checks that s is a valid workspace slug. A valid slug consists of lowercase ASCII letters, digits, and hyphens, is between 1 and 64 characters long, and contains no other characters.

The character rule is the whole rule: there is deliberately no reserved-word list. "export" and "apply" are static path segments on the workspace router at the same depth as its "/{slug}" wildcard, so a workspace named either one is shadowed for the methods those static routes register (GET /api/workspaces/export reaches the envelope export, never Show). That collision is known and accepted rather than validated away — rejecting the names here would turn any workspace already created under one of them into a workspace the daemon refuses to load, which is a worse failure than the partial shadowing it prevents. See api.WorkspaceHandler.Routes for the full decision record and the test that pins it.

func ValidateContentSize added in v0.4.0

func ValidateContentSize(field string, content []byte) error

ValidateContentSize rejects content whose byte length exceeds MaxContentBytes. field names the content in the returned error (e.g. "description", "action payload") so a caller can tell which limit was hit.

func ValidateHostCommandsInstalled added in v0.1.0

func ValidateHostCommandsInstalled(hostCommands map[string]HostCommandSpec, lookPath func(string) (string, error)) []string

ValidateHostCommandsInstalled resolves every configured host_commands entry against the daemon's own host (docs/plans/phase6-container-backend.md §PR6, §決定4: "broker が exec する host command の実体... host_commands config の全 command 解決を daemon 起動時に検証する"). Once the daemon runs in a container (compose deploy, §決定4's DooD model), the "host" a host command resolves against IS the daemon image — an image built with "OS 土台 + boid のみ" would silently break every dispatch that uses a tool like `gh` unless something catches the gap before the first affected job runs. This is that check.

Returns the sorted list of configured command names that could not be resolved. This is advisory only (skeleton level, PR6): a missing command is reported by the caller (typically via slog.Warn — see internal/server.Server.New's call site), not treated as fatal. Making this fail-closed (refuse to start) is a future knob; today a missing command already fails lazily per-dispatch (ResolveHostCommands, host_commands.go), which this check does not change — it only surfaces the gap earlier, at boot, rather than the first time an affected project dispatches.

Commands declared with an explicit *relative* Path (project-local scripts — §決定4: "project-local script は project 側から提供") are skipped, not reported missing: their real location depends on a project's own checkout directory, which this daemon-wide, project-agnostic pass has no access to (ResolveHostCommands already validates those against the right projectDir at dispatch time). An absolute Path is checked directly via os.Stat; an empty Path (the common case — the command is expected to already be on the daemon's PATH, e.g. a provisioned tool like `gh`) is checked via lookPath.

func ValidatePayloadPatch

func ValidatePayloadPatch(patch json.RawMessage, allowedTraits []TraitType) error

func ValidateTriggers added in v0.4.0

func ValidateTriggers(triggers []Trigger) error

ValidateTriggers checks a project.yaml `triggers[]` list at LOAD time (called from parseProjectMetaBytes, spec_loader.go) — the same place validateHookKind validates task_behaviors.*.hooks. A malformed trigger must fail `boid project add`/`boid project fetch` loudly; the trigger sweep loop (internal/api/trigger_loop.go) trusts that every Trigger it reads off a hydrated ProjectMeta already passed this check.

func WatchdogGuidance added in v0.2.4

func WatchdogGuidance(now time.Time, workspaceID string, wd *WorkspaceWatchdog, th WatchdogThresholds) []string

WatchdogGuidance evaluates queue 節 rule 7 for a single workspace: it returns one guidance string per breached threshold (empty when nothing is breached). A nil/never-recorded timestamp is always a breach — "来ない こと" is exactly the failure mode this rule exists to surface (人間は 「来ないこと」に気づけないため, queue 節 rule 7).

This is the "how a guidance item would surface" half of PR-3's watchdog scope: it is a pure function of (now, watchdog row, thresholds) — no agent judgment (決定12) — that the queue view (or, later, a periodic notify sweep) can call directly. It does not itself persist or dedupe guidance items; queue 節 rule 7 says a guidance item is re-emitted "解消 されるまで出し続ける", which a caller gets for free by simply calling this on every render/sweep rather than this function tracking state itself.

func WithActor added in v0.2.4

func WithActor(ctx context.Context, actor string) context.Context

WithActor は ctx に actor (この操作を駆動しているのは誰/何か) を埋め込む。 ApplyAction → Dispatch、Wake → Dispatch のような多段呼び出しチェーンの途中で シグネチャを増やさずに Action.Actor をスタンプできるようにするための伝播経路。

func WithWriterProjectID added in v0.4.0

func WithWriterProjectID(ctx context.Context, projectID string) context.Context

WithWriterProjectID marks ctx as carrying a sandbox write's origin project (docs/plans/boid-internal-signal-inbox.md §4.3/§6.2) — the same context-propagation idiom actor.go's WithActor/ActorFromContext already established for Action.Actor, applied to the one additional fact CreateAction's ingest decision needs that Actor cannot supply: internal/api/task_service.go's UpdateTask stamps ActorHuman even for a sandbox-originated call (its own "Actor caveat" comment says so), so actor is not trustworthy evidence of the writer's project.

internal/server/boid_executor.go's ExecuteBoidBuiltin is the ONLY call site that should ever call this (§6.2: "運搬は1箇所で閉じられる") — every sandbox-originated write funnels through it with a sandbox.TokenContext carrying ProjectID, and every OTHER ctx-building path in this codebase (HTTP handlers via WithActor(r.Context(), ActorHuman), daemon loops via WithActor(ctx, ActorDaemon)) never touches this key. WriterProjectIDFromContext therefore reports "not sandbox-originated" for every human/daemon write with zero special-casing anywhere else in the call graph.

projectID may be "" — a sandbox write whose TokenContext.ProjectID could not be resolved still calls this (with an empty string), which is exactly what lets WriterProjectIDFromContext distinguish "no sandbox writer at all" (ingest-eligible on this axis) from "sandbox writer, but its project is unknown" (fail-close, §4.3).

func WorkspaceExists added in v0.0.13

func WorkspaceExists(dbtx db.DBTX, slug string) (bool, error)

WorkspaceExists reports whether slug has a corresponding row in the workspaces table (MAJOR 5, codex review: SetProjectWorkspace previously assigned any syntactically valid slug without checking it actually existed, leaving a dangling project_workspaces reference — dispatch then runs in a permanently degraded window, and since workspace_db_consolidation's state=committed makes MigrateWorkspaceYAMLToDB a permanent no-op, no later startup ever re-validates and self-heals it).

func WriteHostCommandsConfig added in v0.0.13

func WriteHostCommandsConfig(path string, spec map[string]HostCommandSpec) error

WriteHostCommandsConfig serializes spec as YAML (top-level `host_commands:` map) and atomically writes it to path — a sibling temp file is written, fsynced, and renamed into place (config.WriteFileAtomic), so a reader never observes a partially written file and a write failure never corrupts an existing config. The parent directory is created if it does not exist.

The file is written 0600 (owner read/write only): definitions aggregated from kit.yaml are stored raw/unexpanded (see readKitHostCommandsRaw), but path/env values can still look sensitive, so this config is treated like any other credential-adjacent file on disk.

func WriterProjectIDFromContext added in v0.4.0

func WriterProjectIDFromContext(ctx context.Context) (projectID string, ok bool)

WriterProjectIDFromContext returns the project id WithWriterProjectID stamped, and whether ctx carries one at all. ok==false means this write was never routed through ExecuteBoidBuiltin (a human/daemon/HTTP-originated write) — CreateAction's actor-axis check treats that as "not a sandbox write, self-reference cannot apply". ok==true with an empty projectID means a sandbox write whose project could not be resolved — the fail-close case (§4.3).

Types

type AbortReason

type AbortReason struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

AbortReason holds metadata derived from the aborted-state transition action.

type Action

type Action struct {
	ID         string          `json:"id"`
	TaskID     string          `json:"task_id"`
	Type       string          `json:"type"`
	Payload    json.RawMessage `json:"payload"`
	FromStatus TaskStatus      `json:"from_status,omitempty"`
	ToStatus   TaskStatus      `json:"to_status,omitempty"`
	CreatedAt  time.Time       `json:"created_at"`
	// Actor は誰/何がこの action を押したか (ActorHuman / ActorDaemon /
	// ActorTask(taskID) のいずれか)。旧レコードは空文字 (移行前データ、または
	// 書き込み側が未対応)。docs/plans/cross-project-issue-triage.md 論点11。
	Actor string `json:"actor,omitempty"`
}

func ListActionsByTask

func ListActionsByTask(dbtx db.DBTX, taskID string) ([]*Action, error)

func ListActionsSince added in v0.4.0

func ListActionsSince(dbtx db.DBTX, filter ActionListFilter) ([]*Action, string, error)

ListActionsSince is BoidOpActionList's store implementation (B-3): a SINGLE append-only, workspace-scoped read across every task's actions, replacing the per-task-only ListActionsByTask (store.go) for this use case — see this file's package doc comment / the design doc's "B-3: per-task だけだと tick が O(N) になる" for why a per-task loop is the wrong shape here.

Returns the matching actions oldest-first (ORDER BY created_at, id — the same order the cursor advances in) and the NEXT cursor: the last returned row's cursor, or filter.Since unchanged when no rows matched (so a caller that polls and gets nothing new just keeps resending the same cursor next time, rather than the cursor going stale or resetting to the beginning).

type ActionListFilter added in v0.4.0

type ActionListFilter struct {
	// ProjectIDs scopes to a set of projects via a single SQL IN(...) — used
	// both for an explicit single --project-id (a 1-element slice) and for
	// the "neither project nor workspace given" fallback
	// (TokenContext.AllowedProjectIDs, resolved by the caller — boid_executor.go
	// — before this filter is built). A single query rather than
	// one-call-per-project (the loop BoidOpTaskList/BoidOpCardList's
	// executor uses over AllowedProjectIDs) is deliberate: correctly merging
	// cursor-paginated results across N separately-limited per-project
	// queries needs an N-way merge (each source must contribute up to
	// `limit` candidates, the union re-sorted and re-truncated, and the next
	// cursor derived per-source) — real complexity a single IN(...) query
	// the SQL engine already sorts in one pass avoids entirely.
	ProjectIDs []string
	// WorkspaceID scopes via project_workspaces, matching ListTasks' own
	// WorkspaceID join (store.go). In practice mutually exclusive with
	// ProjectIDs — the caller picks exactly one shape per call, mirroring
	// BoidOpCardList's own project_id/workspace_id branching — but
	// nothing here forbids combining them (both apply as an AND).
	WorkspaceID string
	// TaskID additionally narrows to one task's actions. Safe to combine
	// with ProjectIDs/WorkspaceID as a plain AND condition: a task outside
	// the scope simply matches zero rows — unlike action_send's separate
	// GetTask+AllowsProject check (which exists because that op has no
	// other scope to AND against), there is no way for TaskID alone to
	// widen what this filter returns.
	TaskID string
	// Since is the OPAQUE wire cursor (EncodeActionCursor's output) marking
	// the exclusive lower bound of an append-only scan — empty means "from
	// the beginning". Decoded internally so callers never need to know the
	// encoding.
	//
	// There is deliberately no "start from now, skip all history" sentinel
	// (a `--since latest` equivalent) alongside this. Opus review
	// (2026-08-19) raised it as a real gap — a script that loses its cursor,
	// or connects for the first time, has to page through the ENTIRE
	// history before it reaches the present. Not adding it now is a
	// judgment call, not an oversight: khi's current action volume is in
	// the hundreds (実測, 2026-08-19), so paging the full history at
	// DefaultActionListLimit=200 is a handful of calls, not a real cost —
	// and a "latest" mode is a genuinely new piece of API surface (wire
	// schema, broker/executor scoping, CLI flag, its own tests), not a
	// one-line fix, so it does not belong bundled into an
	// already-in-flight review-fix pass. Revisit if/when action volume
	// grows enough that "page from the beginning" stops being cheap, or a
	// concrete caller (a fresh workspace's first connect) actually needs
	// it.
	Since string
	// Limit is clamped internally via ClampActionListLimit — any value
	// (including 0 or negative) is accepted.
	Limit int
}

ActionListFilter scopes and paginates ListActionsSince (B-3's "workspace スコープの一括読み").

type AdvanceOutcome

type AdvanceOutcome struct {
	Task          *Task
	ActionPayload json.RawMessage // nil unless the fired rule has ActionPayloadFn
}

AdvanceOutcome carries the result of a successful condition-based transition.

type AwaitingPayload

type AwaitingPayload struct {
	Question      string `json:"question,omitempty"`
	QuestionID    string `json:"question_id,omitempty"`
	PendingAnswer string `json:"pending_answer,omitempty"`
	// PendingAnswerActor carries the Actor (see actor.go) of whoever called
	// AnswerTask when the answer had to be parked durably (no live agent
	// waiting) — the slow path in api.TaskAppService.answerBlocking.
	// consumePendingAnswer reads this back so the "answer" Action it records
	// on delivery is attributed to the original answerer, not to the agent's
	// re-ask call that happens to be the one consuming it.
	PendingAnswerActor string `json:"pending_answer_actor,omitempty"`
}

AwaitingPayload holds the fields of the "awaiting" trait in task.Payload.

The Q&A flow is now uniformly the blocking RPC `boid task ask`: the agent stays alive inside a broker connection while the daemon waits for a user answer, which is then handed back over the same socket via the in-memory BlockingAskRegistry. There is no session-resume path: the legacy `notify --ask` → `reopen -m` round trip is no longer wired to claude `--resume`, and every dispatch starts a fresh agent process.

Fields written when an `ask` action lands:

  • Question: human-readable question text shown to the user
  • QuestionID: UUID identifying this Q&A turn (for multi-turn tracking)

Fields written by boid (set when the user submits an answer):

  • PendingAnswer: the user's reply (legacy field; the blocking RPC delivers answers in-memory and never sets this, but legacy `notify --ask` paths still surface it as $BOID_USER_ANSWER on the next hook invocation)

SessionID/Mode/Source have been removed: the harness-resume mode they described is gone, and persisted records with those fields deserialize cleanly (encoding/json ignores unknown keys).

func GetAwaitingPayload

func GetAwaitingPayload(payload json.RawMessage) AwaitingPayload

GetAwaitingPayload reads the awaiting trait from raw payload. Returns an empty struct if the trait is absent or malformed.

type BaseBranchState

type BaseBranchState int

BaseBranchState describes the relationship between the project's working directory HEAD and a task's resolved base_branch. The three cases drive Phase 2-2 supervisor execution location routing:

  • Case1HeadMatches: project dir is already on baseBranch → supervisor runs in project dir directly (worktree=false).
  • Case2ExistsButNotCheckedOut: baseBranch exists locally or on origin but project HEAD is on a different branch → supervisor needs a worktree that checks baseBranch out.
  • Case3NotFound: baseBranch is unknown to both local and origin → supervisor needs a worktree whose base branch must be created from the current project HEAD before the worktree can be allocated.

Detached-HEAD projects cannot serve as a sensible default for any of these cases (case 3 in particular needs a real branch to derive from), so classification reports the dedicated detached-HEAD error rather than guessing.

const (
	// BaseBranchStateUnknown is the zero value. It only appears when an error
	// is returned; callers should never act on it directly.
	BaseBranchStateUnknown BaseBranchState = iota
	// Case1HeadMatches: project HEAD == baseBranch. Worktree is unnecessary;
	// the supervisor can run directly in the project dir.
	Case1HeadMatches
	// Case2ExistsButNotCheckedOut: baseBranch resolves to a ref (local or
	// origin/<baseBranch>) but is not what the project HEAD points at.
	Case2ExistsButNotCheckedOut
	// Case3NotFound: baseBranch does not exist locally and origin/<baseBranch>
	// is unknown to the project repo. Callers that own the project dir create
	// the branch from HEAD before allocating a worktree.
	Case3NotFound
)

func ClassifyBaseBranch

func ClassifyBaseBranch(projectDir, baseBranch string) (BaseBranchState, error)

ClassifyBaseBranch inspects the git repository at projectDir to decide how a task whose resolved base_branch is baseBranch should be scheduled. See BaseBranchState for the three case definitions.

baseBranch must already be expanded (no ${...} templates) and non-empty. P1: empty baseBranch is rejected — the service layer must resolve ${current_branch} before calling ClassifyBaseBranch.

The classify call is read-only: no branches are created, no fetches are issued, and the project HEAD is not mutated. Case 3 mitigation (creating the branch) is the caller's responsibility; ClassifyBaseBranch only reports the state.

func (BaseBranchState) String

func (s BaseBranchState) String() string

String makes BaseBranchState printable for log lines / test failure messages. Not part of the public contract — callers should switch on the enum value, not on the rendered string.

type BehaviorResolution

type BehaviorResolution struct {
	BehaviorName string
	Traits       []string
	Readonly     bool
	BranchPrefix string
	BaseBranch   string
	Payload      json.RawMessage
	Instructions Instructions
}

BehaviorResolution holds the resolved behavior fields after processing either a named behavior or an inline behavior_spec.

The Worktree flag was removed in the branch-policy-simplification Phase 2 (docs/plans/branch-policy-simplification.md). Post-cutover every project-visible job runs in a fresh sandbox clone, so per-task worktree isolation is no longer a concept the resolver needs to carry.

func ResolveBehavior

func ResolveBehavior(meta *ProjectMeta, req BehaviorResolveRequest) (*BehaviorResolution, error)

ResolveBehavior validates and resolves behavior fields from a task creation request. It handles both the named behavior path (meta lookup) and the inline behavior_spec path. When both behavior and behavior_spec are empty, the default is resolved via:

  1. meta.DefaultTaskBehavior if set
  2. implicit "supervisor" fallback if that behavior exists in meta (with WARN)
  3. error if neither is available
  4. hardcoded DefaultBehavior when meta is nil (nil-meta paths, e.g. test wiring)

type BehaviorResolveRequest

type BehaviorResolveRequest struct {
	Behavior     string
	BehaviorSpec *BehaviorSpec
	Payload      json.RawMessage
	Instructions json.RawMessage
}

BehaviorResolveRequest carries the behavior-relevant fields from a task creation request.

type BehaviorSpec

type BehaviorSpec struct {
	Name               string       `yaml:"name" json:"name"`
	Traits             []string     `yaml:"traits,omitempty" json:"traits,omitempty"`
	DefaultInstruction *Instruction `yaml:"default_instruction,omitempty" json:"default_instruction,omitempty"`
}

BehaviorSpec is an inline behavior specification that can be used instead of referencing a named behavior from project.yaml task_behaviors. This allows kits to self-describe the behavior they need without depending on project config.

type BindMount

type BindMount struct {
	Source   string `yaml:"source" json:"source"`
	Target   string `yaml:"target,omitempty" json:"target,omitempty"` // if empty, defaults to Source
	Mode     string `yaml:"mode" json:"mode"`                         // "rw" | "" (ro default)
	IsFile   bool   `yaml:"is_file,omitempty" json:"is_file,omitempty"`
	Optional bool   `yaml:"optional,omitempty" json:"optional,omitempty"` // if true, skip mount when Source does not exist on the host
}

BindMount is a plain shared DTO across orchestration and sandbox planning. It carries mount source/target/mode data and does not encode provider behavior.

func (*BindMount) UnmarshalYAML added in v0.0.8

func (b *BindMount) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML accepts two equivalent forms so handwritten and generated kit.yaml can use whichever is more convenient:

additional_bindings:
  - /host/path              # short form: equivalent to {source: "/host/path"}
  - source: /host/path      # struct form: required when mode/target/is_file/etc. are set
    mode: rw

Without this, yaml.v3 rejects the short form with "cannot unmarshal !!str into orchestrator.BindMount" and the single kit's parse error cascades into project meta hydration falling back to raw meta, silently dropping host_commands from *unrelated* kits.

type BuiltinPolicy

type BuiltinPolicy struct {
	AllowedOps      []string
	AllowedCwdRoots []string
}

BuiltinPolicy is the orchestrator-owned, sandbox-agnostic policy type. dispatcher is responsible for translating this into sandbox.BuiltinPolicy before it reaches the broker.

AllowedOps is a sorted slice (rather than a set) so the value is trivially comparable and serialisable across the orchestrator/dispatcher boundary.

func (BuiltinPolicy) Allows

func (p BuiltinPolicy) Allows(op string) bool

Allows reports whether op is in the allowed set.

func (BuiltinPolicy) AllowsCwd

func (p BuiltinPolicy) AllowsCwd(cwd string) bool

AllowsCwd reports whether cwd is within any of the policy's additional cwd roots.

type Capabilities added in v0.0.2

type Capabilities struct {
	// Docker, when non-nil, enables the per-sandbox native docker proxy.
	// Declared as capabilities.docker: {} in project.yaml.
	Docker *DockerCapability `yaml:"docker,omitempty" json:"docker,omitempty"`
}

Capabilities declares optional sandbox capabilities declared in project.yaml.

type CardAttrs added in v0.4.0

type CardAttrs struct {
	TaskID     string     `json:"task_id"`
	Kind       string     `json:"kind,omitempty"`    // signal|issue|theme
	Urgency    string     `json:"urgency,omitempty"` // now|today|week|someday
	WakeAt     *time.Time `json:"wake_at,omitempty"` // 日時wake条件。nil = 無し
	WakeTaskID string     `json:"wake_task_id,omitempty"`
	// SuggestionVerb is the promoted suggestion column (docs/plans/
	// suggestion-as-state-transition-impl.md §4.1, migration 0044): one of
	// go/working/park/drop/done/reopen (orchestrator.IsCardTransitionAction),
	// or "" when the card carries no current suggestion. Mirrors Kind/Urgency
	// — a real column, not opaque blob-only data. Until docs/plans/
	// webui-detail-list-redesign.md PR-4 it was ALSO a live SQL queue
	// predicate (store.go's "queue_next" filter, since removed — §3.6); it
	// stays promoted regardless because it backs the `/api/cards` read
	// surface (CardView.SuggestionVerb) and the daemon's own
	// notifySuggestionArrived/updated_at-bump change-detection (both key off
	// comparing this column's old vs. new value). Unlike Kind/Urgency the
	// full suggestion (reason/params) stays in Detail's JSON blob too; only
	// the verb is duplicated into this column (see applyAttrsSetSideEffect's
	// doc comment, internal/api/workflow_card.go,
	// for why that duplication is intentional and does not drift).
	SuggestionVerb string          `json:"suggestion_verb,omitempty"`
	Detail         json.RawMessage `json:"detail,omitempty"`
}

CardAttrs is the card-only field set (design doc §3.2's field attribution table). Through card-model-cleanup PR-1 it was the cross-project-issue- triage Phase 1 sidecar row for a triage task, kept out of Task/TaskService/ TaskStore because Task was the API DTO (marshaled to JSON as-is) and a column added there auto-exposed in every API/CLI/Web response. PR-2 (docs/plans/card-model-cleanup.md §3.5, migration 0045) folds the task_triage table into tasks itself (a card row's kind/urgency/wake_at/ wake_task_id/suggestion_verb/detail columns) and gives Task a genuinely nested `card` JSON key (`Task.Card *CardAttrs`) instead — so this struct keeps the exact shape callers already know, but every function below now reads/writes the SAME tasks row addressed by task_id, filtered to type='card', rather than a separate table.

Urgency and WakeAt are real columns because they are queue predicates (queue の決定論的評価 節, 決定12) — everything else that doesn't drive a SQL WHERE clause (summary/source/content_ref/children/suggestion/observed) lives in the Detail JSON blob instead of growing more columns.

There is deliberately no ParkedFrom column: the origin of a park (triaged vs ready vs working) is derived from the actions log (see ParkedFrom below), not duplicated into a second write path that could go stale (決定13: event 追記を正、state は導出).

func GetTaskTriage added in v0.2.4

func GetTaskTriage(dbtx db.DBTX, taskID string) (*CardAttrs, error)

GetTaskTriage retrieves the CardAttrs columns for taskID. Returns an error wrapping sql.ErrNoRows when the task does not exist or is not a card (the same "no row" contract callers wrote against when this queried a separate task_triage table — see this file's own package doc comment).

type CleanupFunc

type CleanupFunc func()

CleanupFunc releases transient resources created while planning a JobSpec (e.g. staging directories for hook scripts). dispatcher invokes it after the sandbox process has exited. A nil CleanupFunc means nothing to release.

type CloneDeclaration added in v0.0.10

type CloneDeclaration struct {
	// Branch is the branch the runner ends up on inside the clone. Always
	// equal to BaseBranch — every task occupies its own BaseBranch directly.
	Branch string

	// BaseBranch is the upstream branch this task's work is based on
	// (task.BaseBranch). Always required.
	BaseBranch string

	// CheckoutOnly is always true (Branch is checked out directly rather than
	// created fresh from a fork point). Kept as an explicit field — rather
	// than collapsed away — so CloneSpec / runner-state.json's declaration
	// shape stays self-describing.
	CheckoutOnly bool

	// BaseBranchForkPoint (ClassifyBaseBranch case 3): the start point used
	// to create BaseBranch locally when it exists on neither the clone's
	// origin nor locally. Empty falls back to refs/remotes/origin/HEAD,
	// resolved by the runner after clone (no extra fetch needed: `git clone`
	// already brings every remote branch's ref). This is independent of the
	// retired per-task fork point: it addresses BaseBranch not existing yet
	// anywhere, not task-to-task isolation.
	BaseBranchForkPoint string
}

CloneDeclaration declares the working-branch state a sandbox-internal clone should end up in, without resolving it — resolution (rev-parse / merge-base / checkout -B) is deferred to the runner, which performs it against the freshly cloned repo (docs/plans/git-gateway-cutover.md: 「dispatcher は JobSpec に宣言のみ載せる...runner が clone 完了後に解決」).

docs/plans/branch-policy-simplification.md Phase 1 retired the per-task "boid/<id8>" branch and its fork-point: every task, root or child, checks out BaseBranch directly (CheckoutOnly is always true now). See BuildCloneDeclaration's doc comment for the rationale.

func BuildCloneDeclaration added in v0.0.10

func BuildCloneDeclaration(task *Task, baseBranchForkPoint string) *CloneDeclaration

BuildCloneDeclaration derives the sandbox-internal clone branch declaration for a task (docs/plans/git-gateway-cutover.md PR6 cutover; docs/plans/branch-policy-simplification.md Phase 1). Dispatcher no longer runs any git command against a host repo — it just carries this declaration through to the sandbox, and the runner resolves it for real after cloning (docs/plans/git-gateway-cutover.md 「5. branch 宣言の JobSpec 化」).

Every task — root or child, worktree or not — checks out task.BaseBranch directly inside its sandbox-internal clone (CheckoutOnly is always true now). The per-task "boid/<id8>" branch and its fork-point, worktree-era concepts are retired here: they existed only to let a child task continue from a parent's uncommitted work on a shared .git. Cutover's independent-fresh-clone-per-job model makes that both impossible (a fresh clone only ever sees origin's already-pushed refs — an uncommitted parent branch is invisible to it) and unnecessary (the clone itself is now the isolation unit, so no two tasks ever contend for the same branch name inside their own sandbox). See docs/plans/branch-policy-simplification.md for the full rationale and the readonly-supervisor design mismatch this removal fixes.

baseBranchForkPoint is ProjectMeta.ForkPoint (the ClassifyBaseBranch case-3 fork point: the start point used to create task.BaseBranch locally when it exists on neither origin nor locally yet), passed straight through to CloneDeclaration.BaseBranchForkPoint. This is a separate, independent axis from the retired per-task fork point described above — see CloneDeclaration.BaseBranchForkPoint's doc comment.

type CommandDef

type CommandDef struct {
	Name               string            `json:"name,omitempty"`
	Path               string            `json:"path,omitempty"`
	AllowedPatterns    []string          `json:"allowed_patterns,omitempty"`
	DeniedPatterns     []string          `json:"denied_patterns,omitempty"`
	AllowedSubcommands []string          `json:"allowed_subcommands,omitempty"`
	Env                map[string]string `json:"env,omitempty"`
	RejectRules        []RejectRule      `json:"reject_rules,omitempty"`
}

CommandDef is the orchestrator-side transport shape for sandbox command policy input. Dispatcher and sandbox mirror this shape; sandbox owns the enforcement semantics.

type ContentSizeError added in v0.4.0

type ContentSizeError struct {
	Field       string
	ActualBytes int
	LimitBytes  int
}

ContentSizeError is ValidateContentSize's error type. Exported so a caller that wants the raw byte counts (rather than parsing Error()'s text) can use errors.As — the message text itself is not a public contract (PR-1 review note: don't pin stderr verbatim).

func (*ContentSizeError) Error added in v0.4.0

func (e *ContentSizeError) Error() string

type Coordinator

type Coordinator struct {
	Evaluator      *Evaluator
	HookExecutor   HookExecutor
	Waiter         JobWaiter
	MaxDepth       int
	LifecycleStore LifecycleStore // optional; nil skips rework_count/abort derivation
}

Coordinator orchestrates the hook → advance flow.

Locking is owned by the workflow service for the entire executing lifetime of each task (see internal/api/service.go). The coordinator dispatches hooks under the assumption that the branch lock is already held by the caller.

func (*Coordinator) DispatchAndAdvance

func (d *Coordinator) DispatchAndAdvance(
	ctx context.Context,
	task *Task,
	meta *ProjectMeta,
	sm *StateMachine,
) (*DispatchResult, error)

DispatchAndAdvance runs the full dispatch cycle: 1. Evaluate and execute hooks (parallel if readonly, sequential otherwise) 2. Merge hook payload patches 3. Evaluate condition-based auto-advance via state machine

func (*Coordinator) ReplayHook

func (d *Coordinator) ReplayHook(
	ctx context.Context,
	task *Task,
	meta *ProjectMeta,
	sm *StateMachine,
	hookID string,
) (*ReplayResult, error)

ReplayHook executes a single named hook in isolation against the task's current state. After the hook completes, lifecycle is derived and sm.Advance is applied — identical to the post-hook phase of DispatchAndAdvance.

Returns an error if the hook ID is not found in the behavior or if the hook does not match the current status (e.g. task not in executing state).

type DBProjectCatalog

type DBProjectCatalog struct {
	DB db.DBTX
}

func (DBProjectCatalog) GetProject

func (c DBProjectCatalog) GetProject(id string) (*Project, error)

func (DBProjectCatalog) ListProjects

func (c DBProjectCatalog) ListProjects() ([]*Project, error)

type DBTaskLookup

type DBTaskLookup struct {
	DB db.DBTX
}

func (DBTaskLookup) GetTask

func (l DBTaskLookup) GetTask(id string) (*Task, error)

type DispatchPlanner

type DispatchPlanner struct {
	Meta     MetaCache
	Hydrator MetaHydrator // optional; when set, loadContext uses GetWithWorkspace instead of Get
	Projects ProjectCatalog
	Tasks    TaskLookup
	Adapter  adapters.HarnessAdapter
}

DispatchPlanner turns state-machine-driven hook fire events into a sandbox-agnostic JobSpec. All sandbox construction concerns (mounts, env, proxy wiring, exit scripts, worktree recreation) live in dispatcher.

func WireDispatchPlanner

func WireDispatchPlanner(cfg PlannerWireConfig) *DispatchPlanner

func (*DispatchPlanner) PlanHook

func (p *DispatchPlanner) PlanHook(event *HookFireEvent) (*JobSpec, CleanupFunc, error)

PlanHook renders a hook fire event into a JobSpec.

Agent-kind hooks (Hook.Kind == HandlerKindAgent) may omit Command — the HarnessAdapter builds its own argv from CLI conventions, so an empty Argv flows through fine. Non-agent hooks (shell-bound) require a resolved Command. The Evaluator may synthesize a command-less agent hook when the behavior declares none of its own (Phase 3-e kit-retirement fallback); the relaxed validation here is what makes those virtual hooks dispatch-ready.

Command is an inline shell command (docs/plans/script-hook-removal.md): see validateHookCommandFields for the exclusivity rules between Command / Agent / Kind.

type DispatchResult

type DispatchResult struct {
	Results     []HandlerResult
	FiredEvents []FiredEvent
	// FinalPayload is the FULL payload this cycle computed: the task's
	// payload AS IT WAS AT THE START of this dispatch cycle (a snapshot that
	// can go stale the instant a long-running hook job starts, since the
	// hook itself may write to the task's payload mid-flight — e.g. via
	// `boid task update --payload-patch`/`--payload-file`), with this
	// cycle's own hook PayloadPatches merged on top. It is what
	// evaluateAndAdvance's state-machine Advance decision is based on; it
	// must NOT be used to persist the task's payload (see PayloadDelta).
	FinalPayload json.RawMessage
	// PayloadDelta is the SAME hook-patch merge as FinalPayload, but folded
	// starting from an empty object instead of the (potentially stale)
	// starting snapshot — i.e. only what THIS cycle's own hooks actually
	// wrote, never the pre-existing payload they didn't touch. Callers that
	// persist a dispatch cycle's result (runDispatchLoop, ReplayHook's
	// caller) must apply THIS to a freshly re-read task row, not
	// FinalPayload: applying the full stale snapshot on top of a fresh row
	// silently reverts any out-of-band write the hook itself made during
	// its own run (Phase 5b PR7 codex review Blocker 1, wiring-seams.md
	// #17) — e.g. a reopened task's `--payload-patch` report write getting
	// clobbered back to the pre-reopen value once the hook completes and
	// this cycle's post-hook persist runs. Empty ("{}") when no hook in
	// this cycle wrote anything, which is the common case for an agent job
	// that reports exclusively through the direct RPC paths — applying an
	// empty delta onto a fresh row is a correct no-op (orchestrator.
	// MergePayload's own empty-update short-circuit returns base
	// unchanged), so a stale snapshot never even gets a chance to overwrite
	// anything.
	PayloadDelta  json.RawMessage
	NewStatus     TaskStatus      // set if orchestrator advanced the state
	ActionPayload json.RawMessage // optional payload to attach to the auto_advance action
}

DispatchResult is the accumulated result of a full dispatch cycle.

type DockerCapability added in v0.0.2

type DockerCapability struct{}

DockerCapability is the opt-in marker for the native docker proxy. Presence (non-nil pointer in Capabilities) enables the proxy; the empty struct is a placeholder for future per-project policy fields.

type DoneReport

type DoneReport struct {
	Message string `json:"message"`
}

DoneReport carries the message the agent reported via `notify --done`.

type EgressPortStore added in v0.2.4

type EgressPortStore struct {
	// contains filtered or unexported fields
}

EgressPortStore is the DB-backed implementation of sandbox.PortStore against the `workspace_egress_port` table (internal/db/migrate/migrations/0039_add_workspace_egress_port.sql).

It lives here rather than in internal/sandbox because that package must not import internal/db — the same reason dispatcher.ProxyAllocator is an interface satisfied from outside. See docs/plans/egress-proxy-stable-port.md.

The key is a proxy key, NOT necessarily a workspace slug: the no-workspace listener uses the reserved key dispatcher.NoWorkspaceProxyKey ("__no_workspace__"), which ValidWorkspaceSlug would reject. Nothing here validates the key as a slug for that reason.

func NewEgressPortStore added in v0.2.4

func NewEgressPortStore(conn *sql.DB) *EgressPortStore

NewEgressPortStore returns an EgressPortStore backed by conn.

func (*EgressPortStore) LoadPort added in v0.2.4

func (s *EgressPortStore) LoadPort(key string) (int, bool, error)

LoadPort returns the port recorded for key, if any.

func (*EgressPortStore) ReservedPorts added in v0.2.4

func (s *EgressPortStore) ReservedPorts() (map[int]string, error)

ReservedPorts returns every recorded reservation as port -> proxy key.

Used by the allocator to avoid handing one key a port another key is already reserving. That distinction matters because proxy listeners are created lazily at dispatch time: a workspace that has not been dispatched since the last daemon restart has a row here with no listener behind it, so a bind attempt on its port succeeds and would silently take it.

func (*EgressPortStore) SavePort added in v0.2.4

func (s *EgressPortStore) SavePort(key string, port int) error

SavePort records port as key's allocation.

Two collisions have to be handled, and both resolve in favour of the caller — by the time this is called the listener is already bound, so the DB's job is to record reality, not to arbitrate it:

  • the same key already has a row (the reallocation path, when a persisted port turned out to be taken): the row is updated in place.
  • a DIFFERENT key already holds this port (`port` is UNIQUE): the stale row is deleted first. The previous holder cannot still be listening on it — this process just bound it — so its record is simply out of date.

Both happen in one transaction so a failure cannot leave two keys claiming one port, or the port claimed by nobody.

type Evaluator

type Evaluator struct{}

func (*Evaluator) Evaluate

func (e *Evaluator) Evaluate(task *Task, hooks []Hook) []Hook

Evaluate returns hooks that should fire for the given task. Hooks fire only during executing state. Hooks with Kind == HandlerKindAgent additionally require an instruction in task.Instructions addressed to that hook's Agent.

Phase 3-e fallback: when the behavior declares no agent-kind hook at all (typical after the boid-kits claude-code/codex retirement landed in PR #604), the evaluator synthesizes a virtual agent-kind hook for the active instruction's agent. The runner-inner-child hands every agent-kind job to its HarnessAdapter directly, so a hook with no Argv is dispatch-ready — see planner.PlanHook and adapters.HarnessAdapter.Run. The synthesis is gated to known harness agents (claude-code / codex / opencode) so unknown agent names do not collide with the shell adapter's Argv requirement.

type ExecAttrs added in v0.4.0

type ExecAttrs struct {
	// Behavior is allowed to be the empty string (a no-yaml project's
	// resolved behavior name) — that is why the DB column backing this
	// field is nullable-but-"IS NOT NULL for execution rows" rather than
	// NOT NULL DEFAULT ”: NULL means "not an execution task", "" means "an
	// execution task with no named behavior". See migration 0045's CHECK
	// constraint comment.
	Behavior     string          `json:"behavior"`
	Traits       []string        `json:"traits,omitempty"`
	Readonly     bool            `json:"readonly,omitempty"`
	BranchPrefix string          `json:"branch_prefix,omitempty"`
	BaseBranch   string          `json:"base_branch,omitempty"`
	Payload      json.RawMessage `json:"payload"`
	Instructions Instructions    `json:"instructions,omitempty"`
	AutoStart    bool            `json:"auto_start,omitempty"`
}

ExecAttrs is the execution-only field set (design doc §3.2's field attribution table): everything that used to live flat on Task and drives an actual sandbox dispatch. Non-nil only on a Task whose Type == TaskTypeExecution — a Card never carries one, so the "嘘の behavior 一式" landmine (a card's dead, unexpanded BaseBranch template — see task_resolve_or_capture.go's history) is now structurally impossible instead of merely unused.

type FailReport

type FailReport struct {
	Message string `json:"message"`
}

FailReport carries the message the agent reported via `notify --fail`.

type FieldProvenance added in v0.1.0

type FieldProvenance string

FieldProvenance classifies where a workspace-default-mergeable field's EFFECTIVE value came from (docs/plans/workspace-default-project.md 論点e).

const (
	// ProvenanceProjectYAML means project.yaml itself set a non-empty value
	// (or, for task_behaviors, defines this canonical behavior name).
	ProvenanceProjectYAML FieldProvenance = "project.yaml"
	// ProvenanceWorkspaceDefault means project.yaml left the field/key unset
	// and the workspace's default project definition supplied it (決定1/決定5).
	ProvenanceWorkspaceDefault FieldProvenance = "workspace default"
	// ProvenanceUnset means neither project.yaml nor the workspace default
	// supplied a value — the field is genuinely empty / the behavior key
	// does not exist anywhere.
	ProvenanceUnset FieldProvenance = "unset"
	// ProvenanceUnavailable means project.yaml itself did not supply a value
	// AND the linked workspace's default project definition could not be
	// read (a real error, not "no workspace linked" / "not configured" /
	// os.ErrNotExist) — so it is genuinely unknown whether a workspace
	// default would have supplied one. Codex review round 1 Major: without
	// this distinction, a workspace load failure was misreported as
	// ProvenanceUnset ("neither source supplied a value"), which is a
	// stronger claim than the code can actually back up — an ordinary
	// dispatch hitting the identical error would hydration-fail, not
	// silently treat the field as unset.
	ProvenanceUnavailable FieldProvenance = "workspace unavailable"
)

type FiredEvent

type FiredEvent struct {
	KitID       string // kit that owns this handler; empty for project-local
	HandlerID   string // hook ID
	JobID       string // ID of the job that executed this handler
	Kind        string // "hook" or "hook_replay"
	SourceState string // task status at the time of dispatch
	Success     bool
	Error       string
}

FiredEvent records a single hook execution for action logging.

type GCLoop

type GCLoop struct {
	Store        GCStore
	Interval     time.Duration
	OlderThan    time.Duration
	InitialDelay time.Duration
}

GCLoop periodically calls GC on a GCStore.

func (*GCLoop) Run

func (l *GCLoop) Run(ctx context.Context)

Run blocks until ctx is done. It waits InitialDelay before the first GC run, then calls Store.GC every Interval. Errors are logged as warnings; the loop always continues.

type GCResult

type GCResult struct {
	Tasks      int64
	Jobs       int64
	Actions    int64
	Runtimes   int64
	SandboxTmp int64 // leaked /tmp/boid-* sandbox artifacts removed
	Devices    int64 // revoked web devices deleted
	// TriggerRuns is the count of finished trigger_runs rows GCTriggerRuns
	// deleted (N-2, Opus review) — trigger_runs otherwise has no retention
	// at all and grows unbounded (khi's 2 triggers alone project to
	// ~105,000 rows/year).
	TriggerRuns int64
	// Signals is the count of signals rows GCSignals deleted
	// (docs/plans/signal-ingest-detailed-design.md §2/§9: "inbox の GC:
	// acked 30 日で既存 GC tx に相乗り") — both acked rows older than the
	// cutoff and unacked (including dead-lettered) rows whose received_at
	// is older than the cutoff, so a permanently-dead signal doesn't linger
	// forever just because nothing ever acks it.
	Signals int64
}

GCResult holds the count of records affected by GC.

func GCTasks

func GCTasks(dbtx db.DBTX, statuses []string, olderThan time.Duration, dryRun bool) (*GCResult, error)

GCTasks deletes terminal tasks older than olderThan and their related data (actions, jobs). If dryRun is true, counts only without deleting. olderThan=0 disables the time filter (all matching tasks are affected). Must be called within a transaction for atomicity.

type GCStore

type GCStore interface {
	GC(olderThan time.Duration, dryRun bool) (*GCResult, error)
}

GCStore is the interface required by GCLoop to run garbage collection.

type GitHeadReadError added in v0.1.0

type GitHeadReadError struct {
	// BareRepoPath and RelPath are the arguments gitShowHEAD was called
	// with, for callers that want to log/report without re-parsing Error().
	BareRepoPath string
	RelPath      string
	Kind         GitHeadReadFailureKind
	// contains filtered or unexported fields
}

GitHeadReadError is the typed error gitShowHEAD wraps its failures in. Callers use errors.As to extract Kind; Error() and Unwrap() preserve gitShowHEAD's pre-existing plain-error message and %w chain exactly, so every current caller (which only checks err != nil) is unaffected — same pattern as ProjectMigrationError (migration_error.go).

func (*GitHeadReadError) Error added in v0.1.0

func (e *GitHeadReadError) Error() string

func (*GitHeadReadError) Unwrap added in v0.1.0

func (e *GitHeadReadError) Unwrap() error

type GitHeadReadFailureKind added in v0.1.0

type GitHeadReadFailureKind int

GitHeadReadFailureKind classifies why gitShowHEAD failed to read relPath out of a bare repo's HEAD tree (docs/plans/workspace-default-project.md 論点c).

const (
	// GitHeadReadFailureOther is the catch-all: HEAD resolves fine (`git
	// rev-parse --verify HEAD` succeeded) but reading relPath still failed
	// for some other reason. Rare in practice — HeadUnresolved and
	// PathAbsent should cover nearly everything gitShowHEAD sees.
	GitHeadReadFailureOther GitHeadReadFailureKind = iota
	// GitHeadReadFailureHeadUnresolved means `git rev-parse --verify HEAD`
	// itself failed: either a bare repo with zero commits yet, or the
	// directory is not a valid git repository at all. The design doc groups
	// both under this one kind because both fail registration identically
	// ("HEAD が解決できない ... repo 自体の異常なので従来通り失敗させる").
	GitHeadReadFailureHeadUnresolved
	// GitHeadReadFailurePathAbsent means HEAD resolves fine but relPath is
	// simply not present in its tree — the "project.yaml was never
	// committed" case a future PR will treat differently from the other
	// two kinds (fall back to a workspace default instead of failing).
	GitHeadReadFailurePathAbsent
)

func (GitHeadReadFailureKind) String added in v0.1.0

func (k GitHeadReadFailureKind) String() string

String renders the failure kind for logging/diagnostics.

type HandlerKind

type HandlerKind string

HandlerKind distinguishes the role a hook plays. An empty kind means a generic hook (no instructions routing). Only agent-kind hooks participate in instructions routing.

const (
	HandlerKindAgent HandlerKind = "agent"
)

func (HandlerKind) IsValid

func (k HandlerKind) IsValid() bool

IsValid reports whether the kind value is recognized.

type HandlerResult

type HandlerResult struct {
	ID           string // hook ID
	Role         Role
	JobID        string // ID of the job that executed this handler
	ExitCode     int
	PayloadPatch json.RawMessage
}

HandlerResult is the result of a single hook execution.

type HandlerTraits

type HandlerTraits struct {
	Consumes []TraitType `json:"consumes,omitempty" yaml:"consumes,omitempty"`
	Produces []TraitType `json:"produces,omitempty" yaml:"produces,omitempty"`
}

type Hook

type Hook struct {
	ID       string        `yaml:"id" json:"id"`
	Name     string        `yaml:"name,omitempty" json:"name,omitempty"`
	Kind     HandlerKind   `yaml:"kind,omitempty" json:"kind,omitempty"`
	Traits   HandlerTraits `yaml:"traits" json:"traits"`
	Requires []string      `yaml:"requires" json:"requires"`
	Agent    string        `yaml:"agent,omitempty" json:"agent,omitempty"`
	Kit      string        `yaml:"-" json:"kit,omitempty"`
	// Command is an inline shell command, run via `sh -c`
	// (docs/plans/script-hook-removal.md). Mutually exclusive with Agent, and
	// not allowed on agent-kind hooks. See DispatchPlanner.PlanHook for the
	// argv selection and validateHookCommandFields for the exclusivity rules.
	Command string `yaml:"command,omitempty" json:"command,omitempty"`
}

func ListHooksForStatus

func ListHooksForStatus(meta *ProjectMeta, task *Task, status TaskStatus) []Hook

ListHooksForStatus returns hooks from the behavior that would match the given status. Since hooks only fire during executing, only executing status yields results. Used by "boid task hook list".

func (*Hook) UnmarshalYAML

func (h *Hook) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML rejects legacy `on:` entries to surface migration breakage clearly.

type HookExecutor

type HookExecutor interface {
	ExecuteHook(ctx context.Context, event *HookFireEvent) (jobID string, err error)
}

HookExecutor launches a hook and returns the job ID.

type HookFireEvent

type HookFireEvent struct {
	EventID   string
	TaskID    string
	ProjectID string
	Hook      Hook
}

type HostCommandSpec

type HostCommandSpec struct {
	Allow []string `yaml:"allow,omitempty" json:"allow,omitempty"`
	Deny  []string `yaml:"deny,omitempty" json:"deny,omitempty"`
	// Stdin is deprecated: it is still parsed for backward compatibility but
	// will be ignored in a future release (loading a spec with stdin: true
	// emits a deprecation warning).
	Stdin  bool              `yaml:"stdin,omitempty" json:"stdin,omitempty"`
	Path   string            `yaml:"path,omitempty" json:"path,omitempty"`
	Env    map[string]string `yaml:"env,omitempty" json:"env,omitempty"`
	Reject []RejectRule      `yaml:"reject,omitempty" json:"reject,omitempty"`
}

HostCommandSpec is the simplified YAML DSL for declaring host commands.

func (HostCommandSpec) ToCommandDef

func (s HostCommandSpec) ToCommandDef(name string) CommandDef

ToCommandDef converts a HostCommandSpec into a CommandDef for internal use.

type HostCommands

type HostCommands map[string]HostCommandSpec

HostCommands supports both list and map YAML forms:

host_commands: [gh, aws]
host_commands:
  gh:
    allow: [pr, issue]
  aws:

func (HostCommands) ToCommandDefs

func (h HostCommands) ToCommandDefs() map[string]CommandDef

ToCommandDefs converts the DSL specs to internal CommandDef map.

func (*HostCommands) UnmarshalYAML

func (h *HostCommands) UnmarshalYAML(value *yaml.Node) error

type Instruction

type Instruction struct {
	Agent   string `json:"agent" yaml:"agent"`
	Name    string `json:"name,omitempty" yaml:"name,omitempty"`
	Message string `json:"message,omitempty" yaml:"message,omitempty"`
	Model   string `json:"model,omitempty" yaml:"model,omitempty"`
}

type Instructions

type Instructions []Instruction

Instructions is the persisted instruction history for a task. The most recent entry is the "active" instruction passed to the agent on dispatch; earlier entries are kept as history (e.g. for reopen tracking).

JSON shape on the wire is an array. For backward compatibility, the legacy single-instruction map form ({"main": {...}}) is also accepted on unmarshal and converted to a single-element array.

func AppendInstruction

func AppendInstruction(existing Instructions, inst Instruction) Instructions

AppendInstruction returns a new instruction list with `inst` appended. The caller is responsible for filling in fields not derived from the previous active entry. Used by `boid task reopen` to record a new context message while preserving history.

func MergeDefaultInstructions

func MergeDefaultInstructions(defaultInstruction *Instruction, requestInstructions json.RawMessage) (Instructions, error)

MergeDefaultInstructions builds the initial instruction list for a new task.

Merge semantics:

  • defaultInstruction == nil: use requestInstructions as-is (no base to inherit from).
  • defaultInstruction != nil:
  • override empty/null/[]/{} → return the default as a single-entry list.
  • override has exactly 1 entry → per-field merge: non-empty fields from the override win; empty fields inherit from defaultInstruction.
  • override has 2+ entries → complete replacement (caller is building an explicit history and partial merge would be ambiguous).

requestInstructions accepts the array form `[{...}, ...]` and the legacy single-map form `{"main": {...}}` (handled by Instructions.UnmarshalJSON).

func (Instructions) Active

func (is Instructions) Active() *Instruction

Active returns the currently-active instruction (the last entry), or nil if the list is empty.

func (*Instructions) UnmarshalJSON

func (is *Instructions) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts both the new array form and the legacy {"main": {...}, "verify": {...}} map form. For the map form, only the "main" entry is preserved (verifying/reworking variants were removed).

type JobCompletion

type JobCompletion struct {
	JobID    string
	Output   string // stdout capture (the hook's own `{"payload_patch": ...}` fallback, if any)
	ExitCode int
}

JobCompletion represents the result of a completed job.

type JobKind

type JobKind string

JobKind is a DB / observability label for a job. It is NOT a sandbox construction signal — dispatcher's mount/env logic must derive everything from Visibility / HostCommands / Instruction, never from Kind. Kind exists purely so the Job row / TUI can tell apart "agent hook" and "user-initiated exec" without re-deriving the category from loosely-related primitives like HandlerID.

const (
	JobKindHook JobKind = "hook"
	JobKindExec JobKind = "exec"
	// JobKindSession is the Phase 3-d label for a user-initiated agent
	// session not tied to a task lifecycle (WebUI [New Session] / `boid
	// agent` CLI). It is distinct from JobKindHook (state-machine driven)
	// and JobKindExec (sandboxed argv with no harness), so the TUI / Web UI
	// can present it as a separate top-level concept.
	JobKindSession JobKind = "session"
)

type JobSpec

type JobSpec struct {
	// Identity used by dispatcher for Job DB persistence and state-machine
	// notification. TaskID and HandlerID are empty for boid-exec jobs.
	TaskID      string
	ProjectID   string
	HandlerID   string
	DisplayName string // human-readable label (hook name or command-session name); persisted to jobs.display_name

	// HookTraitsProduces captures the firing hook's own `traits.produces`
	// list (event.Hook.Traits.Produces) AT DISPATCH TIME — the exact value
	// HandlerResult.allowedTraits (coordinator.go) would use to gate this
	// same hook's file-based payload_patch merge. Phase 5b PR7's
	// `boid task update --payload-patch` RPC (docs/plans/
	// phase5-shim-and-task-context.md) threads this through
	// dispatcher.JobContextSnapshot so it can gate its own merge against
	// the SAME dispatch-time value, never a live re-lookup against the
	// (possibly since-edited/reloaded) project meta — codex review caught a
	// TOCTOU staleness bug in an early cut that re-resolved the hook by ID
	// against current meta at merge time (wiring-seams.md #17's Major 1).
	// nil means "this job's firing hook produces unrestricted" — true for
	// both a virtual/synthesized agent-kind hook (orchestrator.
	// synthesizeAgentHook, whose Traits are always the zero value — the
	// common case for a behavior with no explicit `hooks:` block) and an
	// explicitly declared hook with no traits.produces list of its own;
	// both are indistinguishable from "unrestricted" on the file-based path
	// too (MergePayloadPatch(patch, nil) never filters), so this preserves
	// that behavior exactly rather than inventing a new distinction. Empty
	// for non-hook jobs (boid exec).
	HookTraitsProduces []TraitType

	// Kind is a DB-label / TUI-display category. Sandbox construction details
	// MUST NOT branch on this value.
	Kind JobKind

	// Argv is the command to execute. Argv[0] is either a host absolute path
	// (hook scripts) or a bare command name resolved via broker shim
	// (boid exec). Everything after Argv[0] is passed as-is.
	Argv []string

	// Instruction, when non-nil, materializes at $HOME/.boid/context/instructions.yaml
	// and identifies the agent that should pick up the job. Agent-less jobs
	// (boid exec) leave this nil.
	Instruction *RoutedInstruction

	// Task, when non-nil, materializes at $HOME/.boid/context/task.yaml.
	// boid-exec jobs always leave it nil.
	Task *TaskSnapshot

	// PrimaryInput is the payload the script expects to read on stdin (or,
	// for agent jobs, at $HOME/.boid/context/payload.json).
	// nil means the job reads nothing from boid (e.g. boid-exec with a user TTY).
	PrimaryInput json.RawMessage

	// Visibility describes which host directories the sandbox sees and whether
	// they are writable.
	Visibility Visibility

	// BuiltinPolicies authorises broker-mediated builtin operations (boid, git).
	BuiltinPolicies map[string]BuiltinPolicy

	// HostCommands authorises broker-mediated host command invocations.
	// Hook jobs leave this empty; exec jobs populate it from behavior.
	HostCommands map[string]CommandDef

	// SecretNamespace scopes the broker's secret resolver.
	SecretNamespace string

	// APIGatewayServices, when non-nil, OVERRIDES the dispatcher-resolved
	// (floor ∪ workspace) API gateway service allowlist for this job's
	// token (docs/plans/signal-ingest-detailed-design.md §5.2): a signal-
	// derived trigger's connector exec job is restricted to exactly the ONE
	// service instance its signals.sources[] declaration named, never the
	// workspace's full enabled set. Runner.registerAPIGatewayToken
	// (internal/dispatcher/apigateway_wire.go) intersects this with the
	// normally-resolved set rather than trusting it outright — defense in
	// depth against a stale declaration naming a service the workspace no
	// longer enables (project.yaml load only WARNS about that mismatch,
	// never blocks — see ProjectStore.GetWithWorkspace). nil (every job but
	// a connector trigger) leaves the existing resolveEnabledAPIServices
	// behavior completely unchanged.
	APIGatewayServices []string

	// SignalService / SignalConnector set sandbox.TokenContext.Service/
	// Connector for this job's broker token registration (docs/plans/
	// signal-ingest-detailed-design.md §3.2/§5.2): the ONLY fields that
	// authorize BoidOpSignalIngest/BoidOpSignalCursorGet's broker-side
	// scoping (internal/sandbox/broker.go) to a specific (service,
	// connector) pair. Set only by BuildSessionJobSpec from
	// SessionJobInput.SignalService/SignalConnector, which in turn only a
	// signal-derived trigger's StartExec call populates
	// (sessionDispatcherAdapter.StartExec, internal/server/wire.go). Empty
	// for every other job — signal_ingest/signal_cursor_get stay
	// unreachable in practice for any job that doesn't ALSO get
	// ConnectorBuiltinPolicies (BuiltinPolicies alone is not enough; both
	// must line up, matching TokenContext.Service's own doc comment).
	SignalService   string
	SignalConnector string

	// Env carries extra environment variables the orchestrator wants to export
	// (e.g. behavior-level overrides). dispatcher merges these with its own
	// HOME/PATH/proxy/broker settings.
	Env map[string]string

	// ExecutionState records the task.Status at the time this job was dispatched.
	// Stored in the job DB row so TUI can reconstruct replay context.
	ExecutionState string

	// Interactive, when true, forces TTY allocation regardless of whether an
	// Instruction is attached. Used by daemon-side command execution (Web UI)
	// where the caller always expects a PTY-backed terminal.
	Interactive bool

	// HarnessType identifies which HarnessAdapter implementation the runner
	// hands the agent process off to. Phase 3-d made this invariant
	// non-empty for every dispatched job:
	//   - "shell" for hooks without an `agent:` declaration, every `boid
	//     exec`, and the fall-through for unknown agents
	//   - "claude" / "codex" / "opencode" for the corresponding agent hooks
	//     and user-initiated sessions
	// dispatcher bridges this into sandbox.Spec.HarnessType and the
	// runner-inner-child resolves the adapter via the registry.
	HarnessType string

	// SandboxProfile selects the filesystem layout strategy for the sandbox.
	// Zero value (sandbox.ProfileDefault) preserves existing behaviour.
	// Set to sandbox.ProfileInit for kit-init / workspace-configure generation
	// scripts that need read access to the full host filesystem.
	// When ProfileInit is set, broker registration and the broker socket mount
	// are both skipped.
	SandboxProfile int // sandbox.Profile — kept as int to avoid a circular import
}

JobSpec is the orchestrator-owned, sandbox-agnostic execution request. It is written purely in business vocabulary: "what to run with what visibility and permissions". All sandbox construction details (mounts, env, exit scripts, proxy wiring, stdin routing) are left to dispatcher.

dispatcher is the only layer that bridges JobSpec and sandbox.Spec.

type JobWaiter

type JobWaiter interface {
	WaitForJob(ctx context.Context, jobID string) (JobCompletion, error)
}

JobWaiter waits for a job to complete.

type KitRef

type KitRef struct {
	Ref string `yaml:"ref" json:"ref"`
}

func (*KitRef) UnmarshalYAML

func (k *KitRef) UnmarshalYAML(value *yaml.Node) error

type LegacyProjectMeta added in v0.0.8

type LegacyProjectMeta struct {
	ID                  string                        `yaml:"id"`
	Name                string                        `yaml:"name"`
	Kits                []KitRef                      `yaml:"kits,omitempty"`
	TaskBehaviors       map[string]LegacyTaskBehavior `yaml:"task_behaviors,omitempty"`
	BaseBranch          string                        `yaml:"base_branch,omitempty"`
	ForkPoint           string                        `yaml:"fork_point,omitempty"`
	HostCommands        HostCommands                  `yaml:"host_commands,omitempty"`
	Env                 map[string]string             `yaml:"env,omitempty"`
	SecretNamespace     string                        `yaml:"secret_namespace,omitempty"`
	Capabilities        Capabilities                  `yaml:"capabilities,omitempty"`
	DefaultTaskBehavior string                        `yaml:"default_task_behavior,omitempty"`

	// HadAdditionalBindingsKey records only whether the raw project.yaml (or
	// project.local.yaml) still declares a top-level `additional_bindings:`
	// key — it is NOT unmarshaled from that key itself (yaml:"-"), and no
	// value is ever kept. Before docs/plans/home-workspace-volume.md Phase 4
	// PR4, this type had a typed `AdditionalBindings []BindMount` field: an
	// old project.yaml's additional_bindings migrated into an auto-generated
	// "legacy kit" and from there into the target workspace's own (now also
	// retired) AdditionalBindings field. Both destinations are gone, so the
	// value itself is no longer worth carrying — but computeRemoveKeys
	// (cmd/project_migrate.go) still needs to know whether the key was
	// present at all, so `boid project migrate` keeps offering to strip it
	// from project.yaml (which rejects the key outright — see
	// removedTopLevelKeys in spec_loader.go) even though nothing downstream
	// resolves its value any more. See ReadProjectMetaLegacy for how this is
	// populated.
	HadAdditionalBindingsKey bool `yaml:"-"`
}

LegacyProjectMeta holds the raw contents of a pre-migration project.yaml, including fields that have been moved to workspace.yaml and kit.yaml in the new schema. This type is used only by the migrate command; normal loading goes through ReadProjectMeta.

func ReadProjectMetaLegacy added in v0.0.8

func ReadProjectMetaLegacy(dir string) (*LegacyProjectMeta, error)

ReadProjectMetaLegacy reads .boid/project.yaml (and .boid/project.local.yaml if present) using a raw-map first pass that does NOT reject unknown or removed fields. This is intentionally separate from ReadProjectMeta so that the migrate command can load old-schema files that would otherwise fail validation.

The returned LegacyProjectMeta captures all fields that are subject to migration, including kits/env/host_commands/secret_namespace/capabilities at both the project level and the task_behaviors level (additional_bindings is detected but not carried as a value any more — see LegacyProjectMeta.HadAdditionalBindingsKey).

func (*LegacyProjectMeta) CollectAllKitRefs added in v0.0.8

func (m *LegacyProjectMeta) CollectAllKitRefs() []KitRef

CollectAllKitRefs returns a deduplicated, ordered list of all kit refs referenced at the project level and across all task behaviors.

func (*LegacyProjectMeta) HasLegacyFields added in v0.0.8

func (m *LegacyProjectMeta) HasLegacyFields() bool

HasLegacyFields reports whether the LegacyProjectMeta contains any fields that should be migrated to workspace.yaml or a legacy kit. This is used by the migrate command to detect whether migration is needed at all.

A stray additional_bindings key deliberately does NOT make this return true on its own (Phase 4 PR4, docs/plans/home-workspace-volume.md: the field is retired, there is nothing left to migrate its value to) — but computeRemoveKeys (cmd/project_migrate.go) still offers to strip the key from project.yaml via HadAdditionalBindingsKey independently of this method, so printMigratePlan's "nothing to migrate" short-circuit (which also checks len(removeKeys) == 0) still correctly falls through to show a plan for a project.yaml that has nothing BUT a stray additional_bindings key left.

type LegacyTaskBehavior added in v0.0.8

type LegacyTaskBehavior struct {
	Readonly           *bool        `yaml:"readonly,omitempty"`
	Traits             []string     `yaml:"traits,omitempty"`
	DefaultInstruction *Instruction `yaml:"default_instruction,omitempty"`
	Kits               []KitRef     `yaml:"kits,omitempty"`
}

LegacyTaskBehavior holds a task behavior including the legacy kits field that appears at the behavior level in old project.yaml files.

type Lifecycle

type Lifecycle struct {
	Executed bool         `json:"executed"`
	Done     *DoneReport  `json:"done,omitempty"`
	Fail     *FailReport  `json:"fail,omitempty"`
	Abort    *AbortReason `json:"abort,omitempty"`
}

Lifecycle holds computed lifecycle traits derived from action history and the current dispatch state. It is never persisted to the payload; it is injected transiently before state-machine evaluation.

Done / Fail carry the agent's intent reported via `notify --done` / `notify --fail` (recorded as `done_request` / `fail_request` actions). They gate the executing→done / executing→aborted auto-advance rules. By keeping these as derived traits (rather than firing an immediate state transition inside NotifyTask), the runtime is allowed to exit cleanly via SIGUSR1 → bash EXIT trap → `boid job done` before the dispatch loop advances the state. See docs/plans/lifecycle-accountability.md (Phase 2.c follow-up).

func DeriveLifecycle

func DeriveLifecycle(_ context.Context, taskID string, store LifecycleStore, hookExecuted bool) (Lifecycle, error)

DeriveLifecycle computes lifecycle traits from action history. hookExecuted indicates whether a hook job completed successfully in the current dispatch cycle (used to set lifecycle.executed). If store is nil, only Executed is set from hookExecuted.

Done / Fail are scoped to the current executing cycle: every time the task (re-)enters executing (start / answer / reopen) the prior intent is cleared, so a `done_request` recorded before a `reopen` does not bleed into the new cycle. done_request / fail_request are mutually exclusive — recording one clears the other.

type LifecycleStore

type LifecycleStore interface {
	ListActionsByTask(taskID string) ([]*Action, error)
}

LifecycleStore is the minimal interface required to derive lifecycle traits from persistent action history.

type MergeMode

type MergeMode string
const (
	MergeModeExclusive MergeMode = "exclusive"
	MergeModeShared    MergeMode = "shared"
)

func TraitMergeMode

func TraitMergeMode(trait TraitType) MergeMode

type MetaCache

type MetaCache interface {
	Get(id string) (*ProjectMeta, bool)
}

type MetaHydrator added in v0.0.8

type MetaHydrator interface {
	GetWithWorkspace(ctx context.Context, projectID string) (*ProjectMeta, error)
}

MetaHydrator extends MetaCache with workspace-aware hydration. When a ProjectStore has a WorkspaceStore configured, it implements this interface and returns a ProjectMeta enriched with workspace capabilities/kits/env.

type MetaProjectResolver added in v0.4.0

type MetaProjectResolver interface {
	// MetaProjectIDs returns the project ids within workspaceID that declare
	// signals.sources[] — nil/empty when none do, including when the
	// resolver has no data at all for workspaceID. §6.2 treats both the same
	// way: no metaproject to ingest FOR, so nothing to ingest.
	MetaProjectIDs(workspaceID string) []string
}

MetaProjectResolver answers, for a workspace, which of its projects declare signals.sources[] in their (hydrated) project.yaml — its metaprojects (docs/plans/boid-internal-signal-inbox.md §4.3/§6.2: "メタプロジェクトとは signals.sources[] を宣言している project のこと"). Backed in production by *ProjectStore.MetaProjectIDs — the SAME hydrated meta cache every other project.yaml-derived read already uses, injected here as a narrow interface (mirroring internal/server/boid_executor.go's resolveOrCaptureService/actionListService/projectLookup narrowing convention) rather than depending on *ProjectStore's full surface. See this package's TaskRepository.SetMetaProjectResolver for the wiring seam and the design doc's §6.2 for why the lookup lives here (an internal/orchestrator-owned interface, satisfied by an internal/orchestrator-owned type) rather than being pushed up to internal/api/internal/server the way internal/integrationpack's Pack registry had to be (§6.2's own comparison): *ProjectStore already lives in this package, so — unlike the Pack registry, which lives in a sibling package internal/orchestrator does not and must not import — there is no layering violation to route around, only an instance-wiring one (a bare package-level CreateAction has no constructor-injected fields of its own), which TaskRepository's existing late-binding-setter shape (SetWorkspaceStore/ SetHostCommands on *ProjectStore itself) already solves for the identical problem.

type PlannerWireConfig

type PlannerWireConfig struct {
	Meta     MetaCache
	Hydrator MetaHydrator // optional; when set, dispatch uses GetWithWorkspace
	Projects ProjectCatalog
	Tasks    TaskLookup
	Adapter  adapters.HarnessAdapter
}

type PolicyContext

type PolicyContext struct {
	ProjectDir string
	HomeDir    string
}

PolicyContext carries non-role data needed to compute role-derived policies. ProjectDir lets boid policy accept the host project dir as cwd. HomeDir accepts the sandbox HOME, which is the default WorkDir for hook jobs.

type Project

type Project struct {
	ID          string      `json:"id"`
	WorkspaceID string      `json:"workspace_id"`
	WorkDir     string      `json:"work_dir"`
	Meta        ProjectMeta `json:"meta"`
	// UpstreamURL is the project's git remote origin, captured and normalized
	// to HTTPS (SSH → HTTPS) at `project add` / `project reload` time (see
	// docs/plans/git-gateway-cutover.md PR2). Empty until captured; daemon
	// startup backfills it for projects registered before this field existed.
	// Not read from project.yaml — this is DB-only, machine-local state.
	UpstreamURL string    `json:"upstream_url,omitempty"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
	// Status / StatusMessage reflect the daemon's in-memory ProjectStore
	// view of this project's health (docs/plans/volume-only-daemon.md
	// §論点a: StatusReady / StatusDegraded). Not a DB column — populated at
	// hydrate time (internal/api.ProjectAppService.hydrateProject) from
	// ProjectStore.Status. Omitted from JSON when "ready" (the common case)
	// to keep existing API response bodies unchanged for clients that
	// don't care.
	Status        string `json:"status,omitempty"`
	StatusMessage string `json:"status_message,omitempty"`
}

func GetProject

func GetProject(dbtx db.DBTX, id string) (*Project, error)

GetProject retrieves a project by ID.

func ListProjects

func ListProjects(dbtx db.DBTX) ([]*Project, error)

ListProjects returns all projects ordered by creation time.

type ProjectCatalog

type ProjectCatalog interface {
	GetProject(id string) (*Project, error)
}

type ProjectExplain added in v0.1.0

type ProjectExplain struct {
	ProjectID   string `json:"project_id"`
	WorkspaceID string `json:"workspace_id,omitempty"`

	// TaskBehaviors maps each canonical behavior name present in EITHER
	// project.yaml or the workspace default to its provenance. A name absent
	// from both never appears here (there is nothing to explain).
	TaskBehaviors map[string]FieldProvenance `json:"task_behaviors"`

	BaseBranch          FieldProvenance `json:"base_branch"`
	ForkPoint           FieldProvenance `json:"fork_point"`
	DefaultTaskBehavior FieldProvenance `json:"default_task_behavior"`

	// AnyWorkspaceDefaultApplied is true when at least one field/key above is
	// ProvenanceWorkspaceDefault. Surfaced even without --explain as the
	// minimum one-line indicator the doc requires.
	AnyWorkspaceDefaultApplied bool `json:"any_workspace_default_applied"`

	// BaseBranchSnapshotNote is always populated (constant text) so CLI
	// output can print it without a separate lookup.
	BaseBranchSnapshotNote string `json:"base_branch_snapshot_note"`

	// WorkspaceUnavailable is true when the project is linked to a workspace
	// whose default project definition could not be read (a real error, not
	// merely "unset" — see ProvenanceUnavailable). CLI output surfaces this
	// so the operator knows the explain result is incomplete, not a
	// confirmed "nothing is configured".
	WorkspaceUnavailable bool `json:"workspace_unavailable,omitempty"`

	// IsNoYAMLProject is true when ProjectID carries
	// URLDerivedProjectIDPrefix — the project.yaml-less registration path
	// (PR5). Its id was derived from the git URL, never read from a
	// project.yaml `id:` field.
	IsNoYAMLProject bool `json:"is_no_yaml_project"`

	// NameSource explains how a no-YAML project's Name was determined, for
	// carry-over visibility from the PR5 completion report's flagged
	// follow-up. Empty for a project.yaml-bearing project (Name always comes
	// from project.yaml there, nothing to explain). One of "explicit",
	// "cached", "basename", "url", or "" (name could not be recovered).
	NameSource string `json:"name_source,omitempty"`
}

ProjectExplain is the field-provenance view of a project's effective meta (docs/plans/workspace-default-project.md 論点e, PR6). It answers "where did this value come from" for the 4 fields a workspace default definition can supply: task_behaviors (per canonical behavior name), base_branch, fork_point, default_task_behavior.

func ComputeProjectExplain added in v0.1.0

func ComputeProjectExplain(projectID, workspaceID string, rawMeta *ProjectMeta, wsMeta *WorkspaceMeta, workspaceUnavailable bool) *ProjectExplain

ComputeProjectExplain classifies rawMeta's (the project.yaml-only — pre-hydration — cached meta) 4 workspace-default-mergeable fields against wsMeta (the workspace's default project definition; nil when the project has no linked workspace, the workspace store is not configured, or workspace.yaml/row failed to load — see workspaceUnavailable below for how the last case is distinguished from the first two).

rawMeta must not be nil. wsMeta may be nil.

workspaceUnavailable must be true when wsMeta is nil SPECIFICALLY because an attempt to load the linked workspace failed with a real error (not os.ErrNotExist, not "no workspace linked", not "workspace store unconfigured") — i.e. the same condition that makes a real dispatch's GetWithWorkspace call fail outright. When true, a field that would otherwise read as ProvenanceUnset instead reads as ProvenanceUnavailable: "unset" asserts nothing supplies a value, which is a claim this function cannot back up when the workspace side could not even be read (Codex review round 1 Major).

The task_behaviors comparison is done on names as written (決定4, 論点j), the same way GetWithWorkspace's own merge compares them. Neither input map is mutated: rawMeta.TaskBehaviors is a shared cached map that concurrent hydrate/dispatch calls may be reading (Codex review round 1 Major — an earlier version mutated it in place on every read-only /explain call).

func (*ProjectExplain) TaskBehaviorNames added in v0.1.0

func (e *ProjectExplain) TaskBehaviorNames() []string

TaskBehaviorNames returns the explain's behavior-name keys sorted for stable display.

type ProjectMeta

type ProjectMeta struct {
	ID            string                  `yaml:"id" json:"id"`
	Name          string                  `yaml:"name" json:"name"`
	TaskBehaviors map[string]TaskBehavior `yaml:"task_behaviors" json:"task_behaviors"`
	// Triggers is a TOP-LEVEL project.yaml field (J-1) — deliberately NOT
	// nested under any TaskBehavior. 「いつ始まるか」は task_behaviors の
	// 関心 (「どう実行するか」) とは異なる性質であり、混ぜると器の概念的な
	// 強度が落ちる (6 節「なぜ task_behaviors に入れないか」)。omitempty:
	// triggers を持たない project.yaml (大多数) は export/apply の往復で
	// `triggers: []` のノイズを出さない。
	//
	// workspace envelope の spec.* allowlist (workspace_envelope.go の
	// workspaceEnvelopeSpecFields) には**意図的に載せていない** — 理由は
	// このフィールドと同じ PR の報告を参照 (workspace-level のデフォルト
	// `run:` は特定 1 project の tracked tree にしか存在しないスクリプト
	// パスを指すことになり、workspace 内の複数 project へ一般化できる
	// task_behaviors/base_branch/fork_point とは性質が違う)。`triggers:`
	// を書けるのは project.yaml だけであり、workspace_envelope.go の
	// decodeStrictNode は今後も unknown field として拒否し続ける。
	Triggers []Trigger `yaml:"triggers,omitempty" json:"triggers,omitempty"`
	// Signals declares this (meta)project's signal sources (docs/plans/
	// signal-ingest-detailed-design.md §5.1, PR-5). Only meaningful on a
	// metaproject — a project whose sandbox is where Integration Pack
	// connectors run — but nothing here enforces that; any project.yaml may
	// declare it. Same top-level, project.yaml-only placement rationale as
	// Triggers above (workspaceEnvelopeSpecFields does not list "signals"
	// either, for the identical reason: a bind-mounted Pack directory is a
	// property of ONE tracked-tree project, not something that generalizes
	// across a workspace's projects).
	Signals SignalsConfig `yaml:"signals,omitempty" json:"signals,omitempty"`
	// SessionBehaviors is a free-naming dictionary (same "any key name"
	// model as TaskBehaviors) from a use-case key (e.g. "shape") to a
	// default harness_type/model for sessions launched for that use case.
	// Sessions do NOT resolve through TaskBehaviors/ResolveBehavior — see
	// SessionBehavior's doc comment and buildShapingInstruction's doc
	// comment in internal/api/web.go for the rejected-alternatives history
	// this deliberately avoids repeating.
	SessionBehaviors map[string]SessionBehavior `yaml:"session_behaviors,omitempty" json:"session_behaviors,omitempty"`
	// BaseBranch is the default git base branch for worktrees created by
	// tasks in this project. It is resolved at task creation time (with
	// ${TASK_REMOTE_ID} / ${current_branch} expansion) and persisted on
	// each task row.
	BaseBranch string `yaml:"base_branch,omitempty" json:"base_branch,omitempty"`
	// ForkPoint is the git ref used as the start point when creating a
	// base branch that does not yet exist (ClassifyBaseBranch case 3).
	// Accepts any ref that `git rev-parse --verify` resolves (e.g. "main",
	// "origin/main", a tag, or a commit SHA). When empty, the dispatcher
	// falls back to "refs/remotes/origin/HEAD"; if that is also unset the
	// case-3 worktree creation fails. The project root's working-tree HEAD
	// is intentionally never consulted, since it can drift to an
	// unexpected branch between task creation and dispatch.
	ForkPoint          string            `yaml:"fork_point,omitempty" json:"fork_point,omitempty"`
	HostCommands       HostCommands      `yaml:"host_commands" json:"host_commands"`
	AdditionalBindings []BindMount       `yaml:"additional_bindings" json:"additional_bindings"`
	Env                map[string]string `yaml:"env" json:"env"`
	// SecretNamespace is a runtime-only field injected at hydration time from the
	// linked workspace ID. It is intentionally not read from project.yaml (yaml:"-").
	SecretNamespace string `yaml:"-" json:"secret_namespace,omitempty"`
	// Capabilities declares optional sandbox capabilities. This is a runtime-only
	// field injected from workspace.yaml at hydration time (yaml:"-").
	Capabilities Capabilities `yaml:"-" json:"capabilities,omitempty"`
	// DefaultTaskBehavior names the behavior to use when a CreateTaskRequest
	// omits both behavior and behavior_spec. When empty, the daemon falls back
	// to "supervisor" if that behavior exists (with a deprecation warning);
	// if neither is set, CreateTask returns an error.
	DefaultTaskBehavior string `yaml:"default_task_behavior,omitempty" json:"default_task_behavior,omitempty"`
	// NameSource records how Name was determined for a project.yaml-less
	// (URL-derived id, PR5) registration — "explicit" (--name given),
	// "url" (derived from the git URL), "cached" (recovered from a
	// previously-cached Name on reload), or "basename" (recovered from the
	// bare-repo WorkDir's directory name on reload). Runtime-only
	// (yaml:"-"): never read from project.yaml — a project.yaml-bearing
	// project always leaves this empty, since Name there has an
	// unambiguous single source. Surfaced by `project show --explain`
	// (docs/plans/workspace-default-project.md 論点e, PR6) as a carry-over
	// from PR5's completion report.
	NameSource string `yaml:"-" json:"name_source,omitempty"`
}

func ReadProjectMeta

func ReadProjectMeta(dir string) (*ProjectMeta, error)

func ReadProjectMetaFromBareRepo added in v0.1.0

func ReadProjectMetaFromBareRepo(bareRepoPath string) (*ProjectMeta, error)

ReadProjectMetaFromBareRepo reads and validates .boid/project.yaml from a daemon-managed bare git repository's HEAD (docs/plans/volume-only-daemon.md §論点a: "project.yaml は bare repo の HEAD (default branch) から `git show HEAD:.boid/project.yaml` で読む"). Shares the exact same validation pipeline as the filesystem-based ReadProjectMeta via parseProjectMetaBytes (spec_loader.go).

Unlike ReadProjectMeta, there is no project directory on disk to resolve a relative host_commands.path against — a host_commands entry with a non-absolute Path is rejected here instead of silently resolved against nothing.

func ReadProjectMetaWithKits

func ReadProjectMetaWithKits(dir string) (*ProjectMeta, error)

ReadProjectMetaWithKits reads project.yaml and merges project-level overlays into each behavior. Returns a ProjectMeta whose TaskBehaviors have their resolved Hooks/etc. populated and ready for dispatch.

Note: kits are no longer supported in project.yaml (removed in the new schema); the kit mechanism itself was retired in Phase 2.5 PR6 (docs/plans/workspace-db-consolidation.md). This function used to accept a KitResolver parameter for call-site compatibility even though it was never used; PR7 removed that type and parameter outright (decision 12). The "WithKits" name is now a historical artifact — it's kept as-is since it's a widely-used, purely-internal function name, not worth a rename-only churn across every call site. project.local.yaml is deprecated; use workspace.yaml instead.

type ProjectMigrationError added in v0.0.8

type ProjectMigrationError struct {
	Projects []ProjectMigrationIssue
}

ProjectMigrationError is a typed error carrying one or more migration issues. Callers (e.g. boid start) use errors.As to extract the issues and drive auto-migration; Error() preserves the legacy multi-line format so log output (boid.log) is byte-identical to the pre-typed-error version.

func (*ProjectMigrationError) Error added in v0.0.8

func (e *ProjectMigrationError) Error() string

Error returns the multi-line, human-readable error message. The format for a single issue is byte-identical to the legacy rejectRemovedProjectFields output so existing spec_loader tests pass unchanged. Multiple issues are separated by a single newline.

type ProjectMigrationIssue added in v0.0.8

type ProjectMigrationIssue struct {
	// ProjectID is the registered project ID, when known. Empty when the
	// issue surfaces from a loader path that does not yet have a DB lookup
	// (e.g. ReadProjectMeta called directly with a path).
	ProjectID string
	// Dir is the absolute path to the project root (parent of .boid/) for
	// a filesystem-loaded project, OR the daemon's own internal bare-
	// repository path for a git-URL-registered project (IsBareRepo true
	// — see its own doc comment). Always populated either way, since it
	// remains useful for error text / logs, but only actionable as a
	// `boid project migrate <dir>` argument when IsBareRepo is false.
	Dir string
	// IsBareRepo (codex round-9 review of PR5, Blocker 1) reports whether
	// Dir is the daemon-managed bare repository path for a git-URL-
	// registered project (internal/orchestrator/project_bare_repo.go's
	// ReadProjectMetaFromBareRepo) rather than a real, user-accessible
	// filesystem directory (ReadProjectMeta). `boid project migrate`
	// (cmd/project_migrate.go) reads <dir>/.boid/project.yaml off a real
	// filesystem directory — it cannot be run against a bare-repo path at
	// all, so FormatMigrationIssue/migrationGuidance must not tell the
	// user to do so when this is true.
	IsBareRepo bool
	// Messages are the per-field violation messages in the same order as
	// the old single-string error produced by rejectRemovedProjectFields.
	Messages []string
}

ProjectMigrationIssue describes one project whose project.yaml uses the pre-Phase-3-e schema (top-level kits / host_commands / additional_bindings / secret_namespace / capabilities, or task_behaviors.<name>.kits) and must be migrated to the new workspace+kit layout via `boid project migrate`.

type ProjectMissingError added in v0.0.8

type ProjectMissingError struct {
	ProjectID string // registered project ID
	Dir       string // expected project root (where .boid/project.yaml should live)
	Err       error  // underlying os.ReadFile error (preserved for diagnostics / errors.Is)
}

ProjectMissingError is a typed error indicating that a project registered in the DB failed to load its project.yaml. It is distinct from *ProjectMigrationError, which signals schema migration is required.

Originally (pre docs/plans/volume-only-daemon.md) this covered only the "project directory removed from disk" case, and callers auto-pruned the DB row on sight — safe because the project.yaml was the source of truth, so a row pointing at a vanished directory was unambiguously stale.

docs/plans/volume-only-daemon.md §論点a retired that auto-prune: the pivot-triggering incident it documents was caused by exactly this short-circuit firing on a false "missing" signal (host filesystem temporarily unreachable from inside a container). The declared invariant is now: filesystem/remote observations never justify a hard delete, at any point (startup / dispatch / fetch / GC). wrapPerProjectLoadErr (project_store.go) now returns this type for EVERY per-project load failure that is not a *ProjectMigrationError — a missing directory, a YAML parse error, a corrupt/unreachable bare repo (project_bare_repo.go), all of it — because as of the invariant above they all get the same response: internal/server/wire.go's buildProjectStore marks the project "degraded" (ProjectStore.MarkDegraded) and keeps going. The DB row is only ever removed by an explicit `boid project rm` / `boid workspace delete`. The type name stays as-is (not worth the rename-only churn across call sites) despite no longer being specific to the "missing" case.

func (*ProjectMissingError) Error added in v0.0.8

func (e *ProjectMissingError) Error() string

Error matches the legacy `project "<id>": <inner>` shape used by wrapPerProjectLoadErr so existing log output is byte-identical.

func (*ProjectMissingError) Unwrap added in v0.0.8

func (e *ProjectMissingError) Unwrap() error

Unwrap exposes the underlying os.ReadFile error so callers can errors.Is(err, fs.ErrNotExist) without knowing about ProjectMissingError.

type ProjectRepository

type ProjectRepository struct {
	// contains filtered or unexported fields
}

func NewProjectRepository

func NewProjectRepository(db db.DBTX) *ProjectRepository

func (*ProjectRepository) AssignDefaultWorkspaceToUnlinked added in v0.0.8

func (r *ProjectRepository) AssignDefaultWorkspaceToUnlinked(workspaceID string) (int, error)

AssignDefaultWorkspaceToUnlinked inserts a project_workspaces row pointing at workspaceID for every project that does not yet have one. Returns the number of rows inserted. See the package-level function for the underlying statement.

func (*ProjectRepository) AssignWorkspaceIfExists added in v0.0.13

func (r *ProjectRepository) AssignWorkspaceIfExists(projectID, workspaceID string) error

AssignWorkspaceIfExists atomically checks-then-assigns (MAJOR 3, codex review). See the package-level function's doc comment. r.db must be a *sql.DB — every production wiring path constructs ProjectRepository with srv.db (the daemon's single *sql.DB handle), so this type assertion only fails for a hand-rolled ProjectRepository over a *sql.Tx, which no caller does today.

func (*ProjectRepository) CreateProject

func (r *ProjectRepository) CreateProject(project *Project) error

func (*ProjectRepository) DeleteProject

func (r *ProjectRepository) DeleteProject(id string) error

func (*ProjectRepository) GetProject

func (r *ProjectRepository) GetProject(id string) (*Project, error)

func (*ProjectRepository) GetWorkspaceSummary added in v0.0.13

func (r *ProjectRepository) GetWorkspaceSummary(slug string) (*WorkspaceSummary, error)

GetWorkspaceSummary returns a single workspace's summary (project count + revision). See the package-level function's doc comment for the os.ErrNotExist contract.

func (*ProjectRepository) ListProjectWorkspaceReferences added in v0.0.13

func (r *ProjectRepository) ListProjectWorkspaceReferences() ([]*WorkspaceSummary, error)

ListProjectWorkspaceReferences returns project_workspaces membership directly (see the package-level function's doc comment for why this differs from ListWorkspaces and who still needs it).

func (*ProjectRepository) ListProjects

func (r *ProjectRepository) ListProjects() ([]*Project, error)

func (*ProjectRepository) ListWorkspaces

func (r *ProjectRepository) ListWorkspaces() ([]*WorkspaceSummary, error)

func (*ProjectRepository) SetProjectUpstreamURL added in v0.0.10

func (r *ProjectRepository) SetProjectUpstreamURL(id, upstreamURL string) error

SetProjectUpstreamURL updates a project's captured upstream_url. See the package-level function for the underlying statement.

func (*ProjectRepository) SetProjectWorkspace

func (r *ProjectRepository) SetProjectWorkspace(projectID, workspaceID string) error

func (*ProjectRepository) WorkspaceExists added in v0.0.13

func (r *ProjectRepository) WorkspaceExists(slug string) (bool, error)

WorkspaceExists reports whether slug refers to an existing workspaces table row (MAJOR 5 fix — see WorkspaceExists' doc comment).

type ProjectStatus added in v0.1.0

type ProjectStatus struct {
	// State is StatusReady or StatusDegraded.
	State string
	// Message explains why State is StatusDegraded (empty for StatusReady).
	Message string
}

ProjectStatus is a project's in-memory health snapshot (docs/plans/ volume-only-daemon.md §論点a). See Status/MarkDegraded/MarkReady.

type ProjectStore

type ProjectStore struct {
	// contains filtered or unexported fields
}

ProjectStore holds project metadata in memory, loaded from project.yaml files.

func NewProjectStore

func NewProjectStore() *ProjectStore

NewProjectStore creates a new store.

func (*ProjectStore) Explain added in v0.1.0

func (s *ProjectStore) Explain(projectID string) (*ProjectExplain, error)

Explain returns the field-provenance view of projectID's effective meta (docs/plans/workspace-default-project.md 論点e, PR6) — for each of the 4 workspace-default-mergeable fields, whether the effective value came from project.yaml or the workspace's default project definition. Unlike GetWithWorkspace, this never returns an error for a missing/unreadable workspace: the degraded window (workspace.yaml absent, or no workspace linked / workspace store unconfigured) is reported as "no workspace default applied" (ProvenanceUnset), the same treatment GetWithWorkspace itself gives that window. A real load failure (not os.ErrNotExist) is reported as ProvenanceUnavailable instead — distinct from "unset" because this function genuinely cannot tell whether a workspace default would have supplied a value (Codex review round 1 Major; see ComputeProjectExplain's own doc comment for the classification rule).

func (*ProjectStore) Get

func (s *ProjectStore) Get(id string) (*ProjectMeta, bool)

Get returns the cached meta for a project.

func (*ProjectStore) GetWithWorkspace added in v0.0.8

func (s *ProjectStore) GetWithWorkspace(_ context.Context, projectID string) (*ProjectMeta, error)

GetWithWorkspace returns a ProjectMeta hydrated with workspace-level capabilities, host_commands, additional_bindings, env, SecretNamespace injection, and — since docs/plans/workspace-default-project.md PR4 — the workspace's default project definition (task_behaviors / base_branch / fork_point / default_task_behavior), which project.yaml's own values override field by field (決定1) and canonical-behavior-name by name (決定4).

Hydration rules:

  • If the project has no linked workspace, returns the cached meta unchanged.
  • If linked: always injects meta.SecretNamespace = workspaceID.
  • On workspace.yaml load success: merges Capabilities, host_commands, additional_bindings, Env, and the workspace default project definition.
  • On os.ErrNotExist (degraded window): logs a warning, returns meta with only SecretNamespace injected (no error) — the workspace default is NOT applied in this window either, same as every other workspace-level field.
  • On other errors: returns nil and the error.

The kit mechanism (ws.Kits resolved via a KitResolver and merged in here) was retired in docs/plans/workspace-db-consolidation.md Phase 2.5 PR6; see the NOTE in the body below for what used to live here.

The returned *ProjectMeta is a fresh copy when hydration occurs; callers must not mutate the value returned when workspaceID is empty (it is the cached pointer).

func (*ProjectStore) Load

func (s *ProjectStore) Load(workDir string) (*ProjectMeta, error)

Load reads project.yaml from the work_dir and stores the meta in memory.

func (*ProjectStore) LoadAll

func (s *ProjectStore) LoadAll(projects []*Project) []error

LoadAll reads project.yaml for each registered project — dispatching to LoadBareRepo for a git-URL registered project (IsBareRepoDir) or Load for a filesystem-checkout registered project (the pre-volume-only model, still supported for `boid project init` — see docs/plans/ volume-only-daemon.md §論点a's migration-path note: existing dir-based registrations are left alone, not auto-migrated) — and records each project's workspaceID so that GetWithWorkspace can hydrate at call time.

Per-project errors are returned in the original order. When the inner error is a *ProjectMigrationError, the candidate's project ID is stamped onto every Issue in the returned error so downstream callers (e.g. the boid start parent picking issues out via errors.As) can drive auto-migration without parsing strings — this is the one case internal/server/wire.go's buildProjectStore still treats as fail-fast. Every OTHER per-project failure (missing dir, YAML parse error, corrupt or unreachable bare repo, project.yaml missing from a bare repo's HEAD...) is wrapped as *ProjectMissingError and, in addition to being returned here, is recorded via MarkDegraded before this method returns — callers no longer need a second pass to implement the docs/plans/ volume-only-daemon.md §論点a auto-prune-retirement invariant themselves; LoadAll already leaves every failed candidate in the StatusDegraded state with its DB row (and any previously cached Meta) untouched.

func (*ProjectStore) LoadBareRepo added in v0.1.0

func (s *ProjectStore) LoadBareRepo(bareRepoPath string) (*ProjectMeta, error)

LoadBareRepo reads .boid/project.yaml from a daemon-managed bare git repository's HEAD (docs/plans/volume-only-daemon.md §論点a/b) and stores the meta in memory — the bare-repo counterpart to Load. Used both by ProjectAppService.CreateProjectFromGitURL (first load right after a fresh `git clone --bare`) and ProjectAppService.FetchProject (`boid project fetch <id>`, reload after `git fetch --all`).

func (*ProjectStore) LoadBareRepoExpectingID added in v0.1.0

func (s *ProjectStore) LoadBareRepoExpectingID(bareRepoPath, expectedID, upstreamURL string) (*ProjectMeta, error)

LoadBareRepoExpectingID is LoadBareRepo's id-validated counterpart (PR-2a codex round-3 M2 fix). Pre-fix, LoadBareRepo cached the freshly-read meta under its OWN id BEFORE any caller got a chance to check it against the id the caller actually expected — so if project A's project.yaml `id:` drifted (upstream rename) to collide with an already-registered, completely unrelated project B, A's load silently overwrote B's cache entry, and the caller's own mismatch-cleanup branch (a bare Remove(meta.ID)) then deleted that just-clobbered entry outright — corrupting B's in-memory state even though B itself was never touched on disk.

Used by FetchProject (via the Meta interface) and LoadAll below — both call sites already have a specific expected id to validate the freshly- read meta against, unlike LoadBareRepo's other caller (CreateProjectFromGitURL's first load right after a fresh clone), which has no prior id to compare against: a brand-new registration adopts whatever id project.yaml declares, so that call site is deliberately left on the original LoadBareRepo (unconditional cache commit).

Metadata is read into a scratch value first (ReadProjectMetaFromBareRepo does not touch the cache); the shared cache is only mutated once expectedID has been confirmed to match. A mismatch still returns the scratch meta — so the caller can report both the old and new id in its own error message, same as before this fix — but leaves EVERY existing cache entry, including any prior entry registered under the drifted id itself, completely untouched.

func (*ProjectStore) LoadExpectingID added in v0.1.0

func (s *ProjectStore) LoadExpectingID(workDir, expectedID string) (*ProjectMeta, error)

LoadExpectingID is Load's id-validated counterpart — see LoadBareRepoExpectingID's doc comment for the full M2 rationale, which applies identically to the legacy host-dir registration path LoadAll dispatches to here.

func (*ProjectStore) MarkDegraded added in v0.1.0

func (s *ProjectStore) MarkDegraded(projectID, message string)

MarkDegraded records that projectID's project.yaml/bare-repo could not be loaded, without touching its DB row or its (possibly still-cached) Meta — this is the "エラー化 (status field で可視化)" half of docs/plans/ volume-only-daemon.md §論点a's on-startup-auto-prune-retirement invariant. Overwrites any prior status for projectID.

func (*ProjectStore) MarkReady added in v0.1.0

func (s *ProjectStore) MarkReady(projectID string)

MarkReady clears any degraded status for projectID (back to the implicit "ready" default). Called automatically by Load/LoadBareRepo on a successful load — most callers never need to call this directly; it is exported for the rare caller that needs to clear a status without a full reload (none exist yet, kept for symmetry with MarkDegraded).

func (*ProjectStore) MetaProjectIDs added in v0.4.0

func (s *ProjectStore) MetaProjectIDs(workspaceID string) []string

MetaProjectIDs returns the ids of every project linked to workspaceID (via SetWorkspaceID/the workspaceIDs map) whose cached meta declares signals.sources[] — i.e. workspaceID's metaprojects (docs/plans/ boid-internal-signal-inbox.md §4.3/§6.2). Satisfies MetaProjectResolver (signal_ingest_bridge.go); nil (never a non-nil empty slice) when workspaceID has none, so a caller's len()==0 check works either way.

A project whose meta was never Set (in-memory cache miss — e.g. one still mid-registration) is simply absent from this scan, not an error: the same "cannot tell, so behave as if this project has nothing to declare" posture Get's own (meta, false) return already gives every other caller.

func (*ProjectStore) Remove

func (s *ProjectStore) Remove(id string)

Remove deletes a project's meta from the store.

func (*ProjectStore) Set

func (s *ProjectStore) Set(id string, meta *ProjectMeta)

Set stores meta directly.

func (*ProjectStore) SetDeriveProjectIDFunc added in v0.1.0

func (s *ProjectStore) SetDeriveProjectIDFunc(fn func(upstreamURL string) (string, error))

SetDeriveProjectIDFunc wires the git-URL-to-project-id derivation used by reconcileExpectedProjectID to verify that a url-derived expectedID (see URLDerivedProjectIDPrefix) was ACTUALLY derived from the project's current UpstreamURL, not merely a hand-authored id: value that happens to share the "url-" prefix. See the deriveProjectID field's doc comment for why this is injected rather than called directly.

func (*ProjectStore) SetHostCommands added in v0.0.13

func (s *ProjectStore) SetHostCommands(hostCommands map[string]HostCommandSpec)

SetHostCommands configures the daemon's aggregated host_commands map used to resolve WorkspaceMeta.HostCommands reference names in GetWithWorkspace. Call this before dispatch when workspace host_commands hydration is desired — symmetric with SetWorkspaceStore.

Guarded by s.mu (docs/plans/workspace-db-consolidation.md PR4 Step G, `boid host-commands reload` / POST /api/host_commands/reload): before that endpoint existed, this was only ever called once at startup, strictly before request-serving began, so an unsynchronized field write/read was harmless in practice. A live reload can now race an in-flight GetWithWorkspace call reading the same field, so both sides go through s.mu — see hostCommandSpec below for the read side.

func (*ProjectStore) SetReposRoot added in v0.1.0

func (s *ProjectStore) SetReposRoot(dir string)

SetReposRoot configures the daemon's bare-repo storage root, used by LoadAll to recognize a legacy (pre-volume-only, host-filesystem) project registration and upgrade its degraded-status message accordingly. See the reposRoot field's doc comment.

func (*ProjectStore) SetSynthesizedMeta added in v0.1.0

func (s *ProjectStore) SetSynthesizedMeta(id string, meta *ProjectMeta)

SetSynthesizedMeta caches a meta value that was synthesized rather than read from a project.yaml (docs/plans/workspace-default-project.md PR5, §現状の実測5 / 論点d) — the project.yaml-less registration path (CreateProjectFromGitURL) and its reload counterpart (FetchProject). Unlike the bare Set above, this also clears any prior degraded status: a successful synthesis means the project is usable again (the workspace default resolved), so a stale StatusDegraded left over from an earlier failed reload must not linger.

func (*ProjectStore) SetWorkspaceID added in v0.0.8

func (s *ProjectStore) SetWorkspaceID(projectID, workspaceID string)

SetWorkspaceID updates the cached workspace association for a project. Empty workspaceID clears the association. Subsequent GetWithWorkspace calls will hydrate using the new value (or return the cached meta unchanged when cleared).

func (*ProjectStore) SetWorkspaceStore added in v0.0.8

func (s *ProjectStore) SetWorkspaceStore(ws *WorkspaceStore)

SetWorkspaceStore configures the workspace store used by GetWithWorkspace. Call this before LoadAll when workspace hydration is desired.

func (*ProjectStore) Status added in v0.1.0

func (s *ProjectStore) Status(projectID string) ProjectStatus

Status returns projectID's current health snapshot. A project with no tracked status (never failed to load, or never registered at all) reports {State: StatusReady}.

func (*ProjectStore) WorkspaceStore added in v0.0.8

func (s *ProjectStore) WorkspaceStore() *WorkspaceStore

WorkspaceStore returns the configured workspace store (or nil when none has been wired). Exposed so server-side wiring can hand the same store to dispatcher.Runner for workspace-scoped proxy allowlist resolution at dispatch time, without having to construct a second one.

Note: callers that pass the result into an interface-typed field should guard against the typed-nil trap by checking the concrete return for nil before assigning — see internal/server/wire.go (resolveDispatcherWorkspaceLookup).

type RejectRule added in v0.0.9

type RejectRule struct {
	Match  string `yaml:"match" json:"match"`
	Reason string `yaml:"reason" json:"reason"`
}

RejectRule declares a pattern that rejects an invocation with a human-readable reason. Match is a glob over the joined args string with the same semantics as allow/deny patterns (globMatch in internal/sandbox/policy.go). Reason is surfaced to the agent so it can self-correct. This type is vocabulary/transport only for now; enforcement is wired up separately.

type ReplayResult

type ReplayResult struct {
	Result HandlerResult
	// FinalPayload / PayloadDelta carry the same distinction
	// DispatchResult's own fields do — see DispatchResult's doc comment.
	// FinalPayload is a (potentially stale-by-the-time-the-hook-completes)
	// full snapshot; PayloadDelta is only what this single replayed hook
	// actually wrote, safe to apply onto a freshly re-read task row without
	// reverting any out-of-band write the hook itself made mid-flight
	// (Phase 5b PR7 codex review Blocker 1, wiring-seams.md #17).
	FinalPayload json.RawMessage
	PayloadDelta json.RawMessage
	NewStatus    TaskStatus
	FiredEvents  []FiredEvent
}

ReplayResult is the result of a single-hook replay operation.

type Role

type Role string
const (
	RoleHook Role = "hook"
)

type RoutedInstruction

type RoutedInstruction struct {
	Role    string `json:"role"`
	Agent   string `json:"agent"`
	Name    string `json:"name,omitempty"`
	Message string `json:"message"`
	Model   string `json:"model,omitempty"`
}

func CurrentInstructions added in v0.0.13

func CurrentInstructions(task *Task) []RoutedInstruction

CurrentInstructions returns the task's "active" routed instruction — the history's last entry, re-wrapped as a []RoutedInstruction via FilterInstructions(instructions, active.Agent).

NOT a substitute for a specific job's routed instruction (selectInstruction in planner.go / JobSpec.Instruction), and NOT the data source for the Phase 5b `boid task instructions` broker RPC (docs/plans/phase5-shim-and-task-context.md) — see dispatcher.JobContextSnapshot's doc comment and wiring-seams.md #13 for the full story. The two agree only when exactly one agent-kind hook is live for the task's current phase. Evaluator.Evaluate can fire two agent-kind hooks for different agents from the same task in a single round — any agent appearing anywhere in the instruction history matches (extractInstructionAgents), not just the active/last entry — while selectInstruction/FilterInstructions only route the *last* entry, so the other hook's JobSpec.Instruction is nil. This function has no way to tell those two hooks' jobs apart: it always answers with whichever agent happens to be the history's last entry, regardless of which job asked. Safe as a task-row-level "what is this task's routing state right now" projection (no caller in this codebase uses it that way yet), unsafe as an answer to "what should THIS job be doing".

func FilterInstructions

func FilterInstructions(instructions Instructions, agent string) []RoutedInstruction

FilterInstructions returns the active routed instruction for the given agent. Only the most recent entry in the history is considered (older entries are kept for audit but do not drive dispatch). Returns nil when agent is empty or the active entry does not address it. Callers gate on status==executing before routing (see selectInstruction).

type Rule

type Rule struct {
	Action          string // manual transition trigger (mutually exclusive with Condition)
	FromStatus      string // "*" matches any
	ToStatus        string
	Condition       TransitionCondition                   // auto transition trigger (mutually exclusive with Action)
	Manual          bool                                  // true if the action is user-initiated (shown in available_actions)
	ActionPayloadFn func(json.RawMessage) json.RawMessage // optional; generates action.Payload when the rule fires
}

type SecretFinding added in v0.0.8

type SecretFinding struct {
	// Path is the source file path used for attribution.
	Path string
	// Line / Column are 1-based, from the YAML node position.
	Line   int
	Column int
	// Kind is "high-entropy" or "literal-marker".
	Kind string
	// Pattern names the matching marker (only set for literal-marker findings,
	// e.g. "password=").
	Pattern string
	// Snippet is a redacted fingerprint of the offending text suitable for
	// display in error messages: short values are summarised by length only,
	// longer values are reduced to "<first4>...<last4>" so the report never
	// echoes the raw value back to logs.
	Snippet string
}

SecretFinding describes a YAML scalar value that looks like a raw secret (a high-entropy token, or text containing a literal marker such as "password=").

The scanner is intentionally conservative. The goal is to catch obvious leaks of credentials written into kit.yaml / workspace.yaml during `boid kit init` / `boid workspace configure` generation, not to be a comprehensive DLP system. False positives on long opaque identifiers (digest strings, UUIDs without dashes, image references) are accepted as the cost of a simple implementation.

func ScanSecretsBytes added in v0.0.8

func ScanSecretsBytes(path string, data []byte) ([]SecretFinding, error)

ScanSecretsBytes scans an in-memory YAML document.

path is used only for finding attribution (Finding.Path). Pass the expected on-disk path when scanning generated content before persisting it to disk, or any descriptive label for tests.

func ScanSecretsFile added in v0.0.8

func ScanSecretsFile(path string) ([]SecretFinding, error)

ScanSecretsFile reads path as YAML and returns any suspicious-looking scalar values.

Returns nil + nil if the file parses cleanly and contains no findings. Returns nil + non-nil for I/O failures or YAML parse errors so callers can distinguish "could not check" from "checked and clean".

func (SecretFinding) String added in v0.0.8

func (f SecretFinding) String() string

String returns a human-readable single-line description that never includes the raw value.

type SessionBehavior added in v0.3.8

type SessionBehavior struct {
	HarnessType string `yaml:"harness_type,omitempty" json:"harness_type,omitempty"`
	Model       string `yaml:"model,omitempty" json:"model,omitempty"`
}

SessionBehavior declares the default harness_type/model a project wants for a named session use-case (e.g. "shape" — see WebHandler. PostStartShapingSession in internal/api/web.go). Sessions are not driven by the task state machine's ResolveBehavior, so they cannot reuse TaskBehaviors' default_instruction.model — this is a deliberately separate, session-only free-naming dictionary (ProjectMeta. SessionBehaviors), not a reuse of task_behaviors' key space. Intentionally a minimal struct (no Traits/Hooks/agent-message concept): sessions have no routing or dispatch semantics to configure, only which harness/model to launch with.

type Signal added in v0.4.0

type Signal struct {
	WorkspaceID string
	Service     string
	Connector   string
	ID          string
	OccurredAt  time.Time
	Identity    string
	URL         string
	Author      string
	Title       string
	ReceivedAt  time.Time
	Attempts    int
	// AckedAt is nil while the signal is unacked.
	AckedAt *time.Time
}

Signal is one row of the signals table.

func ClaimSignals added in v0.4.0

func ClaimSignals(dbtx db.DBTX, workspaceID string, limit, maxAttempts int) ([]*Signal, error)

ClaimSignals selects up to limit pending signals (occurred_at ascending) for workspaceID, increments each one's attempts, and returns the post-increment rows. Dead signals (attempts >= maxAttempts) are never selected — this is the "no infinite redelivery" guard (design doc §2, khi's MAX_ATTEMPTS equivalent).

DEPRECATED (2026-08-29): prefer ListSignals + ClaimSignalIDs. Charging on the READ conflates "I looked at this" with "I handed this to a judgment", and those differ for any consumer that reads wider than it judges — see ClaimSignalIDs' doc comment for what that costs. Kept working so a daemon carrying the split and a workspace still on the old one-step call do not have to switch in the same instant (a workspace's code arrives via `boid project fetch`, a separate step from deploying the daemon). Remove once no workspace calls it.

Like IngestSignals, this does a select then a write that must be one atomic unit — see IngestSignals' own doc comment for the transaction contract callers must uphold, and TaskRepository.ClaimSignals for the wrapper that provides it automatically.

func ListSignals added in v0.4.0

func ListSignals(dbtx db.DBTX, filter SignalFilter) ([]*Signal, error)

ListSignals returns filter.WorkspaceID's signals (optionally narrowed by Service/Connector/State), ordered by occurred_at ascending (oldest first — same processing order ClaimSignals uses).

type SignalFilter added in v0.4.0

type SignalFilter struct {
	WorkspaceID string
	Service     string
	Connector   string
	// State defaults to SignalStatePending when empty (matching `boid
	// signal list`'s "未 ack の Signal" default framing, signal-driven-
	// review.md §8.2).
	State SignalState
	Limit int
	// MaxAttempts, when <= 0, defaults to MaxSignalAttempts. Exposed as a
	// filter field (not hardcoded) for the same testability reason
	// MaxSignalAttempts' own doc comment gives.
	MaxAttempts int
}

SignalFilter scopes and paginates ListSignals. WorkspaceID is required — mirroring ActionListFilter's ErrActionListUnscoped posture (action_list.go), this is a workspace-wide read surface with no "give me everything" fallback.

type SignalIngestRow added in v0.4.0

type SignalIngestRow struct {
	ID         string `json:"id"`
	OccurredAt string `json:"occurred_at"` // RFC3339, tz-aware
	Identity   string `json:"identity"`
	URL        string `json:"url,omitempty"`
	Author     string `json:"author,omitempty"`
	Title      string `json:"title,omitempty"`
}

SignalIngestRow is one Signal as read from a connector's JSONL output (signal-ingest-detailed-design.md §5.3 / §7.1 envelope): 1 line = `{id, occurred_at, identity, url?, author?, title?}`. ID/OccurredAt/ Identity are required (§7.2: "JSONL の必須 field"); URL/Author/Title default to "" when omitted. json tags match the envelope field names exactly, since these are also what gets marshaled for the per-row MaxContentBytes size check (§2).

type SignalSource added in v0.4.0

type SignalSource struct {
	// Connector is "<pack>/<connector>" — the Integration Pack and the
	// connector within it to run. No version: v0 requires exactly one
	// installed version of a given Pack name (resolved at StartExec time
	// against the loaded Pack registry, internal/server) — signals.sources
	// itself carries no version pin (docs/plans/
	// signal-ingest-detailed-design.md §5.1's example has none either,
	// unlike config.yaml's `uses: <pack>/<profile>@<version>`).
	Connector string `yaml:"connector" json:"connector"`
	// Service is the service instance name (config.yaml `services:` key)
	// this connector is authorized to reach through the API gateway.
	Service string `yaml:"service" json:"service"`
	// Every is a Go time.ParseDuration string — the derived trigger's poll
	// interval (same field, same floor validation as Trigger.Every).
	Every string `yaml:"every" json:"every"`
	// Config is the connector's own configuration, validated against the
	// Pack manifest's declared configSchema (integrationpack.ConfigSchema)
	// at StartExec time — orchestrator itself never interprets it.
	Config map[string]any `yaml:"config,omitempty" json:"config,omitempty"`
}

SignalSource is one `signals.sources[]` entry.

type SignalState added in v0.4.0

type SignalState string

SignalState selects a subset of a workspace's inbox for ListSignals.

const (
	// SignalStatePending: acked_at IS NULL AND attempts < maxAttempts.
	SignalStatePending SignalState = "pending"
	// SignalStateDead: acked_at IS NULL AND attempts >= maxAttempts — the
	// row is not deleted (no "stuck mid-ingestion" terminal state,
	// signal-driven-review.md §8.1), just excluded from ClaimSignals /
	// HasPendingSignals until a human acks it or GC eventually reaps it.
	SignalStateDead SignalState = "dead"
	// SignalStateAcked: acked_at IS NOT NULL.
	SignalStateAcked SignalState = "acked"
	// SignalStateAll: no state filter.
	SignalStateAll SignalState = "all"
)

type SignalsConfig added in v0.4.0

type SignalsConfig struct {
	// Sources declares this project's signal sources — each entry hydrates
	// into exactly one derived Trigger (deriveSignalTriggers,
	// signal_trigger_derive.go).
	Sources []SignalSource `yaml:"sources,omitempty" json:"sources,omitempty"`
}

SignalsConfig is ProjectMeta.Signals — project.yaml's `signals:` block (docs/plans/signal-ingest-detailed-design.md §5.1, PR-5).

type StateMachine

type StateMachine struct {
	Name  string
	Rules []Rule
}

func NewCardMachine added in v0.4.0

func NewCardMachine() *StateMachine

NewCardMachine returns the state machine governing cards — the suggestion-as-state-transition redesign's "judgment ledger" object (docs/plans/suggestion-as-state-transition.md §3.2, implemented per docs/plans/suggestion-as-state-transition-impl.md §3). This is card machine v2, replacing the nine-status/eight-rule captured/triaged/parked/ ready/working/dropped/done/aborted machine PR-B (#986) split out of the old unified NewMachine — see git history for that shape if it's ever needed for reference; this doc comment describes only what exists now.

Four statuses, closed: parked/working/done/dropped. A card NEVER reaches pending/executing/awaiting/aborted/captured/triaged/ready through this machine's own rule table (captured/triaged/ready are kept as legacy KnownTaskStatuses entries purely so pre-cutover DB rows remain readable — see model.go's own doc comment — this machine has zero rules admitting them). Manual (human-only — see the push-down defense below) transitions:

go      : parked  → working   (accept(go): specced children get dispatched, then this fires)
working : parked  → working   (accept(working): manual work declared, no dispatch)
drop    : parked  → dropped
done    : parked  → done      (closed without ever being worked here — see the 8th-edge note below)
park    : working → parked    (sets a wake condition — see workflow_card.go's park side effect)
done    : working → done
reopen  : done    → parked
reopen  : dropped → parked

---- the eighth edge: done from parked (2026-08-25) ----

Card machine v2 shipped with seven edges, and `done` only from `working`. That mirrored the drop discipline design doc §3.2 states explicitly ("drop は parked からだけ ... working の card を捨てたければ park → drop の 2 手"), but no line in either doc ever gave a REASON to exclude parked→done — it simply fell out of the table. Two everyday cases have no one-step exit without it, and both are cards nobody ever worked on HERE:

  • the work was already finished elsewhere (a card whose Jira issue got closed by someone else, a manual card resolved out-of-band)
  • the card turned out to be a DUPLICATE of another card carrying the real work

The v1 workaround was accept(working) → (next sweep round) accept(done): two human accepts, a full sweep cycle of latency, and — worse — an intermediate `working`, whose model.go meaning is "誰かが手を動かしている", asserted about a card nobody is touching. A card is 判断の台帳 (machine.go's package doc comment); writing a false fact into the ledger to reach a true one is the wrong trade. Note the asymmetry with drop's own 2-step: park → drop passes through `parked` ("前提条件が揃っていない"), a neutral resting state that stays true of a card being set aside — working does not.

The detour also had a documented failure mode that fired in production: docs/plans/suggestion-as-state-transition-impl.md §6's 監視 note predicted that an LLM wanting to close such a card in ONE step would reach for `drop` (always valid from parked) instead, that boid cannot tell that misuse apart from a legitimate drop, and that there is no mechanical detection for it. Because drop releases every identity (UnlinkAllForTask, I-6) while done holds them (I-5), the mistake silently costs the card its identity — the next ingestion of the same source key then creates a BRAND NEW card with no link to the old one's summary, children, action log, or reopen path. That is exactly what happened on 2026-08-25 (khi cards ad8c6808 → cba7c559, re-captured one round after the errant drop). This edge removes the incentive rather than adding another warning nobody can enforce.

What it does NOT weaken: the Go gate stays exactly one edge wide (parked→working is still the only 前進 edge, still human-accept-only), and "Go を過ぎた card は drop できない" is untouched (drop is still parked-only; working→dropped remains unreachable). Closing a card is not starting work on it, so neither invariant is in play here.

This is the network's ENTIRE edge list — see docs/plans/ suggestion-as-state-transition.md §3.2's table, which this rule set implements literally. The invariant it encodes: the only rule the MACHINE itself fires is capture (creating a task directly into "parked" — task_create.go / task_resolve_or_capture.go); every edge above requires a human's accept, whether typed directly (Web UI / CLI hitting ApplyAction) or via the accept(verb) flow answering a khi suggestion (internal/api/suggestion_accept.go). The old wake_triaged/wake_ready/ wake_working three-way split is gone entirely: parked has exactly one origin now (park only ever fires from working), so there is nothing left for a resurfacing mechanism to disambiguate — see queue_sweep.go's SweepWake, now reduced to recording a "wake_due" FACT (below) rather than resolving and applying a transition on the task's behalf.

job_failed is DELIBERATELY NOT registered here, unlike the old machine (which duplicated it from NewExecutionMachine purely so Apply/ AvailableActions never surprised a caller with "unknown action" — see machine_execution.go's own doc comment for why it stays there). A card never runs a job of its own (machine.go's package doc comment: "カードには エージェントセッションが起きない"), and job_failed's only rule targets "aborted" — the one status the redesign explicitly retires from the card's reachable set (design doc §3.2: "card は aborted にも到達しなくなる... card 機械は4状態で本当に閉じる"). Registering it would reopen exactly that fifth status through the rule table even though nothing production-real ever fires it here. progress/done_request/fail_request/child_dispatched/ child_closed stay registered (all non-transitioning, ToStatus=="", so none of them can reopen a fifth status) purely for the same "Apply treats the name as known" parity the old machine established.

---- push-down defense (穴11, docs/plans/suggestion-as-state-transition.md §3.8's closing note) ----

All eight Manual transition rules above are reachable through the public ApplyAction endpoint (HTTP API / Web UI / brokered `boid action send` / CLI all funnel through it) because IsManualAction says yes for all of them — unlike v1, where wake_triaged/wake_ready/dispatch/triage_done were kept Manual:false specifically to keep khi from pushing them directly (a NAME-based defense: give the machine-internal step a different name than any Manual:true rule, so IsManualAction structurally rejects it). v2 folds triage_done back into a plain Manual:true "done" and gives khi no machine-internal step to accidentally collide with at all — so the old name-based trick has nothing left to hide behind, and a naive port would let khi's gateway-brokered `boid action send --type done` (or --type go, park, drop, reopen) push a card's state directly, asserting a transition the daemon never itself decided.

The replacement is actor-based, not name-based: api.ApplyAction checks `sm.Name == CardMachineName && IsCardTransitionAction(req.Type) && actor != ActorHuman` and rejects with 403 before ever calling sm.Apply. IsCardTransitionAction (below) is the exact six-verb closed set — go/ working/park/drop/done/reopen — the only actions on this machine whose ToStatus != "" (attrs_set/child_added/child_specced/child_dropped/noted/ answered/wake_due all stay reachable from any actor, including khi's gateway-brokered pushes, exactly as before). ActorHuman is stamped ONLY by Web UI/CLI-driven code paths (web_service.go, action.go's HTTP handler, task.go) — a gateway-brokered `boid action send` always carries ActorTask(TokenContext.TaskID) instead (internal/server/boid_executor.go), which is never equal to ActorHuman even when TaskID is empty (khi's own trigger-job calls carry TaskID=="", producing the literal string "task:" — still not ActorHuman). accept(verb)'s own internal call to ApplyAction (WebAppService.AnswerSuggestion, workflow_action.go) reuses the SAME request context the human's accept click established, so it carries ActorHuman through and is never blocked by its own defense.

escape hatch (design doc §3.2's explicit requirement): this defense must never block a HUMAN from directly driving every one of the eight edges with no suggestion involved — see TestApplyAction_CardTransitions_HumanCanApplyEveryEdge_NoSuggestion (internal/api) for the pinned proof.

func NewExecutionMachine added in v0.4.0

func NewExecutionMachine() *StateMachine

NewExecutionMachine returns the state machine governing ordinary (session-bearing) tasks — pending/executing/awaiting/done/aborted. This is the "process" island the unified NewMachine (pre-PR-B) used to combine with the card lifecycle below; see machine.go's package doc comment for why the two were split and what stayed unchanged. Selected via internal/api's machineFor for any task that does NOT carry a task_triage sidecar row.

Manual transitions:

start  : pending → executing
done   : executing → done     (UI button; agent path goes through done_request + auto)
done   : awaiting → done      (parent confirms child's done_request)
fail   : executing → aborted  (UI button; agent path goes through fail_request + auto)
reopen : done → executing
reopen : aborted → executing  (recover from failure via fix)
ask    : executing → awaiting
answer : awaiting → executing
abort  : pending/executing/awaiting/done/aborted → aborted (execution lifecycle only)

abort is scoped to the execution-lifecycle statuses (not a "*" wildcard, and — since PR-B — not present in NewCardMachine at all): a card cannot be aborted, only dropped (drop's coverage lives entirely in NewCardMachine). Before the split this was a manually-drawn non-overlap between abort and drop inside one shared rule table; splitting the machine object makes it structural — abort simply does not exist as a rule anywhere a card's status could match.

Event-driven transitions:

job_failed : * → aborted

Non-transitioning records (created directly by NotifyTask, bypassing ApplyAction):

progress      : * → *   (FYI timeline note)
done_request  : * → *   (agent's `notify --done` intent; consumed by DeriveLifecycle)
fail_request  : * → *   (agent's `notify --fail` intent; consumed by DeriveLifecycle)

child_dispatched / child_closed are registered here too (Manual:false, FromStatus "*") even though an ordinary execution task is never itself a triage card's dispatched child's PARENT — see machine_card.go's doc comment for their real writers and rationale (論点9). They are duplicated onto BOTH machines (alongside job_failed/progress/done_request/ fail_request above) purely so StateMachine.Apply/AvailableActions treat the action names as "known" regardless of which machine a caller happens to be holding — the actual writers call tx.CreateAction directly rather than routing through sm.Apply, so which machine object is "the" one registering them has no behavioral effect; keeping them on both avoids a spurious "no transition for action" surprise if a future caller ever does pass them through Apply against whichever machine it was holding.

Auto transitions (condition-based, evaluated after dispatch). Order matters — first match wins:

executing → aborted when lifecycle.executed && lifecycle.fail
executing → done    when lifecycle.executed && lifecycle.done
executing → done    when lifecycle.executed                     (legacy bare; non-agent hooks)

`lifecycle.{executed,done,fail}` are transient traits injected by the coordinator; they are never persisted to the payload. The state machine treats them as input signals derived from the action history (done_request / fail_request) plus the just-finished hook outcome.

The split between `done_request` (intent recorded immediately) and the auto-advance (state transition after `lifecycle.executed` confirms the runtime exited cleanly) preserves the bash EXIT trap → `boid job done` path. Without this split NotifyTask had to SIGTERM the runtime to apply the state transition synchronously, which raced against the SIGUSR1 graceful-stop path and left jobs marked failed.

Hook failures surface as job_failed via the dispatcher path, which routes the task to aborted.

func (*StateMachine) Advance

func (sm *StateMachine) Advance(task *Task) (*Task, bool)

Advance evaluates condition-based rules for the task's current status and payload. Returns the transitioned task and true if a condition was met, or (nil, false) otherwise. Use AdvanceFull when the action payload is also needed.

func (*StateMachine) AdvanceFull

func (sm *StateMachine) AdvanceFull(task *Task) *AdvanceOutcome

AdvanceFull evaluates condition-based rules for the task's current status and payload. Returns an AdvanceOutcome (including optional action payload) if a condition was met, or nil otherwise.

Condition/ActionPayloadFn are only ever set on NewExecutionMachine's rules (never on NewCardMachine's — see machine_card.go), so task.Exec.Payload below is only evaluated when r.Condition != nil, which in practice means task is always an execution task here. The nil guard is defense in depth, not evidence a card is expected to reach this loop body.

func (*StateMachine) Apply

func (sm *StateMachine) Apply(task *Task, action *Action) (*Task, error)

Apply finds an action-based rule matching the action type and current status. Condition-based rules are ignored by Apply. When a matching rule has an empty ToStatus the task status is left unchanged (non-transitioning action, e.g. "progress").

func (*StateMachine) AvailableActions

func (sm *StateMachine) AvailableActions(status TaskStatus) []string

AvailableActions returns the list of manual actions that can be applied to a task in the given status. Condition-based (automatic) rules and non-manual rules are excluded. Terminal statuses (done, aborted) return an empty list.

func (*StateMachine) AvailableActionsHint added in v0.4.0

func (sm *StateMachine) AvailableActionsHint(status TaskStatus) string

AvailableActionsHint returns a human-readable clause naming which manual actions CAN be applied from status right now — e.g. "from status=parked you can apply: go, working, drop" — or a "status=X has no further transitions available" fallback when AvailableActions(status) is empty.

Single source for "this didn't work, but here's what would have", used by every caller that needs to turn a failed/inapplicable action into a self-explanatory message instead of a bare rejection: internal/api's suggestion-accept 409 (applyAnswered, acceptGo) and the Web UI's inapplicable-suggestion notice (components.SuggestionInapplicableReason, task_tree.templ) both call THIS method rather than each re-deriving the list by hand — added specifically because they used to duplicate the same AvailableActions(status)-based string-building logic in two places (fix/unapplicable-suggestion-guard PR review, LOW 4), which could drift apart (e.g. one side's wording updated, the other's forgotten) with no test able to catch it.

func (*StateMachine) CanApplyManualAction added in v0.4.0

func (sm *StateMachine) CanApplyManualAction(actionType string, status TaskStatus) bool

CanApplyManualAction reports whether actionType has a Manual:true rule matching status — regardless of whether that rule transitions the task (ToStatus != "") or not (ToStatus == "") and regardless of whether it would be a self-loop. Unlike AvailableActions, which deliberately EXCLUDES non-transitioning and self-loop rules because those don't fit the generic "action button" UI (see AvailableActions' own doc comment), this is the check a caller uses to gate a DEDICATED button for one specific non-transitioning manual action — e.g. the Web UI's `answered` Accept/Reject buttons, which have their own bespoke rendering (verb badge, reason, basis) and their own POST target, not the generic available_actions button row.

Added for Opus review finding #3 (2026-08-19 revisit of PR-3): sm.Apply already rejects `answered` from done/dropped/aborted (see TestCardMachine_TriageVocabulary_FromStatusEnumerated_NotWildcard), but nothing let the Web UI ask "would this actually be accepted" BEFORE rendering the button — so a triage task's Accept/Reject buttons kept showing after it auto-advanced to done, and clicking them redirected to an opaque `no transition for action "answered" from status "done"` error.

func (*StateMachine) CanApplyTransitionAction added in v0.4.0

func (sm *StateMachine) CanApplyTransitionAction(actionType string, status TaskStatus) bool

CanApplyTransitionAction reports whether actionType has a Manual:true, STATUS-CHANGING (ToStatus != "") rule matching status — i.e. whether sm.Apply(task-in-status, {Type: actionType}) would actually succeed right now. This is CanApplyManualAction's narrower sibling: CanApplyManualAction also returns true for a non-transitioning rule (attrs_set/noted/answered/ ...) matching the same action+status pair, which is exactly right for gating a dedicated non-transitioning button (its own doc comment's example) but wrong for answering "would ACCEPTING this specific verb actually flip the task's status from here" — the question a suggestion's own verb (orchestrator.IsCardTransitionAction's six-verb set) always raises, since every one of those verbs names a real transition, never a non-transitioning fact.

Added for PR-3 (docs/plans/suggestion-as-state-transition-impl.md's follow-up: the card machine rule table admits exactly one status per verb — e.g. "done" only fires from "working" — but nothing let a caller ask "would this verb actually apply from the task's CURRENT status" before rendering a live Accept button or accepting a suggestion. Without this, api.applyAnswered's accept(verb) branch had to let sm.Apply itself reject with an opaque `no transition for action %q from status %q`, and the Web UI had no way to know in advance that clicking Accept would 409.

Deliberately does NOT exclude self-loop rules (ToStatus == FromStatus) the way AvailableActions does: a self-loop rule still makes sm.Apply SUCCEED (no functional status change, but no error either), so hiding it here would make this method say "cannot apply" for something that would, in fact, apply cleanly. AvailableActions' self-loop filter exists purely for its own different job — deciding whether a generic action-bar BUTTON has "and then the status changes" a story to tell — not for this method's job of predicting sm.Apply's success/failure.

func (*StateMachine) IsManualAction added in v0.2.4

func (sm *StateMachine) IsManualAction(actionType string) bool

IsManualAction reports whether actionType has at least one Manual:true rule anywhere in THIS machine, regardless of the task's current status. This is the single source of truth for "is this action name allowed through the public ApplyAction endpoint for a task governed by this machine" (internal/api's HTTP handler / brokered action_send / `boid action send` CLI all funnel through ApplyAction, which first resolves the task's machine via machineFor, then checks IsManualAction against THAT machine — see workflow_action.go). Event-driven and daemon-recorded facts (job_failed, wake_due, child_dispatched, child_closed, progress, done_request, fail_request — all Manual:false, "*" FromStatus where applicable) must return false here — codex review round 2 found job_failed missing from a hand-maintained blocklist in internal/api, which let triaged→(job_failed)→aborted→(reopen)→executing bypass the ready-gate entirely (v1-era statuses; the same reasoning holds under card machine v2's parked/working/done/dropped). A per-name blocklist requires remembering to update it every time a new non-manual rule is added; checking the Rule's own Manual flag here removes that whole class of omission.

(v1's wake_triaged/wake_ready/wake_working/dispatch/triage_done/ reopen_triaged — internal-only manual transitions a separate Wake/Dispatch method used to resolve and apply on the caller's behalf — are gone entirely under card machine v2, docs/plans/suggestion-as-state-transition-impl.md §3.3: wake_due is now a pure non-transitioning fact SweepWake records, dispatch/triage_done/reopen_triaged have no v2 equivalent at all.)

type Suggestion added in v0.3.11

type Suggestion struct {
	Verb   string `json:"verb,omitempty"`
	Action string `json:"action,omitempty"`
	Reason string `json:"reason,omitempty"`
	Basis  string `json:"basis,omitempty"`
}

Suggestion is task_triage.detail.suggestion — the triage agent's single recommendation, derived from primary sources (docs/plans/ cross-project-issue-triage.md:544 のスキーマ案, 逆輸入3). Verb uses the same vocabulary as nose's own response words: go/shape/manual/park/ drop/wake.

func DetailSuggestion added in v0.3.11

func DetailSuggestion(detail json.RawMessage) (Suggestion, bool)

DetailSuggestion extracts task_triage.detail.suggestion from a detail blob, preferring the top-level key (docs/plans/cross-project-issue-triage.md:544 のスキーマ案) and falling back to detail.attrs.suggestion. The fallback is the one actually exercised today: "suggestion" is not a promoted attrs_set key (see applyAttrsSetSideEffect / FoldDetailAttrs, internal/api/workflow_card.go), and attrs_set is currently the only write path for it in this repo — so in practice it lands under detail.attrs, not at the top level. Top-level is still checked first per BD-8's design (a future/alternate writer could place it there directly); this doc comment just flags that assumption as unverified against actual writers, not as dead weight to remove.

Spot-checked against real data 2026-08-18 (`GET /api/triage?status=parked`, 4 parked tasks, 3 with a suggestion): consistent with the code-level fact above — every suggestion was under detail.attrs.suggestion, top-level was null on all 4. This is a one-time, small-N sample, not independent proof that no writer ever places it at the top level (that's the attrs_set argument above); treat it as "nothing observed to contradict the code-level reasoning," not as a standing guarantee that would need re-verifying if this comment is trusted later. Both paths are kept regardless — see decodeSuggestion's doc comment for why an empty top-level object must not win over a real one in attrs.

Each candidate (top-level, then attrs) is decoded independently via its own json.Unmarshal call: a malformed or wrong-shaped value in one location must not blank out a well-formed value in the other. (An earlier version decoded both off a single struct/Unmarshal call, so one bad field anywhere in the blob silently zeroed a good suggestion elsewhere in the same blob — Opus review finding, 2026-08-18.)

Returns the zero Suggestion and false on any absence/parse failure — same best-effort posture as triageSummary (internal/api/tree.go): never errors, so a missing/malformed suggestion blob never sinks the row it lives on (rule 5, 隠さない, is about the row surviving, not every derived field always being present).

type Task

type Task struct {
	ID          string     `json:"id"`
	Type        TaskType   `json:"type"`
	ProjectID   string     `json:"project_id"`
	RemoteID    string     `json:"remote_id,omitempty"`
	Title       string     `json:"title"`
	Description string     `json:"description,omitempty"`
	Status      TaskStatus `json:"status"`
	Ref         string     `json:"ref,omitempty"`
	ParentID    string     `json:"parent_id,omitempty"`
	// IdempotencyKey backs `boid task create --idempotency-key` (docs/plans/
	// signal-ingest-detailed-design.md §8, migration 0047). Unlike Ref, this
	// is NOT an external-world identity — no link/drop/reopen semantics ride
	// on it (that's task_identities' job — see its own doc comment for the
	// distinction). It exists purely so a caller with no external identity to
	// key off of (the common case: a judgment task minting a child task) can
	// make a create call safe to retry: a second CreateTask with the same
	// (ProjectID, ParentID, IdempotencyKey) returns the FIRST task instead of
	// inserting a duplicate (CreateTask's get-or-create, store.go). Empty
	// string means "no key" (stored as SQL NULL — see migration 0047's own
	// comment for why NULL rather than NOT NULL DEFAULT ”).
	//
	// Scoped by ParentID as well as ProjectID (migration 0047's partial
	// unique index is on all three) — NOT project-only. An earlier version of
	// this feature scoped by ProjectID alone and had a confirmed bug (PR
	// #1012 review, Opus M3): two DIFFERENT parent tasks in the same project
	// that happened to reuse the same idempotency_key (e.g. both simply used
	// "step-1") would silently collide — the second parent's create call
	// would succeed and hand back the FIRST parent's child, with no error
	// and no way to tell from the response. Scoping by ParentID too closes
	// this the same way migration 0037 closed the identical hole for Ref
	// (cross-workspace root tasks reusing the same ref).
	//
	// Caller contract this implies (signal-driven-review.md §8.5's stated
	// use case): a judgment task minting a child needs ParentID itself to be
	// STABLE across retries for the dedup to actually catch a duplicate
	// create — the design doc's own example key ("親 card id + 子の世代キー")
	// hints at this by embedding the CARD's id, not the judgment task's own.
	// A trigger re-dispatches a fresh judgment task instance (a new, distinct
	// task id) on every firing (signal-driven-review.md §8.3/§8.4), so if a
	// caller passed the judgment task's OWN id as ParentID (the `BOID_TASK_ID`
	// auto-fill default — see cmd/task.go/boid_shim.go), a resend after a
	// crash would carry a DIFFERENT ParentID than the crashed attempt and the
	// dedup would silently miss, recreating the exact bug this field exists
	// to close. Callers using IdempotencyKey for cross-retry convergence MUST
	// pass an explicit ParentID that outlives the creating task itself (e.g.
	// the persistent card's task id), not rely on the BOID_TASK_ID default —
	// see internal/skills/data/boid-task/SKILL.md's "Resume: reconcile before
	// create" section.
	IdempotencyKey string    `json:"idempotency_key,omitempty"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`

	// Card holds the card-only fields (kind/urgency/wake_at/wake_task_id/
	// suggestion_verb/detail). Non-nil iff Type == TaskTypeCard.
	Card *CardAttrs `json:"card,omitempty"`
	// Exec holds the execution-only fields (behavior/traits/readonly/
	// branch_prefix/base_branch/payload/instructions/auto_start). Non-nil
	// iff Type == TaskTypeExecution.
	Exec *ExecAttrs `json:"exec,omitempty"`

	// 以下はDBに保存しない派生フィールド(list/get クエリ時にサブクエリで集計)
	TotalChildCount   int `json:"total_child_count,omitempty"`
	DoneChildCount    int `json:"done_child_count,omitempty"`
	AbortedChildCount int `json:"aborted_child_count,omitempty"`
	OpenChildCount    int `json:"open_child_count,omitempty"`
	// AwaitingChildCount is the number of direct children currently sitting
	// at TaskStatusAwaiting — added by docs/plans/webui-detail-list-redesign.md
	// PR-4 (§3.5) so the list row's child rollup can surface "⚠ N" without a
	// second query: a card whose dispatched child asked a question was
	// previously invisible from the parent's own row (§2.4's "子が4回 ask を
	// 上げたが親からは dispatched にしか見えなかった" gap) — the detail page's
	// child ledger already closed this for PR-2 (ChildRow.AwaitingQuestionID);
	// this is the list-side counterpart.
	AwaitingChildCount int `json:"awaiting_child_count,omitempty"`
	// Blocked は表示用フィールド(DBには保存しない)
	Blocked bool `json:"blocked,omitempty"`
}

Task is the tagged-union encoding of Task = Card | ExecutionTask (design doc §3.5). Go has no native sum type, so this is the "Go flavored" direct sum: a common core plus exactly one of Card/Exec populated, selected by Type. Card is non-nil iff Type == TaskTypeCard; Exec is non-nil iff Type == TaskTypeExecution — enforced by store.go's scan/insert and by CreateTask's construction, mirroring the DB's own CHECK constraint (migration 0045).

Deliberately NOT an interface + two concrete types: that would force a signature change (and hand-rolled polymorphic JSON/DB-scan code) across every layer that passes *Task around (store/api/web/cmd/client, including the portable Mac/Win client, which is only allowed to import boid's Go types — see design doc §3.5). A caller that reaches for an execution-only field directly (task.Behavior, as it read before this PR) now gets a compile error instead of a silently wrong zero value — every such reference had to be individually reviewed and pointed at task.Exec.X or task.Card.X to make this PR compile, which is this refactor's built-in verification mechanism.

func CloneTaskShallow added in v0.4.0

func CloneTaskShallow(t *Task) *Task

CloneTaskShallow returns a shallow copy of t whose Exec/Card pointers (if set) are ALSO copied, so a caller that mutates a field on the clone's Exec/Card (e.g. `clone.Exec.Payload = merged`) never aliases back into t's own Exec/Card struct. Before the tagged-struct split, `newTask := *task` followed by `newTask.Payload = x` was always safe (Payload was a value-typed field copied by the struct copy); after the split, Exec/Card are POINTERS, so `newTask := *task` only copies the pointer VALUE — both tasks would keep pointing at the SAME ExecAttrs/CardAttrs unless this helper (or equivalent) re-points the clone at its own copy. Every call site that used to do a bare `x := *task` and then mutate a now-relocated field must go through this instead (machine.go's Apply/ AdvanceFull, coordinator.go's DispatchAndAdvance/evaluateAndAdvance, api.attrs_set_done.go's done-status noop) — this is exactly the class of "縫い目" bug a mechanical find/replace of task.X -> task.Exec.X would have missed.

func FindTaskByIdempotencyKey added in v0.4.0

func FindTaskByIdempotencyKey(dbtx db.DBTX, projectID, parentID, idempotencyKey string) (*Task, error)

FindTaskByIdempotencyKey returns the task matching the given idempotency key within the given (projectID, parentID) scope, or nil if no matching task is found. See migration 0047 and Task.IdempotencyKey's doc comment for the field's contract (docs/plans/signal-ingest-detailed-design.md §8) and for why parentID is part of the scope (PR #1012 review, Opus M3: a project-only scope let two different parents silently collide on a reused key).

Unlike FindTaskByRef, there is no UUID-shaped-string special case here: idempotency_key is never treated as a stand-in for a task ID, only as an opaque workspace-internal stable key. The equality comparison below also never needs an explicit `IS NOT NULL` guard — SQL's NULL = 'x' is neither true nor false, so a keyless (NULL) row can never match a non-empty idempotencyKey argument, and this function itself short-circuits before querying when idempotencyKey is empty.

func FindTaskByRef

func FindTaskByRef(dbtx db.DBTX, ref, parentID, projectID string) (*Task, error)

FindTaskByRef returns the task matching the given ref within the given (parentID, projectID) scope, or nil if no matching task is found. If ref is a UUID, the task is looked up by id directly (backward compatibility), but the result is still validated against BOTH parentID and projectID before being returned — treating a scope mismatch the same as "not found" (nil, nil), not an error.

projectID scoping was added in Phase 1 PR-4 (docs/plans/ cross-project-issue-triage.md 論点7, codex review Blocker fix): once root tasks (parentID == "") became dedup-eligible, EVERY workspace's root tasks share parent_id = "", so scoping by parent_id alone let a caller in workspace B silently receive workspace A's task back just by reusing the same source ref string (or, for the UUID branch, by supplying any task ID it happened to know) — a cross-workspace task leak. Callers MUST pass the project they are creating/looking within; there is no "unscoped" call left (idx_tasks_ref_parent_project, migration 0037, enforces the same scope at the DB level for the ref+parent_id uniqueness itself).

func FindTaskByRemote

func FindTaskByRemote(dbtx db.DBTX, remoteID string) (*Task, error)

FindTaskByRemote returns the most recently created task (by created_at DESC, id DESC) matching the given remote_id, or nil if no matching task is found.

func GetTask

func GetTask(dbtx db.DBTX, id string) (*Task, error)

func ListChildren added in v0.0.6

func ListChildren(dbtx db.DBTX, parentID string) ([]*Task, error)

ListChildren returns all direct children of the given parent task, ordered by created_at ASC (oldest first). Returns an empty slice if the task has no children — never nil. parentID must be non-empty; passing "" returns an empty result (root tasks have no parent record, so they can't be queried as children either).

func ListTasks

func ListTasks(dbtx db.DBTX, filter TaskFilter) ([]*Task, error)

func ResolveIdentity added in v0.4.0

func ResolveIdentity(dbtx db.DBTX, projectID, identity string) (*Task, error)

ResolveIdentity looks up the task bound to (projectID, identity). Returns ErrTaskNotFound (the same sentinel GetTask/FindTaskByRef use) when no binding exists — callers that need to distinguish "not found" from other errors should use errors.Is, matching this package's existing convention.

type TaskBehavior

type TaskBehavior struct {
	// Readonly controls whether the sandbox working directory is mounted read-only
	// for tasks using this behavior. When nil (unset), the daemon applies a
	// fail-safe default: readonly=true for all behaviors except the canonical
	// "executor" (which retains readonly=false during the compat period).
	// Set explicitly to override: readonly: false in project.yaml.
	Readonly           *bool        `yaml:"readonly,omitempty" json:"readonly,omitempty"`
	Traits             []string     `yaml:"traits" json:"traits"`
	DefaultInstruction *Instruction `yaml:"default_instruction,omitempty" json:"default_instruction,omitempty"`

	// Hooks is parsed from project.yaml task_behaviors.<name>.hooks at load
	// time. Env, HostCommands, and AdditionalBindings are runtime-overlay
	// fields populated by ReadProjectMetaWithKits after merging kit data and
	// project-level overlays. These are not serialized to YAML.
	Hooks              []Hook            `yaml:"hooks,omitempty" json:"-"`
	Env                map[string]string `yaml:"-" json:"-"`
	HostCommands       HostCommands      `yaml:"-" json:"-"`
	AdditionalBindings []BindMount       `yaml:"-" json:"-"`
}

func LookupBehavior added in v0.1.0

func LookupBehavior(meta *ProjectMeta, name string) (TaskBehavior, bool)

LookupBehavior finds a TaskBehavior in meta.TaskBehaviors by name. The name is matched verbatim — there is no alias or canonicalization step, so what a project.yaml (or workspace default) writes is exactly what callers must ask for.

A nil meta reports not-found rather than panicking: ResolveBehavior's nil-meta paths and DefaultBehaviorResolvable both rely on that.

type TaskFilter

type TaskFilter struct {
	Status      string
	ProjectID   string
	Behavior    string
	WorkspaceID string
	Title       string
	ParentID    *string
	// ActiveOnly narrows the result to non-terminal tasks (docs/plans/
	// webui-detail-list-redesign.md §3.5's 「アクティブのみ (非終端)」トグル).
	// This is a SEPARATE axis from Status — composes with any Status value
	// (including "", meaning "no status predicate at all") rather than being
	// yet another special Status keyword, because "non-terminal" must include
	// TaskStatusParked (unlike the legacy "open" Status keyword's self-clause,
	// which deliberately excludes parked — see notOpenSelfStatusSQLList's own
	// doc comment). Ignored (no-op) when false.
	ActiveOnly bool
	// Limit/Offset implement the list page's pagination (§3.5 / §5 論点4: LIMIT/
	// OFFSET is enough at the current scale; keyset can follow if it stops
	// being enough). Limit <= 0 means "no LIMIT clause" (unbounded, the
	// pre-PR-4 default every non-web caller still gets). Offset > 0 with
	// Limit <= 0 still applies (via SQLite's `LIMIT -1 OFFSET ?`) rather than
	// being silently dropped.
	Limit  int
	Offset int
}

type TaskGCStore

type TaskGCStore struct {

	// RuntimeReaper, when set, is called with each runtime directory path
	// before os.RemoveAll removes it. Use this to Reap docker resources that
	// may still be alive in the upstream daemon (safety net for jobs whose
	// cleanupSandboxAfterWait did not complete, e.g. daemon restart).
	RuntimeReaper func(runtimeDir string) error
	// contains filtered or unexported fields
}

TaskGCStore handles GC of tasks and their related data.

func NewTaskGCStore

func NewTaskGCStore(conn *sql.DB) *TaskGCStore

func (*TaskGCStore) GC

func (s *TaskGCStore) GC(olderThan time.Duration, dryRun bool) (*GCResult, error)

func (*TaskGCStore) WithAttachmentsRoot added in v0.0.7

func (s *TaskGCStore) WithAttachmentsRoot(dir string) *TaskGCStore

WithAttachmentsRoot enables disk-level cleanup of the per-task attachments directory tree rooted at `<dir>/tasks/<id>/attachments`. dir is the data-home (matches dataHomeFor in wire.go). Empty disables the cleanup.

func (*TaskGCStore) WithRuntimeReaper added in v0.0.2

func (s *TaskGCStore) WithRuntimeReaper(fn func(runtimeDir string) error) *TaskGCStore

WithRuntimeReaper sets a callback that is invoked with each runtime directory path before it is deleted. This allows the caller to Reap docker resources created by sandbox jobs (safety net when cleanupSandboxAfterWait didn't run, e.g. after a daemon restart).

func (*TaskGCStore) WithRuntimesDir added in v0.0.11

func (s *TaskGCStore) WithRuntimesDir(dir string) *TaskGCStore

WithRuntimesDir enables disk-level cleanup of per-sandbox runtime directories (`<dir>/<runtime_id>` and the git-gateway clone workspace dir `<dir>/<job_id>/workspace`) for GC target jobs. Empty disables runtime cleanup.

func (*TaskGCStore) WithSandboxTmpDir

func (s *TaskGCStore) WithSandboxTmpDir(dir string) *TaskGCStore

WithSandboxTmpDir enables safety-net cleanup of leaked /tmp/boid-* sandbox artifacts during GC. Pass the directory to scan (typically "/tmp"); empty string disables this cleanup.

func (*TaskGCStore) WithTranscriptsDir added in v0.1.0

func (s *TaskGCStore) WithTranscriptsDir(dir string) *TaskGCStore

WithTranscriptsDir enables disk-level cleanup of the persistent transcript/diagnostics root (`<dir>/<runtime_id>`, holding transcript.log and diagnostics.json — see internal/server's transcriptsDirFor) for GC target jobs, keyed by the same runtime_id as WithRuntimesDir but a separate directory tree (dispatcher.ContainerBackendOptions.TranscriptDir's doc comment explains why the two are no longer colocated: this one is a persistent volume, not the host tmpfs runtimesDir sits on). Empty disables this cleanup — the transcript/diagnostics files then simply accumulate forever, which is exactly the "占有" risk this option exists to prevent.

type TaskLookup

type TaskLookup interface {
	GetTask(id string) (*Task, error)
}

type TaskRepository

type TaskRepository struct {
	// contains filtered or unexported fields
}

func NewTaskRepository

func NewTaskRepository(db db.DBTX) *TaskRepository

func (*TaskRepository) AckSignals added in v0.4.0

func (r *TaskRepository) AckSignals(workspaceID string, ids []string) error

func (*TaskRepository) ClaimSignalIDs added in v0.4.0

func (r *TaskRepository) ClaimSignalIDs(workspaceID string, ids []string) error

func (*TaskRepository) ClaimSignals added in v0.4.0

func (r *TaskRepository) ClaimSignals(workspaceID string, limit, maxAttempts int) ([]*Signal, error)

func (*TaskRepository) CompleteTriggerRun added in v0.4.0

func (r *TaskRepository) CompleteTriggerRun(id string, finishedAt time.Time, exitCode int) error

func (*TaskRepository) CreateAction

func (r *TaskRepository) CreateAction(ctx context.Context, action *Action) error

CreateAction persists action, then — within the SAME transaction — ingests it into the target card's workspace inbox when eligible (docs/ plans/boid-internal-signal-inbox.md §4.5). Same dual-mode shape as DeleteTask/IngestSignals/ClaimSignals above: nests inside an already-open tx when r.db is one (the normal case — every production caller reaches this from inside an existing WithinTx), or opens its own spanning transaction when r.db is a raw *sql.DB, so the INSERT and the ingest can never observe or commit independently of each other.

func (*TaskRepository) CreateTask

func (r *TaskRepository) CreateTask(task *Task) error

func (*TaskRepository) CreateTriggerRun added in v0.4.0

func (r *TaskRepository) CreateTriggerRun(run *TriggerRun) error

CreateTriggerRun / CompleteTriggerRun / ListInFlightTriggerRuns / LatestTriggerRun back docs/plans/ingestion-identity.md PR-4 (B-5)'s trigger_runs ledger (trigger_run.go). Thin wrappers over the package-level functions, same shape as the identity methods above — not task-scoped data, but taskRepo is the object wire.go already threads into TaskWorkflowService's narrow-interface fields (Actions/TaskTriage follow the same precedent).

func (*TaskRepository) DeleteTask

func (r *TaskRepository) DeleteTask(id string) error

func (*TaskRepository) DeleteTaskTriage added in v0.2.4

func (r *TaskRepository) DeleteTaskTriage(taskID string) error

func (*TaskRepository) DeleteTriggerRun added in v0.4.0

func (r *TaskRepository) DeleteTriggerRun(id string) error

func (*TaskRepository) FindTaskByRef

func (r *TaskRepository) FindTaskByRef(ref, parentID, projectID string) (*Task, error)

func (*TaskRepository) FindTaskByRemote

func (r *TaskRepository) FindTaskByRemote(remoteID string) (*Task, error)

func (*TaskRepository) GetSignalCursor added in v0.4.0

func (r *TaskRepository) GetSignalCursor(workspaceID, service, connector string) (string, error)

func (*TaskRepository) GetTask

func (r *TaskRepository) GetTask(id string) (*Task, error)

func (*TaskRepository) GetTaskStatus added in v0.4.0

func (r *TaskRepository) GetTaskStatus(id string) (TaskStatus, error)

GetTaskStatus satisfies api.TaskStatusReader — the narrow read api.TaskAppService.WaitTaskTerminal polls with. See GetTaskStatus (store.go) for why it is not GetTask.

func (*TaskRepository) GetTaskTriage added in v0.2.4

func (r *TaskRepository) GetTaskTriage(taskID string) (*CardAttrs, error)

func (*TaskRepository) HasPendingSignals added in v0.4.0

func (r *TaskRepository) HasPendingSignals(workspaceID string, maxAttempts int) (bool, error)

func (*TaskRepository) IngestSignals added in v0.4.0

func (r *TaskRepository) IngestSignals(workspaceID, service, connector string, rows []SignalIngestRow) error

IngestSignals / GetSignalCursor / ListSignals / ClaimSignals / AckSignals / HasPendingSignals back docs/plans/signal-ingest-detailed-design.md §2 (PR-1)'s inbox store (signal_store.go).

IngestSignals and ClaimSignals each need their SQL statements to run as ONE transaction (signal_store.go's own doc comments — Q13's crash-safety claim rests on this), so — unlike every other wrapper on this type — they follow DeleteTask's pattern above rather than being one-line delegators: when r.db is a raw *sql.DB (not already inside a WithinTx call), they open their own transaction spanning the whole operation.

func (*TaskRepository) LatestTriggerRun added in v0.4.0

func (r *TaskRepository) LatestTriggerRun(projectID, triggerName string) (*TriggerRun, error)

func (*TaskRepository) LinkIdentity added in v0.4.0

func (r *TaskRepository) LinkIdentity(projectID, identity, taskID string) error

LinkIdentity / UnlinkIdentity / UnlinkAllForTask / ResolveIdentity / ListIdentitiesByTask back docs/plans/ingestion-identity.md PR-1 (B-1)'s identity index (task_identity.go). Thin wrappers over the package-level functions, mirroring every other TaskRepository method's shape.

func (*TaskRepository) ListActionsByTask

func (r *TaskRepository) ListActionsByTask(taskID string) ([]*Action, error)

func (*TaskRepository) ListActionsSince added in v0.4.0

func (r *TaskRepository) ListActionsSince(filter ActionListFilter) ([]*Action, string, error)

ListActionsSince backs docs/plans/ingestion-identity.md PR-3 (B-3)'s workspace-scoped action_list read. Thin wrapper, mirroring every other TaskRepository method's shape.

func (*TaskRepository) ListChildren added in v0.0.6

func (r *TaskRepository) ListChildren(parentID string) ([]*Task, error)

func (*TaskRepository) ListIdentitiesByTask added in v0.4.0

func (r *TaskRepository) ListIdentitiesByTask(taskID string) ([]string, error)

func (*TaskRepository) ListInFlightTriggerRuns added in v0.4.0

func (r *TaskRepository) ListInFlightTriggerRuns() ([]*TriggerRun, error)

func (*TaskRepository) ListSignals added in v0.4.0

func (r *TaskRepository) ListSignals(filter SignalFilter) ([]*Signal, error)

func (*TaskRepository) ListTaskTriageByTaskIDs added in v0.3.11

func (r *TaskRepository) ListTaskTriageByTaskIDs(taskIDs []string) (map[string]*CardAttrs, error)

func (*TaskRepository) ListTasks

func (r *TaskRepository) ListTasks(filter TaskFilter) ([]*Task, error)

func (*TaskRepository) ParkedFrom added in v0.2.4

func (r *TaskRepository) ParkedFrom(taskID string) (TaskStatus, error)

func (*TaskRepository) ResolveIdentity added in v0.4.0

func (r *TaskRepository) ResolveIdentity(projectID, identity string) (*Task, error)

func (*TaskRepository) SetMetaProjectResolver added in v0.4.0

func (r *TaskRepository) SetMetaProjectResolver(resolver MetaProjectResolver)

SetMetaProjectResolver wires the metaproject lookup CreateAction's ingest step needs — see the metaResolver field's own doc comment.

func (*TaskRepository) SetTriggerRunJobID added in v0.4.0

func (r *TaskRepository) SetTriggerRunJobID(id, jobID string) error

SetTriggerRunJobID / DeleteTriggerRun back the Opus review Blocker 1 insert-then-dispatch split (trigger_run.go's own doc comments).

func (*TaskRepository) TouchTaskUpdatedAt added in v0.4.0

func (r *TaskRepository) TouchTaskUpdatedAt(id string) error

TouchTaskUpdatedAt backs docs/plans/webui-detail-list-redesign.md PR-3's updated_at bump (api.TaskUpdatedAtToucher) — thin wrapper, same shape as every other TaskRepository method.

func (*TaskRepository) UnlinkAllForTask added in v0.4.0

func (r *TaskRepository) UnlinkAllForTask(taskID string) error

func (*TaskRepository) UnlinkIdentity added in v0.4.0

func (r *TaskRepository) UnlinkIdentity(projectID, identity string) error

func (*TaskRepository) UpdateTask

func (r *TaskRepository) UpdateTask(task *Task) error

func (*TaskRepository) UpsertTaskTriage added in v0.2.4

func (r *TaskRepository) UpsertTaskTriage(tt *CardAttrs) error

type TaskSnapshot

type TaskSnapshot struct {
	ID          string `json:"id"`
	Title       string `json:"title"`
	Status      string `json:"status"`
	Behavior    string `json:"behavior"`
	Description string `json:"description,omitempty"`
	Readonly    bool   `json:"readonly"`
}

TaskSnapshot is the business metadata `boid task current` returns over the broker RPC (Phase 5b PR1, docs/plans/phase5-shim-and-task-context.md). Through the Phase 5b PR6 cutover it also materialized at the now-deleted $HOME/.boid/context/task.yaml; JSON tags stayed lowercase to match that file's key casing (marshalTaskYAML, also deleted) and the snake_case convention every other boid RPC response uses.

Readonly (Phase 5b PR4, docs/plans/phase5-shim-and-task-context.md「PR 分割案 > 5b」4) is the mode-determination source the boid-task skill reads via `boid task current --field readonly`.

func SnapshotTask added in v0.0.13

func SnapshotTask(task *Task) *TaskSnapshot

SnapshotTask projects a Task down to the business-metadata subset TaskSnapshot carries (see its doc comment) — through the Phase 5b PR6 cutover, also historically materialized at the now-deleted $HOME/.boid/context/task.yaml. Exported so internal/api's Phase 5b PR1 `boid task current` RPC (docs/plans/phase5-shim-and-task-context.md) reuses the exact same projection instead of re-deriving it.

Readonly is populated from task.Exec.Readonly directly, the same field IsReadonly reads — there is no second source of truth to drift against. Behavior/Readonly are execution-only (design doc §3.2); SnapshotTask is only ever called from PlanHook, which already requires task.Exec != nil (see its own guard above), so this reads task.Exec unconditionally rather than degrading to zero values a card could never legitimately produce.

type TaskStatus

type TaskStatus string
const (
	TaskStatusPending   TaskStatus = "pending"
	TaskStatusExecuting TaskStatus = "executing"
	TaskStatusAwaiting  TaskStatus = "awaiting"
	TaskStatusDone      TaskStatus = "done"
	TaskStatusAborted   TaskStatus = "aborted"

	// Card machine v2 status vocabulary (docs/plans/
	// suggestion-as-state-transition-impl.md §3.5, carried forward by
	// docs/plans/card-model-cleanup.md §3.3). captured/triaged/ready — the
	// cross-project-issue-triage Phase 1 pre-execution statuses — are
	// deliberately GONE as of the card-model-cleanup PR-2 migration (0045):
	// no rule in NewCardMachine has produced them since card machine v2
	// shipped, and migration 0045 洗い替えs every remaining pre-cutover row
	// carrying one of them to "parked" and drops the values from the DB
	// entirely. Re-introducing a reference to them here would silently
	// reopen a vocabulary the schema's CHECK constraint (migration 0045) no
	// longer accepts.
	TaskStatusParked  TaskStatus = "parked"
	TaskStatusWorking TaskStatus = "working"
	TaskStatusDropped TaskStatus = "dropped"
)

func GetTaskStatus added in v0.4.0

func GetTaskStatus(dbtx db.DBTX, id string) (TaskStatus, error)

GetTaskStatus reads ONLY a task's status, by exact id.

Split out from GetTask because GetTask is not a cheap read: taskSelectCols is followed by taskChildCountCols, five correlated `SELECT COUNT(*) FROM tasks c WHERE c.parent_id = t.id` subqueries, and tasks(parent_id) is deliberately unindexed (docs: the index was judged not to pay for itself) — so each call costs five scans of the tasks table. That is fine for a one-shot lookup and wrong for something polled once a second per waiter, on a pool that is a single connection (internal/db/db.go's SetMaxOpenConns(1)) shared by every dispatch, sweep and web request.

No prefix fallback, unlike GetTask: this is for callers that already resolved an id and are re-reading it, so a partial id here means the caller skipped the resolve rather than that it wants a lookup.

func KnownTaskStatuses added in v0.2.4

func KnownTaskStatuses() []TaskStatus

KnownTaskStatuses は boid が認識する全 TaskStatus 値を返す。バリデーションを行う全箇所 (CreateTaskRequest.InitialStatus・brokered task_list の status 検証等) はここを唯一の 情報源として参照する — 新しい状態を追加する際にリストがずれないようにするため。

card-model-cleanup PR-2 (migration 0045) removed captured/triaged/ready from this list: they are no longer valid tasks.status values in the DB (the new CHECK constraint rejects them), so keeping them here would let validation accept a value no row can ever actually hold.

func ParkedFrom added in v0.2.4

func ParkedFrom(dbtx db.DBTX, taskID string) (TaskStatus, error)

ParkedFrom derives the status a task was parked from (triaged, ready, or working) by looking at the most recent "park" action recorded for it. This is the origin TaskWorkflowService.Wake uses to choose wake_triaged vs wake_ready vs wake_working — see machine.go's NewMachine doc comment for why this is not a stored column.

func ParseTaskStatus added in v0.2.4

func ParseTaskStatus(s string) (TaskStatus, bool)

ParseTaskStatus は文字列を既知の TaskStatus に変換する。大文字小文字は区別しない曖昧さを 持ち込まない(完全一致のみ許可)。

type TaskTriageChild added in v0.2.4

type TaskTriageChild struct {
	ID    string `json:"id"`
	Title string `json:"title,omitempty"`
	// Status is one of the TaskTriageChildStatus* constants above.
	Status string `json:"status"`
	// Spec is required from "specced" onward (this + the child's Title is
	// everything task-ification needs).
	Spec *TaskTriageChildSpec `json:"spec,omitempty"`
	// TaskRef is set once the child has been task-ified ("dispatched" onward):
	// the id of the real boid task TaskWorkflowService.Dispatch created for it.
	TaskRef string `json:"task_ref,omitempty"`
}

TaskTriageChild is one entry of task_triage.detail.children.

func DetailChildren added in v0.2.4

func DetailChildren(detail json.RawMessage) ([]TaskTriageChild, error)

DetailChildren unmarshals the "children" array out of a task_triage.Detail blob. Returns (nil, nil) for an empty/absent detail or a detail with no "children" key — both mean "no children yet", not an error.

type TaskTriageChildSpec added in v0.2.4

type TaskTriageChildSpec struct {
	Project  string `json:"project"`
	Behavior string `json:"behavior,omitempty"`
	// Description is the child task's Web UI-visible description — the
	// narrative/background content (source context, what to do, links).
	// Kept separate from Instruction so the agent-facing instructions
	// message can stay a short, reusable procedure while the human-facing
	// context lives where the Web UI actually renders it (task_triage
	// dispatch previously crammed everything into Instruction, which left
	// the child task's description empty — nose 2026-08-14 feedback).
	Description string `json:"description,omitempty"`
	Instruction string `json:"instruction,omitempty"`
}

TaskTriageChildSpec is the execution recipe a child needs before it can be task-ified (docs/plans/cross-project-issue-triage.md データモデル節). Project is assumed to already be a resolved boid project ID by the time a child reaches "specced" — PR-2 does not do project-ref fuzzy resolution (決定5's routing confirmation is a 整形セッション / Phase 2 concern); an unresolvable Project surfaces as a plain "project not found" error from CreateTask.

type TaskType added in v0.4.0

type TaskType string

TaskType is the discriminator card-model-cleanup PR-2 (docs/plans/ card-model-cleanup.md §3) introduces: every Task is either a Card (a judgment ledger row — no agent session ever runs against it) or an ExecutionTask (a task that runs agent sessions). The two are mutually exclusive and a task never changes type over its lifetime (subtype modeling's two conditions, §2 of the design doc).

const (
	TaskTypeCard      TaskType = "card"
	TaskTypeExecution TaskType = "execution"
)

type TraitType

type TraitType string
const (
	TraitArtifact     TraitType = "artifact"
	TraitVerification TraitType = "verification"
	TraitAwaiting     TraitType = "awaiting"
)

func ActiveTraitTypes

func ActiveTraitTypes(raw json.RawMessage) ([]TraitType, error)

func (TraitType) Base

func (t TraitType) Base() TraitType

Base returns the trait name without the optional "?" suffix.

func (TraitType) IsOptional

func (t TraitType) IsOptional() bool

IsOptional reports whether the trait is declared with a trailing "?".

type TransitionCondition

type TransitionCondition func(payload json.RawMessage) bool

TransitionCondition evaluates whether a condition-based transition should fire.

type Trigger added in v0.4.0

type Trigger struct {
	// Name identifies this trigger within its project (single-flight and
	// trigger_runs history are scoped by (project_id, trigger_name) — 12
	// 節 B-5 "single-flight の粒度は trigger 単位"). Must be non-empty and
	// unique within a project's Triggers slice — see ValidateTriggers.
	Name string `yaml:"name" json:"name"`
	// On selects this trigger's activation predicate (docs/plans/
	// signal-ingest-detailed-design.md §4.1, PR-6). "" and
	// TriggerOnSchedule ("schedule") are equivalent and mean the
	// pre-existing, unchanged behavior: due purely once Every has elapsed
	// since the trigger's last recorded start. TriggerOnSignals ("signals")
	// ADDITIONALLY requires the trigger's project to have a linked
	// workspace with at least one pending (unacked) Signal — see
	// SweepTriggers' due predicate (internal/api/trigger_loop.go) for where
	// this is evaluated. ValidateTriggers rejects any other value at
	// project.yaml load time. omitempty: the overwhelmingly common case
	// (plain schedule triggers, pre-dating this field) round-trips through
	// export/apply without gaining an `on: schedule` line nobody wrote.
	On TriggerOn `yaml:"on,omitempty" json:"on,omitempty"`
	// Every is a Go time.ParseDuration string (e.g. "10m", "1h") — the
	// minimum wall-clock gap between two starts of this trigger. There is
	// deliberately no time-of-day window (12 節 B-5 既定案「トリガの時間帯窓
	// はスクリプトが時刻で自制する」— J-4's「daemon はドメインに依存しない」).
	// Required for BOTH On kinds — for On=="signals" this is also the
	// trigger's debounce window (§4.2: "every 窓内に何件 Signal が来ても発火
	// は1回").
	Every string `yaml:"every" json:"every"`
	// Run is a command string passed to `sh -c` inside the project's
	// sandbox — NOT a script path daemon resolves (J-2: 撤廃済みの script
	// hook 外部参照と同じ轍を踏まない). sandbox の /bin/sh は dash: bashism は
	// `bash scripts/x.sh` と明示する側 (スクリプト作者) の責任で、daemon の
	// 責任ではない。
	Run string `yaml:"run" json:"run"`
	// Timeout is a Go time.ParseDuration string bounding how long ONE round of
	// this trigger may take. Empty (the default, and what every trigger written
	// before this field existed carries) means unbounded.
	//
	// It is a different question from Every and must not be derived from it.
	// Every says how OFTEN to look; Timeout says how LONG a round may run.
	// Before this field existed the daemon had no answer to the second
	// question at all, so trackSkipStreak approximated it as
	// TriggerStuckOverrunMultiplier × Every — which has the wrong shape:
	// shortening the polling interval tightened the "this is taking too long"
	// judgement, even though nothing about the work changed. Workspaces
	// answered it their own way instead, by smuggling `timeout 300` into the
	// front of their own Run string, where the daemon that launched the job
	// cannot see it.
	//
	// Enforced by the sweep loop (internal/api/trigger_loop.go): an overrunning
	// round is ended and reported as a failure, so it reaches trackFailStreak
	// like any other. "Taking too long" therefore stops being something the
	// daemon has to GUESS at and becomes something it ENFORCES.
	Timeout string `yaml:"timeout,omitempty" json:"timeout,omitempty"`

	// Connector, when non-nil, marks this Trigger as one hydrate-DERIVED
	// from a project.yaml `signals.sources[]` entry (docs/plans/
	// signal-ingest-detailed-design.md §5.1, PR-5: source 1 件 = trigger 1
	// 本) — never set by a user-authored `triggers:` entry. yaml:"-": this
	// is a runtime-only field computed by deriveSignalTriggers
	// (signal_trigger_derive.go) from ProjectMeta.Signals, never itself
	// read back out of project.yaml. fireTrigger (internal/api/
	// trigger_loop.go) reads it to attach the connector job's extra env/
	// bind/policy/service-allowlist (§5.2) — every trigger with a nil
	// Connector dispatches exactly as before this PR.
	Connector *TriggerConnector `yaml:"-" json:"connector,omitempty"`
}

Trigger is one project.yaml `triggers[]` entry (docs/plans/ ingestion-identity.md PR-4 / B-5, J-1/J-2). It declares WHEN a command runs (Every, and since PR-6 also On) and WHAT command runs (Run) — nothing else. daemon reads only these fields; it never interprets Run's contents (J-2, this PR's own 不変条件: daemon は run の中身を知らない).

func (Trigger) TriggerTimeout added in v0.4.0

func (t Trigger) TriggerTimeout() time.Duration

TriggerTimeout resolves Timeout for the sweep loop. Zero means unbounded — both for an omitted field and for an unparseable one, which ValidateTriggers rejects at load time so it cannot reach a running daemon. Falling back to "unbounded" rather than to some default keeps a malformed value from inventing a bound nobody wrote.

type TriggerConnector added in v0.4.0

type TriggerConnector struct {
	// Pack is the "<pack>" half of signals.sources[].connector
	// ("<pack>/<connector>").
	Pack string
	// ConnectorName is the "<connector>" half.
	ConnectorName string
	// Service is signals.sources[].service — the service instance name
	// this connector is authorized to reach through the API gateway (§5.2:
	// the connector job's gateway token is restricted to exactly this ONE
	// service, never the workspace's full enabled set).
	Service string
	// Config is signals.sources[].config, decoded from YAML into Go's
	// generic any shapes (map[string]any) — the same representation
	// integrationpack.ConfigSchema.Validate consumes directly, so no
	// intermediate JSON round-trip is needed until the connector job's
	// BOID_SIGNAL_CONFIG env var is actually built. Never nil (an omitted
	// `config:` block derives an empty, non-nil map) so callers can range
	// over it unconditionally.
	Config map[string]any
}

TriggerConnector is the resolved connector identity carried by a hydrate-derived Trigger (Trigger.Connector, docs/plans/ signal-ingest-detailed-design.md §5.1/§5.2, PR-5). It holds only the RAW declaration from project.yaml `signals.sources[]` — no Pack-registry lookup happens at hydrate time (internal/orchestrator has no notion of an Integration Pack registry; that lives in internal/integrationpack, which only internal/server's daemon-startup wiring and dispatch-time connector resolution ever import — see docs/plans/signal-ingest-detailed-design.md §6.2's "internal/integrationpack は新 package" and this package's own layering rule, scripts/check-internal-architecture.sh). Resolving Pack/ version/executable path against the loaded registry happens downstream, at StartExec time (internal/server/wire.go's sessionDispatcherAdapter).

type TriggerOn added in v0.4.0

type TriggerOn string

TriggerOn is Trigger.On's type — a named string type, matching this package's other closed-enum-ish string fields (e.g. SignalState, signal_store.go) rather than a bare string.

const (
	TriggerOnSchedule TriggerOn = "schedule"
	TriggerOnSignals  TriggerOn = "signals"
)

TriggerOnSchedule / TriggerOnSignals are Trigger.On's two valid values (docs/plans/signal-ingest-detailed-design.md §4.1, PR-6). ValidateTriggers also accepts "" as an alias for TriggerOnSchedule (the pre-existing default, before this field existed).

type TriggerRun added in v0.4.0

type TriggerRun struct {
	ID          string
	ProjectID   string
	TriggerName string
	JobID       string
	StartedAt   time.Time
	// FinishedAt is nil while the run is in flight (single-flight's own
	// definition of "busy" — ListInFlightTriggerRuns' WHERE clause).
	FinishedAt *time.Time
	// ExitCode is nil until CompleteTriggerRun records it. A recorded
	// value can be non-zero — a failing trigger command's exit code is
	// data, not an error this store rejects (PR-4's own 検証: 「コマンドが
	// 非ゼロで落ちても…exit code が記録に残る」).
	ExitCode *int
}

TriggerRun is one row of the trigger_runs table — one attempted (or in-flight) execution of a project.yaml trigger.

func LatestTriggerRun added in v0.4.0

func LatestTriggerRun(dbtx db.DBTX, projectID, triggerName string) (*TriggerRun, error)

LatestTriggerRun returns the most recently STARTED run for (projectID, triggerName) — regardless of whether it has finished yet. Returns ErrTriggerRunNotFound when the pair has never run. Callers use this to compute "has `every` elapsed since the last start" (this PR's scheduling condition) independent of single-flight (which is decided by ListInFlightTriggerRuns/finished_at, not by this method).

func ListInFlightTriggerRuns added in v0.4.0

func ListInFlightTriggerRuns(dbtx db.DBTX) ([]*TriggerRun, error)

ListInFlightTriggerRuns returns every row with finished_at IS NULL, across every project/trigger — the single query the trigger sweep loop's reconciliation pass uses once per tick (avoiding one query per trigger definition, same "single batch read" posture as PR-3's ListActionsSince).

type Visibility

type Visibility struct {
	// ProjectDir is the host path to the project working directory.
	// Empty means the project filesystem is not visible.
	ProjectDir string

	// ProjectName is project.yaml's `meta.name` (kebab-case by convention,
	// not enforced), threaded through from the workspace-hydrated
	// ProjectMeta at JobSpec-build time (PlanHook / BuildSessionJobSpec).
	// dispatcher uses it — falling back to filepath.Base(ProjectDir) when
	// empty — to name the sandbox-internal clone directory under the
	// /workspace parent dir (workspace 親化リファクタリング, nose
	// 2026-07-13 decision): every project previously shared the exact same
	// sandbox cwd ("/workspace"), which collided Claude Code's
	// `~/.claude/projects/-workspace/` session-log slug across every boid
	// project. Empty is a legitimate value (a project with no `name:` in
	// project.yaml, or a dispatch path — e.g. gate/hook jobs with no
	// project visible at all — that never resolves one); dispatcher's
	// fallback degrades gracefully rather than erroring.
	ProjectName string

	// AdditionalBindings lists extra host bind-mounts (e.g. kit-provided CLIs
	// like the claude binary) that must be visible inside the sandbox.
	AdditionalBindings []BindMount

	// Writable permits writes to ProjectDir. When ProjectDir is empty, this
	// field has no effect.
	Writable bool

	// DockerEnabled, when true, indicates capabilities.docker was declared in
	// project.yaml. Dispatcher uses this to start a per-sandbox docker proxy.
	DockerEnabled bool

	// Clone declares the sandbox-internal-clone branch state for real dispatch
	// (docs/plans/git-gateway-cutover.md PR5 「5. branch 宣言の JobSpec 化」・
	// PR6 cutover). nil leaves dispatch unaffected (test-only JobSpecs that
	// don't exercise clone-mode). When non-nil, dispatcher does not resolve
	// the branch itself against a host repo — it carries this declaration
	// through to the sandbox so the runner resolves it (rev-parse /
	// merge-base / checkout -B) after cloning inside the sandbox.
	Clone *CloneDeclaration
}

Visibility captures which host paths the sandbox sees and whether they are writable. orchestrator sets this once per JobSpec; dispatcher turns it into mount entries with no further role-aware logic.

type WatchdogThresholds added in v0.2.4

type WatchdogThresholds struct {
	IngestStale time.Duration
	ReviewStale time.Duration
}

WatchdogThresholds are the staleness thresholds rule 7 checks against. Deliberately not yet wired to config.yaml (no real caller/data to calibrate against until PR-4's ingestion lands) — DefaultWatchdogThresholds below is a reasonable starting point, kept as a named type so a future PR can thread it through config without changing WatchdogGuidance's signature.

func DefaultWatchdogThresholds added in v0.2.4

func DefaultWatchdogThresholds() WatchdogThresholds

DefaultWatchdogThresholds returns PR-3's starting-point thresholds: 48h for ingestion silence, 14 days for 棚卸し silence.

type WorkspaceApplyResult added in v0.1.0

type WorkspaceApplyResult struct {
	Slug string `json:"slug"`
	// Created is true when slug had no workspaces row before this call.
	Created bool `json:"created"`
	// Previous is the workspace's meta before this apply (nil when
	// Created).
	Previous *WorkspaceMeta `json:"previous,omitempty"`
	// Meta is the merged/proposed meta this apply wrote (or, for dryRun,
	// would have written).
	Meta *WorkspaceMeta `json:"meta"`
	// Revision is the workspace's row revision after a committed apply.
	// Empty for a dry run (nothing was committed, so there is no new
	// revision to report).
	Revision string `json:"revision,omitempty"`

	// AttachedProjects/DetachedProjects/AlreadyAttachedProjects are project
	// IDs (not names — see ApplyWorkspaceEnvelope's projectIDsByName
	// parameter doc comment for why name resolution happens outside this
	// function). AttachedProjects were newly assigned to Slug by this call;
	// AlreadyAttachedProjects were already assigned to Slug and left alone;
	// DetachedProjects were previously assigned to Slug but absent from the
	// applied document's spec.projects[] list, so they were reassigned to
	// DefaultWorkspaceSlug (Blocker 1's second half: FieldsPresent["projects"]
	// must be honored as "replace the whole assignment set", not just
	// "attach anything additionally listed").
	AttachedProjects        []string `json:"attached_projects,omitempty"`
	AlreadyAttachedProjects []string `json:"already_attached_projects,omitempty"`
	DetachedProjects        []string `json:"detached_projects,omitempty"`

	// MissingProjects is filled in by the caller (ProjectAppService.
	// ApplyWorkspace, internal/api/project_service.go) — a spec.projects[]
	// name that did not resolve to a registered project. Left empty by
	// ApplyWorkspaceEnvelope itself, which only ever sees already-resolved
	// IDs (projectIDsByName).
	MissingProjects []string `json:"missing_projects,omitempty"`

	// InitScriptAction reports what this apply did — or, for a dry run, would
	// do — to the workspace's init.sh: "written", "cleared", "unchanged", or
	// empty when the document carried no spec.init_script key at all (PR9 of
	// docs/plans/workspace-home-volume-persistence.md, 論点 d).
	//
	// Also filled in by the caller, and for a stronger reason than
	// MissingProjects: init.sh is a FILE on the daemon, not a row this
	// function's transaction could touch (WorkspaceEnvelopeSpec.InitScript).
	// It is reported separately from Meta for the same reason — a reader of
	// this result must be able to see that the script and the metadata are
	// two commits, not one.
	InitScriptAction string `json:"init_script_action,omitempty"`

	// Warnings is filled in by the caller (WorkspaceHandler.Apply,
	// internal/api/workspace.go) — non-fatal notices about the applied
	// document that a direct HTTP caller (not going through `boid workspace
	// apply`, which already warns client-side) would otherwise never see,
	// e.g. a retired spec.additional_bindings key that was silently dropped
	// (PR-1d codex round-2 Minor). Left empty by ApplyWorkspaceEnvelope
	// itself.
	Warnings []string `json:"warnings,omitempty"`
}

WorkspaceApplyResult reports what ApplyWorkspaceEnvelope did (or, for dryRun=true, would do) for one workspace envelope document (docs/plans/volume-only-daemon.md PR-1d codex round-1 Blocker 2).

func ApplyWorkspaceEnvelope added in v0.1.0

func ApplyWorkspaceEnvelope(conn *sql.DB, apply *WorkspaceEnvelopeApply, projectIDsByName map[string]string, dryRun bool) (*WorkspaceApplyResult, error)

ApplyWorkspaceEnvelope upserts apply's workspace metadata and (when apply.FieldsPresent["projects"] is true) reconciles its project attach/detach bookkeeping, all in a SINGLE database transaction (docs/plans/volume-only-daemon.md PR-1d codex round-1 Blocker 2): either every change this call makes commits, or none of them do. This replaces the previous client-side "GET current, merge, PUT metadata, then separately attach each project one HTTP call at a time" dance (cmd/workspace_apply.go's old applyOneWorkspace/applyWorkspaceProjects), which had no way to roll back the metadata write if a later project assignment failed.

projectIDsByName maps each spec.projects[].name entry that DID resolve to a registered project (via ProjectAppService.ResolveProjectRef) to that project's ID. A name present in apply.Envelope.Spec.Projects but absent from projectIDsByName is simply not attached/reconciled here — the caller surfaces that as a non-fatal warning (WorkspaceApplyResult. MissingProjects), per the plan doc's cross-PR coordination note that a not-yet-registered project must never fail apply. Resolving names to IDs is deliberately done by the caller, OUTSIDE this transaction: a project's display name lives in the in-memory ProjectMeta cache (hydrated from project.yaml on disk), not a DB column this transaction could query — see ProjectAppService.resolveWorkspaceApplyProjectNames.

dryRun runs every read and write statement below — including the workspace upsert and the project_workspaces mutations — against a real transaction, then rolls back instead of committing. This means a dry run exercises the exact same validation/constraint path a real apply would (Major 1, codex round-1: a dry-run that stopped short of touching the DB could report success on a document a real apply would go on to reject).

type WorkspaceEnvelope added in v0.1.0

type WorkspaceEnvelope struct {
	APIVersion string                    `yaml:"apiVersion"`
	Kind       string                    `yaml:"kind"`
	Metadata   WorkspaceEnvelopeMetadata `yaml:"metadata"`
	Spec       WorkspaceEnvelopeSpec     `yaml:"spec"`
}

WorkspaceEnvelope is the export/apply document shape: an apiVersion/kind/ metadata/spec envelope around a workspace's meta + project assignments.

func NewWorkspaceEnvelopeFromMeta added in v0.1.0

func NewWorkspaceEnvelopeFromMeta(name string, meta *WorkspaceMeta, projects []WorkspaceEnvelopeProject, initScript string) *WorkspaceEnvelope

NewWorkspaceEnvelopeFromMeta builds a WorkspaceEnvelope for `boid workspace export` from a workspace's current WorkspaceMeta, its resolved project entries (name + url, url may be empty pre-PR-2 — see WorkspaceEnvelopeProject's doc comment) and its init.sh. meta may be nil (an empty/never-configured workspace), in which case the spec carries only projects (if any) and the script.

initScript is a plain string rather than a (content, exists) pair because the two states an init.sh can be in are "some bytes" and "none", and the empty string is how the envelope spells the second one — see WorkspaceEnvelopeSpec.InitScript. A caller with nothing to export passes "", which is emitted as `init_script: ""` and read back as an explicit clear.

func (WorkspaceEnvelope) MarshalYAML added in v0.1.0

func (e WorkspaceEnvelope) MarshalYAML() (any, error)

MarshalYAML makes every `yaml.Marshal` of an envelope round-trippable, wherever it is called from, rather than leaving the property to whichever call site remembered to ask for it.

It returns a *yaml.Node: the encoder's own style choice is what has to be overridden, and a node is the only representation that can carry a style.

type WorkspaceEnvelopeApply added in v0.1.0

type WorkspaceEnvelopeApply struct {
	Envelope *WorkspaceEnvelope
	// FieldsPresent records which spec.* keys were present in the source
	// document (by their yaml key name: "host_commands", "env",
	// "allowed_domains", "extra_repos", "services", "container_image",
	// "capabilities", "projects", "init_script", "task_behaviors",
	// "base_branch", "fork_point", "default_task_behavior"). A key absent from this map was not present
	// in the document at all and MergeInto leaves the corresponding
	// WorkspaceMeta field untouched; a key present (even if its decoded value
	// is the zero value / an explicit empty list or map) means the document
	// explicitly wants that field replaced with the decoded value.
	//
	// "init_script" is in this map but not in MergeInto's switch: it has no
	// WorkspaceMeta field to merge into (see WorkspaceEnvelopeSpec.InitScript).
	// Its consumer is ProjectAppService.ApplyWorkspace, which reads the same
	// flag to decide between "leave the file alone" and "write/clear it".
	FieldsPresent map[string]bool
	// AdditionalBindingsDropped is true when the source document had a
	// spec.additional_bindings key (any shape, including an explicit empty
	// list or null) — retired per docs/plans/volume-only-daemon.md §論点g;
	// the value is always discarded. Callers should log/print a warning
	// rather than fail the apply.
	AdditionalBindingsDropped bool
}

WorkspaceEnvelopeApply is the result of decoding one Workspace document for `boid workspace apply`: the parsed envelope plus enough bookkeeping for the K8s-style "missing field = don't touch, present-but-empty = clear" merge semantics (docs/plans/volume-only-daemon.md, PR-1d unilateral decision) that a plain *WorkspaceEnvelope alone cannot represent — a zero- value Go slice/map cannot be told apart from "the key was absent" once decoded into a plain struct.

func DecodeWorkspaceEnvelopeDocuments added in v0.1.0

func DecodeWorkspaceEnvelopeDocuments(data []byte) ([]*WorkspaceEnvelopeApply, error)

DecodeWorkspaceEnvelopeDocuments decodes data as one or more "---"- separated Workspace envelope documents (docs/plans/volume-only-daemon.md §論点g: "複数 workspace は YAML の --- 区切りで 1 file にまとめられる"). An empty/whitespace-only body is an error (unlike DecodeWorkspaceMetaStrict — an apply file with nothing in it is almost certainly a mistake, not a legitimate "no-op apply"). Every document must independently satisfy:

  • apiVersion == WorkspaceEnvelopeAPIVersion
  • kind == WorkspaceEnvelopeKind
  • metadata.name is non-empty and a valid workspace slug
  • spec has no unknown fields (additional_bindings tolerated — see workspaceEnvelopeSpecFields)

func (*WorkspaceEnvelopeApply) MergeInto added in v0.1.0

func (a *WorkspaceEnvelopeApply) MergeInto(current *WorkspaceMeta) *WorkspaceMeta

MergeInto applies a's spec onto current (which may be nil — no existing workspace, i.e. a `boid workspace apply` create rather than update) per field, honoring FieldsPresent's "missing = don't touch" contract, and returns the resulting *WorkspaceMeta. current is never mutated.

spec.init_script is deliberately absent from the field list below: it is a file on the daemon, not a workspaces-table column, so there is nothing on *WorkspaceMeta to merge it into (WorkspaceEnvelopeSpec.InitScript). Its FieldsPresent flag is honored by ProjectAppService.ApplyWorkspace, outside this function and outside the DB transaction — a file write and a transaction cannot be made atomic, and pretending otherwise by routing it through here would only hide that.

type WorkspaceEnvelopeMetadata added in v0.1.0

type WorkspaceEnvelopeMetadata struct {
	Name string `yaml:"name"`
}

WorkspaceEnvelopeMetadata holds the envelope's identifying field: the workspace slug (workspaces.id / WorkspaceSummary.ID).

type WorkspaceEnvelopeProject added in v0.1.0

type WorkspaceEnvelopeProject struct {
	Name string `yaml:"name"`
	URL  string `yaml:"url,omitempty"`
}

WorkspaceEnvelopeProject is one spec.projects[] entry. URL is informational only until PR-2 lands `boid project add <url>` (docs/plans/ volume-only-daemon.md §論点g): apply does not register a project from URL, it only attaches an already-registered project (matched by name) to the workspace.

type WorkspaceEnvelopeSpec added in v0.1.0

type WorkspaceEnvelopeSpec struct {
	HostCommands   []string          `yaml:"host_commands"`
	Env            map[string]string `yaml:"env"`
	AllowedDomains []string          `yaml:"allowed_domains"`
	ExtraRepos     []string          `yaml:"extra_repos"`
	// Services is the workspace-scoped API gateway service allowlist
	// (docs/plans/api-gateway.md §3; WorkspaceMeta.Services). Same
	// no-omitempty / missing-vs-empty rationale as every other field here.
	Services       []string                   `yaml:"services"`
	ContainerImage string                     `yaml:"container_image"`
	Capabilities   Capabilities               `yaml:"capabilities"`
	Projects       []WorkspaceEnvelopeProject `yaml:"projects"`
	// TaskBehaviors / BaseBranch / ForkPoint / DefaultTaskBehavior are the
	// workspace's default project definition (docs/plans/
	// workspace-default-project.md §PR分割案 PR3; see WorkspaceMeta's
	// identically-named fields for the semantics). Same no-omitempty
	// rationale as every other field here — a document that omits
	// task_behaviors must leave the workspace's current value untouched, not
	// silently clear it.
	TaskBehaviors       map[string]TaskBehavior `yaml:"task_behaviors"`
	BaseBranch          string                  `yaml:"base_branch"`
	ForkPoint           string                  `yaml:"fork_point"`
	DefaultTaskBehavior string                  `yaml:"default_task_behavior"`
	// InitScript is the workspace's init.sh, verbatim (PR9 of
	// docs/plans/workspace-home-volume-persistence.md, 論点 d).
	//
	// Like Projects it has NO WorkspaceMeta counterpart, and for a sharper
	// reason: init.sh is a FILE the daemon owns (dispatcher's
	// workspaceInitScriptPath), deliberately not a workspaces-table column —
	// see that function's doc comment for the standing decision (environment-
	// dependent shell content, outside the workspace's otherwise
	// environment-independent DB-backed config). It is carried here anyway
	// because an export that omits it is not a backup: restoring a workspace
	// without its init.sh gives you a home volume with no toolchain in it and
	// a harness that cannot start.
	//
	// MergeInto therefore does not touch it — the hydration happens in
	// internal/api, which holds the store (ProjectAppService.ApplyWorkspace).
	//
	// Missing vs. explicitly-empty is load-bearing exactly as it is for the
	// fields above: no key means "leave this workspace's init.sh alone", and
	// `init_script: ""` means "this workspace has no init.sh", which on apply
	// deletes the target's. An empty script and no script are the same state
	// by construction — the dispatch wrapper writes the bytes to a file and
	// runs bash on it, so zero bytes is a no-op run — and collapsing them
	// keeps a workspace from acquiring a completion-marker hash that describes
	// nothing.
	InitScript string `yaml:"init_script"`
}

WorkspaceEnvelopeSpec mirrors WorkspaceMeta field-for-field (see that type's doc comment for what each field means at runtime) plus Projects, which has no WorkspaceMeta equivalent — project-workspace assignment is separate bookkeeping (project_workspaces / Project.WorkspaceID), not part of the workspace's own meta row.

additional_bindings is deliberately NOT a field here: it was retired in docs/plans/home-workspace-volume.md Phase 4 PR4 and the plan doc for this package (§論点g) explicitly excludes it from the export schema. A source document that still carries a spec.additional_bindings key is tolerated by decodeWorkspaceEnvelopeSpec (see below) — parsed and discarded, with WorkspaceEnvelopeApply.AdditionalBindingsDropped set so the caller can warn — rather than rejected as an unknown field. None of spec's fields carry `omitempty` (PR-1d codex round-1 Blocker 1, extended to every remaining field by round-2's follow-up finding): missing vs. explicitly-empty is a load-bearing distinction for every one of these seven (WorkspaceEnvelopeApply's FieldsPresent-driven merge, and — for projects — ApplyWorkspaceEnvelope's attach/detach reconciliation), and `omitempty` on export would silently collapse "the workspace's field really is empty/zero" into "the field was absent from the document", which on a subsequent apply is indistinguishable from "leave the current value untouched" — an export → apply round trip could then never actually clear a field back to empty (round-2's concrete failure: exporting a workspace with no extra_repos and Docker disabled, then applying that backup over a workspace with a stale extra_repos entry and capabilities.docker enabled, left both untouched because the omitempty tags dropped the keys from the export entirely). yaml.v3 marshals a nil/empty slice, map, or zero-value struct/string as `[]`/`{}`/`""` either way (verified: no `omitempty` needed to avoid a `null` literal here), so dropping the tag is a pure presence-fidelity fix with no representation change for the non-empty case.

type WorkspaceExportSnapshot added in v0.1.0

type WorkspaceExportSnapshot struct {
	Slug     string
	Meta     *WorkspaceMeta
	Revision string
	// ProjectIDs is the list of project IDs assigned to this workspace as
	// of the snapshot transaction.
	ProjectIDs []string
	// Projects maps each of ProjectIDs to its full *Project row (id,
	// work_dir, upstream_url, ...), read from the SAME transaction as
	// ProjectIDs itself (PR-1d codex round-2 Major: the caller previously
	// re-queried each project ID with a separate, post-transaction
	// GetProject call whose error was silently skipped — a concurrent
	// delete landing in that window could produce a "consistent snapshot"
	// export that was quietly missing an assignment). Every ID in
	// ProjectIDs is guaranteed to have an entry here (project_workspaces.
	// project_id REFERENCES projects(id), read within one transaction), so
	// a caller indexing this map by an id drawn from ProjectIDs never needs
	// an "ok" check for correctness — Display name/url resolution (project.
	// yaml's name: field) still happens outside this transaction, from the
	// in-memory ProjectMeta cache, which is not DB-backed at all — see
	// SnapshotWorkspacesForExport's doc comment.
	Projects map[string]*Project
}

WorkspaceExportSnapshot is one workspace's meta + assigned project IDs, read from a single atomic DB transaction alongside every other workspace's snapshot in the same call to SnapshotWorkspacesForExport.

func SnapshotWorkspacesForExport added in v0.1.0

func SnapshotWorkspacesForExport(conn *sql.DB, slugs []string) (snapshots []*WorkspaceExportSnapshot, allProjects map[string]*Project, err error)

SnapshotWorkspacesForExport reads meta + project assignment for every slug in slugs (or every workspace when slugs is nil/empty) from a SINGLE read-only DB transaction (docs/plans/volume-only-daemon.md PR-1d codex round-1 Blocker 3): `boid workspace export`'s previous per-workspace "GET meta, then GET its projects" loop (cmd/workspace_export.go's old exportWorkspaceEnvelopeYAML, called once per workspace) could straddle a concurrent `workspace assign` moving a project between two workspaces mid-export — the project could then appear in neither exported document, or (less likely but still possible) in both. Reading every workspaces row and the entire project_workspaces table inside one transaction closes that window: every project_id this call reports is assigned to exactly one workspace_id, as of one consistent instant — project_workspaces. project_id is the table's PRIMARY KEY (0001_initial.sql), so a project can never appear against two different workspace_id values in the same read.

Every assigned project's full row (WorkspaceExportSnapshot.Projects) is ALSO read from this same transaction (PR-1d codex round-2 Blocker 3 follow-up) — the id/work_dir/upstream_url/workspace_id columns all live in the same `projects` table this function already reads via ListProjects, so there is no reason to defer that read to a second, separately-fallible, post-transaction lookup per project the way the round-1 version did. Only the project's DISPLAY NAME (WorkspaceEnvelopeProject.Name) is deliberately NOT part of this snapshot: it comes from the in-memory ProjectMeta cache (project.yaml's name: field), not a DB column at all — see ProjectAppService.ExportWorkspaceEnvelopes, which resolves that name afterward. Doing that resolution outside this transaction cannot reintroduce the cross-workspace inconsistency this function exists to close: it cannot change which workspace_id a project_id is assigned to, only how that already-fixed assignment is displayed. allProjects (PR-1d codex round-3 regression fix) is EVERY registered project row -- not just ones assigned to a slug in slugs -- read from the exact same transaction as everything else this function returns, keyed by ID. ExportWorkspaceEnvelopes needs the full, tx-consistent project set (not just the exported workspaces' assignments) to detect a project.yaml name colliding with ANOTHER project's name or ID before emitting a spec.projects[] entry a later apply could misresolve. Before this fix, that collision check ran its own separate, post-snapshot ListProjects() call, which could describe a different instant than the export snapshot itself under concurrent project create/delete.

type WorkspaceMeta added in v0.0.8

type WorkspaceMeta struct {
	// Env holds environment variable overrides applied to every sandbox
	// launched under this workspace. Values here take precedence over
	// kit-supplied env but are overridden by project.yaml env.
	Env map[string]string `yaml:"env,omitempty" json:"env,omitempty"`

	// Capabilities declares optional sandbox capability flags for this
	// workspace. Uses the same Capabilities type as ProjectMeta.
	Capabilities Capabilities `yaml:"capabilities,omitempty" json:"capabilities,omitempty"`

	// AllowedDomains is the workspace-scoped HTTP(S) proxy egress allowlist.
	// Domains listed here are ADDED to the daemon-wide allowlist
	// (config.yaml sandbox.allowed_domains); the workspace cannot remove
	// entries from the global floor — that floor exists to keep
	// pypi/github/etc reachable for tool installation.
	//
	// Same matching rules as the global list (see sandbox.Proxy):
	//   - "registry-1.docker.io"  exact match
	//   - ".cosmos.azure.com"     suffix match (matches "<sub>.cosmos.azure.com")
	AllowedDomains []string `yaml:"allowed_domains,omitempty" json:"allowed_domains,omitempty"`

	// ExtraRepos is the workspace-scoped, read-only allowlist of additional
	// git repositories outside this workspace's own projects that jobs may
	// fetch (never push) via the git gateway — e.g. a private go module
	// dependency (docs/plans/git-gateway-cutover.md 「workspace peer」節:
	// 「workspace 設定に read-only の追加許可 repo」). Entries are upstream
	// URLs in any form dispatcher.NormalizeOriginURL accepts (HTTPS or SSH);
	// dispatcher resolves each into a gitgateway.RepoKey at dispatch time and
	// grants it PermFetch alongside this workspace's own projects and peers.
	// Same additive, floor-cannot-shrink relationship to the (currently
	// nonexistent) global floor as AllowedDomains — there is no write grant
	// here, fetch-only by construction.
	ExtraRepos []string `yaml:"extra_repos,omitempty" json:"extra_repos,omitempty"`

	// Services is the workspace-scoped list of API gateway logical service
	// names ENABLED for this workspace, on top of config.yaml's
	// services_floor (docs/plans/api-gateway.md §3: "workspace 単位の
	// service 有効化 — allowed_domains の floor + workspace 加算方式を鏡写し
	// にする"). Same additive, floor-cannot-shrink relationship to the
	// daemon-wide floor as AllowedDomains has to sandbox.allowed_domains —
	// a workspace can only ADD services on top of the floor, never remove a
	// floor entry. An entry naming a service config.yaml's `services:` map
	// does not actually declare is not rejected here (WorkspaceMeta has no
	// visibility into the daemon's service registry) — it simply never
	// resolves to anything reachable at dispatch time; see
	// ResolveEnabledServices and internal/apigateway.CredentialProvider.
	// KnowsService, which is the layer that actually enforces "is this
	// service configured at all".
	Services []string `yaml:"services,omitempty" json:"services,omitempty"`

	// HostCommands is the reference-name list into the aggregated
	// host_commands config assembled at daemon startup (see
	// host_commands_config.go's LoadHostCommandsFromKits /
	// WriteHostCommandsConfig and docs/plans/workspace-db-consolidation.md
	// 「host_commands 実定義の集約先」). Unlike Kits, this field carries only
	// names — no path/allow/env/reject definitions travel with the
	// workspace itself; those live in the daemon-wide
	// ~/.config/boid/host_commands.yaml and are resolved by name at
	// GetWithWorkspace hydration time (ProjectStore.hostCommands).
	// Populated by MigrateWorkspaceYAMLToDB from each workspace's former
	// Kits list, unioned with any host_commands the workspace already had.
	HostCommands []string `yaml:"host_commands,omitempty" json:"host_commands,omitempty"`

	// ContainerImage is a nullable field reserved for the Phase 6 container
	// backend (decision 7, docs/plans/workspace-db-consolidation.md).
	// Dispatch ignores it entirely until then — the field only exists so
	// the schema migration for it does not need to be revisited later.
	ContainerImage string `yaml:"container_image,omitempty" json:"container_image,omitempty"`

	// TaskBehaviors / BaseBranch / ForkPoint / DefaultTaskBehavior are the
	// workspace's "default project" definition (docs/plans/
	// workspace-default-project.md — a project.yaml-less or partial
	// project.yaml inherits these). Mirrors the identically-named ProjectMeta
	// fields (spec_types.go) field-for-field, both in shape and in the
	// validation/normalization pipeline they go through
	// (normalizeWorkspaceDefaultTaskBehaviors, spec_loader.go, 論点j) — but
	// unlike host_commands/env/capabilities above, these four are NOT yet
	// consumed by anything: this is PR3 of that doc's PR split (schema +
	// plumbing only). A future PR wires them into GetWithWorkspace's
	// hydration merge (決定1: project.yaml wins per-field over these
	// workspace defaults; 決定4: task_behaviors merges by canonical behavior
	// name, same-name project.yaml entry wins outright).
	TaskBehaviors map[string]TaskBehavior `yaml:"task_behaviors,omitempty" json:"task_behaviors,omitempty"`
	// BaseBranch is the workspace default's base_branch. Empty means
	// "unspecified" (決定5: there is deliberately no way to explicitly
	// un-set an inherited value — see that decision's doc comment).
	BaseBranch string `yaml:"base_branch,omitempty" json:"base_branch,omitempty"`
	// ForkPoint is the workspace default's fork_point. Same empty-means-
	// unspecified rule as BaseBranch.
	ForkPoint string `yaml:"fork_point,omitempty" json:"fork_point,omitempty"`
	// DefaultTaskBehavior is the workspace default's default_task_behavior.
	// Same empty-means-unspecified rule as BaseBranch.
	DefaultTaskBehavior string `yaml:"default_task_behavior,omitempty" json:"default_task_behavior,omitempty"`
}

WorkspaceMeta holds the machine-local workspace configuration that is stored in ~/.config/boid/workspaces/<slug>.yaml.

A workspace defines host_command references, environment variable overrides, and optional capability flags for sandboxes. Fields that are project-specific (secret_namespace, host_commands, additional_bindings, name, description, version) are intentionally absent; they remain in project.yaml.

A Kits field used to live here (an ordered list of kit slugs, resolved and merged in at hydration time). The kit mechanism itself was retired in docs/plans/workspace-db-consolidation.md Phase 2.5 PR6, and this field was removed outright in PR7 (decision 12: no fallback for the old field kept). The `workspaces` DB table never had a column for it (WorkspaceRepository. Load/Save never read/wrote it), so removing the struct field is a pure cleanup with no persisted-data migration implied. Two client-side call sites still resolve a legacy `kits:` reference list against MaterializeWorkspaceKitsForPersist, but source it from outside this type now (cmd/workspace.go's ensureWorkspaceExistsForAssign extracts it from the raw shadow yaml; cmd/project_migrate.go folds its own auto-generated legacy kit's fields in directly, without any kit list at all) — see those call sites for why.

func DecodeWorkspaceCreateStrict added in v0.0.13

func DecodeWorkspaceCreateStrict(data []byte) (slug string, meta *WorkspaceMeta, err error)

DecodeWorkspaceCreateStrict strictly decodes a POST /api/workspaces create body into its target slug and WorkspaceMeta. An empty body decodes to an empty slug (the caller is expected to reject that with "slug is required") and a zero-value WorkspaceMeta, mirroring DecodeWorkspaceMetaStrict's empty-body handling. A second "---"-delimited document is rejected too (MINOR 2, codex review round 2) — see RejectTrailingYAMLDocument.

func DecodeWorkspaceMetaStrict added in v0.0.13

func DecodeWorkspaceMetaStrict(data []byte) (*WorkspaceMeta, error)

DecodeWorkspaceMetaStrict strictly decodes a workspace meta YAML document (as used by PUT /api/workspaces/{slug} — the whole-document replace body). An empty/whitespace-only body decodes to a zero-value WorkspaceMeta rather than erroring on io.EOF: a body-less create/edit is a legitimate way to declare an empty workspace. A typo'd or unknown field (top-level or nested inside additional_bindings/capabilities) is rejected with an error naming the offending field. A second "---"-delimited document is rejected too (MINOR 2, codex review round 2) — see RejectTrailingYAMLDocument.

type WorkspaceRepository added in v0.0.13

type WorkspaceRepository struct {
	// contains filtered or unexported fields
}

WorkspaceRepository provides DB-backed CRUD for WorkspaceMeta against the `workspaces` table (internal/db/migrate/migrations/0030_add_workspaces_table.sql). It is the authority WorkspaceStore delegates to once MigrateWorkspaceYAMLToDB has cut over (docs/plans/workspace-db-consolidation.md PR3): the yaml files under DefaultWorkspaceDir() become a read-only shadow kept for rollback/export, and this repository becomes the read/write path.

func NewWorkspaceRepository added in v0.0.13

func NewWorkspaceRepository(conn *sql.DB) *WorkspaceRepository

NewWorkspaceRepository returns a WorkspaceRepository backed by conn.

func (*WorkspaceRepository) Create added in v0.0.13

func (r *WorkspaceRepository) Create(slug string, meta *WorkspaceMeta) error

Create inserts a brand-new workspace row at slug. Unlike Save, this is insert-only: a slug that already has a row is rejected with an error wrapping os.ErrExist (docs/plans/workspace-db-consolidation.md Step A — the API layer maps this to HTTP 409 for POST /api/workspaces) rather than silently overwriting it. The plain INSERT (no ON CONFLICT clause) makes SQLite itself the source of truth for the conflict, so a concurrent creator racing this call is still caught by the UNIQUE constraint on workspaces.slug rather than a separate (racy) existence check.

func (*WorkspaceRepository) EnsureDefault added in v0.0.13

func (r *WorkspaceRepository) EnsureDefault() error

EnsureDefault inserts an empty row for DefaultWorkspaceSlug if none exists yet. It is safe to call repeatedly: an existing default workspace (with or without user edits) is left untouched.

func (*WorkspaceRepository) List added in v0.0.13

func (r *WorkspaceRepository) List() ([]string, error)

List returns every configured workspace slug, sorted alphabetically.

func (*WorkspaceRepository) Load added in v0.0.13

func (r *WorkspaceRepository) Load(slug string) (*WorkspaceMeta, error)

Load reads and decodes the WorkspaceMeta for the given slug. Returns an error wrapping os.ErrNotExist when no row exists — matching WorkspaceStore.Load's contract so callers do not need to branch on which backing store is in use.

func (*WorkspaceRepository) LoadWithRevision added in v0.0.13

func (r *WorkspaceRepository) LoadWithRevision(slug string) (*WorkspaceMeta, string, error)

LoadWithRevision reads meta and its revision (updated_at, formatted the same way GetWorkspaceSummary/ListWorkspaces do) from a single row — docs/plans/workspace-db-consolidation.md MAJOR 1 (codex review): GET /api/workspaces/{slug} previously read meta (this method's SELECT) and revision (a separate GetWorkspaceSummary query) as two round trips, which could straddle a concurrent PUT and return a meta/revision pair that never coexisted in the DB. Returns an error wrapping os.ErrNotExist when no row exists for slug, matching Load's contract.

func (*WorkspaceRepository) Remove added in v0.0.13

func (r *WorkspaceRepository) Remove(slug string) error

Remove deletes the workspace row for slug. The reserved DefaultWorkspaceSlug cannot be removed (docs/plans/workspace-db-consolidation.md 「default workspace の実装詳細」). Any project currently assigned to slug is re-pointed at DefaultWorkspaceSlug in the same transaction as the delete, so a project never ends up referencing a workspace that no longer exists. Returns an error wrapping os.ErrNotExist when no row exists for slug.

func (*WorkspaceRepository) Save added in v0.0.13

func (r *WorkspaceRepository) Save(slug string, meta *WorkspaceMeta) error

Save upserts meta at slug: INSERT if the slug has no row yet, or overwrite every column in place if it does. updated_at is always bumped to the current time.

func (*WorkspaceRepository) UpdateIfRevisionMatches added in v0.0.13

func (r *WorkspaceRepository) UpdateIfRevisionMatches(slug string, expectedRevision string, meta *WorkspaceMeta) (newRevision string, matched bool, err error)

UpdateIfRevisionMatches performs a compare-and-swap update: meta at slug is written only if the row's current revision (updated_at) equals expectedRevision, atomically with the check, via a single UPDATE statement (docs/plans/workspace-db-consolidation.md MAJOR 1, codex review). This closes the PUT race the previous "read revision, then Save unconditionally" two-step had: two concurrent PUTs against the same starting ETag could otherwise both pass their (separate-query) If-Match check and both Save, silently losing one writer's update; likewise a DELETE landing between a GET and a subsequent PUT could no longer be resurrected by an upsert-based Save.

matched=false covers three cases the caller cannot tell apart from this return value alone: slug has no row at all, slug exists but its current revision differs from expectedRevision, or expectedRevision is not even a well-formed revision string (e.g. a client-supplied If-Match that was never a real ETag this server issued) — the last case is deliberately folded into "no match" rather than a hard error, since a malformed value trivially can never equal the real (always well-formed) current revision; this keeps the HTTP mapping a plain 412, not a spurious 500, for a garbage If-Match header. ProjectAppService.UpdateWorkspace distinguishes "no row" from the other two with a follow-up existence check (404 vs 412) — see its doc comment.

On success, returns the freshly bumped revision (formatted the same way as LoadWithRevision/GetWorkspaceSummary) so the caller can hand it back to the client as the new ETag without a second read.

type WorkspaceStore added in v0.0.8

type WorkspaceStore struct {
	// contains filtered or unexported fields
}

WorkspaceStore provides persistence for WorkspaceMeta values.

Two backing modes (docs/plans/workspace-db-consolidation.md PR3 cutover):

  • repo == nil: legacy yaml mode. Each workspace is read/written as a YAML file at <dir>/<slug>.yaml. This is the pre-cutover behavior, kept as-is for callers that never wire a repository — e.g. the CLI (cmd/workspace.go and friends still read/write the yaml files directly; PR4 switches them to the API) and MigrateWorkspaceYAMLToDB's own preflight, which needs to read the legacy yaml as the migration's source of truth.
  • repo != nil (set via SetRepository / NewWorkspaceStoreWithRepo): DB mode. Every method delegates to repo instead of touching dir. dir is retained on the struct only as the (now-shadow) yaml location; PR3 does not delete or read it once a repository is wired.

Every method's signature is unchanged from the yaml-only era so existing callers (cmd/workspace.go, cmd/project_migrate.go, cmd/kit.go, cmd/kit_cleanup.go, dispatcher.WorkspaceLookup) need zero code changes — only daemon wiring (internal/server/wire.go) opts into DB mode by calling SetRepository.

func NewWorkspaceStore added in v0.0.8

func NewWorkspaceStore(dir string) *WorkspaceStore

NewWorkspaceStore returns a yaml-mode WorkspaceStore backed by dir. If dir is empty, DefaultWorkspaceDir is called to determine the directory. The directory is not created eagerly; it is created on the first Save call. Call SetRepository afterward (or use NewWorkspaceStoreWithRepo) to switch this store into DB mode.

func NewWorkspaceStoreWithRepo added in v0.0.13

func NewWorkspaceStoreWithRepo(dir string, repo *WorkspaceRepository) *WorkspaceStore

NewWorkspaceStoreWithRepo returns a DB-mode WorkspaceStore: dir is kept only as the shadow yaml location, and every method delegates to repo.

func (*WorkspaceStore) Create added in v0.0.13

func (s *WorkspaceStore) Create(slug string, meta *WorkspaceMeta) error

Create writes a brand-new workspace at slug, insert-only: a slug that already exists (as a DB row in DB mode, or a yaml file in yaml mode) is rejected with an error wrapping os.ErrExist rather than silently overwritten (docs/plans/workspace-db-consolidation.md Step A — the API's POST /api/workspaces create endpoint relies on this to return HTTP 409).

func (*WorkspaceStore) EnsureDefault added in v0.0.8

func (s *WorkspaceStore) EnsureDefault() error

EnsureDefault writes an empty WorkspaceMeta to the DefaultWorkspaceSlug path if no file exists yet. It is safe to call repeatedly and a no-op once the file exists (the existing content — including user edits — is left untouched). Returns nil when the workspace dir cannot be determined yet (DefaultWorkspaceDir failure): callers are expected to surface that via the first Load/Save attempt rather than at boot.

func (*WorkspaceStore) List added in v0.0.8

func (s *WorkspaceStore) List() ([]string, error)

List returns the slug of every workspace stored in the directory, sorted alphabetically. If the directory does not exist, an empty slice and nil error are returned (degraded window).

func (*WorkspaceStore) Load added in v0.0.8

func (s *WorkspaceStore) Load(slug string) (*WorkspaceMeta, error)

Load reads and parses the WorkspaceMeta for the given slug. Returns an error wrapping os.ErrNotExist when the file does not exist.

In DB mode (repo != nil) this delegates straight to repo.Load and never falls back to the yaml file at <dir>/<slug>.yaml. PR3's cutover had a transitional yaml fallback here (a not-found DB row fell back to reading the legacy yaml file) because the daemon had no post-cutover create path yet — a workspace yaml dropped into the workspaces dir *after* daemon startup (missed by MigrateWorkspaceYAMLToDB's one-time migration) would otherwise silently degrade (capabilities/kits/env not injected). PR4 removes that fallback now that POST /api/workspaces (and cmd/workspace.go's `boid workspace assign` auto-create) gives every caller a real way to introduce a DB row outside the migration path — the yaml files under DefaultWorkspaceDir() are now purely a rollback/export shadow (decision 16), never read by DB-mode Load again.

func (*WorkspaceStore) LoadWithRevision added in v0.0.13

func (s *WorkspaceStore) LoadWithRevision(slug string) (*WorkspaceMeta, string, error)

LoadWithRevision reads meta and its revision from a single atomic snapshot in DB mode (docs/plans/workspace-db-consolidation.md MAJOR 1, codex review) — see WorkspaceRepository.LoadWithRevision's doc comment for why this matters. Yaml mode (repo == nil) has no revision concept, so it falls back to plain Load with an empty revision string.

func (*WorkspaceStore) Remove added in v0.0.8

func (s *WorkspaceStore) Remove(slug string) error

Remove deletes the YAML file for the given slug. Returns an error wrapping os.ErrNotExist when the file does not exist. The reserved DefaultWorkspaceSlug cannot be removed. It does not check whether any project references this workspace.

func (*WorkspaceStore) Save added in v0.0.8

func (s *WorkspaceStore) Save(slug string, meta *WorkspaceMeta) error

Save atomically writes meta as YAML to <dir>/<slug>.yaml. The directory is created with mode 0755 if it does not exist. The write is atomic: the data is first written to a temporary file in the same directory and then renamed into place.

func (*WorkspaceStore) SetRepository added in v0.0.13

func (s *WorkspaceStore) SetRepository(repo *WorkspaceRepository)

SetRepository wires repo as this store's DB backing (docs/plans/workspace-db-consolidation.md PR3 cutover). Once set, every method routes through repo instead of the yaml directory.

func (*WorkspaceStore) UpdateIfRevisionMatches added in v0.0.13

func (s *WorkspaceStore) UpdateIfRevisionMatches(slug string, expectedRevision string, meta *WorkspaceMeta) (newRevision string, matched bool, err error)

UpdateIfRevisionMatches performs the CAS update described on WorkspaceRepository.UpdateIfRevisionMatches in DB mode. Yaml mode (repo == nil) has no revision concept to enforce — it always reports matched=true and performs an unconditional Save, i.e. the same non-CAS overwrite semantics this mode's plain Save has always had.

type WorkspaceSummary

type WorkspaceSummary struct {
	ID           string `json:"id"`
	ProjectCount int    `json:"project_count"`
	// Revision is an opaque ETag-like token derived from the workspaces row's
	// updated_at column (RFC3339), used by the PUT /api/workspaces/{slug}
	// If-Match optimistic-concurrency check (docs/plans/
	// workspace-db-consolidation.md decision 17). Empty when the summary was
	// built from a project_workspaces reference with no corresponding
	// workspaces row (should not happen once PR4's ListWorkspaces query is
	// workspaces-table-based, but callers should not assume non-empty).
	Revision string `json:"revision,omitempty"`
}

func GetWorkspaceSummary added in v0.0.13

func GetWorkspaceSummary(dbtx db.DBTX, slug string) (*WorkspaceSummary, error)

GetWorkspaceSummary returns a single workspace's summary (project count + revision), or an error wrapping os.ErrNotExist when slug has no corresponding workspaces row. Used by the workspace API handlers (docs/plans/workspace-db-consolidation.md PR4) to build the create/show/update response and to read the current revision for the PUT If-Match check.

func ListProjectWorkspaceReferences added in v0.0.13

func ListProjectWorkspaceReferences(dbtx db.DBTX) ([]*WorkspaceSummary, error)

ListProjectWorkspaceReferences returns the distinct workspace_id values referenced by any project_workspaces row, with the count of projects referencing each — the pre-PR4 query ListWorkspaces used to run. Unlike ListWorkspaces (workspaces-table-based as of Step B, docs/plans/ workspace-db-consolidation.md), this reflects project_workspaces membership directly and surfaces a reference to a slug that has no corresponding workspaces row at all. That distinction matters exactly once: workspace_migration.go's preflight runs *before* the workspace_db_consolidation migration has written anything to the workspaces table, and needs to detect a project referencing a slug with no legacy yaml file backing it (a broken reference) — which the workspaces-table-based ListWorkspaces would silently miss, since a nonexistent workspaces row simply never appears in a LEFT JOIN FROM workspaces. No other caller should need this function once the migration is long past (dispatch and the API both go through ListWorkspaces).

func ListWorkspaces

func ListWorkspaces(dbtx db.DBTX) ([]*WorkspaceSummary, error)

ListWorkspaces returns every workspace known to the workspaces table, each annotated with its assigned project count and a Revision token (docs/plans/workspace-db-consolidation.md Step B). The query is workspaces-table-based with project_workspaces LEFT JOINed in, so a workspace with zero assigned projects still appears (ProjectCount=0) — unlike the pre-PR4 query, which GROUP-BY'd project_workspaces directly and could only ever surface a slug that at least one project referenced.

type WorkspaceWatchdog added in v0.2.4

type WorkspaceWatchdog struct {
	WorkspaceID         string
	LastIngestSuccessAt *time.Time
	LastTriageReviewAt  *time.Time
}

WorkspaceWatchdog is the queue の決定論的評価 節 rule 7 (沈黙の検知) primitive: per-workspace timestamps of "最終 ingestion 成功" and "最終棚卸し実施". Both are nil when never recorded — that IS a breach for any positive threshold (a workspace that has never ingested anything is exactly the "沈黙" this rule exists to catch).

This is a mechanism only (PR-3 scope, docs/plans/cross-project-issue-triage.md PR-3 instructions): ingestion (PR-4) does not exist yet, so nothing currently calls TouchWorkspaceIngestSuccess in production. The primitive (table + accessors + threshold evaluator) is built now so PR-4's ingestion task has somewhere to write, and so the queue view can already render guidance for last_triage_review_at (which nothing blocks starting to use today, unlike ingestion).

func GetWorkspaceWatchdog added in v0.2.4

func GetWorkspaceWatchdog(dbtx db.DBTX, workspaceID string) (*WorkspaceWatchdog, error)

GetWorkspaceWatchdog returns the watchdog row for workspaceID, or a zero-value (both timestamps nil) when no row exists yet — a workspace with no recorded activity at all is a valid, meaningful state for WatchdogGuidance to evaluate, not an error.

Directories

Path Synopsis
Package refname generates random "adjective_noun" style names for task refs.
Package refname generates random "adjective_noun" style names for task refs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL