orchestrator

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 33 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) — because the pending/executing/awaiting statuses and the parked/working/done/dropped card statuses share only their terminal statuses and never reach each other. An ordinary task is a session-bearing subject (its status tracks a sandboxed process); a card is a judgment ledger khi and nose read and annotate, never running a session of its own.

The entity itself is not split — a card's children are ordinary tasks, and action log / timeline / Web UI / notify all share one representation. 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.

Index

Constants

View Source
const (
	DefaultActionListLimit = 200
	MaxActionListLimit     = 1000
)

DefaultActionListLimit / MaxActionListLimit bound a single BoidOpActionList call's row count — not its response size. MaxActionListLimit (1000) × each action's own payload cap (MaxContentBytes = 64KiB, content_size.go) puts the mathematical worst case at ~64MB, but real payloads are far smaller in practice, keeping a 1000-row response small today. Revisit (tighten the row cap, or add a real response-byte budget) once a workspace is actually driving this op at scale.

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系統。人間が押した action と代行タスクが押した action を actions ログ上で区別できないと、事故ったときに「人間の判断ミスか代行タスクの誤判定か」 が復元不能になる。

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

Child status vocabulary for task_triage.detail.children. Status progresses open → specced → dispatched → closed (task-ifying "specced" into "dispatched" — see TaskWorkflowService.Dispatch).

View Source
const (
	CardRequestOriginHuman = "human"
	CardRequestOriginEvent = "event"
)

CardRequestOriginHuman/Event are the two values a card_requests row's origin can report — see CardRequestOrigin.

View Source
const (
	ActionTypeCommandFinished      = "command_finished"
	ActionTypeCommandFailed        = "command_failed"
	ActionTypeCommandForceReleased = "command_force_released"
)

ActionTypeCommandFinished/Failed/ForceReleased are the card action-log entries FinishCardRequest/FailCardRequest/ForceReleaseCardRequest self-record — see recordCardRequestOutcome.

View Source
const (
	CardRequestTargetKindTask    = "task"
	CardRequestTargetKindSession = "session"
)

CardRequestTargetKind vocabulary — the kind of continuation a launcher created.

View Source
const (
	// ActionTypeCardCreated marks a card's own creation.
	ActionTypeCardCreated = "created"
	// ActionTypeCardEdited marks a card's own title/description having been
	// replaced. One edit is one record — the unit is the operation, not the
	// field — and the payload names the fields, never their bodies.
	ActionTypeCardEdited = "edited"
	// ActionTypeIdentityLinked marks one identity having been bound to a card.
	ActionTypeIdentityLinked = "identity_linked"
	// ActionTypeIdentityUnlinked marks one identity having been released from
	// a card.
	ActionTypeIdentityUnlinked = "identity_unlinked"
)

The daemon's self-recorded card state changes: creation, a content edit and an identity binding each mutate a card outside the action log's reach (the task row, the identity index), so each writes one of these alongside the mutation, in the same transaction.

View Source
const (
	CardEditedFieldTitle       = "title"
	CardEditedFieldDescription = "description"
)

CardEditedField is ActionTypeCardEdited's closed field vocabulary.

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

CardMachineName / ExecutionMachineName are the StateMachine.Name values NewCardMachine/NewExecutionMachine stamp, so a caller (api.ApplyAction) can tell which machine a task resolved to without re-deriving machineFor's sidecar-row judgment — comparing sm.Name against this constant is that check.

View Source
const (
	OperationResultAccepted = "accepted"
	OperationResultStarted  = "started"
	OperationResultRejected = "rejected"
	OperationResultUnknown  = "unknown"

	OperationReasonRequestAccepted                  = "request_accepted"
	OperationReasonExecutionStarted                 = "execution_started"
	OperationReasonSlotOccupied                     = "slot_occupied"
	OperationReasonNotAvailable                     = "not_available"
	OperationReasonInvalidRequest                   = "invalid_request"
	OperationReasonNotFound                         = "not_found"
	OperationReasonConflict                         = "conflict"
	OperationReasonInternalError                    = "internal_error"
	OperationReasonNoReadyWork                      = "no_ready_work"
	OperationReasonRequestFailed                    = "request_failed"
	OperationReasonTargetStarted                    = "target_started"
	OperationReasonOutcomePending                   = "outcome_pending"
	OperationReasonSuggestionAcceptedLaunchRejected = "suggestion_accepted_launch_rejected"
	OperationReasonSuggestionAcceptedLaunchUnknown  = "suggestion_accepted_launch_unknown"
)
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"

	// Task-context RPCs.
	OpBoidTaskCurrent      = "task_current"
	OpBoidTaskInstructions = "task_instructions"
	OpBoidTaskEnv          = "task_env"
	OpBoidTaskPayload      = "task_payload"

	// Attachments RPCs.
	OpBoidTaskAttachmentsList = "task_attachments_list"
	OpBoidTaskAttachmentsGet  = "task_attachments_get"

	// job_done payload_patch direct-pass RPC.
	OpBoidTaskUpdatePayloadPatch = "task_update_payload_patch"

	// OpBoidProjectBehaviors backs `boid project behaviors` from inside the sandbox.
	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: the read half of "daemon is the sole source
	// of state truth".
	OpBoidCardGet  = "card_get"
	OpBoidCardList = "card_list"

	// OpBoidTaskIdentityLink / OpBoidTaskIdentityUnlink / OpBoidTaskIdentityResolve
	// back `boid task identity link/unlink/resolve` from inside the
	// sandbox: 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: 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
	// identity ops above.
	OpBoidTaskResolveOrCapture = "task_resolve_or_capture"

	// OpBoidActionList backs `boid action list` from inside the sandbox:
	// 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 — 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. 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): these are granted only via a
	// connector-scoped reduced policy.
	OpBoidSignalIngest    = "signal_ingest"
	OpBoidSignalCursorGet = "signal_cursor_get"

	// OpBoidCardContext backs `boid card context` from inside the sandbox —
	// part of the general boidPolicy: any job may ask for its own card
	// context, and one with none set gets a clear error rather than a
	// permission denial (see sandbox.BoidOpCardContext's own doc comment).
	OpBoidCardContext = "card_context"

	// OpBoidAgentStart backs `boid agent start` from inside the sandbox —
	// part of the general boidPolicy, same reasoning as OpBoidCardContext:
	// any job may attempt it, and the executor itself rejects one with no
	// card context (or an event-originated one) rather than a policy-level
	// permission denial (see sandbox.BoidOpAgentStart's own doc comment).
	OpBoidAgentStart = "agent_start"

	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 but its
	// project.yaml/bare-repo could not be loaded — see ProjectStatus.Message
	// for why.
	StatusDegraded = "degraded"
)
View Source
const (
	DefaultSignalListLimit = 200
	MaxSignalListLimit     = 1000
)

DefaultSignalListLimit / MaxSignalListLimit bound ListSignals/ClaimSignals row counts, mirroring action_list.go's Default/MaxActionListLimit.

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 a tradeoff surfaced by --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 CardRequestCommandKeyGo = "__go__"

CardRequestCommandKeyGo is the reserved command_key value for a request whose origin is the shared work-execution slot (Go) rather than a project.yaml card_commands entry. ValidateCardCommands rejects an empty card_commands key at load time, so this sentinel never collides with a real one; ReconcileLaunchingCardRequests uses it as its skip predicate.

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

MaxContentBytes bounds `description` and action payload content: content exceeding it is rejected with an error rather than silently truncated, since a head/agent-originated source has no external original to recover from a truncation. 64 KiB gives roughly 4.2x margin over measured description content and 2.9x over measured action payload content — see docs/plans/ingestion-identity.md §13 A-5 for the full measurement data and the rationale for sharing one constant across both fields.

