Documentation
¶
Index ¶
- Constants
- Variables
- func AttachmentsRootForTask(dataHome, taskID string) string
- func DeriveProjectIDFromURL(normalizedURL string) (string, error)
- func EnsureAttachmentsDir(dataHome, taskID string) (string, error)
- func FormatAbortReason(o TaskOutcome) string
- func JobLogNoRuntimeMessage(id string, status JobStatus) string
- func JobLogNoSuchJobMessage(id string) string
- func JobLogTranscriptGoneMessage(runtimeID string) string
- func ListAttachments(dataHome, taskID string) ([]string, error)
- func ReadAttachment(dataHome, taskID, name string) ([]byte, error)
- func ResolveJSONField(raw json.RawMessage, path string) (string, error)
- func ResolveTaskField(task *orchestrator.Task, actions orchestrator.LifecycleStore, path string) (string, error)
- func SanitizeAttachmentName(raw string) (string, error)
- func SaveMultipartAttachments(dataHome, taskID string, files []*multipart.FileHeader) ([]string, error)
- func ValidateAttachmentHeaders(files []*multipart.FileHeader) error
- type AckSignalsRequest
- type AckSignalsResponse
- type ActionApplication
- type ActionHandler
- type ActionListResult
- type ActionListStore
- type ActionStore
- type AnswerSuggestionRequest
- type AnswerTaskRequest
- type ApplyActionRequest
- type BlockingAskRegistry
- func (r *BlockingAskRegistry) Cancel(qid string)
- func (r *BlockingAskRegistry) Has(qid string) bool
- func (r *BlockingAskRegistry) Notify(qid, answer string) bool
- func (r *BlockingAskRegistry) Register(taskID, qid string) error
- func (r *BlockingAskRegistry) Wait(ctx context.Context, qid string) (string, error)
- type BrokerHandler
- type BrokerRegisterRequest
- type BrokerRegisterResponse
- type BrokerRegistry
- type CardHandler
- type CardReadService
- type CardStore
- type CardView
- type ConfigApplyResult
- type ConfigHandler
- func (h *ConfigHandler) Apply(w http.ResponseWriter, r *http.Request)
- func (h *ConfigHandler) Get(w http.ResponseWriter, r *http.Request)
- func (h *ConfigHandler) KitsDir(w http.ResponseWriter, r *http.Request)
- func (h *ConfigHandler) Mutate(w http.ResponseWriter, r *http.Request)
- func (h *ConfigHandler) Routes() chi.Router
- type ConfigMutateOp
- type ConfigMutateRequest
- type ConfigMutateResult
- type ConfigService
- type ConnectorRef
- type CreateProjectFromGitURLRequest
- type CreateProjectRequest
- type CreateTaskRequest
- type DeviceAuthHandler
- type DeviceGCStore
- type DispatchCoordinator
- type DuplicateTaskRequest
- type ExecDispatcher
- type GCAppService
- type GCHandler
- type GCService
- type GCStore
- type GlobalJobStore
- type HookService
- type HostCommandsHandler
- type HostCommandsProvider
- type HostCommandsService
- type ImportError
- type ImportResult
- type Job
- type JobCompletion
- type JobDoneRequest
- type JobHandler
- func (h *JobHandler) AgentStop(w http.ResponseWriter, r *http.Request)
- func (h *JobHandler) Done(w http.ResponseWriter, r *http.Request)
- func (h *JobHandler) Get(w http.ResponseWriter, r *http.Request)
- func (h *JobHandler) List(w http.ResponseWriter, r *http.Request)
- func (h *JobHandler) Log(w http.ResponseWriter, r *http.Request)
- func (h *JobHandler) Patch(w http.ResponseWriter, r *http.Request)
- func (h *JobHandler) Routes() chi.Router
- type JobLifecycle
- type JobListFilter
- type JobLogReader
- type JobLogSSEHandler
- type JobStatus
- type JobStore
- type JobWithContext
- type ListSignalsResponse
- type LoginHandler
- type MetaStore
- type Notifier
- type NotifyTaskRequest
- type OAuthLoginHandler
- type OAuthLoginService
- type OAuthLoginStart
- type Pairer
- type ProjectAppService
- func (s *ProjectAppService) ApplyWorkspace(apply *orchestrator.WorkspaceEnvelopeApply, dryRun bool) (*orchestrator.WorkspaceApplyResult, error)
- func (s *ProjectAppService) CreateProject(workDir string) (*orchestrator.Project, error)
- func (s *ProjectAppService) CreateProjectFromGitURL(ctx context.Context, gitURL, workspaceSlug, nameOverride string) (*orchestrator.Project, error)
- func (s *ProjectAppService) CreateWorkspace(slug string, meta *orchestrator.WorkspaceMeta) (*WorkspaceDetail, error)
- func (s *ProjectAppService) DeleteProject(id string) error
- func (s *ProjectAppService) ExplainProject(id string) (*orchestrator.ProjectExplain, error)
- func (s *ProjectAppService) ExportWorkspaceEnvelopes(slugs []string) ([]byte, error)
- func (s *ProjectAppService) FetchProject(ctx context.Context, id string) (*orchestrator.Project, error)
- func (s *ProjectAppService) GetProject(id string) (*orchestrator.Project, error)
- func (s *ProjectAppService) GetWorkspace(slug string) (*WorkspaceDetail, error)
- func (s *ProjectAppService) GetWorkspaceInitScript(slug string) (*WorkspaceInitScript, error)
- func (s *ProjectAppService) ListProjects(workspaceID string) ([]*orchestrator.Project, error)
- func (s *ProjectAppService) ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
- func (s *ProjectAppService) ReloadProjects() (*ProjectReloadResult, error)
- func (s *ProjectAppService) RemoveWorkspace(slug string) (*WorkspaceRemoval, error)
- func (s *ProjectAppService) ResolveProjectRef(ref string) ([]*orchestrator.Project, error)
- func (s *ProjectAppService) SetProjectWorkspace(id, workspaceID string) (*orchestrator.Project, error)
- func (s *ProjectAppService) SetWorkspaceInitScript(slug string, content []byte, ifMatch string, force bool) (*WorkspaceInitScriptResult, error)
- func (s *ProjectAppService) UpdateWorkspace(slug string, meta *orchestrator.WorkspaceMeta, ifMatch string, force bool) (*WorkspaceDetail, error)
- func (s *ProjectAppService) WithProjectLock(fn func() error) error
- type ProjectHandler
- func (h *ProjectHandler) Create(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) CreateFromGitURL(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) Delete(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) Explain(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) Fetch(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) Get(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) List(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) Reload(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) Routes() chi.Router
- func (h *ProjectHandler) RunTrigger(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) SetWorkspace(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) StartExec(w http.ResponseWriter, r *http.Request)
- func (h *ProjectHandler) StartSession(w http.ResponseWriter, r *http.Request)
- type ProjectReloadResult
- type ProjectRepository
- type ProjectService
- type ProjectWorkDirLookup
- type QueueSweepLoop
- type QueueSweepStore
- type ReopenTaskRequest
- type ReplayHookRequest
- type ReplayHookResult
- type RerunTaskRequest
- type ResolveOrCaptureRequest
- type ResolveOrCaptureResult
- type SecretHandler
- func (h *SecretHandler) Delete(w http.ResponseWriter, r *http.Request)
- func (h *SecretHandler) GetValue(w http.ResponseWriter, r *http.Request)
- func (h *SecretHandler) List(w http.ResponseWriter, r *http.Request)
- func (h *SecretHandler) Routes() chi.Router
- func (h *SecretHandler) Set(w http.ResponseWriter, r *http.Request)
- type SecretStore
- type SessionDispatcher
- type SessionHandler
- type SetProjectWorkspaceRequest
- type SettingsConfigService
- type Signal
- type SignalHandler
- type SignalSource
- type SignalStore
- type StartExecRequest
- type StartExecResult
- type StartSessionRequest
- type StartSessionResult
- type StatusError
- type TaskAnswerService
- type TaskAppService
- func (s *TaskAppService) AnswerTask(ctx context.Context, taskID, questionID, answer string) error
- func (s *TaskAppService) AskTaskBlocking(ctx context.Context, taskID, question string) (string, error)
- func (s *TaskAppService) CreateTask(req CreateTaskRequest) (*orchestrator.Task, error)
- func (s *TaskAppService) DeleteTask(id string, force bool) error
- func (s *TaskAppService) DuplicateTask(sourceID string, autoStart bool) (*orchestrator.Task, error)
- func (s *TaskAppService) GetInstructions(id string) ([]orchestrator.RoutedInstruction, error)
- func (s *TaskAppService) GetInstructionsField(id, path string) (string, error)
- func (s *TaskAppService) GetTask(id string) (*orchestrator.Task, error)
- func (s *TaskAppService) GetTaskCurrent(id string) (*orchestrator.TaskSnapshot, error)
- func (s *TaskAppService) GetTaskCurrentField(id, path string) (string, error)
- func (s *TaskAppService) GetTaskDetail(id string) (*TaskDetailView, error)
- func (s *TaskAppService) GetTaskField(id, path string) (string, error)
- func (s *TaskAppService) ImportTasks(reqs []CreateTaskRequest) (*ImportResult, error)
- func (s *TaskAppService) LinkIdentity(projectID, identity, taskID string) error
- func (s *TaskAppService) ListTasks(filter orchestrator.TaskFilter) ([]*orchestrator.Task, error)
- func (s *TaskAppService) NotifyTask(ctx context.Context, ...) error
- func (s *TaskAppService) RerunTask(id string, req RerunTaskRequest) (*orchestrator.Task, error)
- func (s *TaskAppService) ResolveIdentity(projectID, identity string) (*orchestrator.Task, error)
- func (s *TaskAppService) UnlinkIdentity(projectID, identity string) error
- func (s *TaskAppService) UpdateTask(id string, req UpdateTaskRequest) (*orchestrator.Task, error)
- func (s *TaskAppService) UpdateTaskPayloadPatch(jobID string, patch json.RawMessage, allowedTraits []orchestrator.TraitType) (*orchestrator.Task, error)
- func (s *TaskAppService) WaitTaskTerminal(ctx context.Context, taskID string) (TaskOutcome, error)
- type TaskCreator
- type TaskDetailView
- type TaskEvent
- type TaskEventHub
- type TaskHandler
- func (h *TaskHandler) Answer(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Create(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Delete(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Detail(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Duplicate(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Field(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Get(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Import(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) List(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) ListHooks(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Notify(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Patch(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) ReplayHook(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Rerun(w http.ResponseWriter, r *http.Request)
- func (h *TaskHandler) Routes() chi.Router
- type TaskIdentityStore
- type TaskNotifyService
- type TaskOutcome
- type TaskService
- type TaskStatusReader
- type TaskStore
- type TaskUpdatedAtToucher
- type TaskWaitRegistry
- type TaskWorkflowService
- func (s *TaskWorkflowService) ApplyAction(ctx context.Context, taskID string, req ApplyActionRequest) (*ActionApplication, error)
- func (s *TaskWorkflowService) CompleteJob(ctx context.Context, jobID string, req JobDoneRequest) (*Job, error)
- func (s *TaskWorkflowService) GetCard(taskID string) (*CardView, error)
- func (s *TaskWorkflowService) InitDispatch(ctx context.Context)
- func (s *TaskWorkflowService) ListActions(filter orchestrator.ActionListFilter) (*ActionListResult, error)
- func (s *TaskWorkflowService) ListCards(filter orchestrator.TaskFilter) ([]*CardView, error)
- func (s *TaskWorkflowService) ListHooksForStatus(taskID, status string) ([]orchestrator.Hook, error)
- func (s *TaskWorkflowService) ReplayHook(ctx context.Context, taskID string, req ReplayHookRequest) (*ReplayHookResult, error)
- func (s *TaskWorkflowService) ResolveOrCapture(ctx context.Context, req ResolveOrCaptureRequest) (*ResolveOrCaptureResult, error)
- func (s *TaskWorkflowService) RunTriggerNow(ctx context.Context, projectID, triggerName string) (*TriggerRunNowResult, error)
- func (s *TaskWorkflowService) Shutdown()
- func (s *TaskWorkflowService) StopAgent(runtimeID string)
- func (s *TaskWorkflowService) SweepReconcileChildren(ctx context.Context, _ time.Time) error
- func (s *TaskWorkflowService) SweepTriggers(ctx context.Context, now time.Time) (TriggerSweepResult, error)
- func (s *TaskWorkflowService) SweepWake(ctx context.Context, now time.Time) (woken []string, err error)
- type Transactor
- type TriggerCompletionResult
- type TriggerFireResult
- type TriggerKey
- type TriggerLoop
- type TriggerLoopStore
- type TriggerRunNowResult
- type TriggerRunStore
- type TriggerRunner
- type TriggerSkip
- type TriggerSweepResult
- type TxStore
- type UpdateJobRequest
- type UpdateTaskRequest
- type WSAttachHandler
- type WebAppService
- func (s *WebAppService) AnswerSuggestion(taskID string, req AnswerSuggestionRequest) error
- func (s *WebAppService) AnswerTask(ctx context.Context, taskID, questionID, answer string) error
- func (s *WebAppService) ApplyAction(taskID string, actionType string) error
- func (s *WebAppService) CreateTask(req CreateTaskRequest) (*orchestrator.Task, error)
- func (s *WebAppService) DeleteTask(id string, force bool) error
- func (s *WebAppService) DuplicateTask(id string) (string, error)
- func (s *WebAppService) GetJob(id string) (*JobWithContext, error)
- func (s *WebAppService) GetProjectByID(id string) (*orchestrator.Project, error)
- func (s *WebAppService) GetTaskDetail(id string) (*TaskDetailView, error)
- func (s *WebAppService) ListBehaviors() ([]string, error)
- func (s *WebAppService) ListHooksForStatus(taskID, status string) ([]orchestrator.Hook, error)
- func (s *WebAppService) ListJobs(status string) ([]JobWithContext, error)
- func (s *WebAppService) ListProjects() ([]*orchestrator.Project, error)
- func (s *WebAppService) ListSessions() ([]JobWithContext, error)
- func (s *WebAppService) ListTasks(filter orchestrator.TaskFilter) ([]*orchestrator.Task, error)
- func (s *WebAppService) ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
- func (s *WebAppService) ReopenTask(id string, req ReopenTaskRequest) error
- func (s *WebAppService) ReplayHook(ctx context.Context, taskID string, req ReplayHookRequest) (*ReplayHookResult, error)
- func (s *WebAppService) RerunTask(id string, req RerunTaskRequest) error
- func (s *WebAppService) UpdateTask(id string, req UpdateTaskRequest) error
- type WebHandler
- func (h *WebHandler) GetTaskEdit(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) HookReplayList(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) JobDetail(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) JobTerminal(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostAction(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostAnswer(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostAnswerSuggestion(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostDelete(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostDuplicate(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostEdit(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostHookReplay(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostReopen(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostRerun(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostStartSession(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostStartShapingSession(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) PostTaskCreate(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) QuestionPage(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) ReopenForm(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) Routes() chi.Router
- func (h *WebHandler) SessionList(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) SessionNew(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) Settings(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) TaskDetail(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) TaskDetailFragment(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) TaskEvents(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) TaskList(w http.ResponseWriter, r *http.Request)
- func (h *WebHandler) TaskNew(w http.ResponseWriter, r *http.Request)
- type WebManagementHandler
- func (h *WebManagementHandler) DeleteAllDevices(w http.ResponseWriter, r *http.Request)
- func (h *WebManagementHandler) DeleteDevice(w http.ResponseWriter, r *http.Request)
- func (h *WebManagementHandler) GetDevices(w http.ResponseWriter, r *http.Request)
- func (h *WebManagementHandler) PostPair(w http.ResponseWriter, r *http.Request)
- func (h *WebManagementHandler) Routes() chi.Router
- type WebService
- type WorkflowService
- type WorkspaceDetail
- type WorkspaceHandler
- func (h *WorkspaceHandler) Apply(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) Create(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) ExportEnvelope(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) GetInitScript(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) ImportHome(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) List(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) PutInitScript(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) Remove(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) Routes() chi.Router
- func (h *WorkspaceHandler) Show(w http.ResponseWriter, r *http.Request)
- func (h *WorkspaceHandler) Update(w http.ResponseWriter, r *http.Request)
- type WorkspaceHomeImportResponse
- type WorkspaceHomeImporter
- type WorkspaceHomeSize
- type WorkspaceHomeStore
- type WorkspaceInitScript
- type WorkspaceInitScriptResult
- type WorkspaceInitScriptStore
- type WorkspaceRemoval
- type WorkspaceRemoveResponse
- type WorkspaceSlugLister
- type WorkspaceStore
Constants ¶
const ( AttachmentMaxFileBytes int64 = 10 * 1024 * 1024 // 10 MB per file AttachmentMaxTotalBytes int64 = 30 * 1024 * 1024 // 30 MB per task dir AttachmentMaxNameBytes = 255 )
Attachment-related constants. Values are also enforced client-side in web/static/boid-paste-attach.js; keep the two in sync.
const ( TriggerStuckOverrunMultiplier = 1.5 TriggerStuckFailStreakThreshold = 3 )
TriggerStuckOverrunMultiplier implements 12 節 B-5 既定案「詰まり検出は N 連続見送りで通知」, revised by Opus review Blocker 2 (ii): a run is "stuck" once it has been continuously in flight for longer than TriggerStuckOverrunMultiplier × its OWN `every` — not after N raw sweep ticks. A tick-counted threshold implicitly assumes the sweep interval is close to `every`; TriggerLoop's actual Interval (1m, wire.go) is 10× the example `every: 10m` the reviewer's report used, so 3 raw ticks would fire after 3 minutes even for a trigger whose command normally, harmlessly, takes 5 of every 10 minutes. Expressing the threshold as a multiple of `every` instead scales with each trigger's own schedule automatically — see TriggerLoop.trackSkipStreak.
TriggerStuckFailStreakThreshold is unchanged: it counts consecutive COMPLETED runs with a non-zero exit code, one data point per actual execution regardless of sweep interval — there is no analogous tick-vs-every mismatch for it to correct.
The multiplier moved 3 → 1.5 on 2026-08-24 (nose). At 3 the threshold for khi's sweep (`every: 10m`) was 30 minutes, and both stalls that actually happened that day — 25 and 26 minutes, an agent that ended its turn without calling a tool, then one that forked a subagent and ended its turn waiting for a reply — were resolved by a human noticing before the notification would have fired. A detector that never fires because people are faster than it is not a detector. Healthy runs of that sweep finished in 1–8 minutes, so 1.5× (15m) still clears them comfortably.
It is deliberately still a multiple of `every` rather than a wall-clock constant: the reason for the relative form (each trigger's own schedule setting its own sense of "too long") did not change, only the constant did.
const ConfigMutateSet = apiwire.ConfigMutateSet
const ConfigMutateUnset = apiwire.ConfigMutateUnset
const JobStatusCompleted = apiwire.JobStatusCompleted
const JobStatusFailed = apiwire.JobStatusFailed
const JobStatusRunning = apiwire.JobStatusRunning
const TriggerDispatchFailureExitCode = -2
TriggerDispatchFailureExitCode is the sentinel SweepTriggers reports in TriggerSweepResult.Completed for a StartExec (dispatch) failure — distinct from TriggerRunSelfHealExitCode so the two failure classes stay distinguishable in logs/notifications (self-heal = a job WAS dispatched but its outcome was never observed; this = the job was never dispatched at all). docs/plans/signal-ingest-detailed-design.md §5.2 (PR-5 review finding, B2): before this existed, a dispatch failure (pack not installed, connector config schema violation, ambiguous pack version — new failure classes a connector trigger's StartExec can hit that an ordinary schedule trigger's `sh -c` almost never does) was ONLY slog.Warn'd (fireTrigger's fail-open retry path) and never reached TriggerLoop.trackFailStreak, which reads exclusively from Completed — an operator would see nothing but silent, indefinite per-tick retries in the daemon's own log.
Deliberately does NOT change fireTrigger's own DeleteTriggerRun-on-failure behavior (SweepTriggers' own comment at the call site explains why: an `every`-gapped CompleteTriggerRun would delay the "fail-open, retry next tick" behavior every trigger has always had, all the way out to a full `every` — this sentinel is reported to trackFailStreak ALONGSIDE the existing delete, purely for notification bookkeeping, not as a trigger_runs row of its own).
const TriggerRunSelfHealExitCode = -1
TriggerRunSelfHealExitCode is the sentinel CompleteTriggerRun records for a self-healed row (N-1) — flows into TriggerCompletionResult like any other non-zero exit code, so it also counts toward trackFailStreak's consecutive-failure notification (a self-heal IS a failure worth surfacing). Outside a real command's 0-255 exit code range so it reads unambiguously in logs/notifications.
const TriggerRunSelfHealGrace = 3 * time.Minute
TriggerRunSelfHealGrace bounds how long a trigger_runs row may sit in-flight without ever resolving to a real job's terminal state — either because run.JobID is still empty (SetTriggerRunJobID hasn't landed yet, see fireTrigger) or because s.Jobs.GetJob(run.JobID) keeps erroring (typically: the job row itself is gone, e.g. swept by the 30-day taskless- job GC, since trigger_runs.job_id is not a real FK) — before reconcileInFlight gives up waiting and force-closes it (N-1, Opus review). Without this, a vanished job row wedges single-flight for that (project, trigger) forever: there is no other self-recovery path (a daemon restart's dispatcher.MarkStaleJobsFailed only touches rows that still EXIST in jobs, and `boid trigger run` only ever returns Skipped).
Expressed as elapsed wall-clock time, not a tick counter, deliberately: reconcileInFlight runs from BOTH the periodic TriggerLoop AND RunTriggerNow's own HTTP-handler goroutine, so a shared in-memory counter would need its own mutex to stay -race clean (unlike TriggerLoop.skipStreak/failStreak, which only the single periodic-sweep goroutine ever touches). 3 minutes matches TriggerStuckSkipThreshold-era "3 consecutive sweep ticks" convention at TriggerLoop's own 1-minute Interval (wire.go), while working out to a duration regardless of what Interval or RunTriggerNow call pattern actually applies.
const TriggerTimeoutExitCode = -3
TriggerTimeoutExitCode is the sentinel SweepTriggers records for a run ended by its trigger's own `timeout` — distinct from the other two so the three failure classes stay apart in logs and notifications (self-heal = a job was dispatched but its outcome was never observed; dispatch failure = the job was never dispatched; this = the round ran and took too long).
It flows into TriggerCompletionResult like any other non-zero exit, which is the whole point: with a declared bound, "this is taking too long" stops being something trackSkipStreak has to GUESS at from `every` and becomes an ordinary failure trackFailStreak already knows how to count.
const WorkspaceInitScriptAbsentRevision = apiwire.WorkspaceInitScriptAbsentRevision
const WorkspaceInitScriptCleared = apiwire.WorkspaceInitScriptCleared
const WorkspaceInitScriptContentType = apiwire.WorkspaceInitScriptContentType
from internal/api/workspace_init_script.go
const WorkspaceInitScriptUnchanged = apiwire.WorkspaceInitScriptUnchanged
const WorkspaceInitScriptWritten = apiwire.WorkspaceInitScriptWritten
Variables ¶
var AttachmentAllowedExts = map[string]bool{ ".png": true, ".jpg": true, ".jpeg": true, ".webp": true, ".txt": true, ".md": true, ".json": true, ".log": true, }
AttachmentAllowedExts is the file-extension allowlist for uploads. Both images (for screenshot paste) and a few text formats (for logs / json snippets) are accepted.
var ErrAskPending = errors.New("task_ask: another question is pending")
ErrAskPending is returned by BlockingAskRegistry.Register when the task already has an outstanding blocking ask. It implements decision B1: a second concurrent `boid task ask` for the same task fails immediately rather than queueing behind the first.
var SideEffectConsumesPayload = map[string]bool{ "park": true, "attrs_set": true, "child_added": true, "child_specced": true, "child_dropped": true, "noted": true, }
isShutdownErr reports whether the dispatch failure was caused by the dispatch context being canceled (daemon shutdown). Checks both the ctx directly and the error chain so wrapped child-ctx cancellations are covered. SideEffectConsumesPayload names the action types whose own side effect already consumes the action payload, so ApplyAction must NOT additionally merge that payload into the task's own — see the merge site below for what the pollution looks like.
Exported, and a package-level var rather than a literal inside ApplyAction, so a test can compare it against the COPY of this set that the boid-metaproject skill's python client carries (internal/skills/data/boid-metaproject/scripts/boidmeta/boid_store.py's PAYLOAD_CONSUMING). That copy has to exist — the client refuses to send a payload with a type that would be merged, and it cannot ask the daemon at call time — and a copy nobody checks is exactly how `child_dropped` came to be missing from it for weeks after boid #982 added it here, silently breaking one whole verb in production. Both halves live in one repo now; TestSideEffectConsumesPayload_MatchesMetaprojectClient is what makes that worth anything.
Functions ¶
func AttachmentsRootForTask ¶ added in v0.0.7
AttachmentsRootForTask resolves the on-disk attachments directory for the given task. dataHome is the data root (e.g. filepath.Dir(cfg.DBPath)), the same convention as runtimesDirFor.
taskID must be a single canonical path component (codex review on PR #798, Phase 5b PR2 attachments RPCs): CreateTaskRequest.ID is caller-supplied and saved as the literal DB primary key without validation (internal/api/task_create.go), and the broker (internal/sandbox/broker.go) authorizes attachments ops by comparing that *raw* TaskID string against the token's own context — never a resolved filesystem path. Without this guard, a task literally IDed "alias/../<victim-id>" would pass the broker's string-equality check trivially (both sides carry the identical literal alias) while filepath.Join here silently collapsed it down to the *victim's* real attachments directory — a cross-task leak. Rejecting a non-canonical taskID here (returning "", the same fail-closed sentinel already used for an empty dataHome/taskID) protects every caller uniformly: the write path (EnsureAttachmentsDir, SaveMultipartAttachments) and the read path (ListAttachments, ReadAttachment) all resolve through this one function.
func DeriveProjectIDFromURL ¶ added in v0.1.0
DeriveProjectIDFromURL is the exported form of deriveProjectIDFromURL, wired into orchestrator.ProjectStore.SetDeriveProjectIDFunc (see internal/server/wire.go's buildProjectStore) so ProjectStore.reconcileExpectedProjectID (docs/plans/ workspace-default-project.md 論点h 案1, PR7 round-3 Major fix) can verify that a url-derived expectedID was ACTUALLY derived from the project's current UpstreamURL, rather than merely sharing URLDerivedProjectIDPrefix with one. orchestrator cannot call deriveProjectIDFromURL directly: internal/dispatcher (which it depends on for URL normalization/slugging) already imports orchestrator, and this package imports both — importing this package from orchestrator would cycle. Hence the injection.
func EnsureAttachmentsDir ¶ added in v0.0.7
EnsureAttachmentsDir creates the per-task attachments directory if it does not already exist. Used by handlers right after task creation / before accepting answer attachments so the bind mount has a non-empty source.
func FormatAbortReason ¶ added in v0.4.0
func FormatAbortReason(o TaskOutcome) string
FormatAbortReason renders an outcome's abort reason as one human line, or "" when there is nothing to say — which is the common case for a failure inside the agent's own session, since job_failed records no payload.
func JobLogNoRuntimeMessage ¶ added in v0.1.0
func JobLogNoSuchJobMessage ¶ added in v0.1.0
JobLogNoSuchJobMessage, JobLogNoRuntimeMessage and JobLogTranscriptGoneMessage are the three explanations above, exported so the sandbox-side `boid job log` builtin (internal/server's boidBuiltinExecutor) answers with the same words as the REST endpoint. An agent reading a log inside a sandbox and an operator reading one at a terminal are diagnosing the same thing; having the two surfaces drift into separate vocabularies for it is how "log not available" became meaningless in the first place.
func JobLogTranscriptGoneMessage ¶ added in v0.1.0
func ListAttachments ¶ added in v0.0.13
ListAttachments returns the basenames of the regular files directly under the task's attachments directory, sorted. Subdirectories are never recursed into — attachments are a flat namespace. A task that has never received an attachment (missing directory) returns an empty, non-nil slice rather than an error, matching the RPC's "no data" convention (JSON `[]`, not `null`).
Every symlink is excluded outright, regardless of where it points — codex review on PR #798 (Nit) flagged that the original version only filtered *escaping* symlinks, which could advertise a name ReadAttachment (which now rejects every symlink categorically, via openat2 RESOLVE_NO_SYMLINKS on Linux — see the Major/TOCTOU fix) would then always 404 on. Non-regular entries (FIFOs, sockets, devices — never created by SaveMultipartAttachments, but not something a shared filesystem rules out) are excluded for the same reason: list's admission criteria must exactly match what get can actually serve.
func ReadAttachment ¶ added in v0.0.13
ReadAttachment returns the bytes of one attachment, addressed by its exact basename. name must be a single canonical path component: a traversal or absolute-path attempt ("../../etc/passwd", "/etc/passwd") is rejected by validateAttachmentLookupName before any path is constructed, rather than being silently coerced into some *other* file the way SanitizeAttachmentName's upload-time "pick a safe name to store under" contract does. The actual open+read (readAttachmentBytes, platform- specific — see attachment_read_linux.go) opens the file exactly once and reuses that descriptor for both the containment/type check and the capped read, closing the TOCTOU window a separate check-then-reopen sequence would leave (codex review on PR #798).
func ResolveJSONField ¶ added in v0.0.13
func ResolveJSONField(raw json.RawMessage, path string) (string, error)
ResolveJSONField resolves a dotted path against arbitrary already-marshaled JSON data, using the same segment-traversal / value-formatting rules as ResolveTaskField (missing path → "", scalar → unquoted/stringified, object/array → compact JSON, traversing into a scalar → error). Unlike ResolveTaskField it does no task-specific implicit `payload.` prefixing or `lifecycle` injection — every other Phase 5b PR1 task-context RPC (`boid task current` / `instructions` / `env` / `payload`, docs/plans/phase5-shim-and-task-context.md) shares this generic core so `--field` behaves identically everywhere task_get already established the contract.
func ResolveTaskField ¶
func ResolveTaskField(task *orchestrator.Task, actions orchestrator.LifecycleStore, path string) (string, error)
ResolveTaskField returns the value at the given dotted path against the task.
Path resolution:
- Each dot-separated segment is a JSON key.
- The first segment is matched against top-level Task fields (via JSON tags). When it doesn't match, the path is implicitly resolved inside `payload`, so traits like `awaiting.question`, `artifact.report`, and `lifecycle.abort.message` work without an explicit `payload.` prefix.
- `lifecycle` is a computed trait derived from action history. When lifecycle is referenced, ResolveTaskField calls DeriveLifecycle (when actions is non-nil) and injects the result under `payload.lifecycle` before traversal.
Output format:
- Strings: returned unquoted.
- Numbers and booleans: stringified.
- Objects and arrays: compact JSON.
- Missing path: returns "" with no error.
- Traversing into a scalar with remaining path segments: error.
func SanitizeAttachmentName ¶ added in v0.0.7
SanitizeAttachmentName validates a user-supplied filename and returns the cleaned basename. It rejects anything that doesn't match attachmentNameRe, exceeds the byte cap, has a disallowed extension, or contains only a dot prefix (".env" etc., which the regex would otherwise allow).
func SaveMultipartAttachments ¶ added in v0.0.7
func SaveMultipartAttachments(dataHome, taskID string, files []*multipart.FileHeader) ([]string, error)
SaveMultipartAttachments persists every file under the multipart form field "attachments" into the task-scoped attachments directory. It enforces:
- per-file size cap (AttachmentMaxFileBytes)
- aggregate task-dir size cap (AttachmentMaxTotalBytes)
- filename sanitization (SanitizeAttachmentName)
On success it returns the list of saved basenames. On any error it removes the files it had partially written during this call so the caller can surface the error without leaving orphans behind.
func ValidateAttachmentHeaders ¶ added in v0.0.7
func ValidateAttachmentHeaders(files []*multipart.FileHeader) error
ValidateAttachmentHeaders runs the size + name checks that SaveMultipartAttachments would apply, without touching the filesystem. Web handlers call this *before* creating the task so a bad upload (oversized, bad extension, disallowed name) doesn't leave a half-created task behind.
Types ¶
type AckSignalsRequest ¶ added in v0.4.0
type AckSignalsRequest = apiwire.AckSignalsRequest
type AckSignalsResponse ¶ added in v0.4.0
type AckSignalsResponse = apiwire.AckSignalsResponse
type ActionApplication ¶
type ActionApplication = apiwire.ActionApplication
from internal/api/service.go
type ActionHandler ¶
type ActionHandler struct {
Service WorkflowService
}
func (*ActionHandler) Apply ¶
func (h *ActionHandler) Apply(w http.ResponseWriter, r *http.Request)
func (*ActionHandler) Routes ¶
func (h *ActionHandler) Routes() chi.Router
type ActionListResult ¶ added in v0.4.0
type ActionListResult struct {
Actions []*orchestrator.Action `json:"actions"`
NextCursor string `json:"next_cursor"`
}
ActionListResult is ListActions' return shape: the matching actions plus the cursor a follow-up call should pass as filter.Since.
type ActionListStore ¶ added in v0.4.0
type ActionListStore interface {
// ListActionsSince returns the actions matching filter (oldest first)
// plus the next cursor. See orchestrator.ListActionsSince's own doc
// comment for the pagination/scoping contract.
ListActionsSince(filter orchestrator.ActionListFilter) ([]*orchestrator.Action, string, error)
}
ActionListStore provides the workspace-scoped read backing docs/plans/ ingestion-identity.md PR-3 (B-3)'s BoidOpActionList. Deliberately separate from ActionStore (ListActionsByTask, per-task, embedded in TxStore) for the same reason CardStore/TaskIdentityStore are their own interfaces: this is a non-transactional READ used outside WithinTx — the same "TaskWorkflowService.TaskTriage CardStore" narrowing pattern (workflow.go), not TxStore.
type ActionStore ¶
type ActionStore interface {
// CreateAction takes ctx so the internal-signal ingest step it performs
// (docs/plans/boid-internal-signal-inbox.md §4.5) can see the write's
// origin project via orchestrator.WriterProjectIDFromContext when this
// call was routed through internal/server/boid_executor.go's
// ExecuteBoidBuiltin (the only place that ever stamps it) — never
// consulted for anything else CreateAction does.
CreateAction(ctx context.Context, action *orchestrator.Action) error
ListActionsByTask(taskID string) ([]*orchestrator.Action, error)
}
type AnswerSuggestionRequest ¶ added in v0.4.0
type AnswerSuggestionRequest struct {
Answer string `json:"answer"`
Verb string `json:"verb,omitempty"`
Basis string `json:"basis,omitempty"`
}
AnswerSuggestionRequest is the Web UI's accept/reject form payload for a task_triage suggestion (docs/plans/ingestion-identity.md PR-3, J-6). Answer is required; Verb/Basis are optional (recorded, never validated by the daemon — see answeredPayload's own doc comment).
type AnswerTaskRequest ¶
type AnswerTaskRequest = apiwire.AnswerTaskRequest
type ApplyActionRequest ¶
type ApplyActionRequest = apiwire.ApplyActionRequest
from internal/api/action.go
type BlockingAskRegistry ¶ added in v0.0.6
type BlockingAskRegistry struct {
// contains filtered or unexported fields
}
BlockingAskRegistry coordinates harness-independent blocking Q&A. When an agent calls `boid task ask`, the broker holds the RPC connection open and the server-side handler blocks in Wait until the user/supervisor answers (via TaskHandler.Answer → AnswerTask → Notify) or the context is cancelled (daemon shutdown / agent disconnect).
The registry is purely in-memory: a daemon restart drops every pending ask. That is consistent — the sandbox process backing the blocked RPC dies with the daemon too, so there is nothing to resume.
func NewBlockingAskRegistry ¶ added in v0.0.6
func NewBlockingAskRegistry() *BlockingAskRegistry
NewBlockingAskRegistry returns an initialised registry.
func (*BlockingAskRegistry) Cancel ¶ added in v0.0.6
func (r *BlockingAskRegistry) Cancel(qid string)
Cancel removes the registration for qid (and the task it belongs to). It does not unblock Wait by itself — a blocked Wait observes ctx cancellation — but it frees the B1 slot so the task can ask again. Idempotent and safe to defer.
func (*BlockingAskRegistry) Has ¶ added in v0.0.6
func (r *BlockingAskRegistry) Has(qid string) bool
Has reports whether qid currently has a registration. Intended for tests and diagnostics.
func (*BlockingAskRegistry) Notify ¶ added in v0.0.6
func (r *BlockingAskRegistry) Notify(qid, answer string) bool
Notify delivers answer to the waiter registered for qid. It returns true when a registration exists and the answer was accepted, false when no waiter is registered (e.g. the agent already disconnected and Cancel ran) or an answer was already delivered. The send is non-blocking thanks to the buffered channel, so Notify never blocks even if Wait has not yet been scheduled.
func (*BlockingAskRegistry) Register ¶ added in v0.0.6
func (r *BlockingAskRegistry) Register(taskID, qid string) error
Register reserves the answer channel for (taskID, qid). It MUST be called before the task transitions to awaiting so an answer that arrives immediately afterwards is never dropped. The check-and-insert is atomic under the registry lock, so two concurrent asks for the same task can never both succeed.
B1 (relaxed): a second pending ask for the same task fails with ErrAskPending ONLY when it carries a DIFFERENT question id. Re-registering the SAME qid is a re-attach — an agent whose `boid task ask` was killed by a harness command-timeout retrying the identical question — and is allowed. The re-attach installs a fresh channel; any prior waiter is already tearing down on its cancelled context. (Even if its deferred Cancel later clobbers this channel, the durable PendingAnswer path backstops delivery, so at worst the fast path degrades to one extra ask round-trip.)
func (*BlockingAskRegistry) Wait ¶ added in v0.0.6
Wait blocks until an answer is delivered for qid via Notify or ctx is cancelled. qid must have been registered; an unknown qid is a programming error and returns immediately. The caller is responsible for Cancel(qid) cleanup (typically via defer) on every exit path.
type BrokerHandler ¶
type BrokerHandler struct {
Registry BrokerRegistry
}
func (*BrokerHandler) Register ¶
func (h *BrokerHandler) Register(w http.ResponseWriter, r *http.Request)
func (*BrokerHandler) Routes ¶
func (h *BrokerHandler) Routes() chi.Router
type BrokerRegisterRequest ¶
type BrokerRegisterRequest struct {
Commands map[string]orchestrator.HostCommandSpec `json:"commands"`
BuiltinPolicies map[string]sandbox.BuiltinPolicy `json:"builtin_policies,omitempty"`
ProjectID string `json:"project_id,omitempty"`
}
type BrokerRegisterResponse ¶
type BrokerRegisterResponse struct {
Token string `json:"token"`
Socket string `json:"socket"`
// ResolvedHostCommands used to echo back
// dispatcher.ResolveHostCommands' absolute-path-keyed map so `boid exec`
// could feed it into SandboxRuntimeInfo (matching shim bind-mount
// targets to broker policy keys without re-resolving on the client
// side). That map has been dead weight since the Phase 5 5a-3 cutover
// retired the shim's absolute-host-path bind mount scheme
// (SandboxRuntimeInfo.ResolvedHostCommands was deleted, hostCommandMounts
// and buildHostCommandNamesEnv with it — see
// docs/plans/phase5-shim-and-task-context.md 5a PR3). No client reads
// this field any more; it is retained as omitempty for one release so
// any stale caller decoding the response doesn't blow up on a missing
// key, and will be removed outright once no versions of the CLI still
// speak the older shape.
ResolvedHostCommands map[string]orchestrator.CommandDef `json:"resolved_host_commands,omitempty"`
}
type BrokerRegistry ¶
type BrokerRegistry interface {
RegisterBrokerCommands(commands map[string]orchestrator.HostCommandSpec, builtinPolicies map[string]sandbox.BuiltinPolicy, projectID string) (*BrokerRegisterResponse, error)
}
type CardHandler ¶ added in v0.4.0
type CardHandler struct {
Service CardReadService
}
CardHandler serves the card read surface (docs/plans/ cross-project-issue-triage.md Phase 1 PR-5a).
Mounted at its own /api/cards root (renamed from /api/triage by docs/plans/card-model-cleanup.md PR-3 §4) rather than as /api/tasks/{id}/cards + a sibling list route: the listing needs a collection endpoint of its own, and hanging it off /api/tasks would put a static segment in the same position as the {id} wildcard.
func (*CardHandler) Get ¶ added in v0.4.0
func (h *CardHandler) Get(w http.ResponseWriter, r *http.Request)
Get returns one triage task's full projection (stored columns + the actions-derived parked_from + the opaque detail blob).
func (*CardHandler) List ¶ added in v0.4.0
func (h *CardHandler) List(w http.ResponseWriter, r *http.Request)
List returns the projections of the triage tasks matching the query filters. project_id and status are passed straight through to the same orchestrator.TaskFilter the task listing uses, so "cards_live" (renamed from "triage" — the old name is still accepted as a compatibility alias, docs/plans/webui-detail-list-redesign.md PR-4 §3.6) and any concrete status value all work here too. "queue_next" is ALSO still a valid string to pass, but PR-4 removed its special membership predicate entirely — it now falls through to a literal `t.status = 'queue_next'` match, which can never match a real row, so it deterministically returns an empty list rather than an error (store.go's own doc comment). "queue" (the old broad pre-execution-status superset) was removed in PR-2 — docs/plans/ suggestion-as-state-transition-impl.md §4.1.
func (*CardHandler) Routes ¶ added in v0.4.0
func (h *CardHandler) Routes() chi.Router
type CardReadService ¶ added in v0.4.0
type CardReadService interface {
GetCard(taskID string) (*CardView, error)
ListCards(filter orchestrator.TaskFilter) ([]*CardView, error)
}
CardReadService is the read surface CardHandler needs — narrowed from *TaskWorkflowService so the handler can be tested against a fake.
type CardStore ¶ added in v0.4.0
type CardStore interface {
UpsertTaskTriage(tt *orchestrator.CardAttrs) error
GetTaskTriage(taskID string) (*orchestrator.CardAttrs, error)
// ListTaskTriageByTaskIDs batch-fetches sidecar rows for a set of task
// IDs in O(chunks) queries instead of O(N) GetTaskTriage calls (BD-8
// 残件1) — see orchestrator.ListTaskTriageByTaskIDs's doc comment for
// the chunking rationale and the "batch replaces per-row error
// tolerance" tradeoff. A taskID with no sidecar row is simply absent
// from the returned map, never an error.
ListTaskTriageByTaskIDs(taskIDs []string) (map[string]*orchestrator.CardAttrs, error)
DeleteTaskTriage(taskID string) error
// ParkedFrom derives which status (triaged/ready/working) a parked task
// was parked from, from the actions log (not a stored column — 決定13).
ParkedFrom(taskID string) (orchestrator.TaskStatus, error)
}
CardStore provides access to a card's CardAttrs columns (kind/urgency/ wake_at/wake_task_id/suggestion_verb/detail). Through card-model-cleanup PR-1 these lived in a separate task_triage sidecar table, kept apart from TaskStore because TaskStore's orchestrator.Task was the API DTO (marshaled to JSON with no conversion layer) and a column added there auto-exposed in every task API response. PR-2 (docs/plans/card-model-cleanup.md, migration 0045) folds these columns into the same tasks row (filtered to type='card') and gives Task a genuinely nested `card` JSON key instead — this interface's shape is kept as-is so the many card-lifecycle call sites (workflow_card.go et al.) do not need to change, only what backs them.
SeedTaskTriage — the "assert this task IS a triage task" primitive used to live here — is GONE as of PR-2: a card is type='card' from the moment CreateTask makes it, so there is no longer a separate act of "seeding" a row after the fact (design doc §3.6).
type CardView ¶ added in v0.4.0
type CardView struct {
TaskID string `json:"task_id"`
ProjectID string `json:"project_id"`
Title string `json:"title,omitempty"`
Status orchestrator.TaskStatus `json:"status"`
// Description is the task row's body. It rides along with Title for the
// same reason Title does — a caller rendering the card needs both — but it
// was missed in PR-5a. The cost of that omission is concrete: khi's
// project_card.py renders the note body FROM this view, so without it every
// sweep pays one extra `boid task show --field description` round trip per
// card just to diff what it is about to write (2026-08-14).
Description string `json:"description,omitempty"`
Kind string `json:"kind,omitempty"`
Urgency string `json:"urgency,omitempty"`
WakeAt *time.Time `json:"wake_at,omitempty"`
WakeTaskID string `json:"wake_task_id,omitempty"`
// SuggestionVerb mirrors Kind/Urgency: a promoted task_triage column
// (PR-2, docs/plans/suggestion-as-state-transition-impl.md §4.1), carried
// through verbatim for the same reason those two are — a caller reading
// this view should not have to re-parse Detail's blob to learn what
// store.go's own queue predicate already keys on.
SuggestionVerb string `json:"suggestion_verb,omitempty"`
// ParkedFrom is only populated for a parked task: it answers "which side
// will this wake back to (triaged, ready, or — since BD-9's wake_working
// fix, 2026-08-18 — working)". Deliberately left empty for every other
// status rather than reporting the most recent historical park — a stale
// origin on a task that is no longer parked would be actively misleading
// to a caller deciding whether Go has already been given. A consumer
// (e.g. khi's project_card.py) that branches on this field must handle
// "working" as a valid third value, not just triaged/ready.
ParkedFrom orchestrator.TaskStatus `json:"parked_from,omitempty"`
Detail json.RawMessage `json:"detail,omitempty"`
}
CardView is the read-side projection of a triage task (docs/plans/cross-project-issue-triage.md Phase 1 PR-5a).
決定14 makes the daemon the SOLE source of truth for a triage task's state: khi retires its own decisions log and fold, keeping only claims (source dialect) and the note body. That is only viable if the workspace side can read the state back, and read it COMPLETELY — including the fields that are derived rather than stored. Before PR-5a there was no read surface at all: the sidecar was reachable only from inside the daemon (Web UI's queue_next enrichment), and `boid task show` returns orchestrator.Task's own columns, which deliberately exclude everything triage-specific (see CardStore's doc comment).
The view unions three sources:
- the task row (status/project/title/description) — state itself lives here, not in the sidecar
- the task_triage columns (kind/urgency/wake_at/wake_task_id)
- ParkedFrom, DERIVED from the actions log and stored nowhere (決定13: event 追記を正、state は導出). Omitting it would be the exact gap the PR was asked to close — "action から導出するフィールドが取れないのは 余計おかしい".
Detail is passed through verbatim as an opaque blob. The daemon does not interpret its keys (逆輸入3's boundary: channel-specific knowledge stays on the workspace side), so neither does this projection.
type ConfigApplyResult ¶ added in v0.1.0
type ConfigApplyResult = apiwire.ConfigApplyResult
from internal/api/config.go
type ConfigHandler ¶ added in v0.0.13
type ConfigHandler struct {
Service ConfigService
}
func (*ConfigHandler) Apply ¶ added in v0.1.0
func (h *ConfigHandler) Apply(w http.ResponseWriter, r *http.Request)
Apply handles POST /api/config[?force=true]: `boid config apply -f`/ `edit`'s whole-document replace, gated by If-Match unless ?force=true is passed — the same convention PUT /api/workspaces/{slug} already established (internal/api/workspace.go's Update). See ConfigService.ApplyConfigYAML's doc comment for the validate-persist- reload-and-revision-check contract.
func (*ConfigHandler) Get ¶ added in v0.1.0
func (h *ConfigHandler) Get(w http.ResponseWriter, r *http.Request)
Get handles GET /api/config: the daemon's current effective config.yaml, verbatim, as application/yaml, with an ETag response header mirroring the revision (BLOCKER 1, codex review round 1) so a caller can round-trip it straight into a subsequent POST's If-Match. `boid config get`/`apply`/`edit` all fetch this first as their working copy (`set`/ `unset` route through POST /api/config/mutate instead — see Mutate).
func (*ConfigHandler) KitsDir ¶ added in v0.0.13
func (h *ConfigHandler) KitsDir(w http.ResponseWriter, r *http.Request)
KitsDir handles GET /api/config/kits-dir: the daemon's effective KitsDir, so a CLI client-side helper (cmd/workspace.go's ensureWorkspaceExistsForAssign, MAJOR 1) can resolve a legacy workspace.yaml's `kits:` references against the *running daemon's* kits directory instead of independently re-deriving a default that silently disagrees with it whenever the daemon was started with a custom --kits-dir.
func (*ConfigHandler) Mutate ¶ added in v0.1.0
func (h *ConfigHandler) Mutate(w http.ResponseWriter, r *http.Request)
Mutate handles POST /api/config/mutate: `boid config set/unset`'s single dotted-path operation, performed server-side as one atomic read-modify-write (BLOCKER 1, codex review round 1). See ConfigService.MutateConfig's doc comment.
func (*ConfigHandler) Routes ¶ added in v0.0.13
func (h *ConfigHandler) Routes() chi.Router
type ConfigMutateOp ¶ added in v0.1.0
type ConfigMutateOp = apiwire.ConfigMutateOp
type ConfigMutateRequest ¶ added in v0.1.0
type ConfigMutateRequest = apiwire.ConfigMutateRequest
type ConfigMutateResult ¶ added in v0.1.0
type ConfigMutateResult = apiwire.ConfigMutateResult
type ConfigService ¶ added in v0.0.13
type ConfigService interface {
// KitsDir returns the daemon's effective base directory for installed
// kits (server.Config.KitsDir, resolved once at startup — see
// cmd/start.go's defaultKitsDir()/--kits-dir flag).
KitsDir() string
// ConfigYAML returns the daemon's current effective config.yaml
// document, alongside its current revision — the same bytes `boid
// config get` (no key) prints verbatim, and what every `boid config
// get/apply/edit` invocation fetches first as its "before" snapshot.
// revision is the same value GET /api/config's ETag response header
// carries; round-tripping it into a later POST's If-Match is BLOCKER
// 1's optimistic-concurrency guard (codex review round 1).
ConfigYAML() (data []byte, revision string, err error)
// ApplyConfigYAML validates a full replacement config.yaml document
// (internal/config.ValidateYAML), and on success atomically persists
// it and hot-applies whichever changed keys the daemon can apply live
// (docs/plans/volume-only-daemon.md §論点 f's reload-semantics table),
// returning operator-facing warning lines for anything that could not
// be hot-applied (gateway.forges.* — restart required; sandbox.backend
// — retirement notice). A validation failure leaves the daemon's live
// config and on-disk config.yaml untouched.
//
// Unless force is true, ifMatch must be non-empty and equal the
// current revision — the same ETag/If-Match convention `boid workspace
// edit` already established (see UpdateWorkspace) — otherwise the call
// fails with a *StatusError (428 Precondition Required when ifMatch is
// empty, 412 Precondition Failed when it is stale) and neither
// validates nor persists data.
ApplyConfigYAML(data []byte, ifMatch string, force bool) (ConfigApplyResult, error)
// MutateConfig performs one or more dotted-path set/unset operations as
// a single atomic, server-side read-modify-write (BLOCKER 1, codex
// review round 1) — `boid config set/unset` route here instead of a
// client-side GET → mutate → POST round trip, which left a window for
// two concurrent calls to silently lose one's change. Multiple
// operations (ConfigMutateRequest.Ops, BLOCKER, codex review round 1 on
// PR #831) are applied to the same document before it is validated
// once, so a structural, multi-leaf change (e.g. a brand-new
// gateway.forges.<id> entry) can be created in one call. See
// internal/server/config_edit.go's MutateConfig doc comment for the
// full rationale.
MutateConfig(req ConfigMutateRequest) (ConfigMutateResult, error)
}
ConfigService is the daemon-side dependency behind /api/config (MAJOR 1, codex review round 1, docs/plans/workspace-db-consolidation.md Phase 2.5 PR7's read-only KitsDir surface, extended by docs/plans/ volume-only-daemon.md §論点 f's `boid config get/set/unset/apply/edit` CLI with a full read+validate+persist+hot-reload surface, and further extended by BLOCKER 1's codex review round 1 fix: a server-side mutate endpoint plus ETag/If-Match concurrency on the full-document endpoints). Implemented directly by *server.Server — no adapter type is needed, mirroring HostCommandsService's own convention in this package.
type ConnectorRef ¶ added in v0.4.0
type ConnectorRef = apiwire.ConnectorRef
type CreateProjectFromGitURLRequest ¶ added in v0.1.0
type CreateProjectFromGitURLRequest struct {
URL string `json:"url"`
Workspace string `json:"workspace"`
Name string `json:"name,omitempty"`
}
CreateProjectFromGitURLRequest is POST /api/projects/git's body (docs/plans/volume-only-daemon.md §論点a — `boid project add <git-url> --workspace=<name> [--name=<project-name>]`). Workspace is required; Name empty derives the project name from URL's last path component.
type CreateProjectRequest ¶
type CreateProjectRequest struct {
WorkDir string `json:"work_dir"`
}
type CreateTaskRequest ¶
type CreateTaskRequest = apiwire.CreateTaskRequest
type DeviceAuthHandler ¶ added in v0.0.13
type DeviceAuthHandler struct {
Pairing loginPairing
Store deviceAuthStore
Limiter loginRateLimiter
Registry *auth.ConnectionRegistry
PublicURL string
}
DeviceAuthHandler serves the Bearer device-auth endpoints used by remote CLI clients (docs/plans/cli-remote-connection.md Phase 3 PR0):
- POST /api/auth/device — public, rate-limited. Redeems a pairing code (the same one `boid web pair` issues for the cookie flow) for a long-lived Bearer device token.
- DELETE /api/auth/devices/{id} — Bearer-authenticated, self-revoke only.
It is deliberately a separate surface from WebManagementHandler (mounted at /api/web/*, UNIX-socket-only, trusted local-admin surface with no ownership check: /api/web/pair, /api/web/devices) — this handler is reachable over TCP by a caller who starts out holding nothing but a valid pairing code, so PostDevice carries its own rate limiting and DeleteDevice enforces "only revoke yourself".
func (*DeviceAuthHandler) DeleteDevice ¶ added in v0.0.13
func (h *DeviceAuthHandler) DeleteDevice(w http.ResponseWriter, r *http.Request)
DeleteDevice revokes the caller's own device only, and only when the caller authenticated via Bearer token. The {id} path param must match the Bearer-authenticated device ID the auth middleware placed in the request context (auth.DeviceIDFromContext + auth.AuthMethodFromContext).
The auth-method check exists because a session-cookie caller has other, richer paths for managing their own devices (the WebManagementHandler /api/web/devices UNIX-socket surface used by `boid web revoke`) — this endpoint is explicitly the *Bearer* self-revoke path used by `boid logout`, and mixing the two auth models on the same route would muddle the responsibility split.
This is intentionally stricter than WebManagementHandler.DeleteDevice (UNIX-socket-only local admin, no ownership check) — this endpoint is reachable by any Bearer-holding remote caller, so it must not let one device revoke another's token.
func (*DeviceAuthHandler) PostDevice ¶ added in v0.0.13
func (h *DeviceAuthHandler) PostDevice(w http.ResponseWriter, r *http.Request)
PostDevice redeems a one-time pairing code (auth.PairingManager — the same manager instance the cookie-based /login and /auth flows share) for a long-lived Bearer device token. Unlike those flows, no session cookie is ever set here: the raw token is returned exactly once, in the response body, and only its SHA-256 hash (auth.HashToken) is ever persisted (Store.InsertDeviceToken).
func (*DeviceAuthHandler) Routes ¶ added in v0.0.13
func (h *DeviceAuthHandler) Routes() chi.Router
type DeviceGCStore ¶
type DispatchCoordinator ¶
type DispatchCoordinator interface {
DispatchAndAdvance(ctx context.Context, task *orchestrator.Task, meta *orchestrator.ProjectMeta, sm *orchestrator.StateMachine) (*orchestrator.DispatchResult, error)
ReplayHook(ctx context.Context, task *orchestrator.Task, meta *orchestrator.ProjectMeta, sm *orchestrator.StateMachine, hookID string) (*orchestrator.ReplayResult, error)
}
type DuplicateTaskRequest ¶
type DuplicateTaskRequest = apiwire.DuplicateTaskRequest
type ExecDispatcher ¶ added in v0.0.10
type ExecDispatcher interface {
StartExec(ctx context.Context, req StartExecRequest) (*StartExecResult, error)
}
ExecDispatcher launches a JobKindExec job (arbitrary argv, shell harness, no HarnessAdapter agent) through Runner.Dispatch() and returns the runtime job id. Implemented by internal/server's sessionDispatcherAdapter.
type GCAppService ¶
type GCAppService struct {
Store GCStore
DeviceStore DeviceGCStore // optional; deletes revoked devices on GC
}
func (*GCAppService) GC ¶
func (s *GCAppService) GC(olderThan time.Duration, dryRun bool) (*orchestrator.GCResult, error)
GC implements orchestrator.GCStore so GCAppService can be passed to GCLoop.
func (*GCAppService) Run ¶
func (s *GCAppService) Run(olderThan time.Duration, dryRun bool) (*orchestrator.GCResult, error)
type GCHandler ¶
type GCHandler struct {
Service GCService
// Homes, when non-nil, is the engine-backed view of workspace HOME
// volumes (docs/plans/workspace-home-volume-persistence.md 論点 a-2, PR7)
// used to list them and their sizes in the response (docs/plans/
// home-workspace-volume.md Phase 4 PR5: "サイズ可視化のみで開始、自動
// prune なし"). Left nil, the response omits workspace_homes entirely —
// no size listing, and (unchanged since PR5) no home is ever deleted by
// GC either way. See WorkspaceHomeStore's doc comment for why the engine
// handle, rather than a runtimes directory, is the gate.
Homes WorkspaceHomeStore
// Workspaces, when set, is consulted to flag orphaned homes (a workspace
// HOME volume with no corresponding workspace row) in the
// workspace_homes listing. Optional: a nil Workspaces just means every
// entry reports orphan=true (ListWorkspaceHomeSizes's degrade-gracefully
// path — see its doc comment).
Workspaces WorkspaceSlugLister
}
type GlobalJobStore ¶
type GlobalJobStore interface {
ListJobsWithContext(filter JobListFilter) ([]JobWithContext, error)
}
GlobalJobStore supports cross-task job listing with context (task title, project name).
type HookService ¶
type HookService interface {
ReplayHook(ctx context.Context, taskID string, req ReplayHookRequest) (*ReplayHookResult, error)
ListHooksForStatus(taskID, status string) ([]orchestrator.Hook, error)
}
HookService provides hook replay and hook listing operations.
type HostCommandsHandler ¶ added in v0.0.13
type HostCommandsHandler struct {
Service HostCommandsService
}
func (*HostCommandsHandler) List ¶ added in v0.0.13
func (h *HostCommandsHandler) List(w http.ResponseWriter, r *http.Request)
List handles GET /api/host_commands: the sorted list of host_commands names known to the daemon (docs/plans/workspace-db-consolidation.md plan doc contract: "参照名一覧を返す契約"), useful for Web UI / CLI (`boid host-commands list`) validation of a workspace's host_commands references. MINOR 1 (codex review): this used to return the full aggregated definition map (path/env/policy per name) instead of just the name list the plan doc specifies — a caller validating references has no business seeing (or needing to parse) the internal command policy.
func (*HostCommandsHandler) Reload ¶ added in v0.0.13
func (h *HostCommandsHandler) Reload(w http.ResponseWriter, r *http.Request)
Reload handles POST /api/host_commands/reload: re-read the aggregated config from disk after a hand edit (the plan doc's documented way to add/adjust a host_command without a kit).
func (*HostCommandsHandler) Routes ¶ added in v0.0.13
func (h *HostCommandsHandler) Routes() chi.Router
type HostCommandsProvider ¶ added in v0.0.13
type HostCommandsProvider interface {
HostCommands() map[string]orchestrator.HostCommandSpec
}
HostCommandsProvider exposes the daemon's live aggregated host_commands snapshot (name -> spec) for reference-name validation on workspace create/update (docs/plans/workspace-db-consolidation.md MAJOR 2, codex review: an unresolvable meta.HostCommands reference must be rejected with 400 at write time rather than silently persisted and later warned-about + skipped at dispatch). Implemented by *server.Server, which already exposes this exact method for HostCommandsService above.
type HostCommandsService ¶ added in v0.0.13
type HostCommandsService interface {
// HostCommands returns a snapshot of the daemon's aggregated
// host_commands config (raw/unexpanded — see
// orchestrator.ExpandHostCommandsForDispatch's doc comment for why).
HostCommands() map[string]orchestrator.HostCommandSpec
// ReloadHostCommands re-reads ~/.config/boid/host_commands.yaml from
// disk and swaps it in, live, without a daemon restart.
ReloadHostCommands() error
}
HostCommandsService is the daemon-side dependency behind GET /api/host_commands and POST /api/host_commands/reload (docs/plans/workspace-db-consolidation.md PR4 Step G). Implemented directly by *server.Server (its HostCommands()/ReloadHostCommands() methods already match this shape) — no adapter type is needed, unlike some of the other *Handler.Service fields in this package.
type ImportError ¶
type ImportError = apiwire.ImportError
type ImportResult ¶
type ImportResult = apiwire.ImportResult
type JobCompletion ¶
type JobDoneRequest ¶
type JobHandler ¶
type JobHandler struct {
Jobs JobStore
Global GlobalJobStore // optional: enables cross-task listing when task_id is absent
Service WorkflowService
LogReader JobLogReader // optional: enables static GET /{id}/log
SSEHandler http.Handler // optional: enables SSE streaming for GET /{id}/log?follow=true
}
func (*JobHandler) AgentStop ¶
func (h *JobHandler) AgentStop(w http.ResponseWriter, r *http.Request)
AgentStop asks the daemon to deliver SIGUSR1 to the runtime pgrp. claude.Adapter.Run() catches the signal and forwards SIGTERM to the claude child while the surrounding runner-inner-child keeps running and posts `boid job done --output-file payload_patch.json` through the broker — that callback remains the canonical CompleteJob caller, preserving the agent's session id without racing against UnregisterJob. See WorkflowService.StopAgent for the lifecycle rationale.
func (*JobHandler) Done ¶
func (h *JobHandler) Done(w http.ResponseWriter, r *http.Request)
func (*JobHandler) Get ¶
func (h *JobHandler) Get(w http.ResponseWriter, r *http.Request)
func (*JobHandler) List ¶
func (h *JobHandler) List(w http.ResponseWriter, r *http.Request)
func (*JobHandler) Log ¶
func (h *JobHandler) Log(w http.ResponseWriter, r *http.Request)
func (*JobHandler) Patch ¶ added in v0.0.4
func (h *JobHandler) Patch(w http.ResponseWriter, r *http.Request)
func (*JobHandler) Routes ¶
func (h *JobHandler) Routes() chi.Router
type JobLifecycle ¶
type JobLifecycle interface {
CompleteJob(jobID string, result JobCompletion)
UnregisterJob(jobID string)
CleanupTaskWindow(taskID string)
StopJobRuntime(runtimeID string)
// SignalJobRuntime delivers a single Unix signal to the runtime's process
// group. Phase 3-b uses it to graceful-stop the agent (SIGUSR1) without
// tearing down the surrounding sandbox runtime: claude.Adapter.Run() has a
// signal.Notify(SIGUSR1) handler that translates the group signal into a
// SIGTERM toward the claude child, then normalises the resulting exit
// status into Result.StoppedByDaemon=true.
SignalJobRuntime(runtimeID string, sig syscall.Signal)
}
type JobListFilter ¶
type JobListFilter = apiwire.JobListFilter
type JobLogReader ¶
type JobLogReader interface {
ReadJobLog(runtimeID string) ([]byte, error)
StatJobLog(runtimeID string) (size int64, mtime time.Time, err error)
}
JobLogReader reads the transcript log for a given runtime.
type JobLogSSEHandler ¶
type JobLogSSEHandler struct {
Subscriber dispatcher.RuntimeSubscriber
Registry *auth.ConnectionRegistry
}
JobLogSSEHandler streams live job output as Server-Sent Events on GET /{id}/log?follow=true.
func (*JobLogSSEHandler) ServeHTTP ¶
func (h *JobLogSSEHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
type JobWithContext ¶
type JobWithContext = apiwire.JobWithContext
type ListSignalsResponse ¶ added in v0.4.0
type ListSignalsResponse = apiwire.ListSignalsResponse
type LoginHandler ¶
type LoginHandler struct {
Pairing loginPairing
Signer loginSigner
Store loginDeviceStore
Limiter loginRateLimiter
}
LoginHandler handles /login and /auth.
func (*LoginHandler) GetAuth ¶
func (h *LoginHandler) GetAuth(w http.ResponseWriter, r *http.Request)
GetAuth renders the confirmation page for a magic link / QR scan. It is deliberately side-effect free — it does NOT redeem the token.
The previous version redeemed on GET, which made the single-use code unusable in practice on a phone: browser preloading, QR-scanner link previews, in-app-browser prefetching and even a plain reload all issue a GET of their own, burning the code before (or instead of) the human's real navigation. The human then landed on /login?error=invalid_code holding a code that had just been spent by a robot. Consuming a one-time credential is a state change, so it belongs behind the POST that PostAuth serves.
func (*LoginHandler) GetLogin ¶
func (h *LoginHandler) GetLogin(w http.ResponseWriter, r *http.Request)
func (*LoginHandler) PostAuth ¶ added in v0.1.0
func (h *LoginHandler) PostAuth(w http.ResponseWriter, r *http.Request)
PostAuth redeems the token carried by the confirmation page's form. This is the only path that spends a pairing code from the browser flow.
func (*LoginHandler) PostLogin ¶
func (h *LoginHandler) PostLogin(w http.ResponseWriter, r *http.Request)
type MetaStore ¶
type MetaStore interface {
Get(id string) (*orchestrator.ProjectMeta, bool)
// GetWithWorkspace returns the project meta with workspace.yaml (kits,
// env, capabilities) hydrated in. Use this whenever the caller dispatches
// hooks or otherwise needs the resolved runtime view.
GetWithWorkspace(ctx context.Context, projectID string) (*orchestrator.ProjectMeta, error)
}
type Notifier ¶
Notifier sends an agent-driven notification for a task. Implementations typically exec a user-configured command. nil-safe at the call site: TaskAppService.NotifyTask returns an error when Notify is unset.
type NotifyTaskRequest ¶
type NotifyTaskRequest = apiwire.NotifyTaskRequest
from internal/api/task.go
type OAuthLoginHandler ¶ added in v0.1.0
type OAuthLoginHandler struct {
Service OAuthLoginService
}
OAuthLoginHandler serves `boid secret oauth login <service>`'s three daemon endpoints under whatever prefix internal/server/wire.go mounts it at (POST .../login, GET .../login/{id}, POST .../login/{id}/complete).
func (*OAuthLoginHandler) Complete ¶ added in v0.1.0
func (h *OAuthLoginHandler) Complete(w http.ResponseWriter, r *http.Request)
Complete implements POST .../login/{id}/complete — the loopback flow's browser-callback code (forwarded by the CLI's local listener) or the manual flow's user-pasted OOB code. Every CompleteLogin failure (unknown/expired/already-completed session, state mismatch, upstream exchange failure, ...) is reported as 400 — see Start's own doc comment for why this handler does not attempt to distinguish these from LoginManager's plain error strings.
func (*OAuthLoginHandler) Routes ¶ added in v0.1.0
func (h *OAuthLoginHandler) Routes() chi.Router
func (*OAuthLoginHandler) Start ¶ added in v0.1.0
func (h *OAuthLoginHandler) Start(w http.ResponseWriter, r *http.Request)
Start implements POST .../login. Every failure here is reported as 400 (the request as given cannot be satisfied right now — an unrecognized flow config, a device_authorization_endpoint call failing, ...) except two structurally-derivable cases: h.Service == nil (503 — the daemon has no secret store/OAuth2 machinery configured at all, mirroring SecretHandler's own systemic-unavailability convention) and ProviderForService reporting ok=false (404 — service is genuinely unknown or not an oauth2-kind service, a structural fact this handler can check without parsing any error string).
func (*OAuthLoginHandler) Status ¶ added in v0.1.0
func (h *OAuthLoginHandler) Status(w http.ResponseWriter, r *http.Request)
Status implements GET .../login/{id} — the CLI's device-flow poll (docs/ plans/api-gateway.md §7: the daemon polls the real provider in the background; the CLI only ever polls THIS cheap, local, daemon-session check). 404 when the session id is unknown — ok=false is a structural fact from LoginStatus, never a parsed error string.
type OAuthLoginService ¶ added in v0.1.0
type OAuthLoginService interface {
// ProviderForService resolves a config.yaml services.<name> entry to
// the oauth_providers.<name> its auth.kind: oauth2 config references.
// ok is false when service is unknown OR configured with any auth.kind
// other than oauth2 (mirrors apigateway.CredentialProvider.
// OAuth2ProviderFor exactly — the adapter just forwards to it).
ProviderForService(service string) (provider string, ok bool)
// KnowsProvider reports whether name is itself a configured
// oauth_providers.<name> entry. Start uses it as a fallback when the
// argument does not name a service — see its own doc comment for why
// naming the provider directly is legitimate rather than a typo to
// reject.
KnowsProvider(name string) bool
// StartLogin begins a new login session — see
// apigateway.LoginManager.StartLogin's own doc comment for the full
// per-flow contract (redirectURI is only meaningful for the loopback
// flow; the CLI always supplies it regardless of which flow the
// service turns out to use). account is the optional credential-account
// qualifier (docs/plans/api-gateway-credential-accounts.md D9) — ""
// means unqualified, byte-identical to every call site that predates
// this parameter.
StartLogin(namespace, provider, redirectURI, account string) (*OAuthLoginStart, error)
// CompleteLogin finishes a loopback or manual session — see
// apigateway.LoginManager.CompleteLogin's own doc comment (state is
// ignored for manual, which never had one to check).
CompleteLogin(sessionID, code, state string) error
// LoginStatus reports a session's current lifecycle state — ok is
// false when sessionID is unknown.
LoginStatus(sessionID string) (status, errMsg string, ok bool)
}
OAuthLoginService is the daemon-side surface `boid secret oauth login <service>` (docs/plans/api-gateway.md §7, PR3) drives, implemented by internal/server/wire.go's adapter over apigateway.CredentialProvider (the service->provider lookup) and apigateway.LoginManager (the actual device/loopback/manual flow machinery) — kept as a narrow interface (mirroring api.SecretStore/api.WorkspaceHomeStore's existing convention) so this handler's own tests can substitute a fake without a real OAuth2 token endpoint or secret store.
Every method's return shape is deliberately untyped-error-only (a plain string, no distinguishable error codes) except where a boolean "ok" is structurally derivable without string sniffing (ProviderForService, LoginStatus) — see each handler method's own comment for how that maps to HTTP status codes.
type OAuthLoginStart ¶ added in v0.1.0
type OAuthLoginStart struct {
SessionID string
Flow string
// Account mirrors apigateway.LoginStart.Account — see that field's own
// doc comment for why it exists (version-skew detection, docs/plans/
// api-gateway-credential-accounts.md review item #2).
Account string
AuthorizeURL string
UserCode string
VerificationURI string
VerificationURIComplete string
IntervalSeconds int
ExpiresInSeconds int
}
OAuthLoginStart is the internal/api-owned mirror of apigateway.LoginStart — internal/api deliberately does not import internal/apigateway's own type here (this package's DTOs are the wire contract; the adapter in internal/server/wire.go is what actually touches apigateway types), keeping this handler's own tests free of any apigateway/oauth2-endpoint dependency, the same "handler depends on a narrow service interface with its own DTOs, not a concrete backend package's types" convention api.SecretHandler/api.WorkspaceHandler follow.
type Pairer ¶
WebManagementHandler serves the CLI management API at /api/web/*. All routes are accessible only via UNIX socket (CLI control plane). Pairer issues pairing codes.
type ProjectAppService ¶
type ProjectAppService struct {
Projects ProjectRepository
Meta interface {
Load(workDir string) (*orchestrator.ProjectMeta, error)
// LoadBareRepo reads .boid/project.yaml from a daemon-managed bare
// git repository's HEAD (docs/plans/volume-only-daemon.md §論点a/b)
// — the bare-repo counterpart to Load, used by
// CreateProjectFromGitURL (first load after `git clone --mirror`),
// which has no prior expected id to validate the freshly-read meta
// against (see LoadBareRepoExpectingID's doc comment for why that
// call site is the one exception).
LoadBareRepo(bareRepoPath string) (*orchestrator.ProjectMeta, error)
// LoadBareRepoExpectingID is LoadBareRepo's id-validated counterpart
// (PR-2a codex round-3 M2 fix), used by FetchProject (`boid project
// fetch <id>`, reload after `git fetch --all`) — the one LoadBareRepo
// caller that already has a specific id to check the freshly-read
// meta against. See orchestrator.ProjectStore.LoadBareRepoExpectingID's
// doc comment for the cache-corruption bug this closes: the meta is
// only committed to the shared cache once expectedID is confirmed to
// match, so an id drifted to collide with an unrelated already-
// registered project can never clobber (or, on cleanup, delete) that
// other project's cache entry.
LoadBareRepoExpectingID(bareRepoPath, expectedID, upstreamURL string) (*orchestrator.ProjectMeta, error)
Get(id string) (*orchestrator.ProjectMeta, bool)
Remove(id string)
LoadAll(projects []*orchestrator.Project) []error
SetWorkspaceID(projectID, workspaceID string)
// Status / MarkDegraded expose the on-startup-auto-prune-retirement
// invariant's in-memory status tracking (docs/plans/
// volume-only-daemon.md §論点a). hydrateProject reads Status to
// populate Project.Status/StatusMessage on every read path;
// CreateProjectFromGitURL/FetchProject call MarkDegraded when a
// clone/fetch/load step fails, preserving the DB row per the
// invariant instead of ever deleting it.
Status(id string) orchestrator.ProjectStatus
MarkDegraded(id, message string)
// SetSynthesizedMeta caches a meta value synthesized (not read from a
// project.yaml) for a project.yaml-less project (docs/plans/
// workspace-default-project.md PR5) — used by CreateProjectFromGitURL
// (initial registration, GitHeadReadFailurePathAbsent) and FetchProject
// (post-fetch reload, same failure kind) in place of LoadBareRepo /
// LoadBareRepoExpectingID. Also clears any prior degraded status — see
// orchestrator.ProjectStore.SetSynthesizedMeta's own doc comment.
SetSynthesizedMeta(id string, meta *orchestrator.ProjectMeta)
// Explain returns id's field-provenance view (docs/plans/
// workspace-default-project.md 論点e, PR6) — see
// orchestrator.ProjectStore.Explain's own doc comment.
Explain(id string) (*orchestrator.ProjectExplain, error)
}
// CloneBareRepo clones a git URL as a daemon-managed bare (mirror)
// repository at destPath, injecting forge credentials scoped to
// namespace (the registering project's workspace slug) — wired in
// internal/server/wire.go to dispatcher.CloneBareRepo, closed over the
// daemon's gitgateway.CredentialProvider. nil (e.g. in tests that do not
// exercise CreateProjectFromGitURL) makes that method fail with a clear
// "not wired" error instead of panicking.
CloneBareRepo func(ctx context.Context, url, destPath, namespace string) error
// FetchBareRepo runs `git fetch --all` inside an existing daemon-managed
// bare repo — wired in internal/server/wire.go to
// dispatcher.FetchBareRepo. Same nil-safety convention as CloneBareRepo.
FetchBareRepo func(ctx context.Context, bareRepoPath, namespace string) error
// DataDir is the daemon's data-home (docs/plans/volume-only-daemon.md
// §論点b: "<data_dir>/repos/<workspace-slug>/<project-name>.git/"),
// wired in internal/server/wire.go to dataHomeFor(cfg) — the same value
// TaskGCStore.WithAttachmentsRoot uses. Required by
// CreateProjectFromGitURL to compute a new project's bare-repo path.
DataDir string
// Hydrator is optional. When set, callers that need fully-resolved meta
// (workspace-level capabilities / host_commands / env merged in +
// SecretNamespace injected) go through GetWithWorkspace instead of the
// bare Meta.Get path.
// Wired in internal/server/wire.go alongside the workspace store.
Hydrator orchestrator.MetaHydrator
// CaptureUpstreamURL reads a project work_dir's git origin remote and
// normalizes it to HTTPS (docs/plans/git-gateway-cutover.md PR2). Wired
// in internal/server/wire.go to dispatcher.CaptureUpstreamURL. When nil
// (e.g. in tests that do not exercise this path), upstream_url capture
// is skipped entirely rather than panicking.
CaptureUpstreamURL func(workDir string) (string, error)
// Workspaces provides direct CRUD over a single workspace's
// WorkspaceMeta (docs/plans/workspace-db-consolidation.md PR4). Wired in
// internal/server/wire.go to ProjectStore.WorkspaceStore(). Required for
// the workspace create/show/update/remove endpoints; callers that never
// exercise those (most existing tests) can leave it nil.
Workspaces WorkspaceStore
// HostCommands, when set, returns the daemon's live aggregated
// host_commands snapshot (name -> spec). CreateWorkspace/UpdateWorkspace
// validate every meta.HostCommands reference against this snapshot,
// rejecting an unknown name with 400 (docs/plans/
// workspace-db-consolidation.md MAJOR 2, codex review: an unresolvable
// reference was previously persisted silently and only warned-about +
// skipped at dispatch time). Wired in internal/server/wire.go to
// Server.HostCommands. nil skips the validation entirely — tests that do
// not exercise it can leave this unset, same convention as
// CaptureUpstreamURL/Hydrator above.
HostCommands func() map[string]orchestrator.HostCommandSpec
// WorkspacesConn is the daemon's single *sql.DB handle (docs/plans/
// volume-only-daemon.md PR-1d codex round-1 Blocker 2/3). ApplyWorkspace
// and ExportWorkspaceEnvelopes need a raw connection — not the
// WorkspaceStore/ProjectRepository interfaces above — because both
// operations span workspace-meta AND project-assignment writes/reads
// that must run inside ONE transaction (orchestrator.
// ApplyWorkspaceEnvelope / orchestrator.SnapshotWorkspacesForExport),
// which those two separate, narrower interfaces have no way to express.
// Wired in internal/server/wire.go to srv.db, the same connection every
// other repository in this daemon is already built from. nil skips both
// endpoints with a 500 (same "not wired" convention as Workspaces
// above) — tests that do not exercise them can leave this unset.
WorkspacesConn *sql.DB
// InitScripts reads and writes a workspace's init.sh at the path the
// DISPATCHER reads it from (PR9 of
// docs/plans/workspace-home-volume-persistence.md, 論点 d). Wired in
// internal/server/wire.go to dispatcher.WorkspaceInitScriptStore{}.
//
// nil is the feature's off switch, the same convention Workspaces /
// WorkspacesConn above use: GetWorkspaceInitScript and
// SetWorkspaceInitScript answer 501, and ApplyWorkspace warns about a
// spec.init_script it cannot honor rather than dropping it silently.
//
// One field, held by the service rather than by the handler, because
// three call sites need it — the two endpoints, ApplyWorkspace's
// hydration, and ExportWorkspaceEnvelopes' — and two of those are inside
// this type. Wiring a second copy onto WorkspaceHandler would be
// harmless here (the store is stateless) but would put two answers to
// "where does this daemon keep init.sh" in the wiring graph, which is the
// thing PR8's WorkspaceHomeImporter comment argues against for a case
// where it was NOT harmless.
InitScripts WorkspaceInitScriptStore
// contains filtered or unexported fields
}
func (*ProjectAppService) ApplyWorkspace ¶ added in v0.1.0
func (s *ProjectAppService) ApplyWorkspace(apply *orchestrator.WorkspaceEnvelopeApply, dryRun bool) (*orchestrator.WorkspaceApplyResult, error)
ApplyWorkspace upserts apply's workspace metadata and (when apply.FieldsPresent["projects"] is true) reconciles its project assignments atomically, in a single DB transaction (docs/plans/ volume-only-daemon.md PR-1d codex round-1 Blocker 2, POST /api/workspaces/apply).
Two things happen here BEFORE the transaction opens, deliberately outside orchestrator.ApplyWorkspaceEnvelope's own DB tx: validateHostCommandRefs (needs the daemon's live in-memory host_commands snapshot, not a DB table) and resolveWorkspaceApplyProjectNames (needs the in-memory ProjectMeta cache to turn a project NAME into an ID — see that method's doc comment). Neither runs conditionally on dryRun (MAJOR 1, codex round-1): a dry run must hit the exact same validation a real apply would, not silently skip it and report success on a document real apply would go on to reject.
func (*ProjectAppService) CreateProject ¶
func (s *ProjectAppService) CreateProject(workDir string) (*orchestrator.Project, error)
func (*ProjectAppService) CreateProjectFromGitURL ¶ added in v0.1.0
func (s *ProjectAppService) CreateProjectFromGitURL(ctx context.Context, gitURL, workspaceSlug, nameOverride string) (*orchestrator.Project, error)
CreateProjectFromGitURL registers a project from a git remote URL (docs/plans/volume-only-daemon.md §論点a: `boid project add <git-url> --workspace=<name> [--name=<project-name>]`, the CLI form's server-side counterpart). Unlike CreateProject (the legacy work_dir-based endpoint — `boid project init` no longer calls it at all as of docs/plans/ release-onboarding.md 穴 7/PR6; it only scaffolds locally and prints guidance pointing back at THIS git-URL flow. CreateProject itself is kept around as a lightweight test-fixture registration primitive, per cmd/project.go's own doc comment on projectAddCmd), workspaceSlug is REQUIRED, not eagerly defaulted: there is no host-filesystem project.yaml sitting around to "just register as-is" here, so an unassigned bare clone would be an orphaned volume directory with no way back to it.
This follows the plan doc's §論点a unresolved-point recommendation ("Failure means the register itself fails, no half-added project"): clone, project.yaml load, and DB/workspace-assignment all happen synchronously in this one call, and any failure rolls back everything this call itself created (the bare repo directory, the in-memory Meta cache entry, the DB row) so a failed `project add` never leaves a half-registered project behind. This is a DIFFERENT case from the on-startup-auto-prune-retirement invariant (docs/plans/ volume-only-daemon.md §論点a) that governs already-registered projects going degraded later (FetchProject, daemon startup) — a project that never successfully finished registering has no DB row to preserve in the first place.
func (*ProjectAppService) CreateWorkspace ¶ added in v0.0.13
func (s *ProjectAppService) CreateWorkspace(slug string, meta *orchestrator.WorkspaceMeta) (*WorkspaceDetail, error)
CreateWorkspace inserts a brand-new workspace at slug (docs/plans/workspace-db-consolidation.md PR4 Step C, POST /api/workspaces). See the ProjectService interface doc comment for the status code contract.
func (*ProjectAppService) DeleteProject ¶
func (s *ProjectAppService) DeleteProject(id string) error
DeleteProject removes id's DB row and, when id is a git-URL-registered project, the daemon-managed bare repository backing it (MAJOR 1, codex round-1 review). Before that fix, remove deleted only the DB row and in-memory Meta cache entry, leaving the bare repo directory behind on disk — so a plain `boid project rm` followed by re-adding the SAME URL/name always 409'd (CreateProjectFromGitURL's pre-flight "already registered at this path" check), making the documented degraded-recovery procedure ("rm the project, re-add it") ineffective in practice.
A legacy dir-based project's WorkDir is the user's own host checkout — never daemon-owned — so it is deliberately left untouched; only a WorkDir under this daemon's bare-repo storage root is removed (same isManagedBareRepoPath classification FetchProject's MAJOR 2 fix uses).
MAJOR 3 (PR-2a codex round-2 review): the bare repo is removed BEFORE the DB row, not after. The pre-fix order deleted the DB row FIRST and only logged an os.RemoveAll failure as a warning — so a read-only or otherwise permission-failing repo directory stayed on disk forever (nothing left to retry through, since the row that named it was already gone) while `boid project rm` still reported SUCCESS, and a subsequent `boid project add` of the same URL/name still 409'd with no remaining row through which cleanup could be retried. Removing the repo first means a removal failure now fails the WHOLE call with the DB row (and cached Meta) intact — the exact same "fix the issue, retry `boid project rm`" recovery path this method's own MAJOR-1 fix restored for the 409 case above.
func (*ProjectAppService) ExplainProject ¶ added in v0.1.0
func (s *ProjectAppService) ExplainProject(id string) (*orchestrator.ProjectExplain, error)
ExplainProject handles GET /api/projects/{id}/explain (`boid project show --explain`, docs/plans/workspace-default-project.md 論点e, PR6). Confirms id is a registered project (same 404 shape as GetProject) before delegating the actual field-provenance computation to orchestrator.ProjectStore.Explain.
func (*ProjectAppService) ExportWorkspaceEnvelopes ¶ added in v0.1.0
func (s *ProjectAppService) ExportWorkspaceEnvelopes(slugs []string) ([]byte, error)
ExportWorkspaceEnvelopes returns one or more boid.dev/v1 Workspace yaml documents ("---"-separated when more than one), built from a single atomic DB snapshot (docs/plans/volume-only-daemon.md PR-1d codex round-1 Blocker 3, GET /api/workspaces/export?all=true|?name=<slug>). slugs nil/empty exports every workspace.
func (*ProjectAppService) FetchProject ¶ added in v0.1.0
func (s *ProjectAppService) FetchProject(ctx context.Context, id string) (*orchestrator.Project, error)
FetchProject runs `git fetch --all` inside id's bare repo and reloads project.yaml (`boid project fetch <id>`, docs/plans/volume-only-daemon.md §論点b fetch 経路). Unlike CreateProjectFromGitURL, a failure here does NOT roll anything back or delete the project — id is already a registered project the on-startup-auto-prune-retirement invariant (§論点a) protects; a fetch or reload failure marks it StatusDegraded (via s.Meta.MarkDegraded) and returns an error, leaving the DB row and any previously-loaded Meta exactly as they were.
func (*ProjectAppService) GetProject ¶
func (s *ProjectAppService) GetProject(id string) (*orchestrator.Project, error)
func (*ProjectAppService) GetWorkspace ¶ added in v0.0.13
func (s *ProjectAppService) GetWorkspace(slug string) (*WorkspaceDetail, error)
GetWorkspace returns slug's meta, revision, and assigned project ids (docs/plans/workspace-db-consolidation.md PR4 Step D, GET /api/workspaces/{slug}).
MAJOR 1 (codex review): meta and revision are read from a single atomic snapshot (Workspaces.LoadWithRevision) rather than two separate queries (a plain Load for meta, then GetWorkspaceSummary for revision) — the pre-fix two-query approach could straddle a concurrent PUT and return a meta/revision pair that never coexisted in the DB.
func (*ProjectAppService) GetWorkspaceInitScript ¶ added in v0.1.0
func (s *ProjectAppService) GetWorkspaceInitScript(slug string) (*WorkspaceInitScript, error)
GetWorkspaceInitScript implements ProjectService.GetWorkspaceInitScript.
The workspace row is checked FIRST, so a typo'd slug is a 404 rather than "this workspace has no init.sh" — the two are indistinguishable to a reader of the second message and only one of them is worth acting on.
func (*ProjectAppService) ListProjects ¶
func (s *ProjectAppService) ListProjects(workspaceID string) ([]*orchestrator.Project, error)
func (*ProjectAppService) ListWorkspaces ¶
func (s *ProjectAppService) ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
func (*ProjectAppService) ReloadProjects ¶
func (s *ProjectAppService) ReloadProjects() (*ProjectReloadResult, error)
func (*ProjectAppService) RemoveWorkspace ¶ added in v0.0.13
func (s *ProjectAppService) RemoveWorkspace(slug string) (*WorkspaceRemoval, error)
RemoveWorkspace deletes slug (docs/plans/workspace-db-consolidation.md PR4 Step F, DELETE /api/workspaces/{slug}). The reserved default workspace cannot be removed (decision 8); any project still assigned to slug is re-pointed at default by orchestrator.WorkspaceRepository.Remove's transaction, so this never leaves a dangling project_workspaces reference at the DB layer.
That DB-level transaction has no way to reach into the daemon's in-memory ProjectStore cache (s.Meta), though — so without the snapshot-then-sync dance below, every project that *was* assigned to slug would keep serving GetWithWorkspace hydration off a stale cached workspace_id that no longer has a corresponding workspaces row, silently degrading (host_commands/env/ capabilities not injected, same as the pre-existing "workspace.yaml not found" degraded-mode path) until the next daemon restart. Snapshotting the assigned project ids *before* the delete (list ordering matters: after the delete, ListWorkspaces/ListProjects would already report them as belonging to default and we'd have nothing left to distinguish "was reassigned, needs a cache sync" from "already was on default") then calling s.Meta.SetWorkspaceID for each afterward mirrors the exact same cache update SetProjectWorkspace already performs for a single explicit assignment.
MAJOR 3 (codex review): the whole snapshot -> DB remove -> cache-sync sequence below runs under s.mu (see that field's doc comment), serialized against SetProjectWorkspace's own critical section. Without this, a concurrent SetProjectWorkspace reassigning one of the snapshotted projects to a *different*, still-existing workspace could have its cache write clobbered by this method's stale-snapshot loop landing after it — leaving the in-memory cache pointing at "default" while the DB (and any fresh GetWithWorkspace hydration) says the project belongs to the new workspace.
The init.sh goes with the row, inside the same critical section ¶
PR9 codex round 3, Major 3. The script's deletion started life as a second service call made by WorkspaceHandler.Remove after this one returned, which left a window with the mutex free: a `workspace apply` could upsert the same slug, write a new init.sh and answer 200 in it, and the removal — still in flight — then deleted that script. The end state was a workspace row that existed with a committed apply's script silently missing, indistinguishable from a workspace that never had one.
Doing it here makes the two atomic with respect to every other workspace-mutating entry point, because they all take this mutex: an apply is now either entirely before the removal (its row and its script both go — correct) or entirely after it (a fresh workspace keeps the script it was just given — correct). The HOME volume's deletion stays outside, in the handler: it needs an engine this type does not have, and it is excluded from the migration it actually races by a different mechanism (BeginWorkspaceHomeRemoval, which brackets this call too).
It is still NOT atomic with the row — a file unlink and a database transaction cannot commit together — so the outcome is REPORTED rather than pretended away, which is why this returns a WorkspaceRemoval instead of folding a failed unlink into the error. See WorkspaceRemoval.InitScriptError.
func (*ProjectAppService) ResolveProjectRef ¶
func (s *ProjectAppService) ResolveProjectRef(ref string) ([]*orchestrator.Project, error)
ResolveProjectRef resolves ref to matching projects with the following priority:
- id exact match (returns immediately on first hit)
- name exact match (all projects with that name)
- name substring match, case-insensitive
Returns a single-element slice on unambiguous match, a multi-element slice on ambiguous match, or StatusError{404} when nothing matches.
func (*ProjectAppService) SetProjectWorkspace ¶
func (s *ProjectAppService) SetProjectWorkspace(id, workspaceID string) (*orchestrator.Project, error)
func (*ProjectAppService) SetWorkspaceInitScript ¶ added in v0.1.0
func (s *ProjectAppService) SetWorkspaceInitScript(slug string, content []byte, ifMatch string, force bool) (*WorkspaceInitScriptResult, error)
SetWorkspaceInitScript implements ProjectService.SetWorkspaceInitScript.
The If-Match check and the write are performed under s.mu — the same mutex every other workspace-mutating entry point takes (see the field's doc comment). That closes the read-then-write window against another caller of THIS daemon; it does not, and cannot, close it against somebody editing the file inside the daemon's container by hand, which is exactly the workflow this endpoint exists to replace.
It does not exclude a concurrent DISPATCH, deliberately. resolveWorkspaceHome re-reads and re-hashes the script under its own flock before running it (the PR #787 TOCTOU fix), so a write landing mid-init is either picked up in full by that re-read or missed entirely — never half-applied — and the completion marker records whichever bytes actually ran. Taking the init lock here would buy an ordering nobody needs at the cost of making a CLI command block on a multi-minute toolchain build.
func (*ProjectAppService) UpdateWorkspace ¶ added in v0.0.13
func (s *ProjectAppService) UpdateWorkspace(slug string, meta *orchestrator.WorkspaceMeta, ifMatch string, force bool) (*WorkspaceDetail, error)
UpdateWorkspace replaces slug's meta wholesale (docs/plans/ workspace-db-consolidation.md PR4 Step E, PUT /api/workspaces/{slug}), enforcing optimistic concurrency: ifMatch must equal the workspace's current revision unless force is true (decision 17 — PUT + If-Match, no PATCH). A missing ifMatch (and !force) is rejected with 428 Precondition Required rather than silently proceeding, since accepting an unconditional PUT by default would make the ETag check opt-in instead of the intended opt-out (--force).
MAJOR 1 (codex review): the non-force path no longer reads the current revision and then Saves unconditionally as two separate statements — that window let two concurrent PUTs starting from the same If-Match both pass their check before either had written, silently losing one writer's update, and let a DELETE landing between a GET and a subsequent PUT resurrect the workspace via Save's upsert semantics. Instead, Workspaces.UpdateIfRevisionMatches performs the check-and-write as one atomic UPDATE; matched=false is then disambiguated into 404 (slug is truly gone) vs 412 (slug exists, but ifMatch is stale) with a follow-up existence check — that follow-up races nothing of consequence, since it only picks the HTTP status code for an already-failed write, not any data mutation.
force=true intentionally keeps the old "check existence, then unconditional Save" shape: force explicitly opts out of the revision guarantee (last-write-wins), so there is no CAS invariant left to protect — but Save is upsert-on-conflict, so a plain Save would silently *create* slug if it did not already exist, which PUT (unlike POST) must not do; hence the explicit existence check before it.
func (*ProjectAppService) WithProjectLock ¶ added in v0.1.0
func (s *ProjectAppService) WithProjectLock(fn func() error) error
isManagedBareRepoPath reports whether workDir falls under this daemon's bare-repo storage root (<DataDir>/repos) — i.e. it is (or was, before possibly going corrupt) a git-URL-registered project's daemon-managed bare repo, as opposed to a legacy host-filesystem checkout registered via `boid project init` / the dir-based form of `boid project add` (MAJOR 2, codex round-1 review). This is a structural (path-prefix) check, independent of whether the directory currently looks like a valid bare repo — orchestrator.IsBareRepoDir answers a DIFFERENT question ("is this readable right now") that FetchProject also needs, but must not use for THIS classification (see FetchProject's own call-site comment for the misclassification that produces).
Falls back to the plain orchestrator.IsBareRepoDir structural check when s.DataDir is unset (some tests never wire it) — weaker (misses a corrupt/missing bare repo, same as the pre-fix behavior) but still correct for a healthy one, and DataDir is always wired in production (internal/server/wire.go).
BLOCKER 2 sibling (PR-2a codex round-2 review): routes through orchestrator.PathIsUnderResolved, not the plain (lexical-only) PathIsUnder round-1 left here — this is the ONE classification both FetchProject (fetch-time) and DeleteProject (rm-time, which follows this answer straight into an os.RemoveAll) share, so fixing it here closes the symlinked-ancestor escape for both call sites at once. A resolution error (as opposed to "not under root") fails CLOSED: refuse to classify workDir as daemon-managed rather than risk a write or delete against a path that could not be safely verified. FetchProject then falls through to the ordinary legacy-rejection message; DeleteProject skips the RemoveAll and only removes the DB row, exactly as it already does for any WorkDir that was never daemon-managed at all. WithProjectLock runs fn while holding projectMu — the exact same lock CreateProject/CreateProjectFromGitURL/DeleteProject/FetchProject already serialize their own create/delete/fetch critical sections against (see projectMu's own doc comment). Exported so a caller OUTSIDE this package can share the identical serialization contract without duplicating it — specifically, dispatcher.Runner.Dispatch's own project-registry-guarded dispatch section (docs/plans/volume-only-daemon.md §論点b, PR-2b): gateway-token registration, the selfProject lookup, the gatewayCloneURL/ peerAdvertise snapshot, managed-bare-repo classification, and the FetchBareRepo + PrepareJobCheckout pair all read/derive from a project snapshot and then clone straight off its WorkDir. Round-2 (PR834 PR-2b round-2 codex review Major 1) wrapped only the final FetchBareRepo + PrepareJobCheckout call in this lock, leaving the lookup and URL/token snapshot that FEED it unguarded; round-3 (Major 1) widened Dispatch's own closure to cover the whole sequence, because a concurrent `project rm` + re-add at the identical managed path could otherwise land in the window between dispatch's snapshot and the (locked) clone, producing a mixed checkout (one project's gateway URL/credentials against a DIFFERENT, just-re-registered project's bare-repo content) — see Dispatch's own "project-registry-guarded dispatch section" comment for the full rationale. internal/dispatcher cannot import this package directly (internal/api already imports internal/dispatcher for wiring — the reverse would be an import cycle), so internal/server/wire.go closes over this exact method and hands it to Runner.WithProjectLock as a plain function value instead — see that field's own doc comment and wire.go's assignment (next to runner.GatewayCredentials, which shares the same gwCreds this package's own FetchBareRepo closure was wired from).
A caller with no error path of its own can ignore the returned error by wrapping a niladic function; every current caller already threads one through.
type ProjectHandler ¶
type ProjectHandler struct {
Service ProjectService
SessionDispatcher SessionDispatcher // optional; nil disables the start-session endpoint
ExecDispatcher ExecDispatcher // optional; nil disables the exec endpoint
// TriggerRunner backs POST /api/projects/{id}/triggers/{name}/run —
// docs/plans/ingestion-identity.md PR-4 (B-5) 12 節「手動 1 巡の口」
// (`boid trigger run`, cmd/trigger.go). Optional; nil disables the
// endpoint, same convention as SessionDispatcher/ExecDispatcher above.
TriggerRunner TriggerRunner
}
func (*ProjectHandler) Create ¶
func (h *ProjectHandler) Create(w http.ResponseWriter, r *http.Request)
func (*ProjectHandler) CreateFromGitURL ¶ added in v0.1.0
func (h *ProjectHandler) CreateFromGitURL(w http.ResponseWriter, r *http.Request)
CreateFromGitURL handles POST /api/projects/git (docs/plans/ volume-only-daemon.md §論点a — `boid project add <git-url> --workspace=<name>`, the new git-URL registration model).
func (*ProjectHandler) Delete ¶
func (h *ProjectHandler) Delete(w http.ResponseWriter, r *http.Request)
func (*ProjectHandler) Explain ¶ added in v0.1.0
func (h *ProjectHandler) Explain(w http.ResponseWriter, r *http.Request)
Explain handles GET /api/projects/{id}/explain (docs/plans/ workspace-default-project.md 論点e, PR6 — `boid project show --explain`).
func (*ProjectHandler) Fetch ¶ added in v0.1.0
func (h *ProjectHandler) Fetch(w http.ResponseWriter, r *http.Request)
Fetch handles POST /api/projects/{id}/fetch (docs/plans/ volume-only-daemon.md §論点b fetch 経路 — `boid project fetch <id>`).
func (*ProjectHandler) Get ¶
func (h *ProjectHandler) Get(w http.ResponseWriter, r *http.Request)
func (*ProjectHandler) List ¶
func (h *ProjectHandler) List(w http.ResponseWriter, r *http.Request)
func (*ProjectHandler) Reload ¶
func (h *ProjectHandler) Reload(w http.ResponseWriter, r *http.Request)
func (*ProjectHandler) Routes ¶
func (h *ProjectHandler) Routes() chi.Router
func (*ProjectHandler) RunTrigger ¶ added in v0.4.0
func (h *ProjectHandler) RunTrigger(w http.ResponseWriter, r *http.Request)
RunTrigger handles POST /api/projects/{id}/triggers/{name}/run — docs/plans/ingestion-identity.md PR-4 (B-5) 12 節「手動 1 巡の口」. The project is resolved from the URL ref the same way every other project route does; {name} is the trigger's project.yaml `name:`.
{name} can contain a "/" — a signal-derived trigger is named "signal:<pack>/<connector>" (signal_trigger_derive.go) — so cmd/trigger.go url.PathEscape's it before sending. chi matches routes against the request's ESCAPED path (the same contract SecretHandler's key param already documents/handles, secret.go), so chi.URLParam hands this handler the still-escaped "signal:jira-cloud%2Fassigned-issues" form, not the literal trigger name — url.PathUnescape here mirrors SecretHandler's own.
func (*ProjectHandler) SetWorkspace ¶
func (h *ProjectHandler) SetWorkspace(w http.ResponseWriter, r *http.Request)
func (*ProjectHandler) StartExec ¶ added in v0.0.10
func (h *ProjectHandler) StartExec(w http.ResponseWriter, r *http.Request)
StartExec handles POST /api/projects/{id}/exec. The project is resolved from the URL ref the same way every other project route does; the body specifies argv and the optional readonly / interactive / display_name knobs. Unlike StartSession there is no top-level /api/exec — every exec is project-scoped by construction (`boid exec -p <ref> -- argv...`).
func (*ProjectHandler) StartSession ¶ added in v0.0.6
func (h *ProjectHandler) StartSession(w http.ResponseWriter, r *http.Request)
StartSession handles POST /api/projects/{id}/sessions. The project is resolved from the URL ref (so refs like a name or short id work the same way other project routes do); the body specifies harness_type and the optional knobs (instruction / readonly / model / session_id / display_name).
type ProjectReloadResult ¶
type ProjectRepository ¶
type ProjectRepository interface {
CreateProject(project *orchestrator.Project) error
GetProject(id string) (*orchestrator.Project, error)
ListProjects() ([]*orchestrator.Project, error)
SetProjectWorkspace(projectID, workspaceID string) error
ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
DeleteProject(id string) error
// SetProjectUpstreamURL persists a project's captured upstream_url (see
// docs/plans/git-gateway-cutover.md PR2). Used by ReloadProjects'
// recapture and by the daemon-startup backfill.
SetProjectUpstreamURL(projectID, upstreamURL string) error
// WorkspaceExists reports whether workspaceID refers to an existing
// workspaces table row. Used by ProjectAppService.SetProjectWorkspace to
// reject assignment to a nonexistent slug (docs/plans/
// workspace-db-consolidation.md MAJOR 5 codex review fix).
WorkspaceExists(workspaceID string) (bool, error)
// AssignWorkspaceIfExists atomically checks-then-assigns in a single DB
// transaction (docs/plans/workspace-db-consolidation.md MAJOR 3, codex
// review), replacing the WorkspaceExists+SetProjectWorkspace two-step
// ProjectAppService.SetProjectWorkspace used before: a DELETE landing
// between those two separate calls could leave a dangling
// project_workspaces reference. Returns an error wrapping os.ErrNotExist
// when workspaceID has no corresponding row (DefaultWorkspaceSlug and ""
// are exempt from the check — see the implementation's doc comment).
AssignWorkspaceIfExists(projectID, workspaceID string) error
// GetWorkspaceSummary returns a single workspace's project count and
// revision, or an error wrapping os.ErrNotExist. Used by the workspace
// CRUD handlers (docs/plans/workspace-db-consolidation.md PR4) to build
// responses and to read the current revision for the PUT If-Match check.
GetWorkspaceSummary(slug string) (*orchestrator.WorkspaceSummary, error)
}
type ProjectService ¶
type ProjectService interface {
CreateProject(workDir string) (*orchestrator.Project, error)
// CreateProjectFromGitURL registers a project from a git remote URL
// (docs/plans/volume-only-daemon.md §論点a, POST /api/projects/git —
// `boid project add <git-url> --workspace=<name>`). workspaceSlug is
// required (unlike CreateProject's eager default-workspace assign);
// nameOverride empty derives the project name from the URL's last path
// component. *StatusError{400} for a missing url/workspace or an
// unparseable URL, {404} for an unknown workspace, {409} if a project is
// already registered at the computed bare-repo path, {502} for a clone
// failure, {500} if the daemon has no git-clone/data-dir wiring.
CreateProjectFromGitURL(ctx context.Context, gitURL, workspaceSlug, nameOverride string) (*orchestrator.Project, error)
// FetchProject runs `git fetch --all` inside id's bare repo and reloads
// its project.yaml (POST /api/projects/{id}/fetch — `boid project fetch
// <id>`). *StatusError{404} unknown id, {400} for a legacy (non-bare,
// pre-cutover) project or a project.yaml that fails to parse after
// fetch, {502} for a fetch failure. Never deletes id's row on failure —
// see the method's own doc comment for the on-startup-auto-prune-
// retirement invariant this preserves.
FetchProject(ctx context.Context, id string) (*orchestrator.Project, error)
ListProjects(workspaceID string) ([]*orchestrator.Project, error)
ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
GetProject(id string) (*orchestrator.Project, error)
SetProjectWorkspace(id, workspaceID string) (*orchestrator.Project, error)
DeleteProject(id string) error
ReloadProjects() (*ProjectReloadResult, error)
// ResolveProjectRef resolves a ref string to one or more matching projects.
// Priority: id exact match > name exact match > name substring match (case-insensitive).
// Returns 1 project on unambiguous match, multiple on ambiguous match, StatusError{404} on no match.
ResolveProjectRef(ref string) ([]*orchestrator.Project, error)
// ExplainProject returns id's field-provenance view (docs/plans/
// workspace-default-project.md 論点e, PR6, GET /api/projects/{id}/explain
// — `boid project show --explain`): for each of the 4
// workspace-default-mergeable fields, whether the effective value came
// from project.yaml or the linked workspace's default project
// definition. *StatusError{404} for an unknown id.
ExplainProject(id string) (*orchestrator.ProjectExplain, error)
// CreateWorkspace inserts a brand-new workspace (docs/plans/
// workspace-db-consolidation.md PR4, POST /api/workspaces). Returns a
// *StatusError{409} when slug already has a row, {400} for an invalid
// slug.
CreateWorkspace(slug string, meta *orchestrator.WorkspaceMeta) (*WorkspaceDetail, error)
// GetWorkspace returns slug's meta, revision, and assigned project ids
// (GET /api/workspaces/{slug}). *StatusError{404} when slug is unknown.
GetWorkspace(slug string) (*WorkspaceDetail, error)
// UpdateWorkspace replaces slug's meta wholesale (PUT
// /api/workspaces/{slug}), enforcing optimistic concurrency via ifMatch
// against the workspace's current revision unless force is true.
// *StatusError{428} missing ifMatch, {412} stale ifMatch, {404} unknown
// slug.
UpdateWorkspace(slug string, meta *orchestrator.WorkspaceMeta, ifMatch string, force bool) (*WorkspaceDetail, error)
// RemoveWorkspace deletes slug's row AND its init.sh (DELETE
// /api/workspaces/{slug}), reporting what became of the latter.
// *StatusError{400} for the reserved default slug, {404} unknown slug.
//
// The two deletions are one operation because they have to be excluded
// from a concurrent apply together (PR9 codex round 3, Major 3) — see
// ProjectAppService.RemoveWorkspace. They are still not atomic with each
// other, hence the result: an error inside it means the row is gone and
// the script is not.
RemoveWorkspace(slug string) (*WorkspaceRemoval, error)
// ApplyWorkspace upserts one boid.dev/v1 Workspace envelope document's
// metadata and (when apply.FieldsPresent["projects"] is true) project
// assignments atomically, in a single DB transaction (docs/plans/
// volume-only-daemon.md PR-1d codex round-1 Blocker 2, POST
// /api/workspaces/apply). dryRun exercises the same validation/DB
// statements but rolls back instead of committing (Major 1).
ApplyWorkspace(apply *orchestrator.WorkspaceEnvelopeApply, dryRun bool) (*orchestrator.WorkspaceApplyResult, error)
// ExportWorkspaceEnvelopes returns one or more boid.dev/v1 Workspace
// yaml documents ("---"-separated when more than one), built from a
// single atomic DB snapshot (docs/plans/volume-only-daemon.md PR-1d
// codex round-1 Blocker 3, GET /api/workspaces/export?all=true or
// ?name=<slug>). slugs nil/empty exports every workspace; otherwise
// exactly the given slugs. *StatusError{404} when a requested slug does
// not exist. Each document carries the workspace's init.sh in
// spec.init_script (PR9 of docs/plans/workspace-home-volume-persistence.md,
// 論点 d) — an export without it is not a restorable backup.
ExportWorkspaceEnvelopes(slugs []string) ([]byte, error)
// GetWorkspaceInitScript returns slug's init.sh (GET
// /api/workspaces/{slug}/init-script, PR9 of
// docs/plans/workspace-home-volume-persistence.md 論点 d). A workspace
// with no script is NOT an error: the result carries Exists=false and
// Revision=WorkspaceInitScriptAbsentRevision, and the handler turns that
// into a 404 with the sentinel ETag. *StatusError{400} for an invalid
// slug, {404} for an unknown workspace, {501} when the daemon has no init
// script store wired.
GetWorkspaceInitScript(slug string) (*WorkspaceInitScript, error)
// SetWorkspaceInitScript replaces slug's init.sh with content (PUT
// /api/workspaces/{slug}/init-script), enforcing optimistic concurrency
// via ifMatch against the current revision unless force is true — the
// same 428/412 contract UpdateWorkspace and ApplyConfigYAML use. An
// EMPTY content clears the script (see
// workspaceInitScriptContentIsAbsent). *StatusError{400} for an invalid
// slug or a script containing a NUL byte, {404} unknown workspace,
// {428} missing ifMatch, {412} stale ifMatch, {501} no store wired.
SetWorkspaceInitScript(slug string, content []byte, ifMatch string, force bool) (*WorkspaceInitScriptResult, error)
}
type ProjectWorkDirLookup ¶
type ProjectWorkDirLookup interface {
GetProject(id string) (*orchestrator.Project, error)
}
ProjectWorkDirLookup provides read access to a project's working directory.
type QueueSweepLoop ¶ added in v0.2.4
type QueueSweepLoop struct {
Store QueueSweepStore
Interval time.Duration
InitialDelay time.Duration
}
QueueSweepLoop periodically calls SweepWake, mirroring orchestrator.GCLoop's shape (internal/orchestrator/gc_loop.go) — same InitialDelay-then-Interval idiom, errors logged and never fatal to the loop.
func (*QueueSweepLoop) Run ¶ added in v0.2.4
func (l *QueueSweepLoop) Run(ctx context.Context)
Run blocks until ctx is done. It waits InitialDelay before the first sweep, then calls Store.SweepWake every Interval.
type QueueSweepStore ¶ added in v0.2.4
type QueueSweepStore interface {
SweepWake(ctx context.Context, now time.Time) ([]string, error)
SweepReconcileChildren(ctx context.Context, now time.Time) error
}
QueueSweepStore is the interface QueueSweepLoop needs — narrowed from *TaskWorkflowService so the loop can be unit tested against a fake.
SweepTriage (決定15/16) and SweepReopen (I-5) are GONE as of card machine v2 — both were machine-driven transitions (auto-done, auto-reopen) the redesign retires entirely (design doc §3.3: "機械遷移ゼロ"). done/reopen are now suggested by khi and applied only by a human's accept, through the ordinary ApplyAction/accept(verb) path — there is nothing left for a periodic sweep to decide on their behalf. SweepReconcileChildren (above) is NOT one of those machine-driven transitions — it survives because it never touches task.Status.
type ReopenTaskRequest ¶
type ReopenTaskRequest struct {
Message string `json:"message,omitempty"`
}
type ReplayHookRequest ¶
type ReplayHookRequest struct {
HookID string
Status string // optional: override task.Status before replay
}
ReplayHookRequest is the input for hook replay.
type RerunTaskRequest ¶
type RerunTaskRequest = apiwire.RerunTaskRequest
type ResolveOrCaptureRequest ¶ added in v0.4.0
type ResolveOrCaptureRequest struct {
ProjectID string
Identity string
Title string
Description string
}
ResolveOrCaptureRequest is BoidOpTaskResolveOrCapture's input: project + identity (always, I-2/I-3) plus title/description used ONLY when no task is currently bound to Identity (a fresh `captured` task is created).
type ResolveOrCaptureResult ¶ added in v0.4.0
ResolveOrCaptureResult is the op's return contract (PR-2 節 "B-2: push op は解決結果を返す"): the resolved task's id, and whether it was freshly created by this call (true) or already existed (false — the caller should follow up with action_send to record attrs_set, per the doc's "解決と記録を 1 op に混ぜない").
type SecretHandler ¶
type SecretHandler struct {
Store SecretStore
}
func (*SecretHandler) Delete ¶
func (h *SecretHandler) Delete(w http.ResponseWriter, r *http.Request)
func (*SecretHandler) GetValue ¶
func (h *SecretHandler) GetValue(w http.ResponseWriter, r *http.Request)
func (*SecretHandler) List ¶
func (h *SecretHandler) List(w http.ResponseWriter, r *http.Request)
func (*SecretHandler) Routes ¶
func (h *SecretHandler) Routes() chi.Router
func (*SecretHandler) Set ¶
func (h *SecretHandler) Set(w http.ResponseWriter, r *http.Request)
type SecretStore ¶
type SessionDispatcher ¶ added in v0.0.6
type SessionDispatcher interface {
StartSession(ctx context.Context, req StartSessionRequest) (*StartSessionResult, error)
}
SessionDispatcher launches a session job (claude / codex / opencode under a HarnessAdapter) and returns the runtime job id.
type SessionHandler ¶ added in v0.0.6
type SessionHandler struct {
Service ProjectService
Dispatcher SessionDispatcher
}
SessionHandler exposes the POST /api/sessions surface (and the project-scoped /api/projects/{id}/sessions variant mounted by ProjectHandler). Phase 3-d (PR1) introduced sessions as a first-class JobKind alongside hook and exec so user-initiated agent runs (WebUI [New Session] / `boid agent`) no longer have to piggyback on the project command path.
func (*SessionHandler) Routes ¶ added in v0.0.6
func (h *SessionHandler) Routes() chi.Router
func (*SessionHandler) Start ¶ added in v0.0.6
func (h *SessionHandler) Start(w http.ResponseWriter, r *http.Request)
Start handles POST /api/sessions. The request body must specify project_id. Use the project-scoped variant when the project is implied by the URL.
Session-id resume was removed: every Start launches a fresh agent process, so there is no `/api/sessions/{id}/resume` companion route anymore.
type SetProjectWorkspaceRequest ¶
type SetProjectWorkspaceRequest struct {
WorkspaceID string `json:"workspace_id"`
}
type SettingsConfigService ¶ added in v0.1.0
type SettingsConfigService interface {
// ConfigYAML returns the daemon's current effective config.yaml
// document, alongside its current revision — see
// api.ConfigService.ConfigYAML's doc comment (internal/api/config.go)
// for the full contract; this is the exact same method, just narrowed
// to the one WebHandler needs.
ConfigYAML() (data []byte, revision string, err error)
}
SettingsConfigService is the read surface WebHandler.Settings needs to prefill /settings' initial render. Deliberately narrower than the full api.ConfigService (Apply/Mutate are reached directly by the page's own client-side JS, never through this Go handler) — WebHandler only depends on the one method it actually calls. *server.Server already satisfies this (it implements the full ConfigService for internal/api/config.go's ConfigHandler), so wiring this up at the call site is a one-line addition alongside the existing `configHandler := &api.ConfigHandler{Service: srv}`.
type SignalHandler ¶ added in v0.4.0
type SignalHandler struct {
Store SignalStore
}
SignalHandler serves docs/plans/signal-ingest-detailed-design.md §3.1 (PR-2)'s host API: GET /api/signals (list) and POST /api/signals/ack.
Store is SignalStore (internal/api/store.go, added by PR-1) — wire.go mounts this handler directly against runtime.taskRepo, which already implements SignalStore (see that interface's own doc comment). No new service type is needed the way CardHandler needs CardReadService: the store interface PR-1 shipped is already narrow enough to hand straight to a handler, following the same "thin handler over a narrow store interface" shape CardHandler uses.
func (*SignalHandler) Ack ¶ added in v0.4.0
func (h *SignalHandler) Ack(w http.ResponseWriter, r *http.Request)
Ack handles POST /api/signals/ack. Body: AckSignalsRequest ({"workspace_id": "...", "ids": [...]}); workspace_id defaults the same way List's query param does.
AckSignals (internal/orchestrator/signal_store.go) is itself idempotent — re-acking an already-acked id is a no-op, not an error (signal-driven- review.md §14 Q14) — so this handler adds no extra dedup/already-acked check of its own; doing so would risk diverging from the store's own idempotency contract. The only validation here is "ids must not be empty", which is a client-input bug worth rejecting up front rather than forwarding a request AckSignals would silently no-op on.
func (*SignalHandler) List ¶ added in v0.4.0
func (h *SignalHandler) List(w http.ResponseWriter, r *http.Request)
List handles GET /api/signals?workspace_id=&source=&service=&state=&limit=.
workspace_id defaults to orchestrator.DefaultWorkspaceSlug ("default") when omitted — the CLI's --workspace flag already resolves this default before sending the request (cmd/signal.go), but the handler defaults it too so any direct API caller (curl, a future non-CLI client) gets the same behavior rather than SignalFilter's "workspace id must not be empty" error.
source maps to SignalFilter.Connector UNCHANGED — the signals table stores connector as the composite "<pack>/<connector>" string (signal-ingest-detailed-design.md §2), so --source slack/mentions and the stored value match exactly with no split needed for filtering (only the response envelope's `source` block splits it back apart, in toWireSignals below).
func (*SignalHandler) Routes ¶ added in v0.4.0
func (h *SignalHandler) Routes() chi.Router
type SignalSource ¶ added in v0.4.0
type SignalSource = apiwire.SignalSource
from internal/api/signal_handler.go
type SignalStore ¶ added in v0.4.0
type SignalStore interface {
IngestSignals(workspaceID, service, connector string, rows []orchestrator.SignalIngestRow) error
GetSignalCursor(workspaceID, service, connector string) (string, error)
ListSignals(filter orchestrator.SignalFilter) ([]*orchestrator.Signal, error)
ClaimSignals(workspaceID string, limit, maxAttempts int) ([]*orchestrator.Signal, error)
// ClaimSignalIDs charges one attempt against exactly the ids named — the
// explicit half of the read/claim split (orchestrator.ClaimSignalIDs).
ClaimSignalIDs(workspaceID string, ids []string) error
AckSignals(workspaceID string, ids []string) error
HasPendingSignals(workspaceID string, maxAttempts int) (bool, error)
}
SignalStore backs docs/plans/signal-ingest-detailed-design.md §2 (PR-1)'s inbox store (internal/orchestrator/signal_store.go) — narrowed from *orchestrator.TaskRepository the same way TriggerRunStore is. This PR wires no handler onto it yet (PR-2 adds `GET /api/signals` / `POST /api/signals/ack`, PR-3 adds the connector-facing ingest/cursor ops, PR-6 adds the `on: signals` trigger predicate that calls HasPendingSignals) — see the var _ assertion below for what proves TaskRepository actually satisfies this shape today.
GCSignals is deliberately NOT part of this interface: it is called directly as a package function from within TaskGCStore.GC's existing transaction (repository.go), the same way GCTriggerRuns is — not through a per-workspace narrow interface like the methods above.
type StartExecRequest ¶ added in v0.0.10
type StartExecRequest = apiwire.StartExecRequest
type StartExecResult ¶ added in v0.0.10
type StartExecResult = apiwire.StartExecResult
type StartSessionRequest ¶ added in v0.0.6
type StartSessionRequest = apiwire.StartSessionRequest
type StartSessionResult ¶ added in v0.0.6
type StartSessionResult = apiwire.StartSessionResult
type StatusError ¶
func (*StatusError) Error ¶
func (e *StatusError) Error() string
type TaskAnswerService ¶
type TaskAnswerService interface {
AnswerTask(ctx context.Context, taskID, questionID, answer string) error
}
TaskAnswerService records a user reply to a pending Q&A question and transitions the task back to executing.
type TaskAppService ¶
type TaskAppService struct {
Tasks TaskStore
Actions ActionStore
Jobs JobStore
Meta MetaStore
Workflow WorkflowService
Projects ProjectWorkDirLookup
RuntimesDir string
Notify Notifier
// BlockingAsk coordinates harness-independent blocking Q&A (boid task ask).
// Shared with the sandbox boid builtin executor (which calls AskTaskBlocking)
// and the answer path (AnswerTask), so both halves of a blocking ask use the
// same in-memory registry. Nil disables blocking ask (notify --ask still works).
BlockingAsk *BlockingAskRegistry
// AskDisconnectGrace is how long an awaiting task may sit with no live agent
// parked before the daemon reclaims it (a blocking ask whose foreground
// command was killed by a harness command-timeout). Zero falls back to
// defaultAskDisconnectGrace.
AskDisconnectGrace time.Duration
// TaskWaits is the registry the brokered task_wait op records itself in
// while parked, so the trigger sweep can tell which task a job is waiting
// on. Shared with TaskWorkflowService (wire.go builds one). Nil disables the
// attribution; the wait itself still works.
TaskWaits *TaskWaitRegistry
// WaitPollInterval is how often WaitTaskTerminal re-reads a task row while
// blocked on it. Zero falls back to defaultWaitPollInterval — same
// convention as AskDisconnectGrace above.
WaitPollInterval time.Duration
// Identities backs docs/plans/ingestion-identity.md PR-1 (B-1)'s identity
// index — the non-transactional path the brokered task_identity_link /
// _unlink / _resolve ops (boid_executor.go) call through. The drop side
// effect (I-6) instead goes through TxStore.UnlinkAllForTask inside
// TaskWorkflowService.ApplyAction's own transaction; this field is only
// for the standalone ops, which have no transaction of their own to join.
// Nil disables the three ops with an "unavailable" error, same convention
// as every other optional dependency here.
Identities TaskIdentityStore
}
func (*TaskAppService) AnswerTask ¶
func (s *TaskAppService) AnswerTask(ctx context.Context, taskID, questionID, answer string) error
AnswerTask saves the user's reply and transitions the task awaiting → executing.
func (*TaskAppService) AskTaskBlocking ¶ added in v0.0.6
func (s *TaskAppService) AskTaskBlocking(ctx context.Context, taskID, question string) (string, error)
AskTaskBlocking implements the harness-independent blocking Q&A RPC behind `boid task ask <question>`. The agent stays alive and blocks inside this call until the user/supervisor answers, so the round-trip works for every harness uniformly — there is no session-resume path anywhere in boid (the legacy `notify --ask` → `claude --resume` flow was removed).
The call is disconnect-resilient and idempotent across re-asks. Harnesses kill long-running shell commands on a command-timeout (claude-code / opencode at ~120s), which severs the held connection. When that happens the model retries the identical `boid task ask`; this handler recognises the retry and recovers instead of treating it as a fresh question:
- executing → fresh ask: register the answer channel, transition executing → awaiting via ApplyAction("ask"), fire the user notification (root tasks only; child tasks are seen by their supervisor's monitor loop), then block in Wait.
- awaiting → re-ask: if an answer was parked durably while the agent was disconnected (PendingAnswer), consume it immediately and flip back to executing. Otherwise re-attach to the SAME question id and block again — no second "ask" transition, no new notification.
Register happens before the awaiting transition so an answer that races in immediately afterwards is never dropped. Decision B1 (relaxed): a concurrent ask carrying a DIFFERENT question id still fails with ErrAskPending; a re-ask of the same question is a re-attach and is allowed.
func (*TaskAppService) CreateTask ¶
func (s *TaskAppService) CreateTask(req CreateTaskRequest) (*orchestrator.Task, error)
func (*TaskAppService) DeleteTask ¶
func (s *TaskAppService) DeleteTask(id string, force bool) error
func (*TaskAppService) DuplicateTask ¶
func (s *TaskAppService) DuplicateTask(sourceID string, autoStart bool) (*orchestrator.Task, error)
func (*TaskAppService) GetInstructions ¶ added in v0.0.13
func (s *TaskAppService) GetInstructions(id string) ([]orchestrator.RoutedInstruction, error)
GetInstructions returns the task's "active" routed instruction — the entry orchestrator.CurrentInstructions derives from the last entry in the task's instruction history.
NOT the `boid task instructions` RPC's data source (fixed in codex review on PR #797 before merge — see wiring-seams.md #13 and internal/server/boid_executor.go's BoidOpTaskInstructions case): a task row has no notion of "which job is asking", but orchestrator.Evaluator can fire two agent-kind hooks for different agents from the same task in one round (any agent appearing anywhere in the instruction history matches, not just the active/last entry) — GetInstructions would hand a claude job's RPC call the codex hook's instruction whenever codex happens to be the most recent history entry, and vice versa. Kept as a task-row-level projection for callers that genuinely want "the task's current routing state" independent of any specific job (there are none yet in this codebase; a plausible future one is a Web UI task-detail view). Returns an empty (non-nil) slice rather than nil, even when the task carries no active instruction (not executing, or no instructions history yet).
func (*TaskAppService) GetInstructionsField ¶ added in v0.0.13
func (s *TaskAppService) GetInstructionsField(id, path string) (string, error)
GetInstructionsField resolves a dotted path against the []RoutedInstruction list returned by GetInstructions, mirroring GetTaskField's --field contract.
func (*TaskAppService) GetTask ¶
func (s *TaskAppService) GetTask(id string) (*orchestrator.Task, error)
func (*TaskAppService) GetTaskCurrent ¶ added in v0.0.13
func (s *TaskAppService) GetTaskCurrent(id string) (*orchestrator.TaskSnapshot, error)
GetTaskCurrent returns the task's business-metadata snapshot — the same subset historically materialized at $HOME/.boid/context/task.yaml (orchestrator.SnapshotTask), now also the payload of `boid task current`. Unlike the file (frozen at dispatch time), this re-derives from the task row on every call, so it reflects concurrent `task update` calls.
func (*TaskAppService) GetTaskCurrentField ¶ added in v0.0.13
func (s *TaskAppService) GetTaskCurrentField(id, path string) (string, error)
GetTaskCurrentField resolves a dotted path against the task-current snapshot, mirroring GetTaskField's semantics for `--field` (missing path → "", scalar → unquoted/stringified, object/array → compact JSON).
func (*TaskAppService) GetTaskDetail ¶
func (s *TaskAppService) GetTaskDetail(id string) (*TaskDetailView, error)
func (*TaskAppService) GetTaskField ¶
func (s *TaskAppService) GetTaskField(id, path string) (string, error)
GetTaskField resolves a dotted field path against the task. See ResolveTaskField for the path syntax (top-level fields, payload traits, computed lifecycle).
func (*TaskAppService) ImportTasks ¶
func (s *TaskAppService) ImportTasks(reqs []CreateTaskRequest) (*ImportResult, error)
func (*TaskAppService) LinkIdentity ¶ added in v0.4.0
func (s *TaskAppService) LinkIdentity(projectID, identity, taskID string) error
LinkIdentity binds identity to taskID within projectID's scope. See TaskIdentityStore.LinkIdentity for the idempotent-same-task / ErrIdentityConflict-different-task contract.
func (*TaskAppService) ListTasks ¶
func (s *TaskAppService) ListTasks(filter orchestrator.TaskFilter) ([]*orchestrator.Task, error)
func (*TaskAppService) NotifyTask ¶
func (s *TaskAppService) NotifyTask(ctx context.Context, taskID, message, ask, questionID, progress, done, fail string) error
NotifyTask invokes the configured notify command for the given task. Returns 501 when no notifier is wired and ask is empty (notifications disabled in config). When ask is non-empty the task is transitioned to awaiting; the notification is best-effort and skipped if no notifier is configured. questionID identifies the Q&A turn (generated when empty). When progress is non-empty (progress mode), no hook fires and no state transition occurs — only a progress Action is written to the timeline. ask and progress are mutually exclusive.
Note: ask transitions the task to awaiting but does NOT spawn a resume dispatch when the user replies. The session-id resume path was removed (every dispatch is a fresh agent process); only `boid task ask` (the blocking RPC) can deliver an answer back to a live agent.
Actor note (論点11): every Action this writes is stamped orchestrator.ActorTask(taskID) — treated as the task's own self-report. This call is reachable both from inside a sandbox (`boid task notify`, the common case) and from the host-side HTTP route, so a human operator calling `boid task notify --done` from outside a task also gets logged as `task:<id>` rather than `human`. Defensible under "this call always means the task itself is signalling its own progress/outcome", but worth this note for anyone auditing the actions log.
func (*TaskAppService) RerunTask ¶
func (s *TaskAppService) RerunTask(id string, req RerunTaskRequest) (*orchestrator.Task, error)
func (*TaskAppService) ResolveIdentity ¶ added in v0.4.0
func (s *TaskAppService) ResolveIdentity(projectID, identity string) (*orchestrator.Task, error)
ResolveIdentity looks up the task bound to (projectID, identity). Returns orchestrator.ErrTaskNotFound when no binding exists.
func (*TaskAppService) UnlinkIdentity ¶ added in v0.4.0
func (s *TaskAppService) UnlinkIdentity(projectID, identity string) error
UnlinkIdentity removes one (projectID, identity) binding, if any.
func (*TaskAppService) UpdateTask ¶
func (s *TaskAppService) UpdateTask(id string, req UpdateTaskRequest) (*orchestrator.Task, error)
func (*TaskAppService) UpdateTaskPayloadPatch ¶ added in v0.0.13
func (s *TaskAppService) UpdateTaskPayloadPatch(jobID string, patch json.RawMessage, allowedTraits []orchestrator.TraitType) (*orchestrator.Task, error)
UpdateTaskPayloadPatch applies patch to the task owning jobID using the SAME merge semantics the file-based payload_patch.json → job_done → Coordinator pipeline has always applied (orchestrator.MergePayloadPatch, gated by the trait allowlist the firing hook itself declares via Traits.Produces) — see orchestrator/coordinator.go's HandlerResult.allowedTraits and wiring-seams.md #13/#17. This is deliberately NOT UpdateTask's simpler top-level shallow merge (used by --payload-file): UpdateTask has no notion of a "firing hook", so it can't reproduce this gate.
jobID (not taskID) is the identity this method resolves from, because the allowedTraits gate is keyed off the CALLING job's own HandlerID — the specific hook that was dispatched to produce this job, which may differ from other jobs the same task has had or will have (mirrors why BoidOpTaskInstructions/Env/Payload are JobID-scoped, not TaskID-scoped).
allowedTraits is supplied by the CALLER — it must be the value captured AT DISPATCH TIME (dispatcher.JobContextSnapshot.PayloadPatchAllowedTraits, itself sourced from orchestrator.JobSpec.HookTraitsProduces), never re-derived here from a live project-meta lookup. An earlier version of this method did its own live lookup (GetTask's ProjectID -> current meta -> current behavior -> hook by HandlerID) and codex review caught the TOCTOU staleness bug that creates: if project.yaml is edited/reloaded between dispatch and this call, a live lookup can either apply the WRONG (post-edit) trait list or silently fall back to unrestricted when the hook can no longer be found by name — neither matches what was actually authorized when the job was dispatched. Accepting the dispatch-time value as a parameter makes that class of staleness structurally impossible instead of requiring a "fail closed on lookup failure" special case (see wiring-seams.md #17's Major 1 finding). nil means unrestricted — see JobSpec.HookTraitsProduces's own doc comment for exactly when that's the correct (not just the fallback) value.
The GetTask -> MergePayloadPatch -> UpdateTask sequence below is serialized per task id (payloadPatchLockFor) so two concurrent calls for the same task — e.g. two hooks in the same readonly task's parallel dispatch round, each patching a different trait — cannot race a read-modify-write and silently lose one of their writes (Phase 5b PR7 codex review Blocker 2, wiring-seams.md #17).
func (*TaskAppService) WaitTaskTerminal ¶ added in v0.4.0
func (s *TaskAppService) WaitTaskTerminal(ctx context.Context, taskID string) (TaskOutcome, error)
WaitTaskTerminal blocks until taskID reaches a terminal status and reports how it ended.
This is the daemon half of `boid task wait <id>`, which exists so a trigger's `run:` command can live exactly as long as the task it started. That single change makes the trigger's own machinery cover the task: single-flight stops measuring a launcher that exits in seconds and starts measuring the work, and a failed round arrives at TriggerLoop.trackFailStreak as an ordinary non-zero exit instead of having to be re-derived by the workspace from the action log.
Only ctx cancellation ends the wait early. The broker gives a blocking op a context tied to its connection (sandbox.isBlockingBoidRequest — task_wait must stay listed there or an abandoned wait runs until daemon shutdown), so a sandbox that dies unblocks this. It is NOT a timeout: a task that parks in a non-terminal resting state (`awaiting` on a question nobody answers, `pending` with auto_start off) waits indefinitely. Bounding a round's total duration is the trigger's job, not this call's.
type TaskCreator ¶ added in v0.2.4
type TaskCreator interface {
CreateTask(req CreateTaskRequest) (*orchestrator.Task, error)
}
TaskCreator is the slice of TaskAppService that TaskWorkflowService.Dispatch needs to task-ify a triage task's specced children (docs/plans/ cross-project-issue-triage.md Phase 1 PR-2, 逆輸入1). Implemented by TaskAppService and wired in after TaskAppService itself is constructed (wire.go creates TaskWorkflowService first, TaskAppService second, so this mirrors the same late-binding idiom the reverse direction already uses — see WorkflowService/TaskAppService.Workflow above) to avoid a literal struct-construction cycle between the two services.
type TaskDetailView ¶
type TaskDetailView = apiwire.TaskDetailView
type TaskEventHub ¶
type TaskEventHub struct {
// contains filtered or unexported fields
}
TaskEventHub は taskID ごとに複数の subscriber へイベントを配送する pub-sub ハブ。
func (*TaskEventHub) Broadcast ¶
func (h *TaskEventHub) Broadcast(taskID string, ev TaskEvent)
Broadcast は taskID の全 subscriber に ev を非ブロッキングで配送する。 チャネルが満杯の subscriber はドロップする(hub 全体を止めない)。
type TaskHandler ¶
type TaskHandler struct {
Service TaskService
Hooks HookService // optional: enables hook replay/list when set
Notifier TaskNotifyService // optional: enables POST /{id}/notify when set
Answerer TaskAnswerService // optional: enables POST /{id}/answer when set
}
func (*TaskHandler) Answer ¶
func (h *TaskHandler) Answer(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Create ¶
func (h *TaskHandler) Create(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Delete ¶
func (h *TaskHandler) Delete(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Detail ¶
func (h *TaskHandler) Detail(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Duplicate ¶
func (h *TaskHandler) Duplicate(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Field ¶
func (h *TaskHandler) Field(w http.ResponseWriter, r *http.Request)
Field returns a single dotted-path value extracted from the task. The response is text/plain so it can be consumed directly by shell scripts (e.g. `STATUS=$(boid task show $ID --field status)`).
func (*TaskHandler) Get ¶
func (h *TaskHandler) Get(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Import ¶
func (h *TaskHandler) Import(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) List ¶
func (h *TaskHandler) List(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) ListHooks ¶
func (h *TaskHandler) ListHooks(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Notify ¶
func (h *TaskHandler) Notify(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Patch ¶
func (h *TaskHandler) Patch(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) ReplayHook ¶
func (h *TaskHandler) ReplayHook(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Rerun ¶
func (h *TaskHandler) Rerun(w http.ResponseWriter, r *http.Request)
func (*TaskHandler) Routes ¶
func (h *TaskHandler) Routes() chi.Router
type TaskIdentityStore ¶ added in v0.4.0
type TaskIdentityStore interface {
// LinkIdentity binds identity to taskID within projectID's scope.
// Re-linking the same task is idempotent; linking a DIFFERENT task
// already bound to identity returns orchestrator.ErrIdentityConflict.
LinkIdentity(projectID, identity, taskID string) error
// UnlinkIdentity removes one binding, if any (idempotent — not found is
// not an error).
UnlinkIdentity(projectID, identity string) error
// UnlinkAllForTask releases every identity bound to taskID (I-6: called
// from the drop side effect — see TaskWorkflowService.ApplyAction).
UnlinkAllForTask(taskID string) error
// ResolveIdentity looks up the task bound to (projectID, identity).
// Returns orchestrator.ErrTaskNotFound when no binding exists.
ResolveIdentity(projectID, identity string) (*orchestrator.Task, error)
// ListIdentitiesByTask returns every identity bound to taskID.
ListIdentitiesByTask(taskID string) ([]string, error)
}
TaskIdentityStore provides access to docs/plans/ingestion-identity.md PR-1 (B-1)'s identity index (task_identities table): external key -> task, scoped per project (I-1/I-2/I-3). Deliberately separate from TaskStore for the same reason CardStore is: identity bindings are not part of orchestrator.Task's own JSON shape.
type TaskNotifyService ¶
type TaskNotifyService interface {
NotifyTask(ctx context.Context, taskID, message, ask, questionID, progress, done, fail string) error
}
TaskNotifyService dispatches an agent-driven notification for a task. Wired to *TaskAppService at runtime; left optional on TaskHandler so existing tests do not need to satisfy this interface. ask/questionID are optional Q&A fields: when ask is non-empty the task is transitioned to awaiting after the notification is sent. The session-id resume path was removed, so an answer can only reach an agent that is still alive inside a blocking `boid task ask` RPC. progress is a no-state-change progress note (timeline action only). done / fail are agent self-completion / self-failure: they transition the task to done / aborted respectively and SIGTERM running hook runtimes — the parent supervisor's polling drives the response (verify + optional reopen). ask/progress/done/fail are mutually exclusive.
type TaskOutcome ¶ added in v0.4.0
type TaskOutcome struct {
// ID is the resolved task id (WaitTaskTerminal accepts the same id prefixes
// orchestrator.GetTask does).
ID string
Status orchestrator.TaskStatus
AbortCode string
AbortMessage string
}
TaskOutcome is how a waited-on task ended. AbortCode/AbortMessage carry the abort action's payload and are set only when Status is aborted: abortOnDispatchError writes "dispatch_error" / "daemon_shutdown", while an abort recorded without a payload (job_failed, i.e. a failure inside the agent's own session) leaves both empty. Neither is a closed vocabulary — read them as decoration for a human, never as a branch condition.
func (TaskOutcome) Succeeded ¶ added in v0.4.0
func (o TaskOutcome) Succeeded() bool
Succeeded reports whether the task ended the way the caller wanted. Only `done` counts — every other terminal status, including `dropped`, is a failure. This is what `boid task wait`'s exit code is derived from, and a trigger script's contract is "fail if the task you started did not succeed".
type TaskService ¶
type TaskService interface {
CreateTask(req CreateTaskRequest) (*orchestrator.Task, error)
ListTasks(filter orchestrator.TaskFilter) ([]*orchestrator.Task, error)
GetTask(id string) (*orchestrator.Task, error)
GetTaskDetail(id string) (*TaskDetailView, error)
GetTaskField(id, path string) (string, error)
UpdateTask(id string, req UpdateTaskRequest) (*orchestrator.Task, error)
DeleteTask(id string, force bool) error
ImportTasks(reqs []CreateTaskRequest) (*ImportResult, error)
DuplicateTask(sourceID string, autoStart bool) (*orchestrator.Task, error)
RerunTask(id string, req RerunTaskRequest) (*orchestrator.Task, error)
}
type TaskStatusReader ¶ added in v0.4.0
type TaskStatusReader interface {
GetTaskStatus(id string) (orchestrator.TaskStatus, error)
}
TaskStatusReader is the narrow re-read WaitTaskTerminal polls with, kept separate from TaskStore so adding it did not have to touch every implementation of that much larger interface.
*orchestrator.TaskRepository is the production implementation and the compile-time assertion below pins that, rather than leaving it to a runtime type check that would silently degrade to the expensive path if the real wired type ever stopped satisfying it — the exact failure PR #1014's review found for the signals dependency (docs/plans/signal-ingest-detailed-design.md PR-3, M1), where every unit test passed against a hand-built double while production never picked the interface up at all.
type TaskStore ¶
type TaskStore interface {
CreateTask(task *orchestrator.Task) error
GetTask(id string) (*orchestrator.Task, error)
ListTasks(filter orchestrator.TaskFilter) ([]*orchestrator.Task, error)
UpdateTask(task *orchestrator.Task) error
DeleteTask(id string) error
FindTaskByRemote(remoteID string) (*orchestrator.Task, error)
// FindTaskByRef looks up an existing task by ref, scoped to BOTH
// parentID ("" for a root task) and projectID (Phase 1 PR-4, codex review
// Blocker fix — see orchestrator.FindTaskByRef's doc comment for why
// projectID scoping is required, not optional).
FindTaskByRef(ref, parentID, projectID string) (*orchestrator.Task, error)
// ListChildren returns direct children (one level only) of the given parent
// task, ordered by created_at ASC. Returns an empty slice (not nil) when the
// task has no children. Used by finalizeTerminal to sweep boid/<id8> branches
// once a supervisor reaches a terminal state.
ListChildren(parentID string) ([]*orchestrator.Task, error)
}
type TaskUpdatedAtToucher ¶ added in v0.4.0
TaskUpdatedAtToucher backs docs/plans/webui-detail-list-redesign.md PR-3's updated_at bump (§3.2): a single-column `UPDATE tasks SET updated_at = ? WHERE id = ?` that carries NO status. Deliberately its own interface, not folded into TaskStore — TaskStore.UpdateTask does a blanket rewrite of every column from a caller-held Task snapshot, which is exactly the stale-snapshot race workflow_action.go's skipTaskUpdate guard exists to avoid for attrs_set/child_added/child_specced/child_dropped/noted (see that variable's own doc comment). TouchTaskUpdatedAt carries no status at all, so calling it alongside those actions' own non-transitioning side effects — in the same Tx — cannot stomp a concurrently-committed transition the way an unconditional UpdateTask(stale snapshot) would.
type TaskWaitRegistry ¶ added in v0.4.0
type TaskWaitRegistry struct {
// contains filtered or unexported fields
}
TaskWaitRegistry records which task each in-flight `boid task wait` is parked on, keyed by the waiting job.
It exists for one question the trigger sweep cannot otherwise answer: when a round overruns its trigger's `timeout`, WHAT should be ended? The job is only the launcher — killing it leaves the task it started running, releases single-flight, and lets the next tick begin a second concurrent round of the same work, which is worse than the overrun. The thing to end is the task, and the only place that link exists is the wait itself: the executor knows both ids at the moment it parks (TokenContext.JobID and the resolved task id).
Purely in-memory, like BlockingAskRegistry and for the same reason: the sandbox process backing a parked wait dies with the daemon, so a restart has nothing to resume. A lost entry degrades to today's behavior (the job is stopped, the task is left alone), never to a wrong task being aborted.
func NewTaskWaitRegistry ¶ added in v0.4.0
func NewTaskWaitRegistry() *TaskWaitRegistry
NewTaskWaitRegistry returns an initialised registry.
func (*TaskWaitRegistry) Register ¶ added in v0.4.0
func (r *TaskWaitRegistry) Register(jobID, taskID string) (release func())
Register records that jobID is waiting on taskID and returns the release to call when the wait ends. Both a nil registry and an empty jobID are tolerated and return a no-op release, so a caller never has to branch: a job id is absent for host-side and test callers, and an unregistered wait simply cannot be attributed to a trigger run — which is the same position the daemon was in before this existed.
A second Register for the same job overwrites the first. That is the right resolution rather than an error: a job runs its commands sequentially, so the only way to see two is if a release was missed, and the newer wait is the one actually parked.
type TaskWorkflowService ¶
type TaskWorkflowService struct {
Tasks TaskStore
Jobs JobStore
Projects ProjectRepository
Tx Transactor
Meta MetaStore
Coordinator DispatchCoordinator
Lifecycle JobLifecycle
Hub *TaskEventHub
// TaskTriage provides non-transactional (pre-tx-open) read access to the
// task_triage sidecar for TaskWorkflowService.Dispatch's pre-check /
// children read (docs/plans/cross-project-issue-triage.md Phase 1 PR-2).
// TxStore already embeds CardStore for the in-transaction writes
// Dispatch and applyParkSideEffect need — this field is only for the read
// that has to happen BEFORE opening a transaction (see Dispatch's own doc
// comment for why child-task creation can't run nested inside one). Nil
// is tolerated (treated as "no children"); wire.go always sets this.
TaskTriage CardStore
// Actions provides the workspace-scoped BoidOpActionList read (docs/plans/
// ingestion-identity.md PR-3, B-3) — same "narrower interface over the
// same underlying taskRepo value" pattern as TaskTriage above. Nil is
// tolerated (ListActions returns an "unavailable" error), matching every
// other optional dependency's convention in this file.
Actions ActionListStore
// TaskCreator creates the real boid tasks Dispatch task-ifies specced
// children into. Nil is tolerated as long as there are no specced
// children to dispatch — see Dispatch's own doc comment.
TaskCreator TaskCreator
// Adapter is the harness adapter used to query post-run usage. Phase 3-b
// dropped the StopAgent role: graceful stop is delivered as a SIGUSR1
// directly via Lifecycle.SignalJobRuntime, which claude.Adapter.Run()'s
// signal.Notify handler intercepts. Adapter remains optional; when nil,
// usage / future per-harness queries become no-ops.
Adapter adapters.HarnessAdapter
// Notifier fires queue の決定論的評価 節 rule 4 (notify) whenever a
// suggestion attaches to a card — see notifySuggestionArrived in
// queue_notify.go (PR-2, docs/plans/suggestion-as-state-transition-impl.md
// §4.2, replacing v1's urgency=now-gated notifyQueueEntryIfUrgent /
// notifyUrgencyRaised entirely). Nil is tolerated (no-op), same as
// TaskAppService.Notify's contract.
Notifier Notifier
// TaskWaits is the shared registry recording which task each in-flight
// `boid task wait` is parked on (see TaskWaitRegistry). SweepTriggers reads
// it to know WHAT to end when a round outruns its trigger's `timeout` — the
// task doing the work, not just the job that launched it. Nil is tolerated
// (a timed-out round then only has its job stopped), same convention as
// every other optional dependency here.
TaskWaits *TaskWaitRegistry
// Triggers backs docs/plans/ingestion-identity.md PR-4 (B-5)'s
// trigger_runs single-flight/execution-record read+write
// (SweepTriggers/RunTriggerNow, trigger_loop.go). Nil is tolerated —
// SweepTriggers/RunTriggerNow no-op (matching Notifier/TaskCreator's own
// convention above) rather than panicking, since a daemon built without
// this dependency wired should simply run no triggers, not crash.
Triggers TriggerRunStore
// Exec dispatches the exec job (api.ExecDispatcher.StartExec) a due
// trigger's `run` command executes as (PR-4's "実行" section — daemon
// starts an exec job through the SAME Runner.Dispatch() path `boid exec`
// uses). Nil is tolerated the same way Triggers above is: wire.go can
// only assign this once sessionDispatcherAdapter exists (mountRoutes,
// after buildRuntime constructs this TaskWorkflowService), so a
// construction-order gap must not be fatal — see wire.go's own comment
// at the assignment site.
Exec ExecDispatcher
// Signals backs the `on: signals` trigger predicate's HasPendingSignals
// read (docs/plans/signal-ingest-detailed-design.md §4.2, PR-6,
// SweepTriggers/signalsPendingForTrigger, trigger_loop.go). Nil is
// tolerated the same way Triggers/Exec above are: an on:signals trigger
// simply never becomes due (fail-closed, not a panic) when no
// SignalStore is wired — a plain schedule (on=""/on:schedule) trigger is
// entirely unaffected either way.
Signals SignalStore
// contains filtered or unexported fields
}
func (*TaskWorkflowService) ApplyAction ¶
func (s *TaskWorkflowService) ApplyAction(ctx context.Context, taskID string, req ApplyActionRequest) (*ActionApplication, error)
func (*TaskWorkflowService) CompleteJob ¶
func (s *TaskWorkflowService) CompleteJob(ctx context.Context, jobID string, req JobDoneRequest) (*Job, error)
func (*TaskWorkflowService) GetCard ¶ added in v0.4.0
func (s *TaskWorkflowService) GetCard(taskID string) (*CardView, error)
GetCard returns the read-side projection of one triage task.
A missing TASK is an error (404). A missing SIDECAR ROW is not: the task's status is the single most important piece of state, and a triage task can legitimately exist without a sidecar row (a row created before PR-5a's CreateTask seeding, or one whose first side-effect action has not landed yet). Reporting 404 for those would tell the caller "this task does not exist" about a task that plainly does — the same fail-open posture Dispatch already takes when it treats a missing row as "no children".
func (*TaskWorkflowService) InitDispatch ¶
func (s *TaskWorkflowService) InitDispatch(ctx context.Context)
InitDispatch initialises the lifecycle context used by dispatch-loop goroutines. Must be called before the first action is applied. The returned cancel is stored internally; call Shutdown to invoke it.
func (*TaskWorkflowService) ListActions ¶ added in v0.4.0
func (s *TaskWorkflowService) ListActions(filter orchestrator.ActionListFilter) (*ActionListResult, error)
ListActions returns the actions matching filter (already scoped by the caller) plus the next cursor. See orchestrator.ListActionsSince's own doc comment for the pagination contract.
func (*TaskWorkflowService) ListCards ¶ added in v0.4.0
func (s *TaskWorkflowService) ListCards(filter orchestrator.TaskFilter) ([]*CardView, error)
ListCards returns the projections of every TRIAGE task matching filter.
The discriminator is "has a task_triage row" rather than "has a triage-shaped status". Status alone cannot decide it: `done` is shared with ordinary tasks (a done triage task and a done executor task are indistinguishable by status — the same limitation that forces PR-5b's reopen guard into the service layer), and a meta project holds plenty of ordinary tasks (the ingest/sweep executor tasks) that must not appear in a triage listing. CreateTask seeds the row for every pre-execution task (task_create.go), which is what makes this predicate reliable from birth.
A task whose sidecar lookup fails for a reason OTHER than "no row" is skipped rather than aborting the whole listing: one malformed row must not make the entire queue unreadable (same posture as SweepWake).
func (*TaskWorkflowService) ListHooksForStatus ¶
func (s *TaskWorkflowService) ListHooksForStatus(taskID, status string) ([]orchestrator.Hook, error)
ListHooksForStatus returns hooks that match the given status for the task. If status is empty, the task's current status is used.
func (*TaskWorkflowService) ReplayHook ¶
func (s *TaskWorkflowService) ReplayHook(ctx context.Context, taskID string, req ReplayHookRequest) (*ReplayHookResult, error)
ReplayHook replays a single hook for the given task. If req.Status is non-empty the task's status is overwritten before dispatch. Running jobs on the same task cause a 409 Conflict.
func (*TaskWorkflowService) ResolveOrCapture ¶ added in v0.4.0
func (s *TaskWorkflowService) ResolveOrCapture(ctx context.Context, req ResolveOrCaptureRequest) (*ResolveOrCaptureResult, error)
ResolveOrCapture resolves Identity (scoped to ProjectID, I-3) to an existing task, or — when unresolved — atomically creates a new `parked` card (I-4, J-9: daemon never advances a card past capture — card machine v2, docs/plans/suggestion-as-state-transition-impl.md §3.5, folds the old `captured` status into `parked` directly) and links Identity to it.
Invariants pinned by task_resolve_or_capture_test.go:
- resolve-then-create-and-link happens inside a single Transactor.WithinTx call, so a create that isn't followed by a successful link never commits (no orphan captured task without an identity binding)
- a genuine identity conflict (LinkIdentity finding Identity already bound to a DIFFERENT task) surfaces orchestrator.ErrIdentityConflict UNWRAPPED so callers can errors.Is() it — same convention as PR-1's api/task_identity.go methods
- description is subject to the same size cap as every other content entry point (orchestrator.ValidateContentSize, J-10/A-5)
func (*TaskWorkflowService) RunTriggerNow ¶ added in v0.4.0
func (s *TaskWorkflowService) RunTriggerNow(ctx context.Context, projectID, triggerName string) (*TriggerRunNowResult, error)
RunTriggerNow fires projectID's triggerName trigger immediately, ignoring the `every` elapsed check but NOT single-flight — the manual debugging entry point 12 節 B-5 既定案「手動 1 巡の口」calls for (`boid trigger run <name>`, cmd/trigger.go).
func (*TaskWorkflowService) Shutdown ¶
func (s *TaskWorkflowService) Shutdown()
Shutdown cancels the dispatch context and blocks until all in-flight dispatch loops have returned. Call this before closing the database.
func (*TaskWorkflowService) StopAgent ¶
func (s *TaskWorkflowService) StopAgent(runtimeID string)
StopAgent gracefully stops the agent backing runtimeID by delivering SIGUSR1 to its process group. claude.Adapter.Run()'s signal.Notify(SIGUSR1) handler forwards a SIGTERM to the claude child and returns Result.StoppedByDaemon=true, so the surrounding sandbox runtime survives long enough to post `boid job done` through the broker normally. No-op when runtimeID is empty or no JobLifecycle has been configured.
func (*TaskWorkflowService) SweepReconcileChildren ¶ added in v0.4.0
SweepReconcileChildren re-checks every dispatched child of every working card against its REAL current task status, self-healing any whose task_triage.detail entry still says "dispatched" after the real task already reached done/aborted (PR #987 review, HIGH 8). This is bare bookkeeping over detail.children[].status, NOT a card transition — it does not touch task.Status, so it does not reopen design doc §3.3's "機械遷移 ゼロ" (card machine v2 has zero rules moving a card's own status; this sweep only keeps a CHILD's recorded status from drifting from reality).
v1's SweepTriage did this same reconciliation as a side effect of evaluating auto-done every tick (決定15) — deleting auto-done along with it (see this PR's orchestrator-layer commit) took the reconciliation with it too, which was collateral, not intentional: without a periodic re-check, a "dispatched" entry that never gets its child_closed self-record (recordChildClosedOnParent hitting a transient DB error, or a child GC'd out from under it — orchestrator/store.go's GCTasks deletes a terminal task's row independent of any parent) sticks forever, and khi reads "a child is still running" off that stale entry and never suggests "done" for a card that has, in reality, already finished (a permanently stale working card).
A failure evaluating one task is logged and does not abort the sweep — the same posture SweepWake established.
func (*TaskWorkflowService) SweepTriggers ¶ added in v0.4.0
func (s *TaskWorkflowService) SweepTriggers(ctx context.Context, now time.Time) (TriggerSweepResult, error)
SweepTriggers is TriggerLoop's per-tick work: reconcile in-flight runs, then evaluate every project's triggers[] and fire whichever are due and not single-flight-blocked. Mirrors SweepWake/SweepTriage's shape (both TaskWorkflowService methods called from QueueSweepLoop) — daemon-actor context, tolerant of partial failures (one project/trigger's error is logged and does not abort the sweep for every other one).
Nil Triggers/Projects/Meta/Jobs (any REQUIRED dependency unwired) makes this a no-op, matching TaskWorkflowService's other optional-field conventions (Notifier, TaskCreator) — a daemon built without trigger support wired in simply runs no triggers rather than panicking.
Jobs joins this guard for a different reason than Triggers/Projects/Meta (N-10, Opus review): a nil s.Jobs does not fail loudly the way a nil Projects/Meta would — jobTerminalState just returns an error every call, which reconcileInFlight treats as "leave in flight, retry next tick" (indistinguishable from a transient GetJob hiccup). That is harmless for a tick with nothing in flight yet, but the FIRST successful fire creates a row reconcileInFlight can then never resolve — the exact permanent-wedge shape N-1's self-heal exists to recover from, except self-heal cannot help here either (TriggerRunSelfHealGrace only fires on a jobErr/empty- job-id it CAN observe; a nil s.Jobs makes every subsequent tick's jobTerminalState call fail identically, so it does eventually self-heal, just noisily and after silently wedging every trigger for TriggerRunSelfHealGrace first). s.Exec is deliberately NOT added here: its absence is already handled gracefully per-trigger by the existing fail-open dispatch-failure path below (fireTrigger returns a plain error when s.Exec is nil, same as any other StartExec failure) — folding it into this top-level guard would ALSO skip reconcileInFlight, which is still useful (closing out already-in-flight rows) even when nothing new can be dispatched.
func (*TaskWorkflowService) SweepWake ¶ added in v0.2.4
func (s *TaskWorkflowService) SweepWake(ctx context.Context, now time.Time) (woken []string, err error)
SweepWake implements 決定12's wake evaluation as a periodic, decision-only sweep (clock + task DB only, no agent judgment) — REDUCED, as of card machine v2 (docs/plans/suggestion-as-state-transition-impl.md §3.4, §C), to a pure fact-recording role. v1's SweepWake resolved a parked task's origin (via ParkedFrom) and applied the matching wake_triaged/wake_ready/ wake_working transition itself — the daemon deciding, on its own, what a re-surfaced card should become. Design doc §3.3's "機械遷移ゼロ" retires that: v2's card machine has exactly one park origin (working) and no wake_* rules at all, so there is nothing left to resolve. SweepWake now only records that orchestrator.ShouldWake fired (recordWakeDue) — a wake_due action, no transition, no suggestion. khi reads wake_due off the action log and decides what (if anything) to suggest.
A failure evaluating or recording one task is logged and does not abort the sweep — the same posture v1 established. Returns the ids of tasks wake_due was recorded for this tick.
type Transactor ¶
type TriggerCompletionResult ¶ added in v0.4.0
type TriggerCompletionResult struct {
TriggerKey
ExitCode int
}
TriggerCompletionResult records one trigger_runs row a sweep reconciled (its job reached a terminal status this tick).
type TriggerFireResult ¶ added in v0.4.0
type TriggerFireResult struct {
TriggerKey
JobID string
}
TriggerFireResult records one trigger a sweep actually dispatched.
type TriggerKey ¶ added in v0.4.0
TriggerKey identifies one trigger within one project — the single-flight and elapsed-time scoping unit (12 節 B-5 既定案「single-flight の粒度は トリガ単位」).
type TriggerLoop ¶ added in v0.4.0
type TriggerLoop struct {
Store TriggerLoopStore
Interval time.Duration
InitialDelay time.Duration
// Notifier is optional (nil disables stuck/failure notifications,
// matching TaskWorkflowService.Notifier's own convention).
Notifier Notifier
// contains filtered or unexported fields
}
TriggerLoop periodically calls SweepTriggers, mirroring QueueSweepLoop's shape (queue_sweep.go) exactly: same InitialDelay-then-Interval idiom, Run(ctx) blocks until ctx is done, a sweep error is logged and never stops the loop.
skipStreak/failStreak (stuck/failure-streak notification bookkeeping) are deliberately kept IN-MEMORY on the loop, not persisted to trigger_runs — mirroring QueueSweepLoop.lastBreachFingerprint's own precedent (also process-local, edge-triggered dedup state). A daemon restart resets the streak count to zero; the worst case is one missed or duplicated notification around a restart, never an incorrect fire/skip decision — trigger_runs itself (the single-flight source of truth) is unaffected.
func (*TriggerLoop) Run ¶ added in v0.4.0
func (l *TriggerLoop) Run(ctx context.Context)
Run blocks until ctx is done. It waits InitialDelay before the first sweep, then calls Store.SweepTriggers every Interval.
type TriggerLoopStore ¶ added in v0.4.0
type TriggerLoopStore interface {
SweepTriggers(ctx context.Context, now time.Time) (TriggerSweepResult, error)
}
TriggerLoopStore is TriggerLoop's dependency, narrowed from *TaskWorkflowService — same idiom as QueueSweepStore (queue_sweep.go).
type TriggerRunNowResult ¶ added in v0.4.0
type TriggerRunNowResult struct {
// Skipped is true when single-flight blocked this manual run (a prior
// run for the same (project, trigger) is still in flight). Manual runs
// deliberately do NOT bypass single-flight — only the `every` elapsed
// check is bypassed (仕分け B「手動 1 巡の口」既定案: デバッグに要る, not
// "force a second concurrent run").
Skipped bool `json:"skipped"`
Reason string `json:"reason,omitempty"`
JobID string `json:"job_id,omitempty"`
}
TriggerRunNowResult is RunTriggerNow's / `boid trigger run`'s response shape.
type TriggerRunStore ¶ added in v0.4.0
type TriggerRunStore interface {
CreateTriggerRun(run *orchestrator.TriggerRun) error
CompleteTriggerRun(id string, finishedAt time.Time, exitCode int) error
ListInFlightTriggerRuns() ([]*orchestrator.TriggerRun, error)
LatestTriggerRun(projectID, triggerName string) (*orchestrator.TriggerRun, error)
// SetTriggerRunJobID / DeleteTriggerRun back the Opus review Blocker 1
// insert-then-dispatch split — see orchestrator.CreateTriggerRun's own
// doc comment for the full sequence.
SetTriggerRunJobID(id, jobID string) error
DeleteTriggerRun(id string) error
}
TriggerRunStore backs docs/plans/ingestion-identity.md PR-4 (B-5)'s trigger_runs ledger read/writes — narrowed from *orchestrator. TaskRepository the same way ActionListStore/CardStore are (workflow.go). Deliberately non-transactional (unlike TxStore's WithinTx-scoped methods): each call is a standalone statement, matching this table's actual access pattern in trigger_loop.go (no create+link atomicity requirement the way PR-2's ResolveOrCapture has — a trigger_runs row's create and its later complete are two separate ticks by construction, so there is nothing to wrap in one transaction).
type TriggerRunner ¶ added in v0.4.0
type TriggerRunner interface {
RunTriggerNow(ctx context.Context, projectID, triggerName string) (*TriggerRunNowResult, error)
}
TriggerRunner fires one project.yaml trigger immediately, bypassing the `every` elapsed check but NOT single-flight. Implemented by *api.TaskWorkflowService.RunTriggerNow (trigger_loop.go).
type TriggerSkip ¶ added in v0.4.0
type TriggerSkip struct {
TriggerKey
// Since is the blocking run's StartedAt — how long it has been in
// flight as of this tick.
Since time.Time
// Every is trigger.Every, parsed. Zero if the blocking run's own
// trigger definition's `every` could not be parsed (should not happen —
// ValidateTriggers rejects that at project.yaml load time — but
// trackSkipStreak treats a zero Every defensively, see its own doc
// comment).
Every time.Duration
// Timeout is the trigger's declared bound on one round, zero when it
// declared none. trackSkipStreak prefers it over its own
// TriggerStuckOverrunMultiplier × Every guess: once an author has SAID how
// long a round may run, a shorter guess derived from the polling interval
// is not a second opinion, it is noise — and the overrun it would report is
// already handled, by ending the round rather than notifying about it.
Timeout time.Duration
}
TriggerSkip records one trigger that WAS due this tick but single-flight blocked it — Since/Every are the blocking run's StartedAt and the trigger's own configured interval, both needed by TriggerLoop.trackSkipStreak to judge whether the in-flight duration is actually anomalous relative to `every` (Opus review Blocker 2 (ii): a raw sweep-tick count conflates "waited 3 ticks" with "waited 3 minutes", which are wildly different things when `every` is 10m and the sweep interval is 1m).
type TriggerSweepResult ¶ added in v0.4.0
type TriggerSweepResult struct {
// Fired lists triggers this sweep actually dispatched (`every` had
// elapsed and no in-flight run blocked it).
Fired []TriggerFireResult
// Skipped lists triggers that were DUE (`every` had elapsed) but
// single-flight blocked them this tick (Opus review Blocker 2 (i)): a
// trigger that simply hasn't reached its next `every` yet is NOT a
// skip, even while a prior run of it is still in flight — counting that
// as a skip is what caused every-10m/execution-takes-5m triggers to
// rack up "3 consecutive skips" (and notify) on a completely healthy
// schedule, once the sweep interval (1m) is much shorter than `every`.
Skipped []TriggerSkip
// Completed lists trigger_runs rows this sweep's reconciliation pass
// newly marked finished (their job reached a terminal status).
Completed []TriggerCompletionResult
}
TriggerSweepResult is SweepTriggers' return shape. TriggerLoop.runOnce uses it for stuck/failure-streak bookkeeping (see TriggerLoop's own doc comment); tests use it to pin behavior without reaching into the DB.
type TxStore ¶
type TxStore interface {
TaskStore
ActionStore
CardStore
JobStore
// TaskIdentityStore is embedded so the drop side effect (I-6:
// TaskWorkflowService.ApplyAction's WithinTx switch) can release a
// dropped task's identity bindings atomically with the drop transition
// itself, the same way park/attrs_set/child_added/child_specced apply
// their own sidecar side effects inside the same transaction.
TaskIdentityStore
TaskUpdatedAtToucher
}
type UpdateJobRequest ¶ added in v0.0.4
type UpdateJobRequest struct {
DisplayName *string `json:"display_name"`
}
type UpdateTaskRequest ¶
type UpdateTaskRequest = apiwire.UpdateTaskRequest
type WSAttachHandler ¶
type WSAttachHandler struct {
Subscriber dispatcher.RuntimeSubscriber
Writer dispatcher.RuntimeInputWriter
PublicURL string
Registry *auth.ConnectionRegistry
// Bearer verifies an `Authorization: Bearer <token>` header carried on
// the WS handshake request (docs/plans/cli-remote-connection.md Phase 3
// PR0). When present, it is checked before auth.DeviceIDFromContext —
// see authenticateDevice's doc comment for the precedence rule. PR3
// moved this handler's mount point in internal/server/wire.go out of
// the cookie-only WebAuthMiddleware Group so a Bearer-only caller (the
// CLI's WS-based AttachJob, internal/client/client.go) can actually
// reach this route end-to-end over TCP; the field itself has existed
// since PR0.
Bearer *auth.BearerVerifier
// KeepalivePeriod overrides how often an idle connection is pinged.
// Zero means defaultWSKeepalivePeriod; tests set it short.
KeepalivePeriod time.Duration
}
WSAttachHandler handles WebSocket connections for interactive PTY attach. Route: GET /api/jobs/{id}/attach/ws
func (*WSAttachHandler) ServeHTTP ¶
func (h *WSAttachHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
type WebAppService ¶
type WebAppService struct {
Tasks TaskStore
Actions ActionStore
Jobs JobStore
GlobalJobs GlobalJobStore
Projects ProjectRepository
Meta MetaStore
Workflow WorkflowService
TaskSvc TaskService
Hooks HookService
Answerer TaskAnswerService // optional: enables POST /tasks/{id}/answer
}
func (*WebAppService) AnswerSuggestion ¶ added in v0.4.0
func (s *WebAppService) AnswerSuggestion(taskID string, req AnswerSuggestionRequest) error
AnswerSuggestion sends an "answered" action for taskID, recording nose's accept/reject of the currently-shown suggestion (J-6's "既に開いている穴" — see WebService.AnswerSuggestion's own doc comment for why this is a dedicated method rather than routing through the generic ApplyAction, mirroring ReopenTask's own instruction-payload pattern just above).
func (*WebAppService) AnswerTask ¶
func (s *WebAppService) AnswerTask(ctx context.Context, taskID, questionID, answer string) error
func (*WebAppService) ApplyAction ¶
func (s *WebAppService) ApplyAction(taskID string, actionType string) error
func (*WebAppService) CreateTask ¶
func (s *WebAppService) CreateTask(req CreateTaskRequest) (*orchestrator.Task, error)
func (*WebAppService) DeleteTask ¶
func (s *WebAppService) DeleteTask(id string, force bool) error
DeleteTask delegates to the shared TaskService so the web UI uses the same delete semantics as the JSON API and TUI.
func (*WebAppService) DuplicateTask ¶
func (s *WebAppService) DuplicateTask(id string) (string, error)
DuplicateTask delegates to the shared TaskService so the Web UI uses the same duplication semantics as the JSON API: a fresh task is created via CreateTask + resolveBehavior so that Instructions and Payload come from the behavior's DefaultInstruction / DefaultPayload, not from the source task's runtime state. Without this delegation the duplicate inherited the source's runtime payload (awaiting trait and harness session state) and missing Instructions caused the hook evaluator to skip the agent hook, so no hook fired on Start.
The Web UI button does not auto-start the duplicate; the user clicks Start separately.
func (*WebAppService) GetJob ¶
func (s *WebAppService) GetJob(id string) (*JobWithContext, error)
func (*WebAppService) GetProjectByID ¶
func (s *WebAppService) GetProjectByID(id string) (*orchestrator.Project, error)
func (*WebAppService) GetTaskDetail ¶
func (s *WebAppService) GetTaskDetail(id string) (*TaskDetailView, error)
func (*WebAppService) ListBehaviors ¶
func (s *WebAppService) ListBehaviors() ([]string, error)
func (*WebAppService) ListHooksForStatus ¶
func (s *WebAppService) ListHooksForStatus(taskID, status string) ([]orchestrator.Hook, error)
func (*WebAppService) ListJobs ¶
func (s *WebAppService) ListJobs(status string) ([]JobWithContext, error)
func (*WebAppService) ListProjects ¶
func (s *WebAppService) ListProjects() ([]*orchestrator.Project, error)
func (*WebAppService) ListSessions ¶ added in v0.0.2
func (s *WebAppService) ListSessions() ([]JobWithContext, error)
func (*WebAppService) ListTasks ¶
func (s *WebAppService) ListTasks(filter orchestrator.TaskFilter) ([]*orchestrator.Task, error)
func (*WebAppService) ListWorkspaces ¶
func (s *WebAppService) ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
func (*WebAppService) ReopenTask ¶
func (s *WebAppService) ReopenTask(id string, req ReopenTaskRequest) error
func (*WebAppService) ReplayHook ¶
func (s *WebAppService) ReplayHook(ctx context.Context, taskID string, req ReplayHookRequest) (*ReplayHookResult, error)
func (*WebAppService) RerunTask ¶
func (s *WebAppService) RerunTask(id string, req RerunTaskRequest) error
func (*WebAppService) UpdateTask ¶
func (s *WebAppService) UpdateTask(id string, req UpdateTaskRequest) error
type WebHandler ¶
type WebHandler struct {
Service WebService
Hub *TaskEventHub
SessionDispatcher SessionDispatcher
Registry *auth.ConnectionRegistry
// AttachmentsRoot is the data-home directory under which per-task
// attachments (`tasks/<id>/attachments`) are persisted. When empty (e.g.
// :memory: DB during tests) the multipart code path falls back to
// rejecting attachments while still accepting plain form-urlencoded
// submissions.
AttachmentsRoot string
// ConfigService backs GET /settings (web_settings.go,
// docs/plans/volume-only-daemon.md §論点 f) — nil in any test/wiring
// that never registers the /settings route.
ConfigService SettingsConfigService
// TaskTriage backs the list row's suggestion/summary enrichment
// (docs/plans/cross-project-issue-triage.md Phase 1 PR-3, restated by
// docs/plans/webui-detail-list-redesign.md PR-4 now that the list is one
// flat view instead of four tabs) — nil-safe: when unset, every row
// renders with no suggestion edge/summary badge instead of failing the
// whole list.
TaskTriage CardStore
}
func (*WebHandler) GetTaskEdit ¶
func (h *WebHandler) GetTaskEdit(w http.ResponseWriter, r *http.Request)
func (*WebHandler) HookReplayList ¶
func (h *WebHandler) HookReplayList(w http.ResponseWriter, r *http.Request)
func (*WebHandler) JobDetail ¶
func (h *WebHandler) JobDetail(w http.ResponseWriter, r *http.Request)
func (*WebHandler) JobTerminal ¶
func (h *WebHandler) JobTerminal(w http.ResponseWriter, r *http.Request)
JobTerminal redirects legacy deep-links (/jobs/{id}/terminal) to the job detail page (/jobs/{id}), which now renders the terminal inline.
func (*WebHandler) PostAction ¶
func (h *WebHandler) PostAction(w http.ResponseWriter, r *http.Request)
func (*WebHandler) PostAnswer ¶
func (h *WebHandler) PostAnswer(w http.ResponseWriter, r *http.Request)
func (*WebHandler) PostAnswerSuggestion ¶ added in v0.4.0
func (h *WebHandler) PostAnswerSuggestion(w http.ResponseWriter, r *http.Request)
PostAnswerSuggestion handles the task detail page's Accept/Reject buttons on a task_triage suggestion card (docs/plans/ingestion-identity.md PR-3, J-6). answer is required ("accept"/"reject" — validated downstream by answeredPayload); verb/basis are optional and forwarded verbatim (they come from hidden form fields populated from the suggestion currently shown — see TaskDetailSuggestionSection).
func (*WebHandler) PostDelete ¶
func (h *WebHandler) PostDelete(w http.ResponseWriter, r *http.Request)
PostDelete deletes the task and redirects to the task list. Errors are surfaced via ?error= on the same task page so the user sees the reason (e.g. dependents exist).
func (*WebHandler) PostDuplicate ¶
func (h *WebHandler) PostDuplicate(w http.ResponseWriter, r *http.Request)
func (*WebHandler) PostEdit ¶
func (h *WebHandler) PostEdit(w http.ResponseWriter, r *http.Request)
func (*WebHandler) PostHookReplay ¶
func (h *WebHandler) PostHookReplay(w http.ResponseWriter, r *http.Request)
func (*WebHandler) PostReopen ¶
func (h *WebHandler) PostReopen(w http.ResponseWriter, r *http.Request)
func (*WebHandler) PostRerun ¶
func (h *WebHandler) PostRerun(w http.ResponseWriter, r *http.Request)
func (*WebHandler) PostStartSession ¶ added in v0.0.6
func (h *WebHandler) PostStartSession(w http.ResponseWriter, r *http.Request)
PostStartSession launches a HarnessAdapter-backed session for the project from the Web UI's [New Session] dialog. Phase 3-d (PR1) introduced this alongside PostProjectExecuteCommand so users can start a claude / codex / opencode session without going through the legacy commands path.
func (*WebHandler) PostStartShapingSession ¶ added in v0.3.3
func (h *WebHandler) PostStartShapingSession(w http.ResponseWriter, r *http.Request)
PostStartShapingSession launches the "整形" (shaping) session for a triage card (docs/plans/cross-project-issue-triage.md UC-3, updated for card machine v2 — docs/plans/suggestion-as-state-transition-impl.md §3.5). Unlike PostStartSession (a blank session the operator configures by hand), this is a one-click launcher: the triage task's own project supplies the workspace context (a triage task always lives in the workspace's meta project — 決定5's "対象 project の確定は整形セッションの 仕事", not the caller's), and the card's id/title/description/kind/ urgency are folded into the bootstrap instruction so the agent has the card in hand at turn one instead of the operator re-typing it.
Reachable from a parked card OR a working card that has a task_triage sidecar row. v1 gated this on triaged (PR #987 review, BLOCKER 1: card machine v2 has no "triaged" status at all — captured/triaged folded into parked — so a triaged-only gate made Shape permanently unreachable from every card's own main resting state). working is included alongside parked (2026-08-14 follow-up, unchanged by v2) because a working triage task's children (task_triage.detail.children) keep needing shaping-session work after Go: an existing open child may need its spec defined (filing a Jira issue, deciding what work it covers), or a brand-new child may need to be added altogether — the set of children is not fixed at dispatch time. Gated on the triage row existing (not just status=working) because the overwhelming majority of working tasks are ordinary dev/impl tasks with no task_triage sidecar at all (triageChildrenFor's doc comment); the button is meaningless — there's no children list to add to or shape — without that sidecar. It is deliberately NOT gated on hasOpenChild (2026-08-14 second follow-up): requiring an open child already present would block the "add a brand-new child" use case, which needs a Shape session precisely because no child exists yet.
func (*WebHandler) PostTaskCreate ¶
func (h *WebHandler) PostTaskCreate(w http.ResponseWriter, r *http.Request)
func (*WebHandler) QuestionPage ¶
func (h *WebHandler) QuestionPage(w http.ResponseWriter, r *http.Request)
QuestionPage renders the dedicated Q&A turn page at `/tasks/{id}/questions/{question_id}`. The notification deep-link from `boid task notify --ask` lands here. The page shows the question and either an answer form (when this is the active awaiting turn) or the recorded answer (when an answer action exists for the same question_id).
func (*WebHandler) ReopenForm ¶
func (h *WebHandler) ReopenForm(w http.ResponseWriter, r *http.Request)
func (*WebHandler) Routes ¶
func (h *WebHandler) Routes() chi.Router
func (*WebHandler) SessionList ¶ added in v0.0.2
func (h *WebHandler) SessionList(w http.ResponseWriter, r *http.Request)
func (*WebHandler) SessionNew ¶ added in v0.0.2
func (h *WebHandler) SessionNew(w http.ResponseWriter, r *http.Request)
func (*WebHandler) Settings ¶ added in v0.1.0
func (h *WebHandler) Settings(w http.ResponseWriter, r *http.Request)
Settings handles GET /settings: fetches the daemon's current config.yaml (the same document `boid config get` prints), derives the form-editor fields from it, and renders both the form and raw-YAML tabs from that one snapshot.
func (*WebHandler) TaskDetail ¶
func (h *WebHandler) TaskDetail(w http.ResponseWriter, r *http.Request)
func (*WebHandler) TaskDetailFragment ¶
func (h *WebHandler) TaskDetailFragment(w http.ResponseWriter, r *http.Request)
TaskDetailFragment returns a partial HTML fragment for the task detail page. The `kind` query parameter selects which section to render:
- "timeline": action history section (shared by both entity layouts)
- "status": the meta strip — card or execution variant, by task.Type
"jobs" used to be a third kind (TaskDetailJobsSection); removed (docs/plans/webui-detail-list-redesign.md §7 PR-1 死骸掃除) along with TaskDetailJobsSection itself — nothing on the task detail page ever rendered it (the `jobs` parameter flowed TaskDetail → TabsSection → TabPanel and was never read there either).
func (*WebHandler) TaskEvents ¶
func (h *WebHandler) TaskEvents(w http.ResponseWriter, r *http.Request)
TaskEvents streams Server-Sent Events for a specific task. Subscribes to the TaskEventHub and forwards events until the client disconnects or the device is revoked.
func (*WebHandler) TaskList ¶
func (h *WebHandler) TaskList(w http.ResponseWriter, r *http.Request)
func (*WebHandler) TaskNew ¶
func (h *WebHandler) TaskNew(w http.ResponseWriter, r *http.Request)
type WebManagementHandler ¶
type WebManagementHandler struct {
Pairing Pairer
Store *auth.Store
PublicURL string
Registry *auth.ConnectionRegistry
}
func (*WebManagementHandler) DeleteAllDevices ¶
func (h *WebManagementHandler) DeleteAllDevices(w http.ResponseWriter, r *http.Request)
func (*WebManagementHandler) DeleteDevice ¶
func (h *WebManagementHandler) DeleteDevice(w http.ResponseWriter, r *http.Request)
func (*WebManagementHandler) GetDevices ¶
func (h *WebManagementHandler) GetDevices(w http.ResponseWriter, r *http.Request)
func (*WebManagementHandler) PostPair ¶
func (h *WebManagementHandler) PostPair(w http.ResponseWriter, r *http.Request)
func (*WebManagementHandler) Routes ¶
func (h *WebManagementHandler) Routes() chi.Router
type WebService ¶
type WebService interface {
ListTasks(filter orchestrator.TaskFilter) ([]*orchestrator.Task, error)
GetTaskDetail(id string) (*TaskDetailView, error)
ListProjects() ([]*orchestrator.Project, error)
ListBehaviors() ([]string, error)
ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
ApplyAction(taskID string, actionType string) error
DuplicateTask(id string) (string, error)
DeleteTask(id string, force bool) error
ListJobs(status string) ([]JobWithContext, error)
ListSessions() ([]JobWithContext, error)
GetJob(id string) (*JobWithContext, error)
CreateTask(req CreateTaskRequest) (*orchestrator.Task, error)
UpdateTask(id string, req UpdateTaskRequest) error
RerunTask(id string, req RerunTaskRequest) error
ReopenTask(id string, req ReopenTaskRequest) error
AnswerTask(ctx context.Context, taskID, questionID, answer string) error
// AnswerSuggestion backs docs/plans/ingestion-identity.md PR-3 (B-3+B-4,
// J-6)'s accept/reject buttons on the task_triage suggestion card — the
// "既に開いている穴" this PR closes (決定14 moved judgment to the Web UI,
// but the Web UI had no path to RECORD a reject, so re-suggestion was
// never suppressed). A dedicated method rather than routing through
// ApplyAction (like ReopenTask above): the generic
// WebService.ApplyAction(taskID, actionType) signature has no payload
// parameter, and `answered` needs one ({answer, verb, basis}).
AnswerSuggestion(taskID string, req AnswerSuggestionRequest) error
ListHooksForStatus(taskID, status string) ([]orchestrator.Hook, error)
ReplayHook(ctx context.Context, taskID string, req ReplayHookRequest) (*ReplayHookResult, error)
GetProjectByID(id string) (*orchestrator.Project, error)
}
type WorkflowService ¶
type WorkflowService interface {
ApplyAction(ctx context.Context, taskID string, req ApplyActionRequest) (*ActionApplication, error)
// GetCard / ListCards are the task_triage read surface (card_read.go,
// Phase 1 PR-5a). Part of WorkflowService because the brokered ops that
// expose them to the sandbox reach the daemon through this same interface.
GetCard(taskID string) (*CardView, error)
ListCards(filter orchestrator.TaskFilter) ([]*CardView, error)
CompleteJob(ctx context.Context, jobID string, req JobDoneRequest) (*Job, error)
// StopAgent asks the agent backing runtimeID to terminate gracefully,
// without tearing down the surrounding runner-inner-child. The broker's
// `boid job done` call still fires normally, preserving any payload
// patch the agent wrote up to that point. NotifyTask calls this after
// `ApplyAction("ask")` so the awaiting transition does not race with
// payload_patch capture. No-op when runtimeID is empty.
StopAgent(runtimeID string)
}
type WorkspaceDetail ¶ added in v0.0.13
type WorkspaceDetail = apiwire.WorkspaceDetail
type WorkspaceHandler ¶
type WorkspaceHandler struct {
Service ProjectService
// Homes, when non-nil, is the engine-backed view of workspace HOME
// volumes (docs/plans/workspace-home-volume-persistence.md 論点 a-2, PR7)
// used for Show's size reporting and Remove's home deletion. Left nil,
// both features degrade gracefully: Show omits WorkspaceDetail.Home,
// Remove reports home_deleted=false with no attempt made — the same
// degradation an empty RuntimesDir used to produce, now keyed on the
// feature's only actual dependency. See WorkspaceHomeStore's doc comment.
Homes WorkspaceHomeStore
// HomeImporter, when non-nil, serves POST /api/workspaces/{slug}/home/import
// — PR8's migration of a pre-PR6 host home directory into the workspace's
// HOME volume (docs/plans/workspace-home-volume-persistence.md 論点 f).
// Left nil the route answers 501, the same "the daemon has no runner to do
// this" degradation a nil Homes produces for the size/delete surface.
HomeImporter WorkspaceHomeImporter
}
func (*WorkspaceHandler) Apply ¶ added in v0.1.0
func (h *WorkspaceHandler) Apply(w http.ResponseWriter, r *http.Request)
Apply handles POST /api/workspaces/apply?dry_run=<bool> (docs/plans/ volume-only-daemon.md PR-1d codex round-1 Blocker 2/Major 1): the body is exactly one apiVersion:boid.dev/v1 kind:Workspace yaml document (a multi-document body — more than one "---"-separated document — is rejected; `boid workspace apply` sends one request per document, which is exactly what gives each document its own all-or-nothing DB transaction rather than sharing one across an entire multi-workspace file). dry_run=true runs every read/write the real apply would (same validation, same DB statements) but rolls back instead of committing.
?dry_run is parsed with strconv.ParseBool (PR-1d codex round-2 Major: the previous `== "true"` check failed OPEN — "True", "1", or a typo silently fell through to a real commit instead of the requested preview). An unparseable value is now rejected with 400 rather than defaulting to mutation, and which mode ran is always logged at INFO so a caller can confirm from the server log which path a given request actually took.
Presence, not non-emptiness, gates parsing (PR-1d codex round-3 Major): the round-2 fix still checked `raw != ""`, so `?dry_run=` (empty value) or `?dry_run` (no `=` at all — reachable via `?dry_run=${DRY_RUN}` with an unset shell variable) produced raw=="" and fell through as if the parameter were absent entirely, silently performing a real commit for a caller who explicitly asked for dry_run. url.Values.Has reports whether the key was present in the query string at all, independent of its value, so an explicitly-empty dry_run now reaches strconv.ParseBool("") — which fails — and is rejected with 400, same as any other unparseable value.
The query string is parsed explicitly with url.ParseQuery rather than the convenience r.URL.Query() (PR-1d codex round-4 Minor): (1) Query() returns only the FIRST value for a repeated key, so `?dry_run=false&dry_run=true` silently used "false" and performed a real commit even though the request also said "true" elsewhere — ambiguous/contradictory input, now rejected with 400 rather than picking one arbitrarily; (2) Query() also silently discards the underlying ParseQuery error (e.g. an unescaped ';' separator, rejected by net/url since Go 1.17), which can make a key disappear from the parsed result entirely rather than surface the malformed request — a malformed query string is now itself a 400 instead of silently degrading to "no dry_run param at all" (a real commit).
func (*WorkspaceHandler) Create ¶ added in v0.0.13
func (h *WorkspaceHandler) Create(w http.ResponseWriter, r *http.Request)
Create handles POST /api/workspaces (docs/plans/workspace-db-consolidation.md PR4 Step C). The body is a yaml document with the target slug inlined (`slug: foo`) alongside the workspace meta fields — there is no URL parameter for the new slug, since the daemon does not yet know it.
func (*WorkspaceHandler) ExportEnvelope ¶ added in v0.1.0
func (h *WorkspaceHandler) ExportEnvelope(w http.ResponseWriter, r *http.Request)
ExportEnvelope handles GET /api/workspaces/export?all=true or ?name=<slug> (docs/plans/volume-only-daemon.md PR-1d codex round-1 Blocker 3): returns one or more apiVersion:boid.dev/v1 kind:Workspace yaml documents built from a single atomic DB snapshot (ProjectAppService.ExportWorkspaceEnvelopes / orchestrator. SnapshotWorkspacesForExport), "---"-separated when more than one.
func (*WorkspaceHandler) GetInitScript ¶ added in v0.1.0
func (h *WorkspaceHandler) GetInitScript(w http.ResponseWriter, r *http.Request)
GetInitScript handles GET /api/workspaces/{slug}/init-script: the workspace's init.sh verbatim, with an ETag.
A workspace with no init.sh answers 404 — and still sets the ETag, to the absent sentinel. See WorkspaceInitScriptAbsentRevision for why the sentinel exists, and TestWorkspaceHandler_GetInitScript_AbsentIs404WithTheAbsentETag for why absence cannot be a 200 with an empty body.
func (*WorkspaceHandler) ImportHome ¶ added in v0.1.0
func (h *WorkspaceHandler) ImportHome(w http.ResponseWriter, r *http.Request)
ImportHome handles POST /api/workspaces/{slug}/home/import: replace slug's HOME volume with the tar stream on the request body.
Order of the checks is the contract, not a style choice. Everything that can refuse WITHOUT side effects happens first — media type, workspace row, importer wired — because the first thing the daemon does once past them is destroy the existing home volume.
func (*WorkspaceHandler) List ¶
func (h *WorkspaceHandler) List(w http.ResponseWriter, r *http.Request)
func (*WorkspaceHandler) PutInitScript ¶ added in v0.1.0
func (h *WorkspaceHandler) PutInitScript(w http.ResponseWriter, r *http.Request)
PutInitScript handles PUT /api/workspaces/{slug}/init-script[?force=true]: replace the workspace's init.sh with the request body, gated by If-Match unless force is set — the same convention PUT /api/workspaces/{slug} and POST /api/config already established (428 when If-Match is missing, 412 when it is stale).
An EMPTY body clears the script rather than storing zero bytes; see workspaceInitScriptContentIsAbsent.
func (*WorkspaceHandler) Remove ¶ added in v0.0.13
func (h *WorkspaceHandler) Remove(w http.ResponseWriter, r *http.Request)
Remove handles DELETE /api/workspaces/{slug} (Step F). The reserved default slug and re-assignment of any still-assigned project are enforced at the service/repository layer (ProjectAppService.RemoveWorkspace → orchestrator.WorkspaceRepository.Remove's transaction).
docs/plans/home-workspace-volume.md Phase 4 PR5 adds home deletion on top of the pre-existing row removal: the workspace row is always removed first (via h.Service.RemoveWorkspace), and only then does this attempt to delete slug's home — trusted-side deletion, since a sandboxed job or a remote CLI client has no way to reach the daemon's docker socket itself (and, since PR1 of docs/plans/workspace-home-volume-persistence.md, is denied the boid-ws- volume namespace outright even when it has one). A home-deletion failure — most plausibly the engine's 409 for a volume a running job still holds, see WorkspaceRemoveResponse.HomeDeleteError — is reported in the response but does not turn this into an error response: the row is already gone, and the plan doc explicitly allows this "part-completed" outcome (see WorkspaceRemoveResponse's doc comment) rather than trying to make the two deletions atomic.
What that tolerance does NOT extend to is interleaving with `boid workspace import-home` (PR8 round-2 codex review, Major 1): a part-completed remove leaves a volume an operator can delete by hand, while an overlapping migration leaves a volume full of credentials that no dispatch can mount and this very endpoint can no longer target. Both deletions therefore run inside the exclusion taken below.
A workspace has a THIRD piece — its init.sh — and that one is deleted by RemoveWorkspace itself, not here (PR9 codex round 3, Major 3). Not left behind: dispatch resolves a script from the SLUG alone, so the next workspace created with the same name would inherit the removed one's script and run it against a brand-new, empty HOME volume, with no way to clean it up first (every /{slug}/init-script route 404s once the row is gone). Not deleted from here either, because a second service call means a second critical section, and an apply landing between the two upserted the slug, wrote a script, answered 200 — and had that script deleted by the removal still finishing. The service does both under one hold of its mutex; this function only reports the outcome.
func (*WorkspaceHandler) Routes ¶
func (h *WorkspaceHandler) Routes() chi.Router
func (*WorkspaceHandler) Show ¶ added in v0.0.13
func (h *WorkspaceHandler) Show(w http.ResponseWriter, r *http.Request)
Show handles GET /api/workspaces/{slug} (Step D): meta + summary (revision, assigned project ids), with an ETag response header mirroring the revision so a client can round-trip it straight into a subsequent PUT's If-Match.
func (*WorkspaceHandler) Update ¶ added in v0.0.13
func (h *WorkspaceHandler) Update(w http.ResponseWriter, r *http.Request)
Update handles PUT /api/workspaces/{slug} (Step E): whole-document replace, gated by If-Match unless ?force=true is passed (decision 17 — PUT + If-Match, no PATCH). See ProjectAppService.UpdateWorkspace for the exact status code contract (428 missing If-Match, 412 stale If-Match).
type WorkspaceHomeImportResponse ¶ added in v0.1.0
type WorkspaceHomeImportResponse struct {
Status string `json:"status"`
// Slug is the NORMALIZED workspace slug the daemon migrated — not
// necessarily the one in the URL, since an empty workspace id normalizes to
// the default workspace.
Slug string `json:"slug"`
// Volume is the home volume that now holds the imported contents,
// dockerres.WorkspaceHomeVolumeName(installID, slug) — the same name
// `boid workspace show` reports and `docker volume rm` takes.
Volume string `json:"volume"`
// HomeID is the identity the NEW incarnation of that volume carries. It
// differs from whatever the replaced one had; that difference is what makes
// the completion marker stale and forces the re-init (論点 f leg 1).
HomeID string `json:"home_id,omitempty"`
// PreviousExisted reports whether there was a home volume to replace.
// false means the workspace had never been dispatched into — the
// init-on-first-dispatch contract, not an error.
PreviousExisted bool `json:"previous_existed"`
// MarkerRemoved / MarkerRemoveError report 論点 f leg 2, the deletion of
// <dataHome>/homes-meta/<slug>.init.json. A failure is not fatal (leg 1
// already re-armed the init) and is reported anyway.
MarkerRemoved bool `json:"marker_removed"`
MarkerRemoveError string `json:"marker_remove_error,omitempty"`
// MigrationRecordRemoveError is non-empty when the migration succeeded but
// the daemon could not delete the in-progress record it wrote before
// starting (dispatcher's workspace_home_migration_sentinel.go).
//
// On the wire rather than only in the daemon log because the operator at the
// terminal is the one who can act on it, and the daemon log is not where
// somebody reading a CLI command's output looks. What it COSTS depends on the
// field below.
MigrationRecordRemoveError string `json:"migration_record_remove_error,omitempty"`
// MigrationRecordDiscardsHome says whether that leftover record still
// authorizes the next daemon start to DESTROY this home (codex round 4,
// Blocker 1). Meaningful only alongside MigrationRecordRemoveError.
//
// false is the ordinary case and needs no action: the record was moved into
// its "the home was rebuilt" phase before the deletion failed, so recovery
// only deletes the file. true means it was not, and the consequence lands
// later and looks unrelated when it does — the next daemon start discards
// this workspace's freshly imported home and re-initializes it. The error
// names the file, so deleting it before restarting saves re-doing a multi-GB
// import.
//
// A separate field rather than something the CLI infers, because the CLI has
// no way to tell the two apart: both arrive as "the record could not be
// removed", and only the daemon knows how far it got before that.
MigrationRecordDiscardsHome bool `json:"migration_record_discards_home,omitempty"`
}
WorkspaceHomeImportResponse is the response body for a completed migration.
PreviousExisted and MarkerRemoved are both on the wire rather than folded into a single "ok", because they are 論点 f's two independent re-init legs and the CLI says something different when only one of them fired: with the marker still in place the re-init rests entirely on the new volume identity, which is true but worth telling an operator about.
type WorkspaceHomeImporter ¶ added in v0.1.0
type WorkspaceHomeImporter interface {
ImportWorkspaceHome(ctx context.Context, slug string, tarStream io.Reader) (dispatcher.WorkspaceHomeImportResult, error)
// BeginWorkspaceHomeRemoval excludes a migration of slug's HOME volume until
// the returned function is called. WorkspaceHandler.Remove brackets BOTH of
// its deletions (the row, then the volume) with it.
//
// The only error it returns wraps dispatcher.ErrWorkspaceHomeBusy, so there
// is exactly one thing to map (409) and the refusal always means "a migration
// of this workspace is running; nothing has been changed".
BeginWorkspaceHomeRemoval(slug string) (done func(), err error)
}
WorkspaceHomeImporter is the daemon-side capability POST /api/workspaces/{slug}/home/import needs. *dispatcher.Runner is the only implementation.
Declared here, on the consumer side, and typed in terms of dispatcher.WorkspaceHomeImportResult — a plain struct — for the same reason WorkspaceHomeStore is: this package imports internal/dispatcher and must not grow moby types (論点 a-2, D2), and a test needs to be able to stub it without an engine.
A nil value is the feature's OFF switch, exactly as a nil WorkspaceHandler.Homes is: server/wire.go leaves it nil when there is no runner to serve it, and the handler answers 501 rather than panicking.
Why the removal guard is on THIS interface (codex round 2, Major 1) ¶
BeginWorkspaceHomeRemoval has nothing to do with importing, and it is here rather than on a field of its own for one reason: the exclusion only works if the object that registers a removal is the SAME object that registers a migration. Two fields could be wired to two different Runners — each with its own in-memory registry — and the result would exclude nothing while looking exactly like this. One interface, one field, one instance, and the compiler enforces it.
type WorkspaceHomeSize ¶ added in v0.0.13
type WorkspaceHomeSize = apiwire.WorkspaceHomeSize
from internal/api/workspace_homes.go
func ListWorkspaceHomeSizes ¶ added in v0.0.13
func ListWorkspaceHomeSizes(ctx context.Context, store WorkspaceHomeStore, lister WorkspaceSlugLister) (homes []WorkspaceHomeSize, listErr string, err error)
ListWorkspaceHomeSizes enumerates every workspace HOME volume belonging to this install and reports each one's size, flagging the ones with no corresponding workspace row as orphans (docs/plans/home-workspace-volume.md PR5: "workspace.yaml が消えて home だけ残った孤児はレポートのみ").
Orphan detection depends on a successful WorkspaceSlugLister call. A lister failure means orphan status is simply unknowable for every entry — rather than marking every entry Orphan=true (this function's pre-#791-review behavior, which silently misreported every real workspace's home as an "orphan" on a merely transient DB hiccup), a lister failure now omits the listing outright: homes comes back an empty (non-nil) slice, and listErr carries the lister's error message so a caller can render "size listing unavailable: <reason>" instead of trusting bogus per-entry orphan flags. This preserves the invariant "every WorkspaceHomeSize actually returned has a trustworthy Orphan flag" (codex PR #791 review, Should-fix #3, selection A).
err (the third return) is reserved for a genuine enumeration failure — the engine's volume listing failing. Unlike listErr, a non-nil err means the whole call failed, not just orphan detection; GC's own record-deletion work does not depend on workspace-home reporting succeeding, so callers should still treat a non-nil err as non-fatal to the rest of their own response.
A sizing failure is neither of those: the store still returns the listing, with SizeError set per entry, because the listing is what drives orphan detection and losing it over a busy disk-usage call would be a much worse trade than an entry rendering "?".
type WorkspaceHomeStore ¶ added in v0.1.0
type WorkspaceHomeStore interface {
Get(ctx context.Context, slug string) dispatcher.WorkspaceHomeVolume
List(ctx context.Context) ([]dispatcher.WorkspaceHomeVolume, error)
Remove(ctx context.Context, slug string) (dispatcher.WorkspaceHomeVolume, bool, error)
}
WorkspaceHomeStore is the engine-backed view of workspace HOME volumes. *dispatcher.WorkspaceHomeVolumeStore is the only implementation; server/wire.go builds one from the single docker client buildRuntime already has and hands it to WorkspaceHandler.Homes / GCHandler.Homes.
Declared here, on the consumer side, so this package can be tested with a map-backed stub — and typed in terms of dispatcher.WorkspaceHomeVolume rather than moby's volume.Volume so no moby type reaches internal/api (論点 a-2, D2). internal/api already imports internal/dispatcher; the reverse edge does not exist and must not be created, which is why the data type lives on the dispatcher side.
A nil WorkspaceHomeStore is the feature's OFF switch, and is what the handlers gate on now that RuntimesDir no longer participates (論点 a-2, D5): server/wire.go leaves the field nil exactly when it has no docker client (Config.Backend injected — the test/DI path), and both handlers then omit home information entirely, unchanged from what an empty RuntimesDir used to do. The engine handle is the feature's only remaining dependency, so it is the honest condition; a nil interface is also the only form of "off" that cannot be faked by a typed-nil *client.Client, which is why wire.go assigns the field rather than always constructing a store.
type WorkspaceInitScript ¶ added in v0.1.0
type WorkspaceInitScript struct {
Slug string
// Exists is false for a workspace in the pass-through class (no init.sh).
// Content is then empty and Revision is WorkspaceInitScriptAbsentRevision.
Exists bool
Content []byte
// Revision is the ETag: a content hash, or the absent sentinel.
Revision string
// Path is where the DAEMON keeps it.
Path string
}
WorkspaceInitScript is one workspace's init.sh as the API sees it.
type WorkspaceInitScriptResult ¶ added in v0.1.0
type WorkspaceInitScriptResult = apiwire.WorkspaceInitScriptResult
type WorkspaceInitScriptStore ¶ added in v0.1.0
type WorkspaceInitScriptStore interface {
// Path returns the absolute path of slug's init.sh ON THE DAEMON. It is
// reported to the operator, whose editor may well be on a different
// machine; see the CLI's output for how it is labelled.
Path(slug string) (string, error)
// Read returns slug's init.sh, with exists=false and no error when the
// workspace has none.
Read(slug string) (data []byte, exists bool, err error)
// Write publishes data as slug's init.sh, atomically.
Write(slug string, data []byte) error
// Remove deletes slug's init.sh, reporting whether there was one.
Remove(slug string) (removed bool, err error)
}
WorkspaceInitScriptStore is the daemon-side capability the init-script surface needs: read, write and remove a workspace's init.sh at the path the DISPATCHER reads it from.
Declared here, on the consumer side, and implemented by dispatcher.WorkspaceInitScriptStore — the same split WorkspaceHomeStore/WorkspaceHomeImporter use (論点 a-2, D2): the mechanism (where the file is, how it is published) lives with the code that reads it, the policy (If-Match, the cap, the NUL refusal, empty-means-absent) lives here with the workspace rows.
A nil value turns the feature off — the route answers 501 and `apply` warns rather than silently dropping a spec.init_script — for the DI/test daemons that have no dispatcher wiring.
type WorkspaceRemoval ¶ added in v0.1.0
type WorkspaceRemoval struct {
// InitScriptDeleted is true only when the workspace HAD an init.sh and it
// was removed. false covers a workspace that never had one, a daemon with
// no init script store wired, and a failed deletion.
InitScriptDeleted bool
// InitScriptError is the unlink failure, if any. Deliberately NOT a
// *StatusError: the row removal has already committed, so this must not
// become the response's status — see
// WorkspaceRemoveResponse.InitScriptDeleteError. The message carries the
// daemon-side path, which is what an operator needs to clean up by hand.
InitScriptError error
}
WorkspaceRemoval reports what RemoveWorkspace did to the half of a workspace that is not a row (PR9 codex round 2 Major 1, moved inside the row's critical section by round 3 Major 3).
It exists because a file unlink and a database transaction cannot commit together: by the time the script is touched the row is already gone, so a failure has to be described rather than rolled back or raised. The handler copies both fields into WorkspaceRemoveResponse, which is where their operator-facing meaning is documented.
type WorkspaceRemoveResponse ¶ added in v0.0.13
type WorkspaceRemoveResponse = apiwire.WorkspaceRemoveResponse
type WorkspaceSlugLister ¶ added in v0.0.13
type WorkspaceSlugLister interface {
ListWorkspaces() ([]*orchestrator.WorkspaceSummary, error)
}
WorkspaceSlugLister exposes the set of currently known workspace slugs, used to flag orphaned home volumes (a workspace HOME volume with no corresponding workspace row). *ProjectAppService already satisfies this via its existing ListWorkspaces method — no new implementation is needed, only threading it through as this narrower interface at the handler construction site (server/wire.go) so GCHandler does not need the whole ProjectService surface.
type WorkspaceStore ¶ added in v0.0.13
type WorkspaceStore interface {
Load(slug string) (*orchestrator.WorkspaceMeta, error)
Save(slug string, meta *orchestrator.WorkspaceMeta) error
// Create is insert-only: an error wrapping os.ErrExist when slug already
// has a row (see orchestrator.WorkspaceRepository.Create).
Create(slug string, meta *orchestrator.WorkspaceMeta) error
Remove(slug string) error
// LoadWithRevision returns meta and its revision from a single atomic
// snapshot (docs/plans/workspace-db-consolidation.md MAJOR 1, codex
// review), used by GET /api/workspaces/{slug} so meta and revision can
// never straddle a concurrent write. See
// orchestrator.WorkspaceRepository.LoadWithRevision's doc comment.
LoadWithRevision(slug string) (*orchestrator.WorkspaceMeta, string, error)
// UpdateIfRevisionMatches performs a compare-and-swap update: meta is
// written only if slug's current revision equals expectedRevision,
// atomically with the check. matched=false covers both "no such slug"
// and "revision mismatch" — see
// orchestrator.WorkspaceRepository.UpdateIfRevisionMatches's doc comment.
UpdateIfRevisionMatches(slug string, expectedRevision string, meta *orchestrator.WorkspaceMeta) (newRevision string, matched bool, err error)
}
WorkspaceStore provides direct CRUD over a single workspace's WorkspaceMeta, independent of the project-assignment bookkeeping that lives on ProjectRepository below (docs/plans/workspace-db-consolidation.md PR4). Implemented by *orchestrator.WorkspaceStore (via ProjectStore.WorkspaceStore()), wired in internal/server/wire.go.
Source Files
¶
- action.go
- action_list_read.go
- apiwire_aliases.go
- attachment_read_linux.go
- attachments.go
- attrs_set_done.go
- blocking_ask_registry.go
- broker.go
- card_handler.go
- card_read.go
- config.go
- device_auth.go
- events_handler.go
- gc.go
- helpers.go
- host_commands.go
- job.go
- job_log_sse.go
- job_model.go
- machine_select.go
- oauth_login.go
- payload_patch_lock.go
- project.go
- project_no_yaml.go
- project_service.go
- project_service_init_script.go
- queue_notify.go
- queue_sweep.go
- secret.go
- service.go
- session.go
- signal_handler.go
- store.go
- suggestion_accept.go
- task.go
- task_ask.go
- task_context.go
- task_create.go
- task_event_hub.go
- task_field.go
- task_identity.go
- task_notify.go
- task_resolve_or_capture.go
- task_service.go
- task_wait.go
- task_wait_registry.go
- trigger_loop.go
- web.go
- web_service.go
- web_settings.go
- workflow.go
- workflow_action.go
- workflow_card.go
- workflow_job.go
- workflow_replay.go
- workspace.go
- workspace_home_import.go
- workspace_homes.go
- workspace_init_script.go
- ws_attach.go