Applied at every content-entry point (task_create/task_update/ BoidOpTaskResolveOrCapture for description; action_send and task_notify.go's progress/done_request/fail_request for action payload) — any entry point that skips ValidateContentSize is a bypass, so a new write path must always call it.

View Source
const MaxSignalAttempts = 5

MaxSignalAttempts is the retry ceiling before a signal is considered dead. 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.

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`: 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 (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: 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 (
	// ErrCardRequestNotFound: no card_requests row with the given id.
	ErrCardRequestNotFound = errors.New("card request: not found")
	// ErrCardRequestSlotOccupied: idx_card_requests_active_unique rejected
	// giving a card a second launching-or-attached row.
	ErrCardRequestSlotOccupied = errors.New("card request: card's single execution slot is already occupied")
	// ErrCardRequestDuplicateCause: idx_card_requests_cause_unique_non_failed
	// rejected a cause_id already recorded on another non-failed row.
	ErrCardRequestDuplicateCause = errors.New("card request: cause id already recorded (redelivery)")
	// ErrCardRequestInvalidTransition: the row is not in a status the
	// requested transition accepts from.
	ErrCardRequestInvalidTransition = errors.New("card request: invalid status transition")
	// ErrNoQueuedCardRequests is ClaimQueuedCardRequests' sentinel for "this
	// card has nothing queued right now".
	ErrNoQueuedCardRequests = errors.New("card request: no queued requests for card")
	// ErrCardRequestOwnerMismatch: AttachCardRequestOwned's caller-asserted
	// launcher_job_id did not match the row's CURRENT owner (re-read after
	// the owner-scoped UPDATE affected zero rows) — a genuine ownership
	// violation, distinct from ErrCardRequestInvalidTransition (which also
	// covers the idempotent-retry case where the row is already correctly
	// attached to the SAME caller's own target). Callers must not treat this
	// as a retry-converges outcome.
	ErrCardRequestOwnerMismatch = errors.New("card request: caller is not the request's current owner")
)
View Source
var (
	// ErrCardNotEligibleForDispatch: the card is not parked/working at claim
	// time. Every currently-queued request for it is drained (failed) rather
	// than left queued — see ClaimQueuedCardRequestsForDispatch's doc
	// comment for why leaving them queued would loop forever.
	ErrCardNotEligibleForDispatch = errors.New("card request: card is not parked or working; automatic dispatch skipped")
	// ErrCardForceReleaseBarrierActive: an operator force-released this
	// card and no human operation (a command, Go, or an explicit retry) has
	// cleared the barrier yet. The queued request is left untouched.
	ErrCardForceReleaseBarrierActive = errors.New("card request: card was force-released; automatic dispatch is suppressed until a human operation")
	// ErrCardRequestCommandKeyChanged: the caller resolved a command
	// definition for one command_key, but the card's oldest queued request
	// now carries a different one — the caller must re-resolve and retry.
	ErrCardRequestCommandKeyChanged = errors.New("card request: queued head's command_key changed since it was resolved")
)
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) is the primary enforcement point; this is defense in depth at the query itself.

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 ErrIdentityBindingChanged = errors.New("identity binding changed")

ErrIdentityBindingChanged means metadata could not be written because the identity is no longer bound to the task the caller resolved. Metadata writes deliberately include the expected task id so an unlink/relink race cannot decorate a different task's binding.

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, 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).

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, so a DELETE landing between a separate existence check and the assign cannot leave a dangling project_workspaces reference. conn 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 AttachCardRequest added in v0.5.0

func AttachCardRequest(dbtx db.DBTX, id, targetKind, targetID string) error

AttachCardRequest records the continuation (task or session) a launcher created, transitioning launching → attached. Only valid from launching; attaching twice is rejected rather than re-pointing the target.

No caller identity is asserted here — reserved for the reconcile/recovery paths (attachFoundContinuationOrFail) that establish the continuation's legitimacy some OTHER way (a DB-verified foreign-key match, not a caller-supplied claim). Any path that instead trusts a caller's own assertion of "I am the launcher" — BoidOpTaskCreate, BoidOpAgentStart — MUST use AttachCardRequestOwned instead, so that assertion is re-checked fresh in the same statement that writes, not read separately beforehand and trusted stale.

func AttachCardRequestOwned added in v0.5.0

func AttachCardRequestOwned(dbtx db.DBTX, id, expectedLauncherJobID, targetKind, targetID string) error

AttachCardRequestOwned is AttachCardRequest with the caller's claimed launcher_job_id asserted directly in the UPDATE's WHERE clause, instead of trusting a separate, earlier GetCardRequest read of it. Closes the window where a force-release followed by a different launcher's reclaim, landing between that earlier read and this write, would otherwise let the stale caller's attach steal the new owner's slot (the row is "launching" again by then, just under a different launcher_job_id — a plain status check alone cannot tell the two apart).

Returns ErrCardRequestOwnerMismatch when the row's CURRENT launcher_job_id differs from expectedLauncherJobID — a real ownership violation. Returns ErrCardRequestInvalidTransition (same as AttachCardRequest) for every other zero-rows-affected case, INCLUDING the row already being attached to expectedLauncherJobID's own earlier attach — callers rely on that distinction to keep an idempotent retry converging (re-read and compare target) without misclassifying it as a stolen slot.

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 ("<data_dir>/repos/<workspace-slug>/<project-name>.git/"). dataDir is the daemon's data-home (~/.local/share/boid equivalent).

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. 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 CardExecutionStatesByIDs added in v0.5.0

func CardExecutionStatesByIDs(dbtx db.DBTX, cardIDs []string) (map[string]CardExecutionState, error)

CardExecutionStatesByIDs reads one page in a single consistent SQL snapshot. UNION (not UNION ALL) bounds traversal even if parent links contain a cycle. A command's task target may not have parent_id set, so it is also a seed.

func CardRequestOrigin added in v0.5.0

func CardRequestOrigin(causeID string) string

CardRequestOrigin derives a card_requests row's origin from its cause_id — the one rule both `boid card context` (server.cardRequestOrigin) and this package's own self-record share, so a future change to it cannot update one call site and leave the other behind.

func ClaimQueuedCardRequests added in v0.5.0

func ClaimQueuedCardRequests(dbtx db.DBTX, cardID, launcherJobID string, def CardRequestDefinition) (primary *CardRequest, folded []*CardRequest, err error)

ClaimQueuedCardRequests snapshots every currently-queued request for cardID (oldest first), promotes the oldest to launching (claiming the card's shared slot) while atomically stamping launcherJobID as its owner, and folds the rest into it (status=folded, folded_into=primary.id). A request created after this snapshot is not part of it and stays queued for the next claim.

launcherJobID must be non-empty: stamping it in the SAME statement that promotes the row to launching is what closes the window where a row could sit launching with no launcher of record (see BoidOpAgentStart's ownership check, which now rejects an empty LauncherJobID rather than treating it as unclaimed).

Returns ErrNoQueuedCardRequests when cardID has no queued requests. Returns ErrCardRequestSlotOccupied if another row for this card is already launching/attached.

Must be called within a transaction for atomicity (multiple statements).

func ClaimQueuedCardRequestsForDispatch added in v0.5.0

func ClaimQueuedCardRequestsForDispatch(dbtx db.DBTX, cardID, launcherJobID, expectedCommandKey string, def CardRequestDefinition) (primary *CardRequest, folded []*CardRequest, err error)

ClaimQueuedCardRequestsForDispatch is ClaimQueuedCardRequests plus two guards automatic dispatch needs on top of what a human command/Go already enforce for themselves: the card must currently be parked/working (otherwise every queued request for it is drained instead), and no active force-release barrier may be blocking it. Returns ErrCardRequestCommandKeyChanged if the queued head's command_key no longer matches expectedCommandKey by the time this runs.

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 — the explicit half of the read/claim split: `boid signal list` reads with no side effect, `boid signal claim <id>...` says which rows were actually handed to a judgment (unlike ClaimSignals, which charges every row a consumer's read merely returned, even ones it never judged).

Same typo guard and all-or-nothing failure as AckSignals. An already-acked row is not charged but is not an error either.

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 ClearCardForceReleaseBarrier added in v0.5.0

func ClearCardForceReleaseBarrier(dbtx db.DBTX, cardID string) error

ClearCardForceReleaseBarrier removes cardID's barrier, if any. Idempotent — clearing an already-clear barrier is not an error.

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):

  • "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 because it is not a "touch boid state" capability this 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. Every connector job's in-container runner posts `boid job done` to report its own completion (the same mechanism every other non-foreground job relies on); omitting it from AllowedOps makes the broker reject that call, and the daemon's "runtime exited without boid job done" fallback then forces every connector run's real (successful) exit_code=0 into a recorded exit_code=1/JobStatusFailed.
  • NO "fetch" entry at all: 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 CountActiveCardRequests added in v0.5.0

func CountActiveCardRequests(dbtx db.DBTX, cardID string) (int, error)

CountActiveCardRequests returns the number of card_requests rows currently occupying cardID's shared execution slot (launching or attached). In practice 0 or 1, since the unique index caps it.

func CountUnresolvedChildren added in v0.5.0

func CountUnresolvedChildren(detail json.RawMessage, liveChildren []*Task) (int, error)

CountUnresolvedChildren returns the number of children contending for a card's single work slot: every JSON child not yet task-ified (open/ specced) plus every non-terminal live task row, deduped by Ref against those JSON occupants exactly like acceptGo (internal/api/workflow_card.go) so a child's own task row is never counted as a second occupant.

Unlike DetailOpenSlotChildID (which only asks "is there ANY occupant"), this answers "how many", so a card that accumulated more than one before this invariant existed can be found and listed.

func CreateAction

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

CreateAction inserts a, then runs IngestCardEventRequest against its target card within the SAME transaction (queues a card_requests row; a genuine error fails this call — see its own doc comment). cardEvents may be nil, a quiet no-op then.

func CreateCardRequest added in v0.5.0

func CreateCardRequest(dbtx db.DBTX, req *CardRequest) error

CreateCardRequest inserts a new card_requests row. req.ID is generated when empty. req.Status must be "" (defaults to queued) or CardRequestStatusLaunching, for a caller that already knows the slot is free and wants to claim it in the same INSERT.

Returns ErrCardRequestSlotOccupied or ErrCardRequestDuplicateCause when the corresponding unique index rejects the insert.

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: 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.

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: 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: 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 (`git symbolic-ref --short 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 DefaultMetaprojectID added in v0.5.0

func DefaultMetaprojectID(workspace string) string

DefaultMetaprojectID is stable across restarts and distinct per workspace.

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. Has no production caller — kept for interface/test-double compatibility.

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: 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". 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 DetailOpenSlotChildID added in v0.5.0

func DetailOpenSlotChildID(detail json.RawMessage) (string, error)

DetailOpenSlotChildID returns the id of the first child in detail's "children" list whose status is open or specced — a child not yet task-ified — or "" if none exists. This is the JSON-only half of a card's single-work-slot check; a dispatched child is tracked by its own live task row instead (see workflow_card.go's cardSlotOccupied and task_create.go's cardChildSlotConflict, the two callers that combine this with a real-row check), not by this blob, so it is deliberately excluded here.

A card that already violates the invariant (legacy data predating this check) is not an error here: this returns whichever occupant it finds first, in list order. Enumerating every offending card for cleanup is a separate diagnostic (cmd's card multi-child report), not this function's job.

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), for a caller that needs MORE than the fixed Suggestion struct's four fields expose — e.g. accept(verb)'s params.wake_at/wake_task_id, a write-side addition Suggestion itself does not carry. 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.

A "dispatched" child is refused. That status is the daemon's own mechanical fact 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, not a creation-ordered sequence: two actions created in the same instant are otherwise indistinguishable by created_at alone, risking a silently skipped or re-delivered row. Ordering by (created_at, id) together, on both the SELECT's ORDER BY and the cursor's WHERE threshold, is the standard keyset-pagination technique for this tied-key case.

Real same-instant ties come from internal/dispatcher/store.go's markStaleTasksAborted, which takes one now := time.Now().UTC() outside its per-task loop and inserts N action rows sharing that exact value. See TestListActionsSince_TiedCreatedAt_PageBoundary_NoDuplicatesNoGaps for the reproduction.

func EnsureDefaultMetaprojects added in v0.5.0

func EnsureDefaultMetaprojects(conn *sql.DB, store *ProjectStore) error

EnsureDefaultMetaprojects creates repository-free receivers atomically. The workspace list is read inside the same transaction as membership creation. Called before presenting the Web creation form, including for new workspaces.

func ExistingTaskIDs added in v0.5.0

func ExistingTaskIDs(dbtx db.DBTX, ids []string) (map[string]bool, error)

ExistingTaskIDs returns the subset of ids that still resolve to a live task row, via one batched query — for a caller checking many task references for existence (e.g. GC-safety link resolution) without one round trip per id. Exact-id match only, no GetTask-style prefix fallback.

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. The aggregated host_commands.yaml config on disk stores raw/unexpanded definitions by design (see readKitHostCommandsRaw), but a raw `path: ${HOME}/bin/gh` is useless to exec.LookPath at dispatch time, so 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, while Server.HostCommands() keeps handing out the raw CloneHostCommandsMap snapshot unchanged.

raw is never mutated: the returned map is an independent deep copy (CloneHostCommandsMap) before interpolateHostCommands runs 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 FailCardRequest added in v0.5.0

func FailCardRequest(dbtx db.DBTX, id, errText string) error

FailCardRequest records a request's terminal failure from any non-terminal status, and releases anything folded into it back to queued so the next claim reconsiders them (an automatic failure carries no intent to stop the card — contrast ForceReleaseCardRequest). The failed row itself is kept for inspection/retry, not deleted.

Also self-records a command_failed action on the card's own action log (recordCardRequestTerminalOutcome) — see that function's own doc comment.

Must be called within a transaction for atomicity (two UPDATEs, plus the self-record's own INSERT).

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 FinishCardRequest added in v0.5.0

func FinishCardRequest(dbtx db.DBTX, id, result string) error

FinishCardRequest records a request's successful outcome — attached → finished — and closes out two related sets of rows in the same call: every request folded into id, and every OLDER still-failed request for the same card (a later success absorbs an earlier failure). "Older" is bounded by id's own created_at: id is always the oldest member of its own claim boundary (ClaimQueuedCardRequests promotes the oldest queued row), so a failed request created after id must belong to a LATER boundary this success never actually read, and is deliberately left alone.

Also self-records a command_finished action on the card's own action log (recordCardRequestTerminalOutcome) — see that function's own doc comment.

Only valid from attached. Must be called within a transaction for atomicity (a read plus three UPDATEs, plus the self-record's own INSERT).

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.

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 — 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 GCCardRequests added in v0.5.0

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

GCCardRequests deletes finished/failed card_requests rows older than olderThan. olderThan=0 disables the time filter. queued/launching/ attached/folded rows are never touched regardless of age.

func GCOperationResults added in v0.5.0

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

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 or dead-lettered (attempts >= MaxSignalAttempts) — and, when olderThan > 0, additionally old enough (acked_at, respectively received_at, before the cutoff). olderThan=0 disables only the age filter: a still-pending signal (unacked, attempts < MaxSignalAttempts) is never eligible for deletion regardless of olderThan — the structural gate protects it even on an unbounded sweep (deleting a pending row would strand it forever, since signal_cursors has already advanced past it).

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. olderThan=0 disables the time filter. In-flight rows (finished_at IS NULL) are never touched regardless of age.

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.

Contract: the cursor is exclusive of itself from the connector's point of view — a conformant connector drops anything with `occurred_at <= cursor` before calling `boid signal ingest`. This store just returns the opaque stored value; PK-based dedup in IngestSignals is a separate, independent safety net for exact-duplicate re-sends.

Known risk: if two sibling events share the exact same occurred_at and the cursor advances past that timestamp after only one is ingested, the connector's own `<= cursor` self-filter can silently drop the sibling forever. Pack authors working with tie-prone sources should add a secondary tiebreaker (e.g. id) in their own fetch logic.

func HasCardForceReleaseBarrier added in v0.5.0

func HasCardForceReleaseBarrier(dbtx db.DBTX, cardID string) (bool, error)

HasCardForceReleaseBarrier reports whether cardID currently has an active force-release barrier.

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. Dead signals never count, so a workspace with only dead-lettered signals does not fire its trigger forever.

func IngestCardEventRequest added in v0.5.0

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

IngestCardEventRequest is CreateAction's card-event ingest step: it queues a card_requests row for an eligible action.

A genuine failure here fails the caller's transaction — only ineligibility and ErrCardRequestDuplicateCause (redelivery) are no-ops; every other error propagates.

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) and then advances (workspace, service, connector)'s cursor to max(rows.OccurredAt), but only forward, never backward.

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.

func IsBareRepoDir added in v0.1.0

func IsBareRepoDir(dir string) bool

IsBareRepoDir reports whether dir looks like a daemon-managed bare git repository ("<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.

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 IsCardProject added in v0.5.0

func IsCardProject(meta *ProjectMeta) bool

IsCardProject uses the existing automatic-judgment contract. Existing metaprojects need no new marker or migration to appear in the creation form.

func IsCardRequestDispatchSkip added in v0.5.0

func IsCardRequestDispatchSkip(err error) bool

IsCardRequestDispatchSkip reports whether err from ClaimQueuedCardRequestsForDispatch is a legitimate "nothing claimed this time" outcome rather than a genuine failure.

func IsCardStateSelfRecord added in v0.5.0

func IsCardStateSelfRecord(actionType string) bool

IsCardStateSelfRecord reports whether actionType is one of them.

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 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 IsDefaultMetaproject added in v0.5.0

func IsDefaultMetaproject(p *Project) bool

IsDefaultMetaproject checks the whole managed identity, not a display name.

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), so this is only ever true for an execution task sitting in "pending" (avoiding races with in-flight handlers / post-execution mutations).

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: editable only in "parked", the card's resting/undecided state (a 整形セッション needs to edit these). parked is a card's INITIAL state (not merely a later "set aside" one), so excluding it would make every fresh card permanently uneditable.
  • Execution: editable only in "pending" (execution not yet started).

working is deliberately not editable: 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. 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) 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) 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).

func ListActiveCardRequestsByCardIDs added in v0.5.0

func ListActiveCardRequestsByCardIDs(dbtx db.DBTX, cardIDs []string) (map[string]*CardRequest, error)

ListActiveCardRequestsByCardIDs returns, for each id in cardIDs that has at least one currently queued/launching/attached card_requests row, the single one PickActiveCardRequest would choose — one query across every id (chunked like ExistingTaskIDs) rather than one per card, for a caller (the task list) enriching many rows at once. A cardID with no such row is simply absent from the result map.

func ListCardIDsWithQueuedCardRequests added in v0.5.0

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

ListCardIDsWithQueuedCardRequests returns every distinct card_id currently holding at least one queued card_requests row — the periodic dispatch sweep's work list (recovery for a missed immediate dispatch attempt).

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)). A taskID with no sidecar row is simply absent from the returned map — the same "missing means no enrichment" contract GetTaskTriage's sql.ErrNoRows expresses, just as map absence instead of a per-call error.

Best-effort across BOTH axes, so one malformed row cannot sink the whole call:

  • 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 — the map itself, not the error, is the thing to check for "did I get anything useful".

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. Parsing is strict at every level (top-level keys and each command's fields, including nested reject rules — see hostCommandSpecStrict) so a typo in a hand-edited file 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 or other kit.yaml validation runs on this path.

A missing kitsDir (no kits installed yet, or KitsDir unconfigured) is not an error: it returns an empty map.

Two kits may declare the same command name only when the definitions are identical after normalizeHostCommandSpec 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 should treat this as fatal.

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 — 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 — so a case this file's rule does not anticipate fails the export loudly, naming the key, instead of producing an unrestorable backup discovered only at restore time.

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) against the kits installed under kitsDir, merging their host_commands and env into meta in place — the same expansion MigrateWorkspaceYAMLToDB performs once at cutover. WorkspaceMeta has no Kits field of its own, so callers (e.g. cmd/workspace.go's ensureWorkspaceExistsForAssign) must source kitRefs themselves, typically from a raw on-disk legacy yaml. Without this expansion step, a workspace referencing a kit would silently lose that kit's host_commands/env on save, since the workspaces table has no column to carry an unresolved kit reference.

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 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 run.

Idempotent: once schema_migrations records this version 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, a mismatch aborts with an error requiring manual intervention rather than risk silently mixing old and new state.

The old workspace yaml files and kitsDir are never modified or deleted by this function.

func NormalizeCardVerb added in v0.5.0

func NormalizeCardVerb(verb string) string

NormalizeCardVerb maps a retired card-verb spelling to its current name; any other value, including an already-current name or a non-card-verb string, passes through unchanged. Callers apply this to a card-machine action type (or a suggestion's verb) BEFORE it reaches Apply/ IsManualAction/IsCardTransitionAction, so the rule table and the closed transition set only ever need to know the current spelling.

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 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.

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". Callers that go on to WRITE or DELETE at path based on this answer — SafeBareRepoPath below and internal/api's isManagedBareRepoPath — 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, 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 PeekOldestQueuedCardRequest added in v0.5.0

func PeekOldestQueuedCardRequest(dbtx db.DBTX, cardID string) (id, commandKey string, err error)

PeekOldestQueuedCardRequest reads cardID's oldest queued request's id and command_key without claiming it. Returns ErrNoQueuedCardRequests when cardID has nothing queued.

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 a silent multi-document drop: yaml.Decoder.Decode only ever consumes a single "---"-delimited document per call and silently ignores everything after it, so a hand-authored multi-document workspace yaml would have its second document silently dropped with no error. This calls dec on the same Decoder immediately after the real decode succeeded, expecting io.EOF (nothing left); any other outcome is reported as an error rather than silently discarded.

Exported so cmd/workspace.go's extractLegacyWorkspaceKitRefs can reuse the exact same trailing-document check on raw local workspace.yaml bytes.

func ReleaseCardRequestForTerminalTargetWithCard added in v0.5.0

func ReleaseCardRequestForTerminalTargetWithCard(dbtx db.DBTX, targetKind, targetID string, success bool) (found bool, cardID string, err error)

ReleaseCardRequestForTerminalTargetWithCard releases the attached card_requests row (if any) targeting (targetKind, targetID) the instant that target reaches a terminal state, instead of waiting for ReconcileCardRequestSlots' next tick — otherwise every occupancy check (cardSlotOccupied, cardSlotConflictWithRequests) keeps reporting the slot occupied for up to the reconcile interval after the real work already finished. found is false in the common case (most terminal tasks/jobs are not a card_requests continuation at all). Also returns the released row's own card_id, for a caller that wants to try an immediate dispatch of that card's queued backlog right after freeing its slot.

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.

func RequireUpstreamURL added in v0.0.10

func RequireUpstreamURL(project *Project) error

RequireUpstreamURL returns an error when project has no upstream_url captured. Intentionally NOT wired into any dispatch path yet — exposed and tested here as a ready-made building block for the future cutover where dispatch starts needing upstream_url to build the gateway clone URL.

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 RetryCardRequest added in v0.5.0

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

RetryCardRequest re-queues a failed request explicitly. Only valid from failed; clears the error, the previous launch-time snapshot, and the previous attempt's continuation target (a stale target/result must not survive onto the fresh attempt).

Also clears any force-release barrier on the request's card (ClearCardForceReleaseBarrier) — an explicit Retry lifts automatic- dispatch suppression the same as a fresh human command or Go.

func SafeBareRepoPath added in v0.1.0

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

SafeBareRepoPath is BareRepoPath with defense-in-depth validation applied: 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. 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. This defends against <dataDir>/repos/<workspaceSlug> ITSELF being replaced with a symlink to somewhere outside dataDir entirely: that's 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 would be circular). There is no loss of protection for the traversal-name case either: projectName is already constrained by ValidProjectName to a single clean path segment with no separators and no ".." anywhere, so a validated projectName can never affect which workspace's directory the result lands in regardless of which boundary this checks against.

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 SetCardForceReleaseBarrier added in v0.5.0

func SetCardForceReleaseBarrier(dbtx db.DBTX, cardID string) error

SetCardForceReleaseBarrier plants (or refreshes) cardID's barrier. Idempotent — setting it again while already set is not an error.

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). detail's shape is a schema-light JSON blob by design, so this round-trips through a map rather than a fixed Go struct to avoid silently dropping fields this 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. 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 (CreateTriggerRun's own doc comment describes the insert-then-dispatch split). 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

ShouldWake evaluates the wake rule 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.

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 — 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 is logAttrsSetOnDoneTriage (internal/api/attrs_set_done.go) — 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, and a khi resend of child_specced after an uncertain ack must never regress one of them back to "specced". 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 to forward each document's original field-presence exactly as written, one request per document: re-marshaling the decoded struct would lose the missing-vs-empty distinction, since a zero-value Go field marshals the same whether or not the source had that key at all. Round-tripping through yaml.Node avoids that: an absent key has no corresponding child node, so re-marshaling reproduces the source's exact key set.

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: 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. This keeps the invariant self-healing for any row that somehow still carries a stale copy.

func TaskStatusesByIDs added in v0.5.0

func TaskStatusesByIDs(dbtx db.DBTX, ids []string) (map[string]TaskStatus, error)

TaskStatusesByIDs batch-resolves task ids to their live status, chunked like ExistingTaskIDs — for a caller that needs many tasks' status (e.g. the task list's per-card work-child lookup) without one query per id. An id with no live row is simply absent from the result, not an error.

func TouchTaskUpdatedAt added in v0.4.0

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

TouchTaskUpdatedAt bumps id's updated_at column to now, without the stale-snapshot race a full UpdateTask(t) risks for non-transitioning side effects. See workflow_action.go's skipTaskUpdate doc comment.

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. An 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 (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 — 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 (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 UpdateIdentityMetadata added in v0.5.0

func UpdateIdentityMetadata(dbtx db.DBTX, projectID, identity, taskID string, urlValue, displayName *string) error

func UpdateTask

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

UpdateTask persists every mutable Task column. Keep this in sync with CreateTask's INSERT column list: a column missing here is a silent no-op.

ref and behavior are immutable after creation and intentionally excluded. The CardAttrs columns (kind/urgency/wake_at/wake_task_id/suggestion_verb/ detail) are also excluded — UpsertTaskTriage owns their read-modify-write exclusively; folding them in here would race with it.

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), this is only ever an UPDATE — every card row already has these columns from the moment CreateTask makes it type='card'. 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). 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. 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 ValidateCardCommands added in v0.5.0

func ValidateCardCommands(commands map[string]CardCommand, events CardEventsConfig) error

ValidateCardCommands checks a project.yaml card_commands: / card_events: declaration at load time, mirroring ValidateTriggers for triggers[].

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. Since the daemon runs in a container, the "host" a host command resolves against IS the daemon image — an image missing a tool like `gh` would silently break every dispatch that uses it 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: a missing command is reported by the caller (typically via slog.Warn — see internal/server.Server.New's call site), not treated as fatal. A missing command already fails lazily per-dispatch (ResolveHostCommands, host_commands.go); this check only surfaces the gap earlier, at boot.

Commands declared with an explicit relative Path (project-local scripts) 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) is checked via lookPath.

func ValidateIdentityURL added in v0.5.0

func ValidateIdentityURL(raw string) error

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 this watchdog rule 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 (人間は 「来ないこと」に気づけないため).

This is a pure function of (now, watchdog row, thresholds) — no agent judgment — that the queue view (or, later, a periodic notify sweep) can call directly. It does not itself persist or dedupe guidance items: a guidance item is meant to be 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 WithWriterCardRequestID added in v0.5.0

func WithWriterCardRequestID(ctx context.Context, id string) context.Context

WithWriterCardRequestID marks ctx as carrying a sandbox write's origin card_requests row id, stamped by ExecuteBoidBuiltin (internal/server/boid_executor.go) — the one call site every sandbox-originated write funnels through. id is "" for a write that is not a card-command launcher/continuation.

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 — used to guard against assigning a project to a slug that has no backing workspace row, which would leave a dangling project_workspaces reference nothing later self-heals.

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 WriterCardRequestIDFromContext added in v0.5.0

func WriterCardRequestIDFromContext(ctx context.Context) (id string, ok bool)

WriterCardRequestIDFromContext returns the card_requests row id WithWriterCardRequestID stamped, and whether ctx carries one at all.

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) のいずれか)。旧レコードは空文字 (移行前データ、または
	// 書き込み側が未対応)。
	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: 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 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 and for the "neither project
	// nor workspace given" fallback (TokenContext.AllowedProjectIDs). A
	// single query rather than one-call-per-project is deliberate: merging
	// cursor-paginated results across N separately-limited per-project
	// queries would need a real N-way merge, which a single IN(...) query
	// avoids entirely.
	ProjectIDs []string
	// WorkspaceID scopes via project_workspaces, matching ListTasks' own
	// WorkspaceID join (store.go). In practice mutually exclusive with
	// ProjectIDs, 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.
	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: at today's action volume, paging the full history from
	// scratch is a handful of calls, not a real cost.
	Since string
	// Limit is clamped internally via ClampActionListLimit — any value
	// (including 0 or negative) is accepted.
	Limit int
}

ActionListFilter scopes and paginates ListActionsSince.

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 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: 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: every project-visible job now 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: 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 — 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.
	SuggestionVerb string          `json:"suggestion_verb,omitempty"`
	Detail         json.RawMessage `json:"detail,omitempty"`
}

CardAttrs is the card-only field set. Every function below reads/writes the 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 — 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.

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.

type CardCommand added in v0.5.0

type CardCommand struct {
	// Label is the UI button text for this command, workspace-defined.
	Label string `yaml:"label" json:"label"`
	// Run is a command string passed to `sh -c` inside the project's sandbox.
	Run string `yaml:"run" json:"run"`
	// CardWrite grants this command's continuation the card-write permission
	// `boid card context` reports, independent of any task behavior's own
	// readonly. Optional, defaults to false — a command must opt in.
	CardWrite bool `yaml:"card_write,omitempty" json:"card_write,omitempty"`
}

CardCommand is one project.yaml `card_commands.<key>` entry: a label and a run command. Label and Run are required (ValidateCardCommands).

type CardEditedPayload added in v0.5.0

type CardEditedPayload struct {
	Fields []string `json:"fields"`
}

CardEditedPayload is ActionTypeCardEdited's payload.

type CardEventResolver added in v0.5.0

type CardEventResolver interface {
	CardEventCommand(projectID string) (commandKey string, ok bool)
}

CardEventResolver answers, for a project, the card_commands key its card_events.command declares — "" (ok=false) when it declares none.

type CardEventsConfig added in v0.5.0

type CardEventsConfig struct {
	// Command must name an existing CardCommands key when non-empty
	// (ValidateCardCommands).
	Command string `yaml:"command,omitempty" json:"command,omitempty"`
}

CardEventsConfig is ProjectMeta.CardEvents — project.yaml's `card_events:` block.

type CardExecutionState added in v0.5.0

type CardExecutionState struct {
	Occupied     bool
	NeedsInput   bool
	CommandLabel string
}

CardExecutionState summarizes a card's shared execution slot and input requests anywhere below it. Occupied includes launching and attached Go and command requests, but excludes queued requests.

type CardRequest added in v0.5.0

type CardRequest struct {
	ID         string
	CardID     string
	CommandKey string
	// CauseID's emptiness IS the origin signal downstream (empty = human,
	// non-empty = internal event — see cardContextResponse.Origin and
	// BoidOpAgentStart's event rejection). Every event-caused creation path
	// MUST set a non-empty CauseID, or it becomes indistinguishable from a
	// human request; this store cannot enforce that on a caller's behalf.
	CauseID string
	Status  CardRequestStatus
	// Instruction is the user's free-text input for this request. It lives
	// on the row from creation and stays untouched by
	// ClaimQueuedCardRequests/RetryCardRequest (those only ever reset the
	// launch-time snapshot), so a queued/folded request's input survives
	// until it is actually claimed.
	Instruction   string
	Launched      CardRequestDefinition
	LauncherJobID string
	TargetKind    string
	TargetID      string
	FoldedInto    string
	Result        string
	Error         string
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

CardRequest is one row of the card_requests table.

func GetCardRequest added in v0.5.0

func GetCardRequest(dbtx db.DBTX, id string) (*CardRequest, error)

GetCardRequest fetches a single card_requests row by id.

func GetCardRequestByTaskTarget added in v0.5.0

func GetCardRequestByTaskTarget(dbtx db.DBTX, taskID string) (*CardRequest, error)

GetCardRequestByTaskTarget finds the card_requests row whose continuation is taskID, if any. Returns (nil, nil) — not an error — when taskID is not a card-command continuation, so a caller can treat "no card context" as the ordinary case rather than special-casing a sentinel error.

func ListActiveCardRequests added in v0.5.0

func ListActiveCardRequests(dbtx db.DBTX) ([]*CardRequest, error)

ListActiveCardRequests returns every currently launching/attached card_requests row across EVERY card, oldest first — the bulk counterpart to ListCardRequestsByCard for a caller that needs "which cards have an active request" (e.g. `boid task diagnose-cards`) without issuing one query per card.

func ListCardRequestsByCard added in v0.5.0

func ListCardRequestsByCard(dbtx db.DBTX, cardID string) ([]*CardRequest, error)

ListCardRequestsByCard returns every card_requests row for cardID, oldest first — diagnostics / test inspection, not a hot path.

func PickActiveCardRequest added in v0.5.0

func PickActiveCardRequest(requests []*CardRequest) *CardRequest

PickActiveCardRequest chooses the single card_requests row that best represents a card's "currently in progress" command, by status priority (attached > launching > queued) rather than creation order — multiple non-terminal rows for one card ARE possible in practice; only launching/ attached are mutually exclusive at the database level, so an older queued row (e.g. an internal event request that arrived before a barrier lifted) can otherwise outlive a newer launching/attached one and must never mask it. Skips the shared work slot's own __go__ row — that is Go's work execution, not a card command.

type CardRequestByTaskLookup added in v0.5.0

type CardRequestByTaskLookup interface {
	GetCardRequestByTaskTarget(taskID string) (*CardRequest, error)
}

CardRequestByTaskLookup finds the card_requests row a task is the continuation of, if any.

type CardRequestDefinition added in v0.5.0

type CardRequestDefinition struct {
	CommandKey string
	Label      string
	Run        string
	// Version is an opaque caller-supplied marker (e.g. a hash of
	// label+run) callers may use to detect definition drift; the store
	// itself never interprets it.
	Version string
	// CardWrite is CardCommand.CardWrite, snapshotted the same instant as
	// Label/Run/Version. A CardRequestCommandKeyGo request never sets this.
	CardWrite bool
}

CardRequestDefinition is the command definition snapshotted onto a request the instant it transitions queued → launching, so a later project.yaml edit cannot retroactively change what this request ran.

type CardRequestLifecycleLoop added in v0.5.0

type CardRequestLifecycleLoop struct {
	DB           *sql.DB
	Interval     time.Duration
	InitialDelay time.Duration
}

CardRequestLifecycleLoop periodically calls ReconcileCardRequestSlots to release attached card_requests rows whose continuation has terminated. It never releases on a timer — each tick just repeats the confirm-or-leave-alone check.

RecoverLaunchingCardRequests is deliberately NOT part of this loop: it is the daemon-STARTUP recovery scan (a crash-window that only exists right after a restart), run once via RunStartupRecovery before this loop's first tick, not on every interval.

func (*CardRequestLifecycleLoop) Run added in v0.5.0

Run blocks until ctx is done, calling ReconcileCardRequestSlots every Interval (after an initial InitialDelay). Errors are logged as warnings; the loop always continues.

func (*CardRequestLifecycleLoop) RunStartupRecovery added in v0.5.0

func (l *CardRequestLifecycleLoop) RunStartupRecovery()

RunStartupRecovery runs RecoverLaunchingCardRequests once. Call it once at daemon startup, before Run's periodic reconcile loop begins.

type CardRequestOutcomePayload added in v0.5.0

type CardRequestOutcomePayload struct {
	RequestID           string                      `json:"request_id"`
	CommandKey          string                      `json:"command_key"`
	LaunchedLabel       string                      `json:"launched_label"`
	LauncherJobID       string                      `json:"launcher_job_id"`
	TargetKind          string                      `json:"target_kind"`
	TargetID            string                      `json:"target_id"`
	Origin              string                      `json:"origin"`
	CauseID             string                      `json:"cause_id"`
	Result              string                      `json:"result"`
	Error               string                      `json:"error"`
	Reason              string                      `json:"reason,omitempty"`
	ForceFailedSiblings []CardRequestOutcomeSibling `json:"force_failed_siblings,omitempty"`
}

CardRequestOutcomePayload is the JSON shape every card_requests self-record action (command_finished/command_failed/command_force_released) writes. Exported so a reader (the card timeline read model) can parse it back without duplicating this wire shape — see ParseCardRequestOutcomePayload.

func ParseCardRequestOutcomePayload added in v0.5.0

func ParseCardRequestOutcomePayload(payload json.RawMessage) (CardRequestOutcomePayload, error)

ParseCardRequestOutcomePayload decodes a command_finished/command_failed/ command_force_released action's payload. Returns the zero value and no error for empty/malformed input — a reader must never fail to render a card's timeline over one unparseable historical row.

type CardRequestOutcomeSibling added in v0.5.0

type CardRequestOutcomeSibling struct {
	ID         string `json:"id"`
	CommandKey string `json:"command_key"`
}

CardRequestOutcomeSibling is one row a force-release also force-failed — the payload shape for CardRequestOutcomePayload.ForceFailedSiblings.

type CardRequestSlotOutcome added in v0.5.0

type CardRequestSlotOutcome struct {
	RequestID string
	// Status is the CardRequest status the row moved to: "finished",
	// "failed", or "attached" (RecoverLaunchingCardRequests reattaching a
	// found continuation job).
	Status string
}

CardRequestSlotOutcome is one row ReconcileCardRequestSlots or RecoverLaunchingCardRequests actually changed.

func ReconcileCardRequestSlots added in v0.5.0

func ReconcileCardRequestSlots(conn *sql.DB) ([]CardRequestSlotOutcome, error)

ReconcileCardRequestSlots scans every attached card_requests row and releases the ones whose continuation has reached a terminal state:

  • target_kind=task: the task's own terminal status (done -> finished, aborted/dropped -> failed), or the task row no longer existing at all (deleted -> failed, same as an aborted continuation).
  • target_kind=session: the continuation JOB's terminal status (completed -> finished, failed -> failed). A Run's own hook job finishing does not count — only the session job named by target_id.

A continuation that is still live is left untouched: this function never releases on a guess. Call it repeatedly (a periodic loop) rather than relying on a single pass.

Each row's read-outcome-then-write runs in its OWN transaction (conn is *sql.DB, not db.DBTX, specifically so this can call db.InTxDB per row) — FinishCardRequest/FailCardRequest are themselves multiple statements (closing folded siblings, absorbing older failures) that must not land half-applied, but one row's failure must not roll back every other row this pass already released. A single row's error (e.g. it moved out of "attached" between the listing query above and this row's own transaction, because a concurrent force-release beat this pass to it) is logged and skipped rather than aborting the whole pass — a listing query with no snapshot isolation across many rows can't assume none of them raced.

func ReconcileLaunchingCardRequests added in v0.5.0

func ReconcileLaunchingCardRequests(conn *sql.DB) ([]CardRequestSlotOutcome, error)

ReconcileLaunchingCardRequests is the PERIODIC counterpart to RecoverLaunchingCardRequests: it clears a card_requests row stuck "launching" because its `run:` script exited (or was killed) without ever calling `boid task create` / `boid agent start`, without waiting for a daemon restart.

Gated on the LAUNCHER JOB's own terminal status (launcherJobTerminalOrGone), never on elapsed time: a time-based release could fire while the launcher is still legitimately running a long `run:` script, letting a second claim through alongside it.

CardRequestCommandKeyGo rows are skipped: a Go reservation (acceptGo, workflow_card.go) has no real launcher job — task creation happens synchronously in-process — so treating a missing job row as "terminal" would fail a Go reservation still legitimately mid-flight between its own CreateCardRequest and CreateTaskLinkedToCardRequest calls. acceptGo releases its own reservation synchronously on every error path instead; only a full daemon crash can leave one stuck, and RecoverLaunchingCardRequests' startup scan (unconditional) handles that.

func RecoverLaunchingCardRequests added in v0.5.0

func RecoverLaunchingCardRequests(conn *sql.DB) ([]CardRequestSlotOutcome, error)

RecoverLaunchingCardRequests is the daemon-startup recovery scan: task continuations write request->task in the SAME transaction as CreateTask, so they cannot land here mid-flight. A session continuation cannot — Dispatch (an external process launch) can't share a transaction with the DB write that records it — so a request can restart the daemon still "launching" with the session job already created but never attached.

For every such row, this reverse-looks-up jobs.card_request_id (persisted on the session job at Dispatch time, independent of the crashed daemon's in-memory state) for the SESSION job (role='session', never the launcher's own exec/hook job) created at or after this row's current launching promotion (req.UpdatedAt — stamped atomically with launcher_job_id by ClaimQueuedCardRequests/the launching fast path). The time bound matters: a retried request keeps its id, so a PRIOR attempt's session job can still carry the same card_request_id, and without it the newest attempt could reattach to a stale, already-finished session from an earlier attempt. Found -> attach it. Not found -> the launcher exited before creating anything, so the request goes to failed (retry-able), never finished — releasing a slot on failure is not the same as a successful judgment.

One transaction per row, and a single row's error is logged and skipped rather than aborting the whole scan — same reasoning as ReconcileCardRequestSlots, but more important here: this scan runs once at startup, not on a ticker, so one bad row aborting the loop would leave every OTHER launching row unrecovered until the next daemon restart.

type CardRequestStatus added in v0.5.0

type CardRequestStatus string

CardRequestStatus is card_requests.status's closed vocabulary — mirrors migration 0049's CHECK (status IN (...)).

const (
	CardRequestStatusQueued    CardRequestStatus = "queued"
	CardRequestStatusLaunching CardRequestStatus = "launching"
	CardRequestStatusAttached  CardRequestStatus = "attached"
	CardRequestStatusFolded    CardRequestStatus = "folded"
	CardRequestStatusFinished  CardRequestStatus = "finished"
	CardRequestStatusFailed    CardRequestStatus = "failed"
)

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: dispatcher only places a declaration in JobSpec, and the runner resolves it once the clone completes.

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. 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.

Every task — root or child, worktree or not — checks out task.BaseBranch directly inside its sandbox-internal clone (CheckoutOnly is always true now). There is no per-task branch or fork-point: the clone itself is the isolation unit, so no two tasks ever contend for the same branch name inside their own sandbox.

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.

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.

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) GetCardRequestByTaskTarget added in v0.5.0

func (l DBTaskLookup) GetCardRequestByTaskTarget(taskID string) (*CardRequest, error)

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
	// CardRequests is optional. When set, PlanHook stamps CardID/CardRequestID
	// onto the JobSpec whenever the firing task is itself a card-command
	// continuation, so `boid card context` works from inside it.
	CardRequests CardRequestByTaskLookup
}

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; the relaxed validation here is what makes those virtual hooks dispatch-ready.

Command is an inline shell command: 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 (see 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.

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.

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.

Fallback: when the behavior declares no agent-kind hook at all, 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: 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 a dead, unexpanded BaseBranch template on a card 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.

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.
	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. Without this distinction, a
	// workspace load failure would be misreported as ProvenanceUnset
	// ("neither source supplied a value"), a stronger claim than the code
	// can actually back up.
	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 ForceReleasedSibling added in v0.5.0

type ForceReleasedSibling struct {
	ID         string
	CommandKey string
}

ForceReleasedSibling identifies one folded card_requests row a foldedSiblingsFail pass force-failed alongside the row a caller named.

func ForceReleaseCardRequest added in v0.5.0

func ForceReleaseCardRequest(dbtx db.DBTX, id, reason string) ([]ForceReleasedSibling, error)

ForceReleaseCardRequest is the operator escape hatch for a stuck slot: fails a queued/launching/attached row regardless of whether its continuation has actually terminated. Unlike FailCardRequest, it does NOT requeue folded siblings — it fails them too, since requeuing would let the very next claim restart the card the operator just told to stop. Returns every sibling it force-failed this way, since fold is scoped to the card rather than id's own command_key/cause_id.

Also plants a force-release barrier on id's card (SetCardForceReleaseBarrier): the continuation force-release just detached is NOT itself stopped (a KNOWN GAP — see this function's own callers), and if it later writes again, that write would otherwise queue a fresh automatic request and let ClaimQueuedCardRequestsForDispatch relaunch the very card the operator just told to stop. The barrier suppresses that until a human operation (a card command, Go, or an explicit RetryCardRequest) clears it.

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.
	TriggerRuns int64
	// Signals is the count of signals rows GCSignals deleted: both acked
	// rows and unacked (including dead-lettered) rows older than the cutoff.
	Signals int64
	// CardRequests is the count of finished/failed card_requests rows
	// GCCardRequests deleted.
	CardRequests     int64
	OperationResults 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.

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. Both fail
	// registration identically (a repo-level anomaly), so both share this
	// one kind.
	GitHeadReadFailureHeadUnresolved
	// GitHeadReadFailurePathAbsent means HEAD resolves fine but relPath is
	// simply not present in its tree — the "project.yaml was never
	// committed" case, treated 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`. 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 IdentityLinkedPayload added in v0.5.0

type IdentityLinkedPayload struct {
	Identity string `json:"identity"`
}

IdentityLinkedPayload is ActionTypeIdentityLinked's and ActionTypeIdentityUnlinked's payload.

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 {
	// ID, when non-empty, is the job id dispatcher.Runner.Dispatch must use
	// verbatim instead of generating a fresh one. Caller-supplied ids must
	// be unique (uuid.New().String()). Empty means "generate as usual".
	ID string

	// 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
	DisplayNameDefault bool   // true when DisplayName is generated, rather than explicitly supplied
	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. `boid task update
	// --payload-patch` 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, which would be a TOCTOU staleness bug. 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) 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). 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: 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: 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

	// CardID / CardRequestID set sandbox.TokenContext.CardID/CardRequestID
	// for this job's broker token registration, mirroring SignalService/
	// SignalConnector's own wiring. Empty for every job that isn't a
	// card-command launcher.
	CardID        string
	CardRequestID 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: the field is retired and has no migration
	// destination any more, but computeRemoveKeys (cmd/project_migrate.go)
	// still needs to know whether the key was present, so `boid project
	// migrate` keeps offering to strip it from project.yaml (which rejects
	// the key outright — see removedTopLevelKeys in spec_loader.go). 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 — the field is retired, 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.

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.

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 OperationResult added in v0.5.0

type OperationResult struct {
	ID                       string
	TaskID                   string
	OperationType            string
	OperationLabel           string
	Result                   string
	ReasonCode               string
	TargetTaskID             string
	TargetSessionID          string
	TargetTaskUnavailable    bool
	TargetSessionUnavailable bool
	TargetRequestID          string
	CurrentPhase             string
	Notice                   string
	CreatedAt                time.Time
}

OperationResult records the server-observed outcome of one human UI operation.

type OperationResultStore added in v0.5.0

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

func NewOperationResultStore added in v0.5.0

func NewOperationResultStore(dbtx db.DBTX) *OperationResultStore

func (*OperationResultStore) AllOperationResults added in v0.5.0

func (s *OperationResultStore) AllOperationResults(taskID string) ([]*OperationResult, error)

AllOperationResults supplies the complete history to the item-paginated timeline.

func (*OperationResultStore) CreateOperationResult added in v0.5.0

func (s *OperationResultStore) CreateOperationResult(r *OperationResult) error

func (*OperationResultStore) GetOperationResult added in v0.5.0

func (s *OperationResultStore) GetOperationResult(taskID, id string) (*OperationResult, error)

func (*OperationResultStore) ListOperationResults added in v0.5.0

func (s *OperationResultStore) ListOperationResults(taskID string, limit int) ([]*OperationResult, error)

ListOperationResults returns newest first and resolves a request's eventual task or session association at read time so revisiting the card gains the link.

func (*OperationResultStore) UpdateOperationResult added in v0.5.0

func (s *OperationResultStore) UpdateOperationResult(r *OperationResult) error

UpdateOperationResult finalizes an initial unknown receipt exactly once.

type PlannerWireConfig

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

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. 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 (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. 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.

The task_behaviors comparison is done on names as written, 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.

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"`
	// CardCommands is a free-naming dictionary from a workspace-chosen key
	// to a label and a run command; ValidateCardCommands checks shape only.
	CardCommands map[string]CardCommand `yaml:"card_commands,omitempty" json:"card_commands,omitempty"`
	// CardCommandsOrder is CardCommands' project.yaml declaration order,
	// filled separately since a Go map cannot carry it itself.
	CardCommandsOrder []string `yaml:"-" json:"-"`
	// CardEvents names the CardCommands key that auto-starts for internal
	// card events; empty means none. Consumed by CardEventResolver
	// (card_event_ingest.go) via ProjectStore.CardEventCommand.
	// json:"-" because CardEventsConfig is a non-pointer struct, so
	// omitempty can't omit it.
	CardEvents CardEventsConfig `yaml:"card_events,omitempty" json:"-"`
	// Triggers is a TOP-LEVEL project.yaml field — deliberately NOT nested
	// under any TaskBehavior: "when it starts" is a different concern from
	// task_behaviors' "how it runs". Not part of the workspace envelope
	// spec.* allowlist (workspace_envelope.go's workspaceEnvelopeSpecFields)
	// — a workspace-level default `run:` would point at a script path that
	// only exists in one project's tracked tree, unlike
	// task_behaviors/base_branch/fork_point which generalize across a
	// workspace's projects. `triggers:` can only be written in
	// project.yaml.
	Triggers []Trigger `yaml:"triggers,omitempty" json:"triggers,omitempty"`
	// Signals declares this (meta)project's signal sources. 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 as Triggers
	// above, 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"`
	// 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) 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`.
	NameSource string `yaml:"-" json:"name_source,omitempty"`
}

func DefaultMetaprojectMeta added in v0.5.0

func DefaultMetaprojectMeta(workspace string) *ProjectMeta

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 (default branch), via `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, returning a ProjectMeta ready for dispatch. The "WithKits" name is a historical artifact — kits are no longer supported in project.yaml. 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 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 legacy 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.

wrapPerProjectLoadErr (project_store.go) 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, all of it — because filesystem/remote observations never justify a hard delete: internal/server/wire.go's buildProjectStore marks the project "degraded" (ProjectStore.MarkDegraded) and keeps going instead. The DB row is only ever removed by an explicit `boid project rm` / `boid workspace delete`. The type name stays as-is 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. See the package-level function's doc comment. r.db must be a *sql.DB — every production wiring path constructs ProjectRepository with the daemon's single *sql.DB handle.

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.

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. 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) CardEventCommand added in v0.5.0

func (s *ProjectStore) CardEventCommand(projectID string) (string, bool)

CardEventCommand returns projectID's declared card_events.command key — "" (ok=false) when the project is not cached or declares none. Satisfies CardEventResolver (card_event_ingest.go).

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 — 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 is reported as "no workspace default applied" (ProvenanceUnset). 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 (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, env, SecretNamespace injection, and 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 and canonical-behavior-name by name.

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, 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 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`; 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 can drive auto-migration via errors.As — this remains the one fail-fast case. 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 need no second pass: 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 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. Unlike LoadBareRepo, it never caches the freshly-read meta under its own id before confirming it matches expectedID — otherwise, if project A's project.yaml `id:` drifted to collide with an already-registered, unrelated project B, A's load could silently overwrite B's cache entry.

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 — 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. 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) 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 was ACTUALLY derived from the project's current UpstreamURL, not merely a hand-authored id: value that happens to share the prefix.

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 — 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-completion-time) full
	// snapshot; PayloadDelta is only what this single replayed hook
	// actually wrote, safe to apply onto a freshly re-read task row.
	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): if two agent-kind hooks for different agents fire from the same task in one round, this function always answers with whichever agent is the history's last entry, regardless of which job asked — see wiring-seams.md #13 for the full story. Safe as a task-row-level "what is this task's routing state right now" projection, 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 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.

DEPRECATED: prefer ListSignals + ClaimSignalIDs — charging on the read conflates "I looked at this" with "I handed this to a judgment"; see ClaimSignalIDs' doc comment. Kept until no workspace calls it.

Like IngestSignals, this does a select then a write that must be one atomic unit — see TaskRepository.ClaimSignals for the wrapper that provides that guarantee 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.
	State SignalState
	Limit int
	// MaxAttempts, when <= 0, defaults to MaxSignalAttempts.
	MaxAttempts int
}

SignalFilter scopes and paginates ListSignals. WorkspaceID is required; there is 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: one line = `{id, occurred_at, identity, url?, author?, title?}`. ID/OccurredAt/Identity are required; URL/Author/Title default to "".

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, 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, just excluded from ClaimSignals/HasPendingSignals
	// until a human acks it or GC 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 — a judgment ledger tracking what a human has decided about a card's next step.

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). Manual (human-only — see the push-down defense below) transitions:

go       : parked  → working   (accept(go): specced children get dispatched, then this fires)
go       : working → working   (self-loop: a freshly specced child can be run again while
                                 already working)
start    : parked  → working   (accept(start): manual work declared, no dispatch)
drop     : parked  → dropped
complete : parked  → done      (closed without ever being worked here — a card resolved
                                 out-of-band, or a duplicate; closing is not starting work)
park     : working → parked    (sets a wake condition — see workflow_card.go's park side effect)
complete : working → done
reopen   : done    → parked
reopen   : dropped → parked

This is the network's ENTIRE edge list, implementing the design doc's table literally. 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).

start/complete are the current spelling of the verbs formerly named "working"/"done" — distinct names from the UNRELATED execution machine's own "start"/"done" (see machine_execution.go), which this machine does not touch. This rule table only ever sees the current spelling: api.applyAction normalizes an incoming "working"/"done" against a card task via NormalizeCardVerb before Apply or IsManualAction is consulted, and attrs_set's suggestion.verb goes through the same normalization at validateSuggestionAttr. Past action rows already recorded under the old spelling are never rewritten — only the read side (badge/timeline label lookups) still needs to know both names.

job_failed is deliberately NOT registered here (unlike the execution machine — see machine_execution.go): a card never runs a job of its own, and job_failed's only rule targets "aborted", a status the card model retires entirely. progress/done_request/fail_request/child_dispatched/ child_closed stay registered (all non-transitioning, so none of them can reopen a fifth status) purely so Apply treats the name as known.

---- push-down defense ----

All nine Manual transition rules above are reachable through the public ApplyAction endpoint (HTTP API / Web UI / brokered `boid action send` / CLI all funnel through it). api.ApplyAction additionally checks `sm.Name == CardMachineName && IsCardTransitionAction(req.Type) && actor != ActorHuman` and rejects with 403 before ever calling sm.Apply — this keeps a gateway-brokered `boid action send --type complete` (or go/park/drop/reopen) from pushing a card's state directly, asserting a transition the daemon never itself decided. IsCardTransitionAction (below) is the exact six-verb closed set this restricts; attrs_set/child_added/child_specced/ child_dropped/noted/answered/wake_due stay reachable from any actor. ActorHuman is stamped ONLY by Web UI/CLI-driven code paths; a gateway-brokered `boid action send` always carries ActorTask(TokenContext.TaskID) instead, which is never equal to 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 is never blocked by its own defense.

See TestApplyAction_CardTransitions_HumanCanApplyEveryEdge_NoSuggestion (internal/api) for the pinned proof that a human can still directly drive every edge with no suggestion involved.

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. See machine.go's package doc comment for how this relates to the card lifecycle (machine_card.go). 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 not present in NewCardMachine at all): a card cannot be aborted, only dropped (drop's coverage lives entirely in NewCardMachine). Splitting the machine object into two makes this 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. 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 both call THIS method rather than each re-deriving the list by hand.

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. Lets a caller ask "would this actually be accepted" before rendering a button, rather than rendering it unconditionally and surfacing sm.Apply's rejection as an opaque 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. This lets a caller ask "would this verb actually apply from the task's current status" before rendering a live Accept button, rather than letting sm.Apply reject with an opaque error.

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) must return false here. Checking the Rule's own Manual flag, rather than a hand-maintained per-name blocklist, removes the risk of forgetting to update a blocklist when a new non-manual rule is added.

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. 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 and falling back to detail.attrs.suggestion (the path actually exercised today, since attrs_set — the only write path for it — folds into detail.attrs, not the top level; top-level is still checked first in case a future/alternate writer places it there directly). 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.

Returns the zero Suggestion and false on any absence/parse failure — never errors, so a missing/malformed suggestion blob never sinks the row it lives on.

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`. 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).
	//
	// Scoped by ParentID as well as ProjectID — NOT project-only: two
	// DIFFERENT parent tasks in the same project that happened to reuse the
	// same idempotency_key (e.g. both simply used "step-1") would otherwise
	// silently collide, with the second parent's create call handing back
	// the FIRST parent's child.
	//
	// Caller contract this implies: a judgment task minting a child needs
	// ParentID itself to be STABLE across retries for the dedup to actually
	// catch a duplicate create — e.g. 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, 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. 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, 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. The
	// detail page's own pinned child item has its own equivalent
	// (timeline.CardChildDetail via the awaiting-question link); 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. 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.

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). A caller that reaches for an execution-only field directly must go through task.Exec.X or task.Card.X — a compile error instead of a silently wrong zero value.

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. Because Exec/Card are POINTERS, a bare `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 mutates a cloned task's Exec/Card field must go through this (machine.go's Apply/AdvanceFull, coordinator.go's DispatchAndAdvance/evaluateAndAdvance, api.attrs_set_done.go's done-status noop).

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 Task.IdempotencyKey's doc comment for the field's contract. Unlike FindTaskByRef, there is no UUID-shaped-string special case: idempotency_key is never treated as a stand-in for a task ID.

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 — a scope mismatch is treated as "not found", not an error.

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 (includes parked).
	// Composes with Status via AND; no-op when false.
	ActiveOnly bool
	// Limit<=0 means unbounded. Offset still applies (via SQLite's
	// `LIMIT -1 OFFSET ?`) even when Limit<=0.
	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), keyed by the same runtime_id as WithRuntimesDir but a separate (persistent-volume) directory tree. Empty disables this cleanup, so those files accumulate forever.

type TaskIdentity added in v0.5.0

type TaskIdentity struct{ Identity, URL, DisplayName string }

func ListIdentityMetadataByTask added in v0.5.0

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

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) ActiveCardRequestsByCardIDs added in v0.5.0

func (r *TaskRepository) ActiveCardRequestsByCardIDs(cardIDs []string) (map[string]*CardRequest, error)

ActiveCardRequestsByCardIDs backs the task list's per-row command activity badge — a single batched read across every card on the current page, no transaction needed.

func (*TaskRepository) AttachCardRequestOwned added in v0.5.0

func (r *TaskRepository) AttachCardRequestOwned(id, expectedLauncherJobID, targetKind, targetID string) error

AttachCardRequestOwned backs `boid agent start`'s recording of the session continuation it just created (server.cardRequestReader) — the caller's job id is asserted in the write itself, not trusted from an earlier read (see AttachCardRequestOwned's own doc comment).

func (*TaskRepository) CardExecutionStatesByIDs added in v0.5.0

func (r *TaskRepository) CardExecutionStatesByIDs(cardIDs []string) (map[string]CardExecutionState, error)

func (*TaskRepository) ClaimQueuedCardRequestsForDispatch added in v0.5.0

func (r *TaskRepository) ClaimQueuedCardRequestsForDispatch(cardID, launcherJobID, expectedCommandKey string, def CardRequestDefinition) (*CardRequest, []*CardRequest, error)

ClaimQueuedCardRequestsForDispatch backs the automatic card-request dispatcher's claim step, same InTxDB-over-raw-*sql.DB shape as ForceReleaseCardRequest. A "nothing claimed" sentinel (IsCardRequestDispatchSkip) is captured separately rather than returned as the closure's own error, so a drain side effect it may carry still commits instead of being rolled back with it.

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) ClearCardForceReleaseBarrier added in v0.5.0

func (r *TaskRepository) ClearCardForceReleaseBarrier(cardID string) error

ClearCardForceReleaseBarrier backs a human-issued card command / Go / explicit retry ending automatic-dispatch suppression for a card — a single DELETE, no transaction needed on its own (callers that need it atomic with a claim run it inside their own WithinTx via TxStore instead).

func (*TaskRepository) CompleteTriggerRun added in v0.4.0

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

func (*TaskRepository) CountActiveCardRequests added in v0.5.0

func (r *TaskRepository) CountActiveCardRequests(cardID string) (int, error)

CountActiveCardRequests backs the shared execution-slot occupancy check — a single read, no transaction needed.

func (*TaskRepository) CreateAction

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

CreateAction persists action, then — within the SAME transaction — queues a card_events request for the target card when eligible. Same dual-mode shape as DeleteTask above: nests inside an already-open tx when r.db is one, or opens its own spanning transaction when r.db is a raw *sql.DB, so the INSERT and the ingest can never commit independently.

func (*TaskRepository) CreateCardRequest added in v0.5.0

func (r *TaskRepository) CreateCardRequest(req *CardRequest) error

CreateCardRequest backs a card command launcher's request creation — a single INSERT, no transaction needed (api.CardCommandLauncherStore).

func (*TaskRepository) CreateTask

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

func (*TaskRepository) CreateTaskLinkedToCardRequest added in v0.5.0

func (r *TaskRepository) CreateTaskLinkedToCardRequest(t *Task, requestID, ownerJobID string) error

CreateTaskLinkedToCardRequest runs CreateTask(t) and AttachCardRequestOwned(requestID, ownerJobID, "task", t.ID) IN THE SAME TRANSACTION, so a task continuation is never observable without its request association, AND the attach re-asserts ownerJobID as the current owner in its own write rather than trusting an earlier, separate ownership read (see AttachCardRequestOwned's own doc comment for the race this closes). A retry that hits CreateTask's own Ref/IdempotencyKey get-or-create and finds the SAME task already attached is treated as success, not an error.

func (*TaskRepository) CreateTriggerRun added in v0.4.0

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

CreateTriggerRun / CompleteTriggerRun / ListInFlightTriggerRuns / LatestTriggerRun are thin wrappers over trigger_run.go's trigger_runs ledger.

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) FailCardRequest added in v0.5.0

func (r *TaskRepository) FailCardRequest(id, errText string) error

FailCardRequest backs a card command launcher's slot release on dispatch failure — two UPDATEs (fail + release folded siblings) that must land together, same InTxDB-over-raw-*sql.DB shape as ForceReleaseCardRequest.

func (*TaskRepository) FindTaskByIdempotencyKey added in v0.5.0

func (r *TaskRepository) FindTaskByIdempotencyKey(projectID, parentID, idempotencyKey string) (*Task, 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) ForceReleaseCardRequest added in v0.5.0

func (r *TaskRepository) ForceReleaseCardRequest(id, reason string) ([]ForceReleasedSibling, error)

ForceReleaseCardRequest backs POST /api/card-requests/{id}/release, the operator escape hatch for a stuck slot (api.CardRequestReleaseStore). FailCardRequest is two UPDATEs that must land together — same InTxDB-over-raw-*sql.DB shape as ClaimSignals above.

func (*TaskRepository) GetCardRequest added in v0.5.0

func (r *TaskRepository) GetCardRequest(id string) (*CardRequest, error)

GetCardRequest backs `boid card context`'s live lookup of the calling job's card_requests row (server.cardRequestReader).

func (*TaskRepository) GetCardRequestByTaskTarget added in v0.5.0

func (r *TaskRepository) GetCardRequestByTaskTarget(taskID string) (*CardRequest, 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) HasCardForceReleaseBarrier added in v0.5.0

func (r *TaskRepository) HasCardForceReleaseBarrier(cardID string) (bool, error)

HasCardForceReleaseBarrier backs a caller checking a card's suppression state directly — a single read, no transaction needed.

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 wrap signal_store.go's inbox store.

IngestSignals and ClaimSignals each need their SQL statements to run as one transaction, 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, they open their own spanning transaction.

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 are thin wrappers over task_identity.go's identity index.

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 is the workspace-scoped action_list read.

func (*TaskRepository) ListActiveCardRequests added in v0.5.0

func (r *TaskRepository) ListActiveCardRequests() ([]*CardRequest, error)

ListActiveCardRequests backs `boid task diagnose-cards`' bulk lookup of every card with an active request — a single read, no transaction needed.

func (*TaskRepository) ListCardIDsWithQueuedCardRequests added in v0.5.0

func (r *TaskRepository) ListCardIDsWithQueuedCardRequests() ([]string, error)

ListCardIDsWithQueuedCardRequests backs the periodic dispatch sweep's work list — a single read, no transaction needed.

func (*TaskRepository) ListCardRequestsByCard added in v0.5.0

func (r *TaskRepository) ListCardRequestsByCard(cardID string) ([]*CardRequest, error)

ListCardRequestsByCard backs a manual command's "return a link to the current execution" response when the card's slot is already occupied — a single read, no transaction needed.

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) ListIdentityMetadataByTask added in v0.5.0

func (r *TaskRepository) ListIdentityMetadataByTask(taskID string) ([]TaskIdentity, 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) PeekOldestQueuedCardRequest added in v0.5.0

func (r *TaskRepository) PeekOldestQueuedCardRequest(cardID string) (id, commandKey string, err error)

PeekOldestQueuedCardRequest backs the automatic dispatcher's pre-claim command definition resolution — a single read, no transaction needed.

func (*TaskRepository) ReleaseCardRequestForTerminalTargetWithCard added in v0.5.0

func (r *TaskRepository) ReleaseCardRequestForTerminalTargetWithCard(targetKind, targetID string, success bool) (found bool, cardID string, err error)

ReleaseCardRequestForTerminalTargetWithCard backs finalizeTerminal's immediate slot release AND the immediate re-dispatch attempt that follows it — same InTxDB-over-raw-*sql.DB shape as FailCardRequest.

func (*TaskRepository) ResolveIdentity added in v0.4.0

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

func (*TaskRepository) SetCardEventResolver added in v0.5.0

func (r *TaskRepository) SetCardEventResolver(resolver CardEventResolver)

SetCardEventResolver wires the card_events.command lookup CreateAction's card-event ingest step needs — see the cardEventResolver field's own doc comment.

func (*TaskRepository) SetCardForceReleaseBarrier added in v0.5.0

func (r *TaskRepository) SetCardForceReleaseBarrier(cardID string) error

SetCardForceReleaseBarrier backs test setup / a future operator-facing force-release path that wants to plant a barrier directly — a single upsert, no transaction needed on its own.

func (*TaskRepository) SetTriggerRunJobID added in v0.4.0

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

SetTriggerRunJobID / DeleteTriggerRun back the insert-then-dispatch split — see trigger_run.go's own doc comments.

func (*TaskRepository) TaskStatusesByIDs added in v0.5.0

func (r *TaskRepository) TaskStatusesByIDs(taskIDs []string) (map[string]TaskStatus, error)

TaskStatusesByIDs backs the task list's per-row work-child activity badge — a single batched read of a page's dispatched children's real task status, no transaction needed.

func (*TaskRepository) TouchTaskUpdatedAt added in v0.4.0

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

TouchTaskUpdatedAt satisfies api.TaskUpdatedAtToucher.

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) UpdateIdentityMetadata added in v0.5.0

func (r *TaskRepository) UpdateIdentityMetadata(projectID, identity, taskID string, url, displayName *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. JSON tags stay lowercase, matching the snake_case convention every other boid RPC response uses.

Readonly 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). Exported so internal/api's `boid task current` RPC 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. SnapshotTask is only ever called from PlanHook, which already requires task.Exec != nil, 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. captured/triaged/ready — earlier
	// pre-execution statuses — are deliberately GONE: no rule in
	// NewCardMachine produces them any more, and a migration converted
	// every remaining pre-cutover row carrying one of them to "parked" and
	// dropped the values from the DB entirely. Re-introducing a reference
	// to them here would silently reopen a vocabulary the schema's CHECK
	// constraint 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 — cheaper than GetTask (whose child-count subqueries scan tasks.parent_id, which is unindexed), for callers that poll tightly. No prefix fallback.

func KnownTaskStatuses added in v0.2.4

func KnownTaskStatuses() []TaskStatus

KnownTaskStatuses は boid が認識する全 TaskStatus 値を返す。バリデーションを行う全箇所 (CreateTaskRequest.InitialStatus・brokered task_list の status 検証等) はここを唯一の 情報源として参照する — 新しい状態を追加する際にリストがずれないようにするため。

captured/triaged/ready はこのリストから除外済み: DB の CHECK 制約が拒否する 値であり、ここに残すとどの行も実際には持ち得ない値をバリデーションが受理 してしまう。

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.
	Description string `json:"description,omitempty"`
	Instruction string `json:"instruction,omitempty"`
}

TaskTriageChildSpec is the execution recipe a child needs before it can be task-ified. Project is assumed to already be a resolved boid project ID by the time a child reaches "specced" — there is no project-ref fuzzy resolution here; 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: 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.

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)). 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. "" and
	// TriggerOnSchedule ("schedule") are equivalent: 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).
	// ValidateTriggers rejects any other value at project.yaml load time.
	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 — that is a script's own concern,
	// not the daemon's. Required for BOTH On kinds — for On=="signals" this
	// is also the trigger's debounce window.
	Every string `yaml:"every" json:"every"`
	// Run is a command string passed to `sh -c` inside the project's
	// sandbox — NOT a script path the daemon resolves. sandbox's /bin/sh is
	// dash: bashisms are the script author's responsibility, not the
	// daemon's.
	Run string `yaml:"run" json:"run"`
	// Timeout is a Go time.ParseDuration string bounding how long ONE round
	// of this trigger may take. Empty means unbounded.
	//
	// 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.
	//
	// 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.
	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 — 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 — every
	// trigger with a nil Connector dispatches exactly as before.
	Connector *TriggerConnector `yaml:"-" json:"connector,omitempty"`
}

Trigger is one project.yaml `triggers[]` entry. It declares WHEN a command runs (Every, and also On) and WHAT command runs (Run) — nothing else. The daemon reads only these fields; it never interprets Run's contents.

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). 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). 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. 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.
	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: 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. 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 this watchdog checks against. Deliberately not yet wired to config.yaml (no real caller/data to calibrate against until ingestion lands) — DefaultWatchdogThresholds below is a reasonable starting point, kept as a named type so a future change can thread it through config without changing WatchdogGuidance's signature.

func DefaultWatchdogThresholds added in v0.2.4

func DefaultWatchdogThresholds() WatchdogThresholds

DefaultWatchdogThresholds returns a starting-point set of 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: FieldsPresent["projects"] is 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.
	//
	// 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.
	// 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.

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: either every change this call makes commits, or none of them do. This replaces a previous client-side "GET current, merge, PUT metadata, then separately attach each project one HTTP call at a time" dance, 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, rather than stopping short of touching the DB and reporting 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, 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 emitted as `init_script: ""`, read back as an explicit clear — see WorkspaceEnvelopeSpec.InitScript.

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 yaml key name. 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 with a zero-value
	// decode) means the document wants that field replaced.
	//
	// "init_script" is in this map but not in MergeInto's switch — its
	// consumer is ProjectAppService.ApplyWorkspace, which reads the same
	// flag directly to decide whether to write/clear the file.
	FieldsPresent map[string]bool
	// AdditionalBindingsDropped is true when the source document had a
	// spec.additional_bindings key (any shape) — 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 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. An empty/whitespace-only body is an error — 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 has no *WorkspaceMeta column to merge into. ProjectAppService.ApplyWorkspace honors its FieldsPresent flag separately, outside this function's DB transaction (a file write cannot be made atomic with it anyway).

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 currently informational only: 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.
	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 — see WorkspaceMeta's
	// identically-named fields for the semantics.
	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. Unlike other fields it
	// has no WorkspaceMeta counterpart — init.sh is a file the daemon owns,
	// not a workspaces-table column — so MergeInto does not touch it;
	// ProjectAppService.ApplyWorkspace reads FieldsPresent["init_script"]
	// directly to decide whether to write/clear the file. An empty script
	// and no script collapse to the same state: both are a no-op run.
	InitScript string `yaml:"init_script"`
}

WorkspaceEnvelopeSpec mirrors WorkspaceMeta field-for-field (see that type's doc comment) plus Projects, which has no WorkspaceMeta equivalent — project-workspace assignment is separate bookkeeping, not part of the workspace's own meta row.

additional_bindings is deliberately NOT a field here (retired field); decodeWorkspaceEnvelopeSpec tolerates it in a source document, parsing and discarding it with AdditionalBindingsDropped set for the caller to warn on.

None of spec's fields carry `omitempty`: missing vs. explicitly-empty is a load-bearing distinction (WorkspaceEnvelopeApply's FieldsPresent-driven merge) — omitempty would make "field is empty" indistinguishable from "field absent, leave untouched", breaking export→apply round trips that are meant to clear a field.

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. 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 still happens outside this transaction,
	// from the in-memory ProjectMeta cache, which is not DB-backed at all.
	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, so a concurrent `workspace assign` moving a project between two workspaces mid-export cannot make the project appear in neither (or both) exported documents. project_workspaces.project_id is the table's PRIMARY KEY, 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. 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 — see ProjectAppService. ExportWorkspaceEnvelopes, which resolves that name afterward; doing so outside this transaction cannot reintroduce cross-workspace inconsistency, since it only changes how an already-fixed assignment is displayed.

allProjects is EVERY registered project row — not just ones assigned to a slug in slugs — read from the exact same transaction, keyed by ID. ExportWorkspaceEnvelopes needs the full, tx-consistent project set 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.

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. 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.
	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 — additive only, a workspace can never remove a floor
	// entry. An entry naming a service config.yaml's `services:` map does
	// not declare is not rejected here; it simply never resolves to
	// anything reachable at dispatch time — see ResolveEnabledServices.
	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). 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.
	HostCommands []string `yaml:"host_commands,omitempty" json:"host_commands,omitempty"`

	// ContainerImage is a nullable field reserved for the container backend.
	// Dispatch ignores it entirely until then.
	ContainerImage string `yaml:"container_image,omitempty" json:"container_image,omitempty"`

	// TaskBehaviors / BaseBranch / ForkPoint / DefaultTaskBehavior are the
	// workspace's "default project" definition — a project.yaml-less or
	// partial project.yaml inherits these. Mirrors the identically-named
	// ProjectMeta fields field-for-field, both in shape and in the
	// validation/normalization pipeline they go through
	// (normalizeWorkspaceDefaultTaskBehaviors, spec_loader.go). See
	// docs/plans/workspace-default-project.md for the hydration-merge rules
	// (project.yaml wins per-field over these workspace defaults).
	TaskBehaviors map[string]TaskBehavior `yaml:"task_behaviors,omitempty" json:"task_behaviors,omitempty"`
	// BaseBranch is the workspace default's base_branch. Empty means
	// "unspecified" — there is deliberately no way to explicitly un-set an
	// inherited value.
	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 and the field removed. Two client-side call sites still resolve a legacy `kits:` reference list against MaterializeWorkspaceKitsForPersist, but source it from outside this type now — see cmd/workspace.go's ensureWorkspaceExistsForAssign and cmd/project_migrate.go.

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 — 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 — 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. It is the authority WorkspaceStore delegates to once MigrateWorkspaceYAMLToDB has cut over: 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 (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, so GET /api/workspaces/{slug} cannot 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. 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. This closes the PUT race a "read revision, then Save unconditionally" two-step would have: 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:

  • 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) 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.

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 — 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 — the yaml files under DefaultWorkspaceDir() are purely a rollback/export shadow, never read by DB-mode Load.

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 — 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. 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. Empty when the summary was
	// built from a project_workspaces reference with no corresponding
	// workspaces row — 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 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. Unlike ListWorkspaces (workspaces-table-based), this reflects project_workspaces membership directly and surfaces a reference to a slug that has no corresponding workspaces row at all — needed by workspace_migration.go's preflight, which runs before the workspaces table has anything written to it and must detect a project referencing a slug with no legacy yaml file backing it. No other caller should need this function (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. The query is workspaces-table-based with project_workspaces LEFT JOINed in, so a workspace with zero assigned projects still appears (ProjectCount=0).

type WorkspaceWatchdog added in v0.2.4

type WorkspaceWatchdog struct {
	WorkspaceID         string
	LastIngestSuccessAt *time.Time
	LastTriageReviewAt  *time.Time
}

WorkspaceWatchdog is the "沈黙の検知" 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).

Nothing currently calls TouchWorkspaceIngestSuccess in production — the primitive (table + accessors + threshold evaluator) is built ahead of its ingestion caller so that task has somewhere to write, and so the queue view can already render guidance for last_triage_review_at.

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