@hearsay-tools/squawk 0.18.0-dev.8318 → 0.18.0-dev.8324

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,158 +1,51 @@
1
- import { memoizeRead } from './bounded-read-cache.js';
2
- import { cachedWorktreeSizeBytes } from './worktree-size-cache.js';
3
- import { readRepoRefs, forgetRepoRead } from './repo-read-cache.js';
4
- import { runnerSkillsQuerySchema } from '../contract/index.js';
5
- import { readRunnerSkills } from './runner-skills.js';
6
- import { runCheckout, preparePublishCheckout, reclaimCheckoutError } from './run-checkout.js';
7
- import { adoptFallbackControl, protectFallbackRun, runArtifactDirectory } from './project-run-files.js';
8
- import { deleteSavedWorkflow } from './workflow-files.js';
9
- import { projectPaths, fallbackProjectWriteError } from '../project-paths.js';
10
- import { productIdentity } from '../home/identity.js';
11
- import { productEnv } from '../core/product-env.js';
1
+ import { projectPaths } from '../project-paths.js';
12
2
  import { reportsRoutes } from './reports-api.js';
13
- import { writeMergedConfig } from './config-merge.js';
14
- import { applyWorkspaceConfigPatch } from './workspace-config-patch.js';
15
- import { retryAutomationLogReceipt } from './automation-log-retry.js';
16
- import { automationCreateSchema, automationUpdateSchema, automationCheckRequestSchema, automationLogQuerySchema } from '../contract/index.js';
17
- import { planSchema, parseWorkflowSchema } from '../contract/index.js';
18
- import { uiStateBody } from '../contract/index.js';
19
- import { queuedMessagePatchSchema, continueSchema, archiveSchema, openInSchema } from '../contract/index.js';
20
- import { refreshQuery, browseQuerySchema, worktreeFilesQuerySchema } from '../contract/index.js';
21
- import { mergeNumberParams, prChangesParams, prChangesQuery, mergeBodySchema } from '../contract/index.js';
22
- import { gitCommitSchema, reclaimBodySchema, repoBranchSchema } from '../contract/index.js';
23
- import { setConfigSchema, setAgentConfigSchema } from '../contract/index.js';
24
- import { saveWorkflowInputSchema as saveWorkflowSchema } from '../contract/index.js';
25
- import { patchRunInputSchema as patchRunSchema, messageInputSchema as messageSchema } from '../contract/index.js';
26
- import { setWorkspaceConfigInputSchema as workspaceConfigUpdateSchema } from '../contract/index.js';
27
- import { reclaimRunParamsSchema } from '../contract/index.js';
28
- import { githubChecksQuerySchema } from '../contract/index.js';
29
- import { githubRefsQuerySchema } from '../contract/index.js';
30
- import { commitQuerySchema } from '../contract/index.js';
31
- import { imageMimeType } from '../contract/index.js';
32
- import { providerForActiveRun } from '../contract/index.js';
33
- import { removedRunnerMessage } from '../contract/index.js';
34
- import { isAbsoluteHostPath } from '../core/host-path.js';
35
- import { resolveArchiveOnMerge, resolveGlobalArchiveOnMerge } from '../archive-on-merge-setting.js';
36
- import { permissionDecisionSchema } from '../contract/index.js';
37
- import { runIdParamSchema as permissionRunIdParamSchema } from '../contract/index.js';
38
3
  import { CheckoutProgressCache } from './checkout-progress.js';
39
4
  import { createWorkspaceLiveRoutes } from './workspace-live-routes.js';
40
5
  import { createActivityRoutes } from './activity-routes.js';
41
6
  import { createRunnersRoutes } from './runners-routes.js';
42
7
  import { createWorkspaceProjects, createWorkspaceProjectContexts, createTaskWebhooks } from './workspace-projects.js';
43
- import { subscribeRunFeed } from './run-event-feed.js';
44
- import { latestSession } from '../contract/index.js';
45
- import { probeWritableDir } from './probe-writable-dir.js';
46
- import { ARCHIVED_RUNS_PAGE_DEFAULT } from '../contract/index.js';
47
- import { RUNS_SEARCH_PER_PROJECT_MAX, archivedRunsQuerySchema, createRunInputSchema, runSummariesQuerySchema, runsSearchQuerySchema } from '../contract/index.js';
48
- import { workspaceEventsQuerySchema } from '../contract/index.js';
49
- import { automationListQuerySchema } from '../contract/index.js';
50
- import { localTimeZone } from '../contract/index.js';
51
- import { DelegationService } from '../delegation/service.js';
52
- import { runRelationships } from './run-relationships.js';
53
- import { delegationFailure } from '../delegation/routes.js';
54
- import { githubItemParamsSchema } from '../contract/index.js';
55
- import { workerDestroyRequestSchema, workerEmptyRequestSchema, runRelationshipsSchema } from '../contract/index.js';
56
- import { existsSync } from 'node:fs';
57
8
  import { randomUUID } from 'node:crypto';
58
- import { createAutomationService, onceCreateAnswer } from '../automations/service.js';
59
- import { createAutomationToolService } from '../automations/tool-adapter.js';
60
- import { GithubPoller } from '../automations/github-poller.js';
61
- import { githubRepository } from '../automations/github-repository.js';
62
- import { ProjectAutomationScheduler } from '../automations/scheduler.js';
63
- import { launchAutomationRun, launchScheduledRun, reconcileAutomationReceipts } from '../automations/task-template.js';
64
- import { isGithubAutomation, } from '../automations/types.js';
65
- import { mkdir, readFile, stat, writeFile } from 'node:fs/promises';
66
9
  import { basename, dirname, join } from 'node:path';
67
10
  import { fileURLToPath } from 'node:url';
68
11
  import { Hono } from 'hono';
69
12
  import { bodyLimit } from 'hono/body-limit';
70
13
  import { matchedRoutes } from 'hono/route';
71
- import { jsonZodValidator, paramZodValidator, queryZodValidator } from './validators.js';
72
- import { registryEntry, sendAgentReport } from '../runs/webhook.js';
73
- import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
74
- import { z } from 'zod';
75
- import { repoPullInputSchema, deleteBranchesInputSchema } from '../contract/index.js';
76
- import { pinRunInputSchema, archiveFinishedRequestSchema, markAllReadRequestSchema, notifyRunInputSchema, } from '../contract/index.js';
77
- import { githubSearchQuerySchema, githubProjectsQuerySchema, githubListQuerySchema, githubCommentCountsQuerySchema, } from '../contract/index.js';
78
- import { setWorkspaceUiStateInputSchema } from '../contract/index.js';
79
14
  // A contract VALUE, like `workspaceUiStateSchema` in workspace/migrations.ts — the request
80
15
  // schema this route validates with is the same one the client compiles against.
81
- import { openProjectInSchema } from '../contract/index.js';
82
- import { registeredRunnerId, registeredRunners, resolveRunnerId, runnerDefinition } from '../core/runner-registry.js';
83
- import { REMOVED_RUNNER_IDS } from '../runs/legacy-run-rows.js';
84
- import { attachmentFileParamSchema, } from '../contract/index.js';
85
- import { agentWebhookParamsSchema, sendAgentReportInputSchema } from '../contract/index.js';
86
- import { agentWebhook, agentWebhooks, taskWebhooks as taskWebhookList } from '../workspace/webhooks.js';
16
+ import { registeredRunners } from '../core/runner-registry.js';
87
17
  import { environmentStamp } from '../core/backend-detect.js';
88
- import { AGENT_MODELS_LOCKED_ERROR, agentModelsLocked } from '../core/agent-model-policy.js';
89
18
  import { createModelsRoutes } from './models-routes.js';
90
19
  import { createProviderSignInRoutes } from './provider-sign-in-routes.js';
91
- import { allUsage, currentUsage, onUsage } from '../core/process-usage.js';
92
- import { loadWorkflows } from '../workflows/load.js';
93
- import { normalizeWorkflowDoc, skillStackOf, skillsToSteps, stepsIssue, workflowFileSchema, } from '../workflows/types.js';
94
- import { planChain, slugify } from '../planner.js';
95
- import { readHandoff, renderHandoffRecords } from '../handoff.js';
96
- import { HistoryCursorError, deriveRunContextEvents, readRunHistoryPage, validateLiveCursor, } from '../runs/event-history.js';
97
- import { ARCHIVED_WINDOW, readRunIndexFromDisk, searchRunIndexFromDisk } from '../runs/run-index.js';
98
- import { searchTokens } from '../contract/index.js';
99
- import { ownPullRequestNumbers } from '../runs/pull-requests.js';
100
- import { ColdRepoHandles } from './cold-repo-handles.js';
101
- import { isV2WireEventType } from '../runs/ui-event-sink.js';
102
- import { runEventsQuerySchema, runHistoryQuerySchema, runIdParamSchema, } from '../contract/index.js';
103
- import { resolveAttachmentPathAsync } from '../workflows/attachment-path.js';
104
- import { artifactParamsSchema, fileLinkQuerySchema } from '../contract/index.js';
105
- import { listArtifacts, readArtifact, readArtifactMetadata } from '../artifacts/store.js';
106
- import { artifactPreview, loadFileLink, rasterMime } from '../artifacts/resolve.js';
107
- import { toPastedContent } from '../workflows/pasted-content.js';
108
- import { isUntouchedCancelledRun } from '../workflows/run/run-guards.js';
109
- import { worktreeDiff } from '../git-worktree.js';
110
- import { releaseThenRemoveWorktree } from '../git-worktree-release.js';
111
- import { isReclaimable, reclaimWorktree, reclaimWorktrees, selectReclaimableWorktrees } from '../runs/retention.js';
112
- import { getCommit, getDiff, getRepoInfo, getStatus } from './git.js';
20
+ import { allUsage, onUsage } from '../core/process-usage.js';
21
+ import { getRepoInfo } from './git.js';
113
22
  import { createHealthCache, HEALTH_TTL_MS } from './health-cache.js';
114
- import { COMMIT_FORMATS, FILE_FORMATS, negotiate } from './accept-negotiation.js';
115
23
  import { authorityOfHost, authorityOfOrigin, hostnameOfHost, hostnameOfOrigin } from './host-authority.js';
116
24
  import { pluginHealth, pluginLoadReport } from '../plugin/loader.js';
117
25
  import { createBackendChecks } from './backend-checks.js';
118
- import { createGithubBranchForge } from './repo-branch-forge.js';
119
- import { classifyInputFor, deleteBranches, forgetRepoBranches, readRepoBranchCounts, readRepoBranches } from './repo-branches.js';
120
- import { claimRepoGitMutation, localPullBranches, pullRepoCheckout } from './repo-pull.js';
121
- import { collectChanges, collectCommitChanges, collectRunCommits, commitAll, createOrSwitchBranch, pushCurrentBranch, readWorktreePath, } from './git-changes.js';
122
- import { healthConfig, loadConfig, resolveWorktreeRetention } from '../config.js';
123
- import { reportWorktreeCommands } from '../worktree-setup.js';
124
- import { readConfigFile, writeConfigFile } from '../agent-config/files.js';
125
- import { readAgentModelDefaults } from '../agent-config/models.js';
126
- import { listAgentConfig } from '../agent-config/service.js';
127
- import { findConfigFile } from '../agent-config/catalog.js';
128
- import { defaultWorkspaceConfig, loadWorkspaceConfig, mergeWriteWorkspaceConfig, effectiveComposerDefault } from '../workspace/config.js';
26
+ import { healthConfig } from '../config.js';
27
+ import { defaultWorkspaceConfig, loadWorkspaceConfig } from '../workspace/config.js';
129
28
  import { DEFAULT_AGENT_ACCOUNT_ID, defaultAgentAccountStore, loadAgentAccounts } from '../workspace/agent-accounts.js';
130
29
  import { defaultAgentProfile, listAgentProfiles, resolveStoredProfile } from '../workspace/agent-profiles.js';
131
- import { profileEnv } from '../core/agent-profiles.js';
132
- import { shellQuote, withEnvPrefix } from '../core/shell-env.js';
133
- import { resumeCommand } from '../core/runner-cli.js';
134
- import { mergeWriteWorkspaceUiState, readWorkspaceUiState } from '../workspace/ui-state.js';
135
- import { createWorkspaceRunFeed, currentRecord } from './workspace-run-feed.js';
136
- import { mergeWriteProjectUiState, readUiState } from '../ui-state.js';
137
- import { expandTilde } from '../paths.js';
30
+ import { createWorkspaceRunFeed } from './workspace-run-feed.js';
138
31
  import { isLoopbackHostHeader, resolveCapabilities } from './capabilities.js';
139
- import { browseDirectory, resolveBrowseRoot } from './fs-browse.js';
140
- import { resolveForge, forgeWebRoot, resolveForgeRoot, GithubPrNotFoundError, GH_CHECKS_MAX, GH_REF_STATUS_MAX } from './forge/index.js';
141
- import { refNumberFromUrl } from '../contract/index.js';
142
- import { projectAdmissionRefusal, withProjectAdmission } from './cockpit-ownership.js';
32
+ import { resolveForge } from './forge/index.js';
33
+ import { withProjectAdmission } from './cockpit-ownership.js';
143
34
  import { prepareProjects } from '../project-migration/auto.js';
144
- import { freshCliHandoff, openRunApp, openRunCli, openRunDefaultApp } from './open-in-targets.js';
145
- import { agentCliRunner, detectOpenTargets } from './open-in-app.js';
146
35
  import { ProviderRuntimeAuthObserver } from './provider-auth-runtime.js';
147
- import { continueRunProviders } from './provider-action-gate.js';
148
36
  import { attachProjectWebhooks, createBootContext, createProviderStatus, resolveServerDeps, watchProviderRuntimeAuth } from './server-deps.js';
149
- import { NO_WEBHOOK_ERROR, agentProfileRefusal, clientRequestOf, launchRun, modelLockRefusal, notifyRefusal, providerGateRefusal, replayedRun, resolveStartWorkflow, startRunInput, } from './start-run-options.js';
150
37
  import { ASSET_CACHE_CONTROL, BUILD_HINT_HTML, assetContentType, isSafeAssetFilename, resolveGetRequest, } from './static-ui.js';
151
38
  import { compression, createStaticAssets, isFile } from './static-assets.js';
152
39
  import { registerBrandFileRoutes } from './brand-file-routes.js';
153
40
  import { createProjectsRoutes } from './projects-routes.js';
154
41
  import { createAgentProfilesRoutes, createProvidersRoutes } from './providers-routes.js';
155
- import { hostedProfileRefusal, streamSSENoBuffer, UI_STATE_BODY_LIMIT, WorkspaceEventBus } from './server-types.js';
42
+ import { hostedProfileRefusal, WorkspaceEventBus } from './server-types.js';
43
+ import { createAutomationsRouteBundles } from './automations-routes.js';
44
+ import { createGithubRoutes } from './github-routes.js';
45
+ import { createOpenTargetsRoutes, createRepoRoutes, createWorktreesRoutes } from './repo-routes.js';
46
+ import { createFsBrowseRoutes, createRunsIndexRoutes, createWorkspaceConfigRoutes, createWorkspaceEventsRoutes } from './workspace-routes.js';
47
+ import { createAgentConfigRoutes, createAgentWebhooksRoutes, createConfigRoutes, createPlanRoutes, createSkillsRoutes, createSseRoutes, createUiStateRoutes, createWorkflowsRoutes } from './project-settings-routes.js';
48
+ import { createRunsRoutes, withLiveUsage } from './runs-routes.js';
156
49
  // ---- project-scoped routing (multi-project spec, step 2.2) -----------------
157
50
  export { WorkspaceEventBus } from './server-types.js';
158
51
  /**
@@ -189,27 +82,7 @@ export function projectRouteManifest(app) {
189
82
  }
190
83
  return manifest;
191
84
  }
192
- /** 409 body for every automations route while GitHub automations are off (#801). */
193
- const AUTOMATIONS_OFF = 'Automations are disabled — unset CEZ_AUTOMATIONS or set it to 1 and restart to enable them';
194
- /** 404 body for a run whose row is in runs.db but whose record this Squawk cannot decode (#779). */
195
- const UNREADABLE_RUN_ERROR = `this run could not be read by this Squawk: its record in runs.db does not fit this version (a newer Squawk may have written it). It is left in the database untouched.`;
196
85
  // ---- workspace SSE (multi-project spec, step 2.8) --------------------------
197
- // Queued prompt stack bounds (#472). The per-message bounds mirror `messageSchema`
198
- // above; the one that actually matters is the FOLDED total, because 20 messages of
199
- // 100 000 chars each would otherwise compose a ~2 M-character {{task}}.
200
- const MAX_QUEUED_MESSAGES = 20;
201
- const MAX_QUEUED_ATTACHMENTS = 8;
202
- const MAX_FOLDED_TASK_CHARS = 200_000;
203
- /** Length of the prompt a run would execute with — `task` plus its whole stack,
204
- * composed exactly as `hydrateQueuedInput` composes it. Checked against the
205
- * PROSPECTIVE state so the user is stopped at the write, not at dequeue where
206
- * there would be no one left to tell. */
207
- function foldedLength(task, stack) {
208
- return [task, ...stack.map((m) => m.text)]
209
- .map((part) => part.trim())
210
- .filter((part) => part.length > 0)
211
- .join('\n\n').length;
212
- }
213
86
  // Request-body size guards (#429). A generous global cap keeps a single
214
87
  // localhost request from being unbounded (the largest legit body is 4 pasted
215
88
  // images at ~7 MB base64 each); the ui-state PUT gets a much tighter cap since
@@ -280,12 +153,6 @@ export function createApp(deps) {
280
153
  const serverGeneration = randomUUID();
281
154
  const checkoutProgress = new CheckoutProgressCache();
282
155
  const workspaceEvents = deps.workspaceEvents ?? new WorkspaceEventBus();
283
- const emitAutomationChange = (project, automationId, revision, deleted = false) => workspaceEvents.emit('automation-change', {
284
- project: project.id,
285
- automationId,
286
- revision,
287
- ...(deleted ? { deleted: true } : {}),
288
- });
289
156
  const automationsChanged = () => deps.automationsChanged?.();
290
157
  const providerRuntimeAuth = deps.providerRuntimeAuth
291
158
  ?? new ProviderRuntimeAuthObserver(providerAuth, (status) => {
@@ -662,38 +529,6 @@ export function createApp(deps) {
662
529
  return { error: `unknown ${provider} account: ${profileId}` };
663
530
  return { profile: resolveStoredProfile(stored) };
664
531
  };
665
- const openHandoffCheckout = (c, suffix = '') => {
666
- const checkout = runCheckout(c.get('project'), c.req.param('id'), 'open');
667
- if ('status' in checkout)
668
- return checkout;
669
- // Hosted mode: there is no "my machine" to open a terminal on. The UI
670
- // hides the button when localHandoff is false — this is defense in depth.
671
- return !capabilities().localHandoff
672
- ? { status: 409, body: { error: `local handoff is disabled — this cockpit runs in hosted mode (CEZ_REMOTE)${suffix}` } }
673
- : checkout;
674
- };
675
- /**
676
- * The environment a terminal handoff must carry so the CLI lands on the right account.
677
- *
678
- * `profileId` is the one RECORDED on the step that owns the session, never the project's
679
- * current selection: `claude --resume <id>` reads `<configDir>/sessions`, so a handoff for a
680
- * run started on the work account and resumed after the project was switched back would find
681
- * nothing and silently open a fresh conversation.
682
- */
683
- const handoffEnv = async (provider, profileId) => {
684
- const resolved = await resolveWorkspaceProfile(provider, profileId);
685
- if ('error' in resolved) {
686
- return { error: `this session belongs to an account that no longer exists (${profileId})` };
687
- }
688
- const { profile } = resolved;
689
- return { env: profile.isDefault ? {} : profileEnv(provider, profile.path) };
690
- };
691
- /** The copy-paste fallback shown when no terminal could be opened — same account, spelled for
692
- * this platform's shell. `null` when the account environment cannot be embedded safely. */
693
- const handoffFallbackCommand = (cwd, command, env) => {
694
- const prefixed = withEnvPrefix(command, env, process.platform);
695
- return prefixed === null ? null : `cd ${shellQuote(cwd)} && ${prefixed}`;
696
- };
697
532
  /** A registered project's realpath'd root, or null when the id is unknown. */
698
533
  const projectRootFor = async (projectId) => {
699
534
  try {
@@ -757,2052 +592,64 @@ export function createApp(deps) {
757
592
  // events on the workspace stream. `checkoutId` is the cockpit's own
758
593
  // correlation token, echoed on every event so two tabs cloning at once never
759
594
  // render each other's progress.
760
- // ---- workspace settings (multi-project spec, step 2.7) -------------------
761
- // WORKSPACE-level routes: single-mount (never mirrored under /api/p/),
762
- // same-origin. The config routes carry the settings UI's slice of
763
- // `~/.cezar/config.json` — global knobs only; the registry stays on
764
- // /api/projects above, and schemaVersion (a migration cursor, not a
765
- // setting) is deliberately omitted.
766
- const workspaceConfigBody = (config) => ({
767
- browseRoot: config.browseRoot,
768
- projectsDir: config.projectsDir,
769
- archiveOnMerge: config.archiveOnMerge ?? null,
770
- effectiveArchiveOnMerge: resolveGlobalArchiveOnMerge(config).enabled,
771
- archiveOnMergeSource: resolveGlobalArchiveOnMerge(config).source,
772
- composerDefaults: {
773
- autonomous: config.composerDefaults.autonomous ?? null,
774
- worktree: config.composerDefaults.worktree ?? null,
775
- inheritedAutonomous: productEnv('AUTONOMOUS_DEFAULT') === '0'
776
- ? false
777
- : productEnv('AUTONOMOUS_DEFAULT') === '1'
778
- ? true
779
- : 'source-dependent',
780
- inheritedWorktree: effectiveComposerDefault(undefined, productEnv('WORKTREE_DEFAULT'), true),
781
- },
782
- resources: {
783
- maxParallel: config.resources.maxParallel,
784
- maxMonitoringSessions: config.resources.maxMonitoringSessions,
785
- monitoringWakeIntervalMinutes: config.resources.monitoringWakeIntervalMinutes,
786
- autoResumeOnUsageLimit: config.resources.autoResumeOnUsageLimit,
787
- memoryLimitMb: config.resources.memoryLimitMb,
788
- worktreeRetentionDefault: config.resources.worktreeRetentionDefault,
789
- },
790
- // SPREAD, never `runner: maybeUndefined`: hono would type the key as always-present while
791
- // `JSON.stringify` drops it, which is the exact drift `contract-parity` catches. And absent has
792
- // to keep meaning "no opinion" here, or the fallback collapses into "always claude".
793
- agentDefaults: {
794
- ...(config.agentDefaults.runner !== undefined ? { runner: config.agentDefaults.runner } : {}),
795
- ...(config.agentDefaults.models !== undefined ? { models: config.agentDefaults.models } : {}),
796
- },
797
- });
798
- // ---- chained family: workspace settings + GUI prefs (workspace-level) ----
799
- const workspaceConfigRoutes = new Hono()
800
- .get('/workspace/config', async (c) => c.json(workspaceConfigBody(await loadWorkspaceConfig(deps.home.workspaceConfig))))
801
- .put('/workspace/config', jsonZodValidator(() => workspaceConfigUpdateSchema, { runners: { ids: ['agentDefaults.runner'], keys: ['agentDefaults.models'] } }), async (c) => {
802
- const parsed = { data: c.req.valid('json') };
803
- const { browseRoot, projectsDir, archiveOnMerge, resources } = parsed.data;
804
- for (const [configuredRoot, create] of [
805
- [browseRoot, false],
806
- [projectsDir, true],
807
- ]) {
808
- if (configuredRoot === undefined)
809
- continue;
810
- // Validated ON CHANGE, never at load (spec): browse roots must already
811
- // exist; checkout roots use `mkdir -p`. Both get a real write probe.
812
- // Any failure → 400 and NO change persisted.
813
- const expanded = expandTilde(configuredRoot);
814
- if (!isAbsoluteHostPath(expanded))
815
- return c.json({ error: `not writable: ${configuredRoot} is not an absolute path` }, 400);
816
- if (!create) {
817
- try {
818
- if (!(await stat(expanded)).isDirectory()) {
819
- return c.json({ error: `browse folder is not a directory: ${configuredRoot}` }, 400);
820
- }
821
- }
822
- catch (err) {
823
- if (err.code === 'ENOENT') {
824
- return c.json({ error: `browse folder does not exist: ${configuredRoot}` }, 400);
825
- }
826
- return c.json({ error: `browse folder unavailable: ${err instanceof Error ? err.message : String(err)}` }, 400);
827
- }
828
- }
829
- const probeError = await probeWritableDir(expanded, create);
830
- if (probeError !== null)
831
- return c.json({ error: `not writable: ${probeError}` }, 400);
832
- }
833
- let written;
834
- try {
835
- written = await mergeWriteWorkspaceConfig((config) => {
836
- applyWorkspaceConfigPatch(config, parsed.data);
837
- }, deps.home);
838
- }
839
- catch (err) {
840
- // e.g. a read-only home — nothing was persisted (atomic tmp+rename).
841
- return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
842
- }
843
- if (archiveOnMerge !== undefined)
844
- deps.archiveOnMergeChanged?.();
845
- // A resource change takes effect WITHOUT a restart: refresh the shared
846
- // semaphore's in-memory snapshot and pump every manager (step 2.5's hook).
847
- if (resources !== undefined)
848
- await deps.semaphore?.refresh();
849
- return c.json(workspaceConfigBody(written));
850
- })
851
- // Global GUI state (`~/.cezar/ui-state.json`) — same parse/key-cap/shallow-
852
- // merge semantics as the per-repo /api/v1/ui-state route below (the shared half
853
- // is `uiStateBodySchema`), but backed by the workspace file.
854
- .get('/workspace/ui-state', async (c) => c.json(await readWorkspaceUiState(deps.home.workspaceUiState, deps.home)))
855
- // The tighter body cap rides on `use` rather than inline on the route: `bodyLimit` is typed
856
- // as a bare MiddlewareHandler, and passing one to `.put()` collapses the route's schema, so
857
- // the PUT went missing from `AppType` and `hc` could not see its body at all. `use` runs at
858
- // the same point (before the handler, so the cap still precedes any read) and leaves the
859
- // chain's type accumulation alone. Method-agnostic here, which the GET does not mind.
860
- .use('/workspace/ui-state', bodyLimit({ maxSize: UI_STATE_BODY_LIMIT }))
861
- .put('/workspace/ui-state', jsonZodValidator(setWorkspaceUiStateInputSchema, { runners: { strictKeys: { path: 'dismissedProviderAuthFailures', also: REMOVED_RUNNER_IDS } } }), async (c) => {
862
- const parsed = { data: c.req.valid('json') };
863
- try {
864
- return c.json(await mergeWriteWorkspaceUiState((state) => ({
865
- ...state,
866
- ...parsed.data,
867
- }), deps.home));
868
- }
869
- catch (err) {
870
- // A read-only home degrades to an unsaved pref, never a crash.
871
- return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
872
- }
873
- });
874
- // Partial updates only — absent keys stay untouched. Bounds mirror the
875
- // workspace schema (src/workspace/config.ts, step 1.2) exactly, so a value
876
- // this route accepts can never be degraded away by the next load's `.catch`.
877
- // ---- chained family: filesystem browse (workspace-level) ----
878
- const fsBrowseRoutes = new Hono()
879
- .get('/fs/browse', queryZodValidator(browseQuerySchema), async (c) => {
880
- const query = c.req.valid('query');
881
- const root = resolveBrowseRoot(await workspaceBrowseRoot());
882
- const result = await browseDirectory({
883
- root,
884
- path: query.path,
885
- showHidden: query.showHidden === '1',
886
- });
887
- if (!result.ok)
888
- return c.json({ error: result.error }, result.status);
889
- return c.json(result.body);
890
- });
891
- // ---- chained family: skills (project-scoped) ----
892
- const skillsRoutes = new Hono()
893
- .get('/runner-skills', queryZodValidator(runnerSkillsQuerySchema, { runners: { ids: ['runner'] } }), async (c) => {
894
- if (c.req.valid('query').account !== undefined && !capabilities().localHandoff)
895
- return c.json(hostedProfileRefusal, 409);
896
- const result = await readRunnerSkills(c.req.valid('query'), c.get('project').root, deps.home, skillCatalog, resolveWorkspaceProfile);
897
- if ('error' in result)
898
- return c.json(result, 400);
899
- return c.json(result);
900
- });
901
- // ---- chained family: GUI prefs / ui-state (project-scoped) ----
902
- const uiStateRoutes = new Hono()
903
- .get('/ui-state', async (c) => c.json(await readUiState(c.get('project').root)))
904
- // On `use`, not inline on the route — see the workspace ui-state PUT above.
905
- .use('/ui-state', bodyLimit({ maxSize: UI_STATE_BODY_LIMIT }))
906
- .put('/ui-state', jsonZodValidator(uiStateBody), async (c) => {
907
- // `.passthrough()` keeps unknown prefs, but a
908
- // single request may not stuff an unbounded key set (#429) — the shared
909
- // schema+cap half of both ui-state routes lives in `uiStateBody`.
910
- const patch = c.req.valid('json');
911
- try {
912
- return c.json(await mergeWriteProjectUiState(c.get('project').root, (current) => ({ ...current, ...patch })));
913
- }
914
- catch (err) {
915
- return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
916
- }
917
- });
918
- // ---- chained family: workflows (project-scoped) --------------------------
919
- // One chained expression, mounted by `createApp` into BOTH the legacy `api`
920
- // table and the versioned `v1` one — see `healthRoutes` for why the chain
921
- // shape (not the statement shape) is what carries the types.
922
- const workflowsRoutes = new Hono()
923
- .get('/workflows', async (c) => c.json(await loadWorkflows(c.get('project').root)))
924
- // Save an approved plan as a reusable chain (spec 008): YAML in
925
- // `.ai/cezar/workflows/<slug>.yaml` — from then on it's in the dropdown
926
- // like any other workflow.
927
- .post('/workflows', jsonZodValidator(saveWorkflowSchema, { runners: { ids: ['steps.*.runner'] } }), async (c) => {
928
- const { root: repoRoot } = c.get('project');
929
- const parsed = { data: c.req.valid('json') };
930
- const steps = parsed.data.steps ?? skillsToSteps(parsed.data.skills ?? []);
931
- const issue = stepsIssue(steps);
932
- if (issue)
933
- return c.json({ error: issue }, 400);
934
- const slug = slugify(parsed.data.name) || 'chain';
935
- const dir = join(projectPaths(repoRoot).write, 'workflows');
936
- const path = join(dir, `${slug}.yaml`);
937
- // Pure skill stacks are written in the portable compact form (spec 012) —
938
- // `name` + `skills:` — so the file imports cleanly in any repo.
939
- const stack = skillStackOf(steps);
940
- const doc = {
941
- name: parsed.data.name,
942
- ...(parsed.data.description ? { description: parsed.data.description } : {}),
943
- ...(stack ? { skills: stack } : { steps }),
944
- };
945
- try {
946
- await mkdir(dir, { recursive: true });
947
- // `wx` = fail if the file exists — no silent overwrite of a chain.
948
- await writeFile(path, stringifyYaml(doc), {
949
- encoding: 'utf8',
950
- flag: parsed.data.overwrite ? 'w' : 'wx',
951
- });
952
- }
953
- catch (err) {
954
- if (err instanceof Error && 'code' in err && err.code === 'EEXIST') {
955
- return c.json({ error: `workflow file already exists: ${path}`, exists: true }, 409);
956
- }
957
- const message = err instanceof Error ? err.message : String(err);
958
- return c.json({ error: message }, 500);
959
- }
960
- return c.json({ path, name: parsed.data.name }, 201);
961
- })
962
- // Delete saved workflows only; built-ins always remain (spec 012).
963
- .delete('/workflows/:name', async (c) => {
964
- const result = await deleteSavedWorkflow(c.get('project').root, c.req.param('name'));
965
- if ('error' in result)
966
- return c.json({ error: result.error }, result.status);
967
- return c.json({ ok: true, path: result.path });
968
- })
969
- // Import support for the builder (spec 012): parse + validate a pasted
970
- // workflow YAML (either form) and hand back the normalized definition. The
971
- // server owns YAML parsing — the GUI stays dependency-free.
972
- .post('/workflows/parse', jsonZodValidator(parseWorkflowSchema), async (c) => {
973
- const parsed = { data: c.req.valid('json') };
974
- let raw;
975
- try {
976
- raw = parseYaml(parsed.data.yaml);
977
- }
978
- catch (err) {
979
- const message = err instanceof Error ? err.message : String(err);
980
- return c.json({ error: `not valid YAML: ${message}` }, 400);
981
- }
982
- const doc = workflowFileSchema.safeParse(raw);
983
- if (!doc.success) {
984
- return c.json({ error: doc.error.issues.map((i) => i.message).join('; ') }, 400);
985
- }
986
- const normalized = normalizeWorkflowDoc(doc.data);
987
- const issue = stepsIssue(normalized.steps);
988
- if (issue)
989
- return c.json({ error: issue }, 400);
990
- return c.json(normalized);
991
- });
992
- // ---- chained family: plan (project-scoped) ----
993
- const planRoutes = new Hono()
994
- .post('/plan', jsonZodValidator(planSchema), async (c) => {
995
- const { root: repoRoot, manager } = c.get('project');
996
- const parsed = { data: c.req.valid('json') };
997
- const planner = resolveRunnerId((await loadConfig(repoRoot, deps.home)).defaultRunner);
998
- const blocked = await providerActionError([planner], { repoRoot, picks: { [planner]: parsed.data.agentProfile } });
999
- if (blocked)
1000
- return c.json({ error: blocked }, 409);
1001
- const badProfile = await agentProfileRefusal(resolveWorkspaceProfile, planner, parsed.data.agentProfile);
1002
- if (badProfile)
1003
- return c.json({ error: badProfile.error }, badProfile.status);
1004
- return c.json(await planChain(repoRoot, parsed.data.task, skillCatalog, deps.home, manager.createRunner, parsed.data.agentProfile));
1005
- });
1006
- const manualChecks = new Map();
1007
- /**
1008
- * The automations gate (#801): with `CEZ_AUTOMATIONS=0`, every route of the feature
1009
- * answers 409 before touching a store, a lease or GitHub.
1010
- *
1011
- * Written as MIDDLEWARE rather than a line in each handler so the family cannot drift: a route
1012
- * added to either chain below inherits the gate from its path, where a per-handler check is one
1013
- * omission away from an ungated endpoint.
1014
- *
1015
- * Registered against EXPLICIT paths, never `use('*')`. Both chains are mounted with
1016
- * `.route('/', …)` alongside a dozen unrelated sub-apps, and `route()` re-registers a sub-app's
1017
- * middleware under the mount prefix — so a `'*'` here would gate the entire `/api/v1` surface,
1018
- * including `/health`. The two-line pairing (`/automations` and `/automations/*`) is what makes
1019
- * a path match both the collection and everything under it.
1020
- */
1021
- const requireAutomations = async (c, next) => {
1022
- if (!capabilities().automations)
1023
- return c.json({ error: AUTOMATIONS_OFF }, 409);
1024
- await next();
1025
- };
1026
- /** The schedule runner for a route's project: launches into that project's own run manager. */
1027
- const scheduleHandle = (project) => {
1028
- const timeZone = localTimeZone();
1029
- return {
1030
- projectId: project.id,
1031
- store: project.automationStore,
1032
- timeZone,
1033
- launch: (definition, occurrence, receiptId) => launchScheduledRun({
1034
- root: project.root,
1035
- manager: project.manager,
1036
- store: project.store,
1037
- definition,
1038
- occurrence,
1039
- receiptId,
1040
- projectName: basename(project.root),
1041
- timeZone,
1042
- }),
1043
- onChange: (automationId, revision) => emitAutomationChange(project, automationId, revision),
1044
- // A route's write settles a crash-left reservation first, as the timer does (#1465).
1045
- reconcile: async () => { reconcileAutomationReceipts(project.automationStore, project.store); },
1046
- };
1047
- };
1048
- /** The automations family's behavior, shared with the session tools (#1465). */
1049
- const automationService = createAutomationService({ home: deps.home,
1050
- timeZone: localTimeZone,
1051
- discovery: { models: modelCatalog, providers: () => providerStatus() },
1052
- scheduleHandle: (project) => scheduleHandle(project),
1053
- emitChange: (project, automationId, revision, deleted) => emitAutomationChange(project, automationId, revision, deleted),
1054
- changed: automationsChanged,
1055
- // Awaits the driver's settled probe (per-repo cache + in-flight dedupe, 5 s timeout, never
1056
- // throws): a "still being checked" answer would leave the cockpit's GitHub option disabled
1057
- // because it does not refetch when the probe completes. `/health` keeps `detectCached`.
1058
- githubAvailability: async (root) => {
1059
- const forge = resolveProjectForge(await getRepoInfo(root));
1060
- return forge ? forge.detect() : { available: false, reason: 'No GitHub remote is configured' };
1061
- },
1062
- hasGithubRemote: async (root) => Boolean(resolveProjectForge(await getRepoInfo(root))), });
1063
- // #1465: every project's manager gets the schedule tools over this service. A manager reads
1064
- // them at call time, so a session recovered before its project's context finished building
1065
- // reaches them once this runs. The tools themselves are disabled by CEZ_AUTOMATIONS=0.
1066
- const attachAutomationTools = (project) => project.manager.setAutomationTools?.(createAutomationToolService(automationService, project, { timeZone: localTimeZone }));
1067
- attachAutomationTools(bootContext);
1068
- for (const id of contexts.ids()) {
1069
- const ctx = contexts.peek(id);
1070
- if (ctx)
1071
- attachAutomationTools(ctx);
1072
- }
1073
- contexts.onContextBuilt(attachAutomationTools);
1074
- // ---- chained family: GitHub automations (project-scoped) ----
1075
- // Every handler below reads `c.get('project')` — the definitions, their runtime state and the
1076
- // execution log are per-project files — so the family is project-scoped and mounted with the
1077
- // rest of the mirrored table. The one exception is the manual-check read, which touches no
1078
- // project at all; it is its own workspace-level family below.
1079
- const automationsRoutes = new Hono()
1080
- .use('/automations', requireAutomations)
1081
- .use('/automations/*', requireAutomations)
1082
- .use('/automation-log', requireAutomations)
1083
- .use('/automation-log/*', requireAutomations)
1084
- .get('/automations', queryZodValidator(automationListQuerySchema), async (c) => {
1085
- return c.json(await automationService.list(c.get('project'), c.req.valid('query')));
1086
- })
1087
- .post('/automations', jsonZodValidator(() => automationCreateSchema, { runners: { ids: ['task.runner', 'task.steps.*.runner'] } }), async (c) => {
1088
- const result = await automationService.create(c.get('project'), c.req.valid('json'));
1089
- if (!result.ok)
1090
- return c.json({ error: result.error }, result.status);
1091
- const once = onceCreateAnswer(result.automation);
1092
- return c.json({ automation: result.automation, ...(once ? { once } : {}) }, 201);
1093
- })
1094
- .get('/automations/:id', (c) => {
1095
- const result = automationService.get(c.get('project'), c.req.param('id'));
1096
- if (!result.ok)
1097
- return c.json({ error: result.error }, result.status);
1098
- return c.json(result.body);
1099
- })
1100
- .put('/automations/:id', jsonZodValidator(() => automationUpdateSchema, { runners: { ids: ['task.runner', 'task.steps.*.runner'] } }), async (c) => {
1101
- const result = await automationService.update(c.get('project'), c.req.param('id'), c.req.valid('json'));
1102
- if (!result.ok)
1103
- return c.json({ error: result.error }, result.status);
1104
- return c.json({ automation: result.automation });
1105
- })
1106
- .delete('/automations/:id', async (c) => {
1107
- const result = await automationService.remove(c.get('project'), c.req.param('id'));
1108
- if (!result.ok)
1109
- return c.json({ error: result.error }, result.status);
1110
- return c.body(null, 204);
1111
- })
1112
- .post('/automations/:id/enable', async (c) => {
1113
- const result = await automationService.enable(c.get('project'), c.req.param('id'));
1114
- if (!result.ok)
1115
- return c.json({ error: result.error }, result.status);
1116
- return c.json({ automation: result.automation });
1117
- })
1118
- .post('/automations/:id/pause', async (c) => {
1119
- const result = await automationService.pause(c.get('project'), c.req.param('id'));
1120
- if (!result.ok)
1121
- return c.json({ error: result.error }, result.status);
1122
- return c.json({ automation: result.automation });
1123
- })
1124
- // One-time schedules only (#1465): archive without launching. 409 for any other automation.
1125
- .post('/automations/:id/cancel', async (c) => {
1126
- const result = await automationService.cancel(c.get('project'), c.req.param('id'));
1127
- if (!result.ok)
1128
- return c.json({ error: result.error }, result.status);
1129
- return c.json({ automation: result.automation });
1130
- })
1131
- // Run now: a schedule fired once by hand, paused or not, outside the timer and under the same
1132
- // lease. A repeating schedule keeps `nextRunAt` and `enabled`; a one-time schedule is consumed
1133
- // (archived) by it. A GitHub automation's equivalent is `check`.
1134
- .post('/automations/:id/run', async (c) => {
1135
- const result = await automationService.runNow(c.get('project'), c.req.param('id'));
1136
- if (!result.ok)
1137
- return c.json({ error: result.error }, result.status);
1138
- return c.json({ runId: result.runId }, 202);
1139
- })
1140
- // The body is validated as MIDDLEWARE, which is what puts it in the route type — and moves
1141
- // the 400 ahead of this route's 404: `POST /automations/<unknown>/check` with a malformed
1142
- // body now answers 400 rather than 404. Nothing else about either answer changed.
1143
- .post('/automations/:id/check', jsonZodValidator(() => automationCheckRequestSchema), async (c) => {
1144
- const project = c.get('project');
1145
- const store = project.automationStore;
1146
- const automation = store.get(c.req.param('id'));
1147
- if (!automation)
1148
- return c.json({ error: 'not found' }, 404);
1149
- if (!isGithubAutomation(automation))
1150
- return c.json({ error: 'a schedule has nothing to preview; use run' }, 409);
1151
- const parsed = { data: c.req.valid('json') };
1152
- // `string`, not `randomUUID`'s template-literal type: the wire carries an opaque id, and
1153
- // leaking `${string}-${string}-…` into the route type would make the contract describe the
1154
- // generator rather than the answer.
1155
- const id = randomUUID();
1156
- const check = { id, automationId: automation.id, mode: parsed.data.mode, status: 'queued', createdAt: new Date().toISOString() };
1157
- if (manualChecks.size >= 200)
1158
- manualChecks.delete(manualChecks.keys().next().value);
1159
- manualChecks.set(id, check);
1160
- void withProjectAdmission(project.dataDir, async function manualCheck() {
1161
- check.status = 'running';
1162
- try {
1163
- const repository = githubRepository(project.root, (await getRepoInfo(project.root))?.remote);
1164
- if (!repository)
1165
- throw new Error('No GitHub remote is configured');
1166
- const scheduler = new ProjectAutomationScheduler({
1167
- projectId: project.id,
1168
- store,
1169
- timeZone: localTimeZone(),
1170
- github: { ...repository, poller: new GithubPoller() },
1171
- launch: parsed.data.mode === 'execute'
1172
- ? (definition, candidate, receiptId) => launchAutomationRun({ root: project.root, manager: project.manager, store: project.store, definition, candidate, receiptId })
1173
- : undefined,
1174
- onChange: (automationId, revision) => emitAutomationChange(project, automationId, revision),
1175
- });
1176
- const result = await scheduler.check(automation, parsed.data.mode);
1177
- Object.assign(check, { status: 'complete', completedAt: new Date().toISOString(), matches: result.candidates.length, truncated: result.truncated });
1178
- }
1179
- catch (error) {
1180
- Object.assign(check, { status: 'error', completedAt: new Date().toISOString(), error: error instanceof Error ? error.message : String(error) });
1181
- }
1182
- }, (error) => { Object.assign(check, { status: 'error', completedAt: new Date().toISOString(), error: error.message }); });
1183
- return c.json({ checkId: id }, 202);
1184
- })
1185
- .get('/automation-log', queryZodValidator(automationLogQuerySchema), (c) => {
1186
- return c.json({ records: c.get('project').automationStore.logs(c.req.valid('query')) });
1187
- })
1188
- .post('/automation-log/:receiptId/retry', async (c) => {
1189
- const result = await retryAutomationLogReceipt({
1190
- project: c.get('project'),
1191
- receiptId: c.req.param('receiptId'),
1192
- scheduleHandle,
1193
- emitChange: emitAutomationChange,
1194
- });
1195
- if (result.status === 202)
1196
- return c.json(result.body, 202);
1197
- return result.status === 404 ? c.json(result.body, 404) : c.json(result.body, 409);
1198
- });
1199
- // ---- chained family: manual automation checks (workspace-level) ----
1200
- // Workspace-level because the handler reads no project: a check lives in the server-memory map
1201
- // above, keyed by an unguessable id that the project-scoped POST hands back. Mounting it under
1202
- // `/api/v1/p/:projectId` too would be a second spelling of a lookup that consults no project.
1203
- const automationChecksRoutes = new Hono()
1204
- .use('/automation-checks/*', requireAutomations)
1205
- .get('/automation-checks/:checkId', (c) => {
1206
- const check = manualChecks.get(c.req.param('checkId'));
1207
- return check ? c.json(check) : c.json({ error: 'not found' }, 404);
595
+ const workspaceConfigRoutes = createWorkspaceConfigRoutes({
596
+ home: deps.home,
597
+ semaphore: deps.semaphore,
598
+ archiveOnMergeChanged: deps.archiveOnMergeChanged,
599
+ });
600
+ const fsBrowseRoutes = createFsBrowseRoutes(workspaceBrowseRoot);
601
+ const skillsRoutes = createSkillsRoutes({ home: deps.home, capabilities, skillCatalog, resolveWorkspaceProfile });
602
+ const uiStateRoutes = createUiStateRoutes();
603
+ const workflowsRoutes = createWorkflowsRoutes();
604
+ const planRoutes = createPlanRoutes({ home: deps.home, skillCatalog, providerActionError, resolveWorkspaceProfile });
605
+ const { automationsRoutes, automationChecksRoutes } = createAutomationsRouteBundles({
606
+ home: deps.home,
607
+ capabilities,
608
+ modelCatalog,
609
+ providerStatus,
610
+ bootContext,
611
+ contexts,
612
+ workspaceEvents,
613
+ automationsChanged,
614
+ resolveProjectForge,
1208
615
  });
1209
- // ---- runs ----------------------------------------------------------------
1210
- // Additive `usage` field (#348): the latest CPU/RSS/proc-count sample of the
1211
- // run's live process tree — absent for finished runs and when `ps` yields
1212
- // nothing. The stored record itself is never touched.
1213
- const withUsage = (run, finishBlocked) => {
1214
- const usage = currentUsage(run.id);
1215
- const { sessionId, backend } = latestSession(run);
1216
- const command = sessionId ? resumeCommand(resolveRunnerId(backend), sessionId) : null;
1217
- return { ...run, ...(usage ? { usage } : {}), ...(command ? { cliResumeCommand: command } : {}),
1218
- ...(runnerDefinition(resolveRunnerId(backend)).cli.interactive === false ? { cliHandoff: false } : {}),
1219
- ...(finishBlocked !== undefined ? { finishBlocked } : {}) };
1220
- };
1221
- // A list row (#817) with the same live `usage` sample `withUsage` attaches. The sampler is
1222
- // process-wide, so a workspace-level answer can carry it for every project's runs at once — a
1223
- // cold project's stored summaries included. Appended last, exactly where `toRunSummary` puts it.
1224
- const withLiveUsage = (summary) => {
1225
- const usage = currentUsage(summary.id);
1226
- return usage ? { ...summary, usage } : summary;
1227
- };
1228
616
  // One run feed for every workspace stream connection (hearsay-tools/cezarion#2730): one store
1229
617
  // subscription per project, one process-wide `seq`, each frame built once per mode.
1230
618
  const workspaceRunFeed = createWorkspaceRunFeed({
1231
619
  bootStore: bootContext.store, contexts, onWorkspaceEvent: (listener) => workspaceEvents.on(listener),
1232
620
  onUsage, allUsage, withLiveUsage,
1233
621
  });
1234
- /**
1235
- * Gate every run control by family ownership: refuse foreign or quarantined writers with 409;
1236
- * adopt proven dead owners without resuming agents. Reads remain available. Stop carries its
1237
- * cancellation through adoption. `adoptFallbackControl` runs first for a `.ai/squawk/` family.
1238
- */
1239
- const requireRunControl = async (c, next) => {
1240
- const id = c.req.param('id');
1241
- if (c.req.method === 'GET' || c.req.method === 'HEAD' || id === undefined)
1242
- return next();
1243
- const { store, manager } = c.get('project');
1244
- if (store.claims.runOwnership(id) === 'orphaned') {
1245
- const stop = c.req.method === 'POST' && c.req.path.endsWith('/cancel');
1246
- if (await manager.adoptOrphanedRun(id, { stop }) && stop && store.getRun(id)?.status === 'cancelled')
1247
- c.set('stoppedOnAdoption', true);
1248
- }
1249
- const refusal = store.claims.writeRefusal(id);
1250
- if (!refusal)
1251
- return next();
1252
- // The delegation route in this family answers in the delegation error shape it always uses.
1253
- return c.req.path.endsWith('/worker-destroy')
1254
- ? c.json({ code: 'incompatible_state', error: refusal }, 409)
1255
- : c.json({ error: refusal }, 409);
1256
- };
1257
- // ---- chained family: runs lifecycle + artifacts (project-scoped) ----
1258
- const delegationService = deps.delegation?.service ?? new DelegationService(deps.workerCleanup);
1259
- delegationService.setDiscovery({ models: modelCatalog, providers: providerStatus });
1260
- const runsRoutes = new Hono()
1261
- .use('/runs/:id', adoptFallbackControl, requireRunControl)
1262
- .use('/runs/:id/*', adoptFallbackControl, requireRunControl)
1263
- // Legacy (older clients): every full record. The cockpit and `cez task` read `/run-summaries`.
1264
- .get('/runs', (c) => c.json(c.get('project').store.queries.listAllRunsForLegacyRoute().map(run => withUsage(run))))
1265
- // The slim list (#817): the same runs in the same order as `GET /runs`, from the stored
1266
- // `toRunSummary` column with memory laid over it (#779), so the list decodes no record.
1267
- // `?archived=recent` (#864) is the window the cockpit reads: every unarchived run plus the newest
1268
- // `ARCHIVED_WINDOW` archived roots. The default stays every run, for clients that list them all.
1269
- .get('/run-summaries', queryZodValidator(runSummariesQuerySchema), (c) => {
1270
- const archivedWindow = c.req.valid('query').archived === 'recent' ? ARCHIVED_WINDOW : undefined;
1271
- return c.json(c.get('project').store.queries.listRunSummaries({ archivedWindow }).runs.map(withLiveUsage));
1272
- })
1273
- // The archived roots past that window, a page at a time, newest first (#864).
1274
- .get('/run-summaries/archived', queryZodValidator(archivedRunsQuerySchema), (c) => {
1275
- const { before, limit, q } = c.req.valid('query');
1276
- const project = c.get('project');
1277
- // The page shows each task's origin line, so `q` matches what it names: the automation's
1278
- // name, or its recorded id while automations are off, as the cockpit's filter does (#1616).
1279
- const automationNames = new Map(capabilities().automations
1280
- ? project.automationStore.list().map((automation) => [automation.id, automation.name]) : []);
1281
- const page = project.store.queries.listArchivedRuns({
1282
- limit: limit ?? ARCHIVED_RUNS_PAGE_DEFAULT,
1283
- automationNames,
1284
- ...(before !== undefined ? { before } : {}),
1285
- ...(q !== undefined ? { q } : {}),
1286
- });
1287
- if ('error' in page)
1288
- return c.json({ error: page.error }, 400);
1289
- const body = { ...page, runs: page.runs.map(withLiveUsage) };
1290
- return c.json(body);
1291
- })
1292
- .get('/runs/:id/relationships', paramZodValidator(runIdParamSchema), queryZodValidator(workerEmptyRequestSchema), (c) => {
1293
- const { store } = c.get('project');
1294
- const run = store.getRun(c.req.valid('param').id);
1295
- if (!run)
1296
- return c.json({ error: 'not found' }, 404);
1297
- return c.json(runRelationshipsSchema.parse(runRelationships(store, run)));
1298
- })
1299
- .post('/runs/:id/worker-destroy', queryZodValidator(workerEmptyRequestSchema, { code: 'invalid_input', message: 'Invalid cleanup query' }), paramZodValidator(runIdParamSchema, { code: 'invalid_input', message: 'Invalid worker ID' }), jsonZodValidator(workerDestroyRequestSchema, { absent: {}, malformed: null, code: 'invalid_input', message: 'Invalid cleanup input' }), async (c) => {
1300
- const project = c.get('project');
1301
- delegationService.registerProject(project);
1302
- try {
1303
- const result = await delegationService.destroyForHuman(project.id, c.req.valid('param').id, c.req.valid('json'));
1304
- return result.state === 'incomplete' ? c.json(result, 409) : c.json(result, 200);
1305
- }
1306
- catch (error) {
1307
- const failure = delegationFailure(error);
1308
- return c.json(failure.body, failure.status);
1309
- }
1310
- })
1311
- // Registered before the `/:id/...` routes so "archive-finished" and "read-all"
1312
- // never match as a run id.
1313
- .post('/runs/archive-finished', jsonZodValidator(archiveFinishedRequestSchema, { absent: {}, malformed: null }), (c) => c.json(c.get('project').store.archive.archiveFinished(c.req.valid('json').scope, c.req.valid('json').automation)))
1314
- // The read-receipt sweep (#unread-done-items) — the mark-read twin of the archive
1315
- // sweep above, and under the same registration-order guard.
1316
- .post('/runs/read-all', jsonZodValidator(markAllReadRequestSchema, { absent: {}, malformed: null }), (c) => c.json({ read: c.get('project').store.readFlags.markAllRead(c.req.valid('json').automation) }))
1317
- .post('/runs/:id/archive', jsonZodValidator(archiveSchema, { absent: ({}) }), async (c) => {
1318
- const { store } = c.get('project');
1319
- const id = c.req.param('id');
1320
- // An empty/absent body archives (the common case); a malformed body degrades
1321
- // to `{}` just as before, but a wrong-typed `archived` is now a 400 (#429).
1322
- // Archiving also retires any pending usage-limit resume, but that rule belongs to
1323
- // `setArchived` itself — the bulk sweep must obey it too (spec
1324
- // 2026-08-03-auto-resume-after-usage-limit).
1325
- const parsed = { data: c.req.valid('json') };
1326
- const run = store.archive.setArchived(id, parsed.data.archived !== false);
1327
- return run ? c.json(run) : c.json({ error: 'not found' }, 404);
1328
- })
1329
- // Pin one task to the top of this project's list, or unpin it (#935). The archive route's
1330
- // twin in every respect: an absent body pins (the common case), the answer is the updated
1331
- // record, and the change rides the existing `run` SSE because `setPinned` touches. No new
1332
- // event and no new response shape.
1333
- .post('/runs/:id/pin', paramZodValidator(runIdParamSchema), jsonZodValidator(pinRunInputSchema, { absent: {}, malformed: null }), (c) => {
1334
- const { store } = c.get('project');
1335
- const run = store.readFlags.setPinned(c.req.valid('param').id, c.req.valid('json').pinned !== false);
1336
- return run ? c.json(run) : c.json({ error: 'not found' }, 404);
1337
- })
1338
- // Task webhook opt-in for one run (#589), valid in every state — handing a finished task to a
1339
- // bot for follow-up is a real case. Turning it on sends one `task.subscribed` delivery with
1340
- // the note; the note never reaches the agent session. Either direction leaves a durable
1341
- // `handoff` event so the thread shows when and why. Idempotent: repeating `true` with a
1342
- // new note is how "Send a note…" works.
1343
- .post('/runs/:id/notify', paramZodValidator(runIdParamSchema), jsonZodValidator(notifyRunInputSchema), async (c) => {
1344
- const project = c.get('project');
1345
- const { id } = c.req.valid('param');
1346
- const { notify, message } = c.req.valid('json');
1347
- if (!project.store.getRun(id))
1348
- return c.json({ error: 'not found' }, 404);
1349
- if (notify) {
1350
- const entry = await projectRegistryEntry(project.id).catch(() => undefined);
1351
- if (taskWebhookList(entry).length === 0)
1352
- return c.json({ error: NO_WEBHOOK_ERROR }, 400);
1353
- }
1354
- const run = project.store.updateRun(id, { notify: notify ? true : undefined });
1355
- if (!run)
1356
- return c.json({ error: 'not found' }, 404);
1357
- project.store.eventLog.appendEvent(id, {
1358
- type: 'handoff',
1359
- notify,
1360
- ...(message === undefined ? {} : { message }),
1361
- });
1362
- if (notify)
1363
- taskWebhooks.attach(project).subscribed(id, message);
1364
- return c.json(run);
1365
- })
1366
- // The per-task off switch for that resume (the workspace setting is Settings → Resources).
1367
- // Idempotent: a run with nothing pending answers 200 too, because "this task will not
1368
- // resume itself" is equally true either way.
1369
- .delete('/runs/:id/auto-resume', (c) => {
1370
- const { store, manager } = c.get('project');
1371
- const id = c.req.param('id');
1372
- if (!store.getRun(id))
1373
- return c.json({ error: 'not found' }, 404);
1374
- manager.cancelAutoResume(id);
1375
- return c.json({ cancelled: true });
1376
- })
1377
- .post('/runs/:id/read', (c) => {
1378
- // No body: opening a thread marks it read, full stop. Stamps `seenAt = now` and
1379
- // returns the updated record (which also rides the `run` SSE via `touch`).
1380
- const run = c.get('project').store.readFlags.setRead(c.req.param('id'));
1381
- return run ? c.json(run) : c.json({ error: 'not found' }, 404);
1382
- })
1383
- .post('/runs/:id/unread', (c) => {
1384
- // The mark-unread twin (#775) — bodyless like its read counterpart: clearing the
1385
- // receipt is the whole action, so there is nothing to say about it. Sits under
1386
- // `/runs/:id/`, so the `read-all` registration-order caveat above does not apply.
1387
- const run = c.get('project').store.readFlags.setUnread(c.req.param('id'));
1388
- return run ? c.json(run) : c.json({ error: 'not found' }, 404);
1389
- })
1390
- .post('/runs', jsonZodValidator(createRunInputSchema, { runners: { ids: ['runner', 'steps.*.runner'] } }), async (c) => {
1391
- const { id: projectId, root: repoRoot, manager, store } = c.get('project');
1392
- const body = c.req.valid('json');
1393
- const clientRequest = clientRequestOf(body);
1394
- if (clientRequest) {
1395
- const replay = replayedRun(store.queries, clientRequest);
1396
- if (replay && 'error' in replay)
1397
- return c.json({ error: replay.error }, replay.status);
1398
- if (replay)
1399
- return c.json(replay.run, 200);
1400
- }
1401
- const locked = modelLockRefusal(repoRoot, body, deps.home);
1402
- if (locked)
1403
- return c.json({ error: locked.error }, locked.status);
1404
- const resolved = await resolveStartWorkflow(repoRoot, body);
1405
- if ('error' in resolved)
1406
- return c.json({ error: resolved.error }, resolved.status);
1407
- const { workflow } = resolved;
1408
- const runner = body.runner === undefined ? (await loadConfig(repoRoot, deps.home)).defaultRunner : registeredRunnerId(body.runner);
1409
- const blocked = await providerGateRefusal(providerActionError, workflow, runner, { repoRoot, picks: { [runner]: body.agentProfile } });
1410
- if (blocked)
1411
- return c.json({ error: blocked.error }, blocked.status);
1412
- const badProfile = await agentProfileRefusal(resolveWorkspaceProfile, runner, body.agentProfile);
1413
- if (badProfile)
1414
- return c.json({ error: badProfile.error }, badProfile.status);
1415
- const noWebhook = await notifyRefusal(body.notify, projectId, projectRegistryEntry);
1416
- if (noWebhook)
1417
- return c.json({ error: noWebhook.error }, noWebhook.status);
1418
- const started = launchRun(manager, workflow, startRunInput(body), clientRequest);
1419
- if ('error' in started)
1420
- return c.json({ error: started.error }, started.status);
1421
- return c.json(started.run, started.status);
1422
- })
1423
- .get('/runs/:id', (c) => {
1424
- const { store, manager } = c.get('project');
1425
- const id = c.req.param('id');
1426
- const run = store.getRun(id);
1427
- if (run)
1428
- return c.json(withUsage(run, manager.finishBlockedReason(run.id) ?? null));
1429
- // A row in runs.db this version cannot decode (#779): listed until read, so say why it will not open.
1430
- return c.json({ error: store.isUnreadable(id) ? UNREADABLE_RUN_ERROR : 'not found' }, 404);
1431
- })
1432
- .get('/runs/:id/history', paramZodValidator(runIdParamSchema), queryZodValidator(runHistoryQuerySchema), async (c) => {
1433
- const { store } = c.get('project');
1434
- const { id } = c.req.valid('param');
1435
- if (!store.getRun(id))
1436
- return c.json({ error: 'not found' }, 404);
1437
- try {
1438
- return c.json(await readRunHistoryPage(store.claims.sourceDataDir(id), id, c.req.valid('query').cursor));
1439
- }
1440
- catch (error) {
1441
- if (error instanceof HistoryCursorError)
1442
- return c.json({ error: error.message }, error.status);
1443
- throw error;
1444
- }
1445
- })
1446
- .get('/runs/:id/history-context', paramZodValidator(runIdParamSchema), async (c) => {
1447
- const { store } = c.get('project');
1448
- const { id } = c.req.valid('param');
1449
- if (!store.getRun(id))
1450
- return c.json({ error: 'not found' }, 404);
1451
- return c.json(await deriveRunContextEvents(store.claims.sourceDataDir(id), id));
1452
- })
1453
- // Editable titles (#389). The UI displays `titleSummary ?? title`, so a
1454
- // user edit sets BOTH: `title` (the record's own name — the raw task stops
1455
- // being it the moment the user renames the run) and `titleSummary` (what
1456
- // actually displays). The auto-summarizer only ever fills an *unset*
1457
- // titleSummary (TurnBookkeeper.recordTurnEnd), so an edit wins over any past or
1458
- // future auto-summary. Answers the updated record.
1459
- .patch('/runs/:id', jsonZodValidator(patchRunSchema), async (c) => {
1460
- const { store, manager } = c.get('project');
1461
- const id = c.req.param('id');
1462
- if (!store.getRun(id))
1463
- return c.json({ error: 'not found' }, 404);
1464
- const parsed = { data: c.req.valid('json') };
1465
- // The prompt is editable only while the run is still queued (#472). Checked
1466
- // BEFORE the title write so a rejected PATCH is a no-op rather than a partial
1467
- // one. `title` itself keeps working on any status — no regression to #389.
1468
- if (parsed.data.task !== undefined) {
1469
- const foldedChars = foldedLength(parsed.data.task, store.getRun(id)?.queuedMessages ?? []);
1470
- if (foldedChars > MAX_FOLDED_TASK_CHARS) {
1471
- return c.json({
1472
- error: `prompt too long — ${MAX_FOLDED_TASK_CHARS} character limit across the task and its queued messages (would be ${foldedChars})`,
1473
- }, 400);
1474
- }
1475
- if (!manager.editTask(id, parsed.data.task)) {
1476
- return c.json({ error: 'run already started' }, 409);
1477
- }
1478
- }
1479
- if (parsed.data.title !== undefined) {
1480
- // titleOrigin 'user' permanently stops the namer's live updates for this run
1481
- // (spec 2026-07-17-task-auto-naming).
1482
- store.updateRun(id, {
1483
- title: parsed.data.title,
1484
- titleSummary: parsed.data.title,
1485
- titleOrigin: 'user',
1486
- });
1487
- }
1488
- // Completion controls and task access (hearsay-tools/cezarion#2784) change at any status.
1489
- const { title: _title, task: _task, ...options } = parsed.data;
1490
- if (Object.values(options).some(value => value !== undefined))
1491
- store.updateRun(id, options);
1492
- return c.json(store.getRun(id));
1493
- })
1494
- .post('/runs/:id/cancel', (c) => {
1495
- const { store, manager } = c.get('project');
1496
- const id = c.req.param('id');
1497
- if (!store.getRun(id))
1498
- return c.json({ error: 'not found' }, 404);
1499
- // Still asked of the manager after an adoption stopped the run: a worker's stop bookkeeping is its.
1500
- const cancelled = manager.cancel(id) || c.get('stoppedOnAdoption') === true;
1501
- return c.json({ cancelled });
1502
- })
1503
- // Live-session participation (spec 002): deliver a user message (text +
1504
- // pasted screenshots) into the run's open claude session.
1505
- .post('/runs/:id/permissions', paramZodValidator(permissionRunIdParamSchema), jsonZodValidator(permissionDecisionSchema), (c) => {
1506
- const { store, manager } = c.get('project');
1507
- const { id } = c.req.valid('param');
1508
- if (!store.getRun(id))
1509
- return c.json({ error: 'not found' }, 404);
1510
- const { requestId, optionId } = c.req.valid('json');
1511
- if (!manager.respondPermission(id, requestId, optionId)) {
1512
- return c.json({ error: 'permission request is no longer available or option is invalid' }, 409);
1513
- }
1514
- return c.json({ delivered: true });
1515
- })
1516
- .post('/runs/:id/messages', jsonZodValidator(messageSchema), async (c) => {
1517
- const { store, manager } = c.get('project');
1518
- const id = c.req.param('id');
1519
- const run = store.getRun(id);
1520
- if (!run)
1521
- return c.json({ error: 'not found' }, 404);
1522
- const parsed = { data: c.req.valid('json') };
1523
- // Stacking onto a queued prompt mutates an existing task and invokes no provider.
1524
- // Provider availability still gates live delivery after the record leaves `queued`, but
1525
- // must not strand prompt authoring just because an unrelated fallback provider is
1526
- // disconnected (provider-auth spec: disabling never blocks existing-task mutations).
1527
- // In the dequeue race, the ladder below safely turns this into a starting-state buffer.
1528
- if (run.status !== 'queued') {
1529
- const blocked = await providerActionError([resolveRunnerId(providerForActiveRun(run))], { repoRoot: c.get('project').root, run, live: true });
1530
- if (blocked)
1531
- return c.json({ error: blocked }, 409);
1532
- }
1533
- const content = [
1534
- ...parsed.data.images.map(toPastedContent),
1535
- ...(parsed.data.text.trim() ? [{ type: 'text', text: parsed.data.text }] : []),
1536
- ];
1537
- // Three-rung delivery ladder (#472). Branch on the ENGINE's answer rather
1538
- // than a status read here: the handler cannot observe the dequeue safely
1539
- // (the record is written a tick later), the engine can.
1540
- // live session → delivered · still queued → folded into the prompt
1541
- // starting up → buffered · anything else → 409, exactly as before
1542
- if (manager.sendMessage(id, content))
1543
- return c.json({ delivered: true });
1544
- const currentRun = store.getRun(id);
1545
- const stack = currentRun?.queuedMessages ?? [];
1546
- // Bounds apply only to a message that is actually about to be stacked. Without this
1547
- // gate an over-long message posted to a *finished* run would answer `400 prompt too
1548
- // long` when the truthful answer is `409 session closed`. The status read is safe
1549
- // here because it only decides whether to reject EARLY — `enqueueMessage` still
1550
- // re-checks against the engine's own queue before writing anything.
1551
- if (currentRun?.status === 'queued') {
1552
- if (stack.length >= MAX_QUEUED_MESSAGES) {
1553
- return c.json({ error: `too many queued messages — ${MAX_QUEUED_MESSAGES} message limit` }, 400);
1554
- }
1555
- const stackedImages = stack.reduce((n, m) => n + (m.images?.length ?? 0), 0);
1556
- if (stackedImages + parsed.data.images.length > MAX_QUEUED_ATTACHMENTS) {
1557
- return c.json({ error: `too many queued attachments — ${MAX_QUEUED_ATTACHMENTS} attachment limit across the stack` }, 400);
1558
- }
1559
- const prospective = foldedLength(currentRun.task, [...stack, { text: parsed.data.text }]);
1560
- if (prospective > MAX_FOLDED_TASK_CHARS) {
1561
- return c.json({
1562
- error: `prompt too long — ${MAX_FOLDED_TASK_CHARS} character limit across the task and its queued messages (would be ${prospective})`,
1563
- }, 400);
1564
- }
1565
- }
1566
- const queued = manager.enqueueMessage(id, content);
1567
- if (queued)
1568
- return c.json({ queued: true, message: queued });
1569
- if (manager.deferMessage(id, content))
1570
- return c.json({ deferred: true });
1571
- return c.json({ error: 'session closed' }, 409);
1572
- })
1573
- // Edit / remove a stacked message (#472). Registered before any conflicting
1574
- // `/:id` route so `queued-messages` never matches as a run id.
1575
- .patch('/runs/:id/queued-messages/:msgId', jsonZodValidator(queuedMessagePatchSchema), async (c) => {
1576
- const { store, manager } = c.get('project');
1577
- const id = c.req.param('id');
1578
- const run = store.getRun(id);
1579
- if (!run)
1580
- return c.json({ error: 'not found' }, 404);
1581
- const parsed = { data: c.req.valid('json') };
1582
- const msgId = c.req.param('msgId');
1583
- const stack = run.queuedMessages ?? [];
1584
- const existing = stack.find((m) => m.id === msgId);
1585
- if (!existing)
1586
- return c.json({ error: 'not found' }, 404);
1587
- const effectiveText = parsed.data.text ?? existing.text;
1588
- const effectiveImageCount = parsed.data.images?.length ?? existing.images?.length ?? 0;
1589
- if (!effectiveText.trim() && effectiveImageCount === 0) {
1590
- return c.json({ error: 'message needs text or at least one attachment' }, 400);
1591
- }
1592
- const others = stack.filter((m) => m.id !== msgId);
1593
- const stackedImages = others.reduce((n, m) => n + (m.images?.length ?? 0), 0);
1594
- if (stackedImages + effectiveImageCount > MAX_QUEUED_ATTACHMENTS) {
1595
- return c.json({ error: `too many queued attachments — ${MAX_QUEUED_ATTACHMENTS} attachment limit across the stack` }, 400);
1596
- }
1597
- const prospective = foldedLength(run.task, [...others, { text: effectiveText }]);
1598
- if (prospective > MAX_FOLDED_TASK_CHARS) {
1599
- return c.json({
1600
- error: `prompt too long — ${MAX_FOLDED_TASK_CHARS} character limit across the task and its queued messages (would be ${prospective})`,
1601
- }, 400);
1602
- }
1603
- const images = parsed.data.images?.map(toPastedContent);
1604
- const message = manager.editQueuedMessage(id, msgId, {
1605
- ...(parsed.data.text !== undefined ? { text: parsed.data.text } : {}),
1606
- ...(images !== undefined ? { images } : {}),
1607
- });
1608
- if (!message)
1609
- return c.json({ error: 'run already started' }, 409);
1610
- return c.json({ message });
1611
- })
1612
- .delete('/runs/:id/queued-messages/:msgId', (c) => {
1613
- const { store, manager } = c.get('project');
1614
- const id = c.req.param('id');
1615
- const run = store.getRun(id);
1616
- if (!run)
1617
- return c.json({ error: 'not found' }, 404);
1618
- const msgId = c.req.param('msgId');
1619
- if (!(run.queuedMessages ?? []).some((m) => m.id === msgId)) {
1620
- return c.json({ error: 'not found' }, 404);
1621
- }
1622
- if (!manager.removeQueuedMessage(id, msgId))
1623
- return c.json({ error: 'run already started' }, 409);
1624
- return c.json({ removed: true });
1625
- })
1626
- // "Finish": gracefully close a waiting session — the run completes as done.
1627
- .post('/runs/:id/finish', (c) => {
1628
- const { store, manager } = c.get('project');
1629
- const id = c.req.param('id');
1630
- if (!store.getRun(id))
1631
- return c.json({ error: 'not found' }, 404);
1632
- const finished = manager.finish(id);
1633
- if (!finished)
1634
- return c.json({ error: manager.finishBlockedReason(id) ?? 'no open session' }, 409);
1635
- return c.json({ finished: true });
1636
- })
1637
- // "Continue" (spec 003): reopen a finished run's session in-process.
1638
- .post('/runs/:id/continue', jsonZodValidator(continueSchema, { absent: ({}), runners: { ids: ['runner'] } }), async (c) => {
1639
- const { root: repoRoot, store, manager } = c.get('project');
1640
- const id = c.req.param('id');
1641
- const run = store.getRun(id);
1642
- if (!run)
1643
- return c.json({ error: 'not found' }, 404);
1644
- // Bounded resume text (#429); an empty/absent body still just re-runs on the
1645
- // run's current backend, and a runner/model override reopens on that engine (#401).
1646
- const parsed = { data: c.req.valid('json') };
1647
- if (agentModelsLocked(repoRoot, process.env, deps.home) &&
1648
- (parsed.data.model?.trim() || parsed.data.effort?.trim())) {
1649
- return c.json({ error: AGENT_MODELS_LOCKED_ERROR }, 409);
1650
- }
1651
- // Untouched tasks execute their original workflow, including step-level runners.
1652
- // Resolve the same fallback as POST /runs, and pass it through so validation
1653
- // and execution use the same provider even when the record inherited config.
1654
- // Before the provider check: a run saved on a removed runner has no provider of its own.
1655
- if (run.removedRunner !== undefined && parsed.data.runner === undefined) {
1656
- return c.json({ error: removedRunnerMessage(run.removedRunner) }, 409);
1657
- }
1658
- const untouched = isUntouchedCancelledRun(run);
1659
- const { original: originalProvider, target: provider, required } = await continueRunProviders(run, parsed.data.runner, untouched, async () => (await loadConfig(repoRoot, deps.home)).defaultRunner);
1660
- const blocked = await providerActionError(required, { repoRoot, run, untouched, runners: { original: originalProvider, target: provider } });
1661
- if (blocked)
1662
- return c.json({ error: blocked }, 409);
1663
- const result = manager.continueRun(id, {
1664
- text: parsed.data.text,
1665
- images: parsed.data.images?.map(toPastedContent),
1666
- runner: untouched || parsed.data.runner !== undefined ? provider : undefined,
1667
- ...(untouched ? { originalRunner: originalProvider } : {}),
1668
- model: parsed.data.model,
1669
- effort: parsed.data.effort,
1670
- });
1671
- if (!result.ok)
1672
- return c.json({ error: result.error }, 409);
1673
- return c.json({ continued: true });
1674
- })
1675
- // "Open in terminal" (spec 003): hand the session off to a real terminal —
1676
- // in the task's worktree when it still exists (spec 006).
1677
- .post('/runs/:id/open-in-cli', async (c) => {
1678
- const project = c.get('project');
1679
- const checkout = openHandoffCheckout(c, '; resume the session from a machine that has the checkout');
1680
- if ('status' in checkout)
1681
- return c.json(checkout.body, checkout.status);
1682
- if (checkout.run.removedRunner !== undefined)
1683
- return c.json({ error: removedRunnerMessage(checkout.run.removedRunner) }, 409);
1684
- const { sessionId, backend: savedBackend, profileId } = latestSession(checkout.run), backend = resolveRunnerId(savedBackend);
1685
- if (!sessionId)
1686
- return c.json({ error: 'no agent session to resume' }, 409);
1687
- if (runnerDefinition(backend).cli.interactive === false)
1688
- return c.json({ error: 'this runner has no interactive CLI' }, 409);
1689
- const resume = checkout.resumeAllowed ? resumeCommand(backend, sessionId) : undefined;
1690
- // Fails closed on an id we do not recognise — see resumeCommand (open-mercato/cezar#431).
1691
- if (resume === null)
1692
- return c.json({ error: 'the recorded session id has an unexpected shape' }, 409);
1693
- const blocked = await providerActionError([backend], { repoRoot: project.root, picks: { [backend]: resume ? profileId ?? DEFAULT_AGENT_ACCOUNT_ID : undefined } });
1694
- if (blocked)
1695
- return c.json({ error: blocked }, 409);
1696
- const cwd = checkout.directory();
1697
- const refusal = fallbackProjectWriteError(cwd);
1698
- if (refusal)
1699
- return c.json({ error: refusal }, 409);
1700
- const account = resume
1701
- ? { command: resume, ...await handoffEnv(backend, profileId) }
1702
- : await freshCliHandoff(backend, project.root, deps.home);
1703
- if ('error' in account)
1704
- return c.json({ error: account.error }, 409);
1705
- const { command } = account;
1706
- const fallback = handoffFallbackCommand(cwd, command, account.env);
1707
- // Fail closed for the same reason as the session id: a terminal opened without the
1708
- // account's config dir resumes nothing and says nothing about why.
1709
- if (fallback === null) {
1710
- return c.json({ error: 'this account\'s folder cannot be used in a terminal command' }, 409);
1711
- }
1712
- const opened = await openTerminal(cwd, command, account.env);
1713
- if (!opened) {
1714
- return c.json({ error: 'no terminal emulator found', command: fallback }, 409);
1715
- }
1716
- return c.json({ opened: true, command });
1717
- })
1718
- // Open a run's worktree (or the repo root) in the chosen local app.
1719
- .post('/runs/:id/open-in', jsonZodValidator(openInSchema), async (c) => {
1720
- const project = c.get('project');
1721
- const checkout = openHandoffCheckout(c);
1722
- if ('status' in checkout)
1723
- return c.json(checkout.body, checkout.status);
1724
- // Follows the safeParse convention (#429); the downstream allowlist match is the real
1725
- // injection guard, this just validates the shape.
1726
- const { target, path: relPath } = c.req.valid('json');
1727
- const dir = checkout.directory();
1728
- if (target === 'default') {
1729
- const worktree = checkout.defaultWorktree();
1730
- if (typeof worktree !== 'string')
1731
- return c.json(worktree.body, worktree.status);
1732
- return openRunDefaultApp(c, worktree, relPath, openFile);
1733
- }
1734
- const cliRunner = agentCliRunner(target);
1735
- if (cliRunner) {
1736
- return openRunCli(c, checkout.run, cliRunner, dir, project.root, { home: deps.home,
1737
- providerActionError, resumeCommand, handoffEnv, handoffFallbackCommand, openTerminal,
1738
- }, checkout);
1739
- }
1740
- return openRunApp(c, target, dir, openApp);
1741
- })
1742
- // Handoff journal plus stored records (hearsay-tools/cezarion#1809): unknown task is 404; no file is ''.
1743
- .get('/runs/:id/handoff', (c) => {
1744
- const { store } = c.get('project');
1745
- const run = store.getRun(c.req.param('id'));
1746
- if (!run)
1747
- return c.json({ error: 'not found' }, 404);
1748
- return c.text(renderHandoffRecords(readHandoff(store.claims.sourceDataDir(run.id), run.id), run.handoffRecords), 200, {
1749
- 'content-type': 'text/markdown; charset=utf-8',
1750
- });
1751
- })
1752
- .get('/runs/:id/images/:file', paramZodValidator(attachmentFileParamSchema), async (c) => {
1753
- const { store } = c.get('project');
1754
- const run = store.getRun(c.req.param('id'));
1755
- if (!run)
1756
- return c.json({ error: 'not found' }, 404);
1757
- const file = c.req.valid('param').file;
1758
- const path = await resolveAttachmentPathAsync(store.claims.sourceDataDir(run.id), run.id, file);
1759
- if (!path)
1760
- return c.json({ error: 'not found' }, 404);
1761
- const ext = file.split('.').pop() ?? '';
1762
- const image = IMAGE_TYPES[ext];
1763
- // An image answers exactly as it always has — the cockpit renders it in an `<img>`.
1764
- // Everything else is a user-supplied file (#950) and leaves under the download headers.
1765
- const type = image ?? FILE_TYPES[ext] ?? 'application/octet-stream';
1766
- return new Response(await readFile(path), {
1767
- headers: {
1768
- 'content-type': type,
1769
- 'cache-control': 'private, max-age=31536000, immutable',
1770
- ...(image
1771
- ? {}
1772
- : {
1773
- 'x-content-type-options': 'nosniff',
1774
- // Engine-generated names are `pasted-3.pdf`-shaped, but a header value is not the
1775
- // place to find out otherwise: anything exotic degrades to an underscore rather
1776
- // than to a quote that could split the header.
1777
- 'content-disposition': `attachment; filename="${file.replace(/[^A-Za-z0-9._-]/g, '_')}"`,
1778
- }),
1779
- },
1780
- });
1781
- })
1782
- // Task diff (spec 006): what this run changed — its worktree vs its base.
1783
- .get('/runs/:id/diff', async (c) => {
1784
- const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'existing-worktree' });
1785
- if ('body' in checkout)
1786
- return c.json(checkout.body, checkout.status);
1787
- if (!checkout.directory)
1788
- return c.text('(no worktree — this task ran directly in the repo working tree)');
1789
- const result = await worktreeDiff(checkout.directory, checkout.run.baseBranch ?? 'HEAD', undefined, checkout.beforeLiveIndex);
1790
- if (typeof result !== 'string')
1791
- return c.json({ error: result.error }, 409);
1792
- return c.text(result);
1793
- })
1794
- .get('/runs/:id/changes', async (c) => {
1795
- const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'working-directory' });
1796
- if ('body' in checkout)
1797
- return c.json(checkout.body, checkout.status);
1798
- const { run, directory: workingDirectory } = checkout;
1799
- const result = await collectChanges(workingDirectory, run.baseBranch ?? 'HEAD', {
1800
- beforeLiveIndex: checkout.beforeLiveIndex,
1801
- taskBranch: run.branch,
1802
- // Anchors a repointed worktree at the branch as this run found it (#751).
1803
- runStartedAt: run.startedAt,
1804
- // A read-only GET against the user's real checkout must never modify its index.
1805
- intentToAdd: run.worktreePath ? undefined : false,
1806
- });
1807
- if (!result.ok)
1808
- return c.json({ error: result.error }, 409);
1809
- return c.json(result.changes);
1810
- })
1811
- // The run's own commits (<base>..HEAD on the worktree branch) — the Commits tab.
1812
- .get('/runs/:id/commits', async (c) => {
1813
- const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'working-directory' });
1814
- if ('body' in checkout)
1815
- return c.json(checkout.body, checkout.status);
1816
- const { run, directory: workingDirectory } = checkout;
1817
- const result = await collectRunCommits(workingDirectory, run.baseBranch ?? 'HEAD');
1818
- if (!result.ok)
1819
- return c.json({ error: result.error }, 409);
1820
- return c.json({ commits: result.commits });
1821
- })
1822
- // One of the run's commits, structured like the Changes tab (reuses collectCommitChanges).
1823
- .get('/runs/:id/commit/:sha', async (c) => {
1824
- const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'working-directory' });
1825
- if ('body' in checkout)
1826
- return c.json(checkout.body, checkout.status);
1827
- const { directory: workingDirectory } = checkout;
1828
- const result = await collectCommitChanges(workingDirectory, c.req.param('sha'));
1829
- if (!result.ok)
1830
- return c.json({ error: result.error }, 409);
1831
- return c.json(result.commit);
1832
- })
1833
- .get('/runs/:id/file-link', paramZodValidator(artifactParamsSchema.omit({ artifactId: true })), queryZodValidator(fileLinkQuerySchema), async (c) => {
1834
- const { root, store } = c.get('project');
1835
- const checkout = runCheckout(c.get('project'), c.req.valid('param').id, 'read', { directory: 'recorded-path-or-root' });
1836
- if ('body' in checkout)
1837
- return c.json(checkout.body, checkout.status);
1838
- const { run, directory: workingDirectory } = checkout;
1839
- const query = c.req.valid('query');
1840
- const loaded = await loadFileLink({ dataDir: store.claims.sourceDataDir(run.id), runId: run.id, projectRoot: root, workingDirectory, path: query.path });
1841
- if (query.raw === '1') {
1842
- if (!loaded.imageBytes || loaded.preview.type !== 'file')
1843
- return c.json({ error: 'Only bounded raster images can be served inline.' }, 409);
1844
- return c.body(new Uint8Array(loaded.imageBytes).buffer, 200, {
1845
- 'content-type': rasterMime(loaded.preview.path), 'x-content-type-options': 'nosniff',
1846
- 'content-security-policy': "default-src 'none'; sandbox", 'cache-control': 'private, no-store',
1847
- });
1848
- }
1849
- return c.json(loaded.preview);
1850
- })
1851
- .get('/runs/:id/artifacts', paramZodValidator(artifactParamsSchema.omit({ artifactId: true })), async (c) => {
1852
- const { store } = c.get('project');
1853
- const id = c.req.valid('param').id;
1854
- if (!store.getRun(id))
1855
- return c.json({ error: 'not found' }, 404);
1856
- return c.json({ artifacts: await listArtifacts(runArtifactDirectory(store, id), id) });
1857
- })
1858
- .get('/runs/:id/artifacts/:artifactId', paramZodValidator(artifactParamsSchema), async (c) => {
1859
- const { store } = c.get('project');
1860
- const { id, artifactId } = c.req.valid('param');
1861
- if (!store.getRun(id))
1862
- return c.json({ error: 'not found' }, 404);
1863
- const entry = await readArtifact(runArtifactDirectory(store, id), id, artifactId);
1864
- if (!entry)
1865
- return c.json({ error: 'Published file is missing or unavailable.' }, 404);
1866
- return c.json(artifactPreview(entry.metadata, entry.bytes));
1867
- })
1868
- .get('/runs/:id/artifacts/:artifactId/metadata', paramZodValidator(artifactParamsSchema), async (c) => {
1869
- const { store } = c.get('project');
1870
- const { id, artifactId } = c.req.valid('param');
1871
- if (!store.getRun(id))
1872
- return c.json({ error: 'not found' }, 404);
1873
- const artifact = await readArtifactMetadata(runArtifactDirectory(store, id), id, artifactId);
1874
- if (!artifact)
1875
- return c.json({ error: 'Published file is missing or unavailable.' }, 404);
1876
- return c.json({ artifact });
1877
- })
1878
- .get('/runs/:id/artifacts/:artifactId/download', paramZodValidator(artifactParamsSchema), async (c) => {
1879
- const { store } = c.get('project');
1880
- const { id, artifactId } = c.req.valid('param');
1881
- if (!store.getRun(id))
1882
- return c.json({ error: 'not found' }, 404);
1883
- const entry = await readArtifact(runArtifactDirectory(store, id), id, artifactId);
1884
- if (!entry)
1885
- return c.json({ error: 'Published file is missing or unavailable.' }, 404);
1886
- return c.body(new Uint8Array(entry.bytes).buffer, 200, {
1887
- 'content-type': 'application/octet-stream', 'x-content-type-options': 'nosniff',
1888
- 'content-disposition': `attachment; filename="${entry.metadata.name.replace(/[^A-Za-z0-9._-]/g, '_')}"`,
1889
- 'content-security-policy': "default-src 'none'; sandbox", 'cache-control': 'private, no-store',
1890
- });
1891
- })
1892
- .get('/runs/:id/artifacts/:artifactId/image', paramZodValidator(artifactParamsSchema), async (c) => {
1893
- const { store } = c.get('project');
1894
- const { id, artifactId } = c.req.valid('param');
1895
- if (!store.getRun(id))
1896
- return c.json({ error: 'not found' }, 404);
1897
- const entry = await readArtifact(runArtifactDirectory(store, id), id, artifactId);
1898
- if (!entry)
1899
- return c.json({ error: 'Published file is missing or unavailable.' }, 404);
1900
- const mime = rasterMime(entry.metadata.name);
1901
- if (!mime)
1902
- return c.json({ error: 'Only raster images can be served inline.' }, 409);
1903
- return c.body(new Uint8Array(entry.bytes).buffer, 200, {
1904
- 'content-type': mime, 'x-content-type-options': 'nosniff',
1905
- 'content-security-policy': "default-src 'none'; sandbox", 'cache-control': 'private, no-store',
1906
- });
1907
- })
1908
- // Files tab: directory listing (path omitted or a dir) or file content
1909
- // (size-capped, binary flagged). Traversal-safe — readWorktreePath rejects
1910
- // anything escaping the worktree. `raw=1` (R5 Step 1.6) serves the BYTES of
1911
- // image files only, for the preview's inline <img> — never HTML/JS/etc., so
1912
- // no worktree file can become a same-origin document, and never past the
1913
- // size cap. The no-script CSP neutralizes SVG opened as a top-level URL.
1914
- //
1915
- // An `Accept` that asks for images reaches the same raw branch without the flag — which is
1916
- // what an `<img>` sends — while the flag still wins whenever it is present and `*<slash>*`
1917
- // (every `fetch`) still gets the JSON listing. See `negotiate`.
1918
- .get('/runs/:id/files', queryZodValidator(worktreeFilesQuerySchema), async (c) => {
1919
- const query = c.req.valid('query');
1920
- c.header('vary', 'Accept');
1921
- const wantsRaw = query.raw !== undefined
1922
- ? query.raw === '1'
1923
- : negotiate(c.req.header('accept'), FILE_FORMATS) === 'image/*';
1924
- const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'working-directory' });
1925
- if ('body' in checkout)
1926
- return c.json(checkout.body, checkout.status);
1927
- const { directory: workingDirectory } = checkout;
1928
- const result = await readWorktreePath(workingDirectory, query.path ?? '');
1929
- if (result.kind === 'invalid' || result.kind === 'missing') {
1930
- return c.json({ error: result.error }, 409);
1931
- }
1932
- if (result.kind === 'dir') {
1933
- return c.json({
1934
- // `as const` or the literal widens to `string` during Hono's route-type inference,
1935
- // which erases the discriminant a consumer narrows on — `entry.type === 'dir'` then
1936
- // leaves `never` and every field access on it fails. The wire was always 'dir'.
1937
- type: 'dir',
1938
- path: result.path,
1939
- entries: result.entries,
1940
- });
1941
- }
1942
- if (wantsRaw) {
1943
- const mime = imageMimeType(result.path);
1944
- if (mime === null || result.tooLarge) {
1945
- // `?raw=1` ASKED for bytes, so it hears why it cannot have them (a 409 with the
1946
- // reason). An `Accept` is only a preference, so a
1947
- // resource with no image representation falls THROUGH to the JSON answer below rather
1948
- // than turning a browser's navigation to a text file into an error.
1949
- if (query.raw !== undefined) {
1950
- const error = mime === null
1951
- ? `raw serving is limited to images: ${result.path}`
1952
- : `file too large to serve raw (${result.size} bytes): ${result.path}`;
1953
- return c.json({ error }, 409);
1954
- }
1955
- }
1956
- else {
1957
- const bytes = await readFile(join(workingDirectory, result.path));
1958
- return c.body(new Uint8Array(bytes).buffer, 200, {
1959
- 'content-type': mime,
1960
- 'x-content-type-options': 'nosniff',
1961
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox",
1962
- });
1963
- }
1964
- }
1965
- return c.json({
1966
- type: 'file',
1967
- path: result.path,
1968
- size: result.size,
1969
- binary: result.binary,
1970
- tooLarge: result.tooLarge,
1971
- ...(result.content !== undefined ? { content: result.content } : {}),
1972
- });
1973
- })
1974
- .post('/runs/:id/git/commit', jsonZodValidator(gitCommitSchema), async (c) => {
1975
- const checkout = runCheckout(c.get('project'), c.req.param('id'), 'mutate');
1976
- if ('status' in checkout)
1977
- return c.json(checkout.body, checkout.status);
1978
- const parsed = { data: c.req.valid('json') };
1979
- const result = await commitAll(checkout.directory, parsed.data.message);
1980
- if (!result.ok)
1981
- return c.json({ error: result.error }, 409);
1982
- return c.json({ committed: true, sha: result.sha });
1983
- })
1984
- .post('/runs/:id/git/push', async (c) => {
1985
- const { root: repoRoot } = c.get('project');
1986
- const checkout = runCheckout(c.get('project'), c.req.param('id'), 'mutate');
1987
- if ('status' in checkout)
1988
- return c.json(checkout.body, checkout.status);
1989
- const { run } = checkout;
1990
- const result = await pushCurrentBranch(checkout.directory);
1991
- if (!result.ok)
1992
- return c.json({ error: result.error }, 409);
1993
- const repoBase = forgeWebRoot((await getRepoInfo(repoRoot))?.remote) ?? undefined;
1994
- resolveForgeRoot(repoRoot, deps.forgeFactory).branchPushed(ownPullRequestNumbers(run, repoBase));
1995
- return c.json({
1996
- pushed: true,
1997
- branch: result.branch,
1998
- remote: result.remote,
1999
- upstreamSet: result.upstreamSet,
2000
- });
2001
- })
2002
- // Draft PR from the review gate (spec 009): final autosave → push →
2003
- // `gh pr create --draft`; on success the run completes as done with the PR
2004
- // badge. Failures come back as 409 with a `manual` merge command the GUI
2005
- // shows next to the toast. CEZ_DRY_RUN=1 fakes the URL (no push, no gh).
2006
- .post('/runs/:id/pr', async (c) => {
2007
- const { root: repoRoot, store } = c.get('project');
2008
- const id = c.req.param('id');
2009
- const checkout = runCheckout(c.get('project'), id, 'publish');
2010
- if ('status' in checkout)
2011
- return c.json(checkout.body, checkout.status);
2012
- const { release } = checkout;
2013
- try {
2014
- const prepared = await preparePublishCheckout(c.get('project'), id);
2015
- if ('status' in prepared)
2016
- return c.json(prepared.body, prepared.status);
2017
- const { run } = prepared;
2018
- const outcome = await resolveForgeRoot(repoRoot, deps.forgeFactory).createPR({
2019
- repoRoot,
2020
- run,
2021
- handoffText: readHandoff(store.claims.sourceDataDir(id), id),
2022
- });
2023
- if (!outcome.ok) {
2024
- return c.json({ error: outcome.error, manual: `git merge ${run.branch}` }, 409);
2025
- }
2026
- store.move(id, 'draft-pr', { pullRequestUrl: outcome.url });
2027
- store.eventLog.appendEvent(id, {
2028
- type: 'note',
2029
- message: `draft PR created: ${outcome.url}${outcome.dryRun ? ' (dry run — no real PR)' : ''}`,
2030
- });
2031
- return c.json({ url: outcome.url, dryRun: outcome.dryRun }, 201);
2032
- }
2033
- finally {
2034
- release();
2035
- }
2036
- })
2037
- // Archived tasks keep their worktree for inspection; this is the explicit
2038
- // "🧹 Remove worktree" cleanup (spec 006).
2039
- .post('/runs/:id/remove-worktree', protectFallbackRun('worktree'), async (c) => {
2040
- const { root: repoRoot, store } = c.get('project');
2041
- const id = c.req.param('id');
2042
- const checkout = runCheckout(c.get('project'), id, 'remove', {
2043
- claim: 'publish', checksActive: true, deletion: 'worktree',
2044
- nullClaimError: 'worktree cleanup pending — retry after cleanup is confirmed',
2045
- });
2046
- if ('status' in checkout)
2047
- return c.json(checkout.body, checkout.status);
2048
- const { run, release } = checkout;
2049
- try {
2050
- if (run.worktreePath)
2051
- await releaseThenRemoveWorktree({ previewHost: deps.previewHost }, id, repoRoot, run.worktreePath, run.branch);
2052
- store.updateRun(id, { worktreePath: undefined, branch: undefined });
2053
- return c.json({ removed: true });
2054
- }
2055
- finally {
2056
- release();
2057
- }
2058
- })
2059
- .delete('/runs/:id', protectFallbackRun('record'), async (c) => {
2060
- const { root: repoRoot, store } = c.get('project');
2061
- const id = c.req.param('id');
2062
- const checkout = runCheckout(c.get('project'), id, 'remove', {
2063
- claim: 'publish', checksActive: true, deletion: 'record',
2064
- nullClaimError: 'worktree cleanup pending — retry after cleanup is confirmed',
2065
- });
2066
- if ('status' in checkout)
2067
- return c.json(checkout.body, checkout.status);
2068
- const { run, release } = checkout;
2069
- try {
2070
- if (run.delegation?.role !== 'worker' && run.worktreePath)
2071
- await releaseThenRemoveWorktree({ previewHost: deps.previewHost }, id, repoRoot, run.worktreePath, run.branch);
2072
- return store.retention.deleteRun(id) ? c.json({ deleted: true }) : c.json({ error: 'history cleanup incomplete — retry deletion' }, 409);
2073
- }
2074
- finally {
2075
- release();
2076
- }
2077
- });
2078
- // ---- chained family: open-targets (project-scoped) ----
2079
- const openTargetsRoutes = new Hono()
2080
- .get('/open-targets', (c) => c.json({ targets: capabilities().localHandoff ? detectOpenTargets() : [] }))
2081
- // Open the PROJECT ROOT itself (Settings → "Project folder" → Open with). The run route
2082
- // above opens a task worktree and needs a run to name one; this is the repo the cockpit is
2083
- // scoped to, which the scope middleware has already resolved — so no path is accepted from
2084
- // the client and there is nothing to contain.
2085
- .post('/open-in', jsonZodValidator(openProjectInSchema), async (c) => {
2086
- const { root } = c.get('project');
2087
- if (!capabilities().localHandoff) {
2088
- return c.json({ error: 'local handoff is disabled — this cockpit runs in hosted mode (CEZ_REMOTE)' }, 409);
2089
- }
2090
- const { target } = c.req.valid('json');
2091
- // Refused here rather than left to the menu, on the same principle as the accounts route:
2092
- // a `cli:<runner>` handoff would START AN AGENT in the checkout everything else runs in a
2093
- // worktree to protect. Which app APPLIES is a property of the route, not of one client.
2094
- if (agentCliRunner(target) !== null) {
2095
- return c.json({ error: 'agent CLIs open a task worktree, not the project folder' }, 400);
2096
- }
2097
- if (!detectOpenTargets().some((candidate) => candidate.id === target)) {
2098
- return c.json({ error: `no such app on this machine: ${target}` }, 400);
2099
- }
2100
- const opened = await openApp(target, root);
2101
- if (!opened)
2102
- return c.json({ error: `could not open ${target}`, path: root }, 409);
2103
- return c.json({ opened: true, path: root });
2104
- });
2105
- // Agent screenshots and user attachments — what the run manager persisted out of tool
2106
- // results and pasted messages (`persistAttachment`). `basename` pins reads inside the
2107
- // run's own dir.
2108
- const IMAGE_TYPES = {
2109
- img: 'application/octet-stream', // Legacy catch-all image uploads retain inline headers.
2110
- png: 'image/png',
2111
- jpg: 'image/jpeg',
2112
- webp: 'image/webp',
2113
- gif: 'image/gif',
2114
- };
2115
- /**
2116
- * What a NON-image attachment is served as (#950). These are user-supplied bytes coming back
2117
- * from the cockpit's own origin, so the content type is the narrowest true one and it never
2118
- * travels alone: `nosniff` stops a browser from upgrading it to something executable, and an
2119
- * attachment disposition stops it from being rendered as a document in the cockpit's origin at
2120
- * all. Anything not named here keeps the pre-existing `application/octet-stream` default.
2121
- */
2122
- const FILE_TYPES = {
2123
- pdf: 'application/pdf',
2124
- txt: 'text/plain; charset=utf-8',
2125
- md: 'text/plain; charset=utf-8',
2126
- };
2127
- // ---- chained family: worktrees (project-scoped) ----
2128
- const worktreesRoutes = new Hono()
2129
- .get('/worktrees', async (c) => {
2130
- const { root: repoRoot, store } = c.get('project');
2131
- // The keep-limit the panel reports is the one the enforcer will actually
2132
- // apply — inherited from the workspace default when this repo sets none.
2133
- const keep = await resolveWorktreeRetention(repoRoot, deps.home);
2134
- const withWorktree = store.queries.listRunsWithWorktree();
2135
- // Listing is on-disk dirs only; parent liveness for #575 reads the store by id
2136
- // so a live `worktree: false` parent is not treated as gone (#570 honesty).
2137
- const runs = withWorktree.filter((r) => r.worktreePath && existsSync(r.worktreePath));
2138
- // The rows the enforcer would reclaim right now: reclaimable AND past the newest `keep`.
2139
- const getRun = memoizeRead((id) => store.getRun(id));
2140
- const workersOf = memoizeRead((id) => store.queries.listWorkersOf(id));
2141
- const pastKeep = new Set(selectReclaimableWorktrees(withWorktree, keep, getRun, workersOf));
2142
- const worktrees = await Promise.all(runs.map(async (r) => ({
2143
- runId: r.id,
2144
- title: r.title ?? r.id,
2145
- status: r.status,
2146
- branch: r.branch ?? null,
2147
- // POSIX `du` — degrades to null (Windows / du missing / error); never blocks.
2148
- sizeBytes: await cachedWorktreeSizeBytes(r.worktreePath),
2149
- finishedAt: r.finishedAt ?? null,
2150
- reclaimable: isReclaimable(r, getRun, workersOf),
2151
- pastKeep: pastKeep.has(r.id),
2152
- })));
2153
- // Total is null when any size degraded, so the panel never shows a wrong sum.
2154
- const totalBytes = worktrees.some((w) => w.sizeBytes === null)
2155
- ? null
2156
- : worktrees.reduce((sum, w) => sum + (w.sizeBytes ?? 0), 0);
2157
- return c.json({ worktrees, totalBytes, keep });
2158
- })
2159
- .post('/worktrees/reclaim', jsonZodValidator(() => reclaimBodySchema, { absent: ({}), message: 'invalid body' }), async (c) => {
2160
- const { root: repoRoot, store } = c.get('project');
2161
- // The body is validated (an empty or `{}` one is accepted) but carries nothing this
2162
- // handler reads; retention is best-effort, so 200 always.
2163
- const { manager } = c.get('project');
2164
- const reclaimed = await reclaimWorktrees(repoRoot, store, await resolveWorktreeRetention(repoRoot, deps.home), {
2165
- claim: (run) => manager.claimWorktreeReclaim(run.id),
2166
- previewHost: deps.previewHost,
2167
- });
2168
- if (reclaimed.length > 0) {
2169
- forgetRepoBranches(repoRoot);
2170
- forgetRepoRead(repoRoot);
2171
- }
2172
- return c.json({ reclaimed });
2173
- })
2174
- // One row's reclaim (issue 08 §B4): the DIRECTORY only, by retention's own rule and helper —
2175
- // the `cez/<id8>` branch is kept, which is what makes this safe to offer on every finished
2176
- // row. `/runs/:id/remove-worktree` (directory AND branch) stays the task screen's action.
2177
- .post('/worktrees/:runId/reclaim', paramZodValidator(reclaimRunParamsSchema), async (c) => {
2178
- const { root: repoRoot, store } = c.get('project');
2179
- const checkout = runCheckout(c.get('project'), c.req.valid('param').runId, 'remove', {
2180
- claim: 'reclaim', checksActive: false, deletion: 'inline',
2181
- nullClaimError: 'this worktree is in use or already reclaimed — only a finished task\'s worktree can be reclaimed',
2182
- });
2183
- if ('status' in checkout)
2184
- return c.json(checkout.body, checkout.status);
2185
- const { run, release } = checkout;
2186
- const worktreeReclaimedAt = await reclaimWorktree(repoRoot, store, run, { previewHost: deps.previewHost }).finally(release);
2187
- if (!worktreeReclaimedAt) {
2188
- return c.json({ error: await reclaimCheckoutError(run) }, 409);
2189
- }
2190
- forgetRepoBranches(repoRoot);
2191
- forgetRepoRead(repoRoot);
2192
- return c.json({ runId: run.id, worktreeReclaimedAt });
2193
- });
2194
- // ---- chained family: SSE streams (project-scoped) ----
2195
- const sseRoutes = new Hono()
2196
- .get('/runs/:id/events', paramZodValidator(runIdParamSchema), queryZodValidator(runEventsQuerySchema), async (c) => {
2197
- const { store, dataDir } = c.get('project');
2198
- const { id } = c.req.valid('param');
2199
- if (!store.getRun(id))
2200
- return c.json({ error: 'not found' }, 404);
2201
- const query = c.req.valid('query');
2202
- if (query.cursor) {
2203
- try {
2204
- await validateLiveCursor(store.claims.sourceDataDir(id), id, query.cursor);
2205
- }
2206
- catch (error) {
2207
- if (error instanceof HistoryCursorError)
2208
- return c.json({ error: error.message }, error.status);
2209
- throw error;
2210
- }
2211
- }
2212
- const lastEventId = Number.parseInt(c.req.header('Last-Event-ID') ?? '', 10);
2213
- const requestedAfter = Math.max(query.afterSeq ?? 0, Number.isSafeInteger(lastEventId) && lastEventId >= 0 ? lastEventId : 0);
2214
- return streamSSENoBuffer(c, async (stream) => {
2215
- const controller = new AbortController();
2216
- const stop = () => controller.abort();
2217
- const onRun = (write) => {
2218
- if (write.run.id === id)
2219
- void stream.writeSSE({ event: 'run', data: JSON.stringify(currentRecord(store, write)) });
2220
- };
2221
- const unsubscribe = store.lifecycle.subscribe({ 'run.created': onRun, 'run.updated': onRun });
2222
- stream.onAbort(() => { stop(); unsubscribe(); });
2223
- const feed = subscribeRunFeed({ store, dataDir }, {
2224
- projectId: c.get('project').id, runId: id, afterSeq: requestedAfter,
2225
- ...(query.cursor ? { cursor: query.cursor } : {}),
2226
- }, {
2227
- event: async (event) => {
2228
- await stream.writeSSE({ id: String(event.seq), event: isV2WireEventType(event.type) ? 'ui-event' : 'run-event', data: JSON.stringify(event) });
2229
- },
2230
- reset: () => { stop(); void stream.close(); },
2231
- // The legacy full-replay endpoint predates the finite batch limit. Preserve its
2232
- // ability to deliver a large persisted event; new multiplex clients rehydrate it.
2233
- }, controller.signal, Infinity);
2234
- const run = store.getRun(id);
2235
- if (run)
2236
- await stream.writeSSE({ event: 'run', data: JSON.stringify(run) });
2237
- try {
2238
- while (!stream.aborted && !controller.signal.aborted) {
2239
- await stream.writeSSE({ event: 'ping', data: '' });
2240
- await stream.sleep(15_000);
2241
- }
2242
- }
2243
- finally {
2244
- stop();
2245
- unsubscribe();
2246
- await feed;
2247
- }
2248
- });
2249
- })
2250
- // Global SSE: run-summary updates for the list view + inbox changes.
2251
- // Scoped `/p/:projectId/events` carries that project's stream in today's
2252
- // shape; the legacy unprefixed alias stays bound to the boot project ONLY
2253
- // (spec "Legacy aliases" — widening it would be a silent behavioral break;
2254
- // the all-project stream arrives as `/api/workspace/events` in step 2.8).
2255
- .get('/events', (c) => {
2256
- const { store } = c.get('project');
2257
- return streamSSENoBuffer(c, async (stream) => {
2258
- const onRun = (write) => void stream.writeSSE({ event: 'run', data: JSON.stringify(currentRecord(store, write)) });
2259
- const onDeleted = ({ runId: id }) => void stream.writeSSE({
2260
- event: 'run-deleted',
2261
- data: JSON.stringify({ id }),
2262
- });
2263
- // Live resource telemetry (#348): the sampler ticks ~every 2 s only
2264
- // while some run has a registered process; each tick is relayed as one
2265
- // `usage` message (runId → {cpuPct, rssBytes, procCount}). Never
2266
- // persisted — the NDJSON transcripts stay usage-free. The sampler is
2267
- // module-global, so a snapshot carries EVERY project's runs — split it
2268
- // by ownership and relay only this project's rows, never a stamped
2269
- // whole (multi-project spec, step 2.4: filtered, not stamped).
2270
- const offUsage = onUsage((usage) => {
2271
- const owned = {};
2272
- for (const [runId, sample] of Object.entries(usage)) {
2273
- if (store.getRun(runId))
2274
- owned[runId] = sample;
2275
- }
2276
- void stream.writeSSE({ event: 'usage', data: JSON.stringify(owned) });
2277
- });
2278
- const unsubscribe = store.lifecycle.subscribe({ 'run.created': onRun, 'run.updated': onRun, 'run.deleted': onDeleted });
2279
- stream.onAbort(() => {
2280
- unsubscribe();
2281
- offUsage();
2282
- });
2283
- while (!stream.aborted) {
2284
- await stream.writeSSE({ event: 'ping', data: '' });
2285
- await stream.sleep(15_000);
2286
- }
2287
- });
2288
- });
2289
- // ---- chained family: workspace SSE stream (workspace-level) ----
2290
- const workspaceEventsRoutes = new Hono()
2291
- // `?runs=summary` (hearsay-tools/cezarion#2730) carries list rows with a contiguous `seq`
2292
- // instead of full records; without it the stream stays byte-identical for older readers.
2293
- .get('/workspace/events', queryZodValidator(workspaceEventsQuerySchema), (c) => {
2294
- const mode = c.req.valid('query').runs === 'summary' ? 'summary' : 'full';
2295
- return streamSSENoBuffer(c, async (stream) => {
2296
- // The boot context never lives in the lazy map: the feed keeps it under its registry id
2297
- // (`resolveBootProject`, NOT `bootContext.id`, which may be the reserved alias when
2298
- // registration was suppressed).
2299
- const bootProject = await resolveBootProject();
2300
- // Attach, relay and `ready` happen in one synchronous block, so no frame can slip
2301
- // between the feed's `seq` and this connection's `ready`.
2302
- const detach = workspaceRunFeed.connect(bootProject, mode, (event, data) => void stream.writeSSE({ event, data }));
2303
- // Workspace-level events (project-added / project-removed / checkout-progress plus
2304
- // host-wide unstamped provider-status) — relayed verbatim under their own names. The
2305
- // feed detaches a removed project's store itself.
2306
- const offWorkspace = workspaceEvents.on((event, data) => {
2307
- void stream.writeSSE({ event, data: JSON.stringify(data) });
2308
- });
2309
- stream.onAbort(() => {
2310
- detach();
2311
- offWorkspace();
2312
- });
2313
- await stream.writeSSE({
2314
- event: 'ready',
2315
- data: JSON.stringify(mode === 'summary' ? { generation: serverGeneration, seq: workspaceRunFeed.seq() } : { generation: serverGeneration }),
2316
- });
2317
- while (!stream.aborted) {
2318
- await stream.writeSSE({ event: 'ping', data: '' });
2319
- await stream.sleep(15_000);
2320
- }
2321
- });
2322
- });
2323
- /** A ref-status list: `null` means malformed (the caller answers 400), `[]` means "not asked
2324
- * for". Absent and empty are the same request — neither names a number. */
2325
- const parseRefNumbers = (raw) => {
2326
- const parts = (raw ?? '').split(',').map((p) => p.trim()).filter(Boolean);
2327
- if (parts.length > GH_REF_STATUS_MAX)
2328
- return null;
2329
- const numbers = [];
2330
- for (const part of parts) {
2331
- const n = Number(part);
2332
- if (!Number.isInteger(n) || n <= 0 || String(n) !== part)
2333
- return null;
2334
- numbers.push(n);
2335
- }
2336
- return numbers;
2337
- };
2338
- const githubRoutes = new Hono()
2339
- .get('/github',
2340
- // `limit` stays a bare string: the handler's `Number.parseInt`/`Number.isFinite` fallback to
2341
- // 30 already accepts `?limit=banana`, and a numeric schema would 400 it instead. The
2342
- // cursors and done flags page each side on its own (hearsay-tools/cezarion#1183); the
2343
- // schema refuses a done side that also carries its cursor, and both sides done.
2344
- queryZodValidator(githubListQuerySchema), async (c) => {
2345
- const { root: repoRoot } = c.get('project');
2346
- const query = c.req.valid('query');
2347
- const limit = Number.parseInt(query.limit ?? '', 10);
2348
- return c.json(await resolveForgeRoot(repoRoot, deps.forgeFactory).list({
2349
- refresh: query.refresh === '1',
2350
- limit: Number.isFinite(limit) ? limit : 30,
2351
- issuesCursor: query.issuesCursor,
2352
- prsCursor: query.prsCursor,
2353
- issuesDone: query.issuesDone === '1',
2354
- prsDone: query.prsDone === '1',
2355
- }));
2356
- })
2357
- .get('/github/projects', queryZodValidator(githubProjectsQuerySchema), async (c) => {
2358
- return c.json(await resolveForgeRoot(c.get('project').root, deps.forgeFactory).projects(c.req.valid('query').generation));
2359
- })
2360
- .get('/github/comments/:kind/:number', queryZodValidator(refreshQuery), async (c) => {
2361
- const { root: repoRoot } = c.get('project');
2362
- const parsed = commentsParams.safeParse({
2363
- kind: c.req.param('kind'),
2364
- number: c.req.param('number'),
2365
- });
2366
- if (!parsed.success)
2367
- return c.json({ error: 'invalid kind or number' }, 400);
2368
- return c.json(await resolveForgeRoot(repoRoot, deps.forgeFactory).comments(parsed.data.kind, parsed.data.number, { refresh: c.req.valid('query').refresh === '1' }));
2369
- })
2370
- // One issue/PR by number, any state (#692) — the task page's item tabs. Same in-payload
2371
- // degrade as the siblings: `item: null` is "no such number", `available: false` is "could not
2372
- // ask"; never a 5xx.
2373
- .get('/github/items/:kind/:number', paramZodValidator(githubItemParamsSchema, { message: 'invalid kind or number' }), queryZodValidator(refreshQuery), async (c) => {
2374
- const { root: repoRoot } = c.get('project');
2375
- const { kind, number } = c.req.valid('param');
2376
- return c.json(await resolveForgeRoot(repoRoot, deps.forgeFactory).item(kind, number, { refresh: c.req.valid('query').refresh === '1' }));
2377
- })
2378
- // Lazy checks glyphs for on-screen PR rows (#664). Additive sibling of /api/github — the list
2379
- // call dropped `statusCheckRollup` (the dominant cost), so the glyph is hydrated here per
2380
- // visible row. `prs` is a comma-separated list of positive integers, capped at GH_CHECKS_MAX;
2381
- // anything malformed is a 400. Same in-payload availability degrade as the list (never a 5xx).
2382
- // `prs` is the one genuinely REQUIRED query key on this server, so it is the one validated
2383
- // strictly — `.min(1)` because `?prs=` answered `missing prs query` before it answered
2384
- // `invalid prs query`, and both spellings must keep their own words.
2385
- .get('/github/checks', queryZodValidator(githubChecksQuerySchema, { message: 'missing prs query' }), async (c) => {
2386
- const { root: repoRoot } = c.get('project');
2387
- const raw = c.req.valid('query').prs;
2388
- const parts = raw.split(',').map((p) => p.trim()).filter(Boolean);
2389
- if (parts.length === 0 || parts.length > GH_CHECKS_MAX)
2390
- return c.json({ error: 'invalid prs query' }, 400);
2391
- const numbers = [];
2392
- for (const part of parts) {
2393
- const n = Number(part);
2394
- if (!Number.isInteger(n) || n <= 0 || String(n) !== part)
2395
- return c.json({ error: 'invalid prs query' }, 400);
2396
- numbers.push(n);
2397
- }
2398
- return c.json(await resolveForgeRoot(repoRoot, deps.forgeFactory).checks(numbers));
2399
- })
2400
- // Comment counts for loaded list rows (hearsay-tools/cezarion#1183). The list defers them
2401
- // (`commentsDeferred`) because they were ~0.4 s of every page; the cockpit asks here after
2402
- // paint. Same shape and in-payload degrade as /github/checks: at most 100 positive numbers,
2403
- // 400 on anything malformed, never a 5xx.
2404
- .get('/github/comment-counts', queryZodValidator(githubCommentCountsQuerySchema, { message: 'invalid comment-counts query' }), async (c) => {
2405
- const { kind, numbers, refresh } = c.req.valid('query');
2406
- return c.json(await resolveForgeRoot(c.get('project').root, deps.forgeFactory).commentCounts(kind, numbers.split(',').map(Number), { refresh: refresh === '1' }));
2407
- })
2408
- // Search across ALL states (#730). Additive sibling of `/github`, which lists the OPEN set
2409
- // only (`gh issue/pr list` defaults to `--state open`) — so the tab's in-memory filter can
2410
- // never match a closed or merged item, and this is the path it falls back to. Same in-payload
2411
- // availability degrade as the list (never a 5xx); malformed params are a 400. Deliberately
2412
- // uncached: it is typed-into, not polled, and the driver's own cap bounds the work.
2413
- .get('/github/search', queryZodValidator(githubSearchQuerySchema, { message: 'invalid search query' }), async (c) => {
2414
- const { root: repoRoot } = c.get('project');
2415
- const { kind, q, limit } = c.req.valid('query');
2416
- const forge = resolveForgeRoot(repoRoot, deps.forgeFactory);
2417
- if (!forge.searchItems)
2418
- return c.json({ available: false, reason: 'GitHub is unavailable', items: [] });
2419
- return c.json(await forge.searchItems(kind, q, limit === undefined ? {} : { limit }));
2420
- })
2421
- // Batched status for the PR/issue chips a task table paints. Additive sibling of
2422
- // /github/checks and shaped like it: comma-separated positive integers, capped at
2423
- // GH_REF_STATUS_MAX per kind, malformed input is a 400, and an unreachable forge degrades in
2424
- // the payload. Unlike /github/checks BOTH keys are optional — a table may hold only issues —
2425
- // but at least one must name something, or the request asks for nothing.
2426
- .get('/github/ref-status', queryZodValidator(githubRefsQuerySchema), async (c) => {
2427
- const { root: repoRoot } = c.get('project');
2428
- const { prs, issues } = c.req.valid('query');
2429
- const parsedPrs = parseRefNumbers(prs);
2430
- const parsedIssues = parseRefNumbers(issues);
2431
- if (parsedPrs === null || parsedIssues === null)
2432
- return c.json({ error: 'invalid ref-status query' }, 400);
2433
- if (parsedPrs.length === 0 && parsedIssues.length === 0) {
2434
- return c.json({ error: 'missing prs or issues query' }, 400);
2435
- }
2436
- return c.json(await resolveForgeRoot(repoRoot, deps.forgeFactory).refStatus({ prs: parsedPrs, issues: parsedIssues }));
2437
- })
2438
- .get('/github/prs/:number/merge-state', paramZodValidator(mergeNumberParams, { message: 'invalid pull request number' }), queryZodValidator(refreshQuery), async (c) => {
2439
- const { root: repoRoot } = c.get('project');
2440
- const parsed = { data: c.req.valid('param') };
2441
- const forge = resolveProjectForge(await getRepoInfo(repoRoot));
2442
- if (!forge?.prMergeState)
2443
- return c.json({ available: false, reason: 'GitHub merge state is unavailable' });
2444
- return c.json(await forge.prMergeState(parsed.data.number, { refresh: c.req.valid('query').refresh === '1' }));
2445
- })
2446
- .post('/github/prs/:number/merge', paramZodValidator(mergeNumberParams, { message: 'invalid pull request number' }), jsonZodValidator(() => mergeBodySchema, { message: 'invalid merge request' }), async (c) => {
2447
- const { root: repoRoot } = c.get('project');
2448
- const parsedNumber = { data: c.req.valid('param') };
2449
- const body = { data: c.req.valid('json') };
2450
- const forge = resolveProjectForge(await getRepoInfo(repoRoot));
2451
- if (!forge?.mergePR)
2452
- return c.json({ error: 'GitHub merge is unavailable' }, 409);
2453
- const result = await forge.mergePR(parsedNumber.data.number, body.data);
2454
- if (result.merged) {
2455
- return c.json(result);
2456
- }
2457
- return c.json({
2458
- error: result.error,
2459
- ...(result.code ? { code: result.code } : {}),
2460
- ...(result.current ? { current: result.current } : {}),
2461
- }, result.status);
2462
- })
2463
- .get('/github/prs/:number/changes',
2464
- // Split out of one `safeParse` over both inputs, because a path param and the query string
2465
- // are separate validation targets to Hono and only a split makes each visible to the route
2466
- // type. Both keep the single 400 sentence the combined parse answered. `refresh` stays
2467
- // STRICT here (`?refresh=true` is a 400 today, unlike everywhere else on this server).
2468
- paramZodValidator(prChangesParams, { message: 'invalid pull request number or refresh flag' }), queryZodValidator(prChangesQuery, { message: 'invalid pull request number or refresh flag' }), async (c) => {
2469
- const { root: repoRoot } = c.get('project');
2470
- const parsed = { data: c.req.valid('param') };
2471
- const forge = resolveForgeRoot(repoRoot, deps.forgeFactory);
2472
- if (!forge.prDiff)
2473
- return c.json({ available: false, reason: 'GitHub is unavailable' });
2474
- try {
2475
- return c.json(await forge.prDiff(parsed.data.number, { refresh: c.req.valid('query').refresh === '1' }));
2476
- }
2477
- catch (err) {
2478
- if (err instanceof GithubPrNotFoundError)
2479
- return c.json({ error: err.message }, 404);
2480
- throw err;
2481
- }
2482
- });
2483
- // The full comment thread for one issue/PR (#499). Additive sibling of /api/github — lazy
2484
- // (fetched only while a detail view is open), zod-validated params, 400 on garbage, and the
2485
- // same in-payload availability degrade (gh missing / offline / 404 all render as a hint).
2486
- const commentsParams = z.object({
2487
- kind: z.enum(['issue', 'pr']),
2488
- number: z.coerce.number().int().positive(),
2489
- });
2490
- const branchForge = deps.branchForge ?? createGithubBranchForge({ forgeFactory: deps.forgeFactory });
2491
- const branchClassifyInput = (project) => classifyInputFor({ ...project, home: deps.home }, branchForge);
2492
- // ---- chained family: repo / git (project-scoped) ----
2493
- const repoRoutes = new Hono()
2494
- .get('/repo', async (c) => {
2495
- const { root: repoRoot, store } = c.get('project');
2496
- const info = await getRepoInfo(repoRoot);
2497
- if (!info)
2498
- return c.json({
2499
- info: null,
2500
- status: [],
2501
- log: [],
2502
- branches: [],
2503
- baseBranch: null,
2504
- tracking: null,
2505
- });
2506
- // Status stays fresh for edits made outside Squawk; only ref-derived reads are cached.
2507
- const [status, config] = await Promise.all([
2508
- getStatus(info.root),
2509
- loadConfig(repoRoot, deps.home),
2510
- ]);
2511
- // The helper validates refs and branch-owner evidence before reusing log attribution.
2512
- const refs = await readRepoRefs(info, config.baseBranch, store.queries);
2513
- return c.json({
2514
- info,
2515
- status,
2516
- log: refs.log,
2517
- branches: refs.branches,
2518
- baseBranch: config.baseBranch ?? null,
2519
- tracking: refs.tracking,
2520
- });
2521
- })
2522
- // Every local branch, classified (issue 08 §A/§B2) — cached on the refs state, so the
2523
- // sidebar's counts do not shell out on every render.
2524
- .get('/repo/branches', async (c) => {
2525
- const input = await branchClassifyInput(c.get('project'));
2526
- if (!input)
2527
- return c.json({ base: '', prStateKnown: false, branches: [], counts: { notLanded: 0, cleanup: 0 } });
2528
- return c.json(await readRepoBranches(input));
2529
- })
2530
- // The same classification's counts alone (hearsay-tools/cezarion#2029): the always-mounted Git
2531
- // sidebar reads these, so it never pays for a diff stat per branch.
2532
- .get('/repo/branches/counts', async (c) => {
2533
- const input = await branchClassifyInput(c.get('project'));
2534
- if (!input)
2535
- return c.json({ base: '', prStateKnown: false, counts: { notLanded: 0, cleanup: 0 }, allBranches: 0 });
2536
- return c.json(await readRepoBranchCounts(input));
2537
- })
2538
- // Delete local branches (issue 08 §B3). The server re-classifies and never trusts the
2539
- // client's class: nothing here can delete work that is not on the base without the typed
2540
- // confirmation, and nothing in use can be deleted at all.
2541
- .post('/repo/branches/delete', jsonZodValidator(deleteBranchesInputSchema), async (c) => {
2542
- const input = await branchClassifyInput(c.get('project'));
2543
- if (!input)
2544
- return c.json({ error: 'not a git repository', refused: [] }, 409);
2545
- const body = c.req.valid('json');
2546
- // The cockpit's checkout switch and pull hold this, not the worktree lock: without it a switch
2547
- // could check a candidate out after the delete read the worktree list, and `update-ref` would
2548
- // delete the branch HEAD now names.
2549
- const release = claimRepoGitMutation(input.root);
2550
- if (!release)
2551
- return c.json({ error: 'a branch switch or pull is running — try again when it finishes', refused: [] }, 409);
2552
- const result = await deleteBranches(input, body.names, body.confirm).finally(release);
2553
- forgetRepoRead(input.root);
2554
- if (result.deleted.length === 0) {
2555
- return c.json({ error: result.refused[0]?.reason ?? 'nothing was deleted', refused: result.refused }, 409);
2556
- }
2557
- return c.json(result, 200);
2558
- })
2559
- .get('/repo/diff', async (c) => {
2560
- const { root: repoRoot } = c.get('project');
2561
- const info = await getRepoInfo(repoRoot);
2562
- if (!info)
2563
- return c.text('not a git repository');
2564
- return c.text(await getDiff(info.root));
2565
- })
2566
- // One commit's message + stat + patch — the Repo view expands it inline.
2567
- // `?structured=1` is the ADDITIVE sibling (R5 Step 1.7): the new repo view's commit-diff
2568
- // shape `{sha, subject, author, when, files, stat}` with 409 + reason on failure. The
2569
- // legacy text answer below is what the route returns without the flag, in-band failure
2570
- // sentences included.
2571
- //
2572
- // `Accept: application/json` reaches the same structured answer without the flag, and
2573
- // `Accept: text/plain` asks for the blob; the flag still wins whenever it is present, and a
2574
- // request with no opinion still gets the blob. See `negotiate`.
2575
- .get('/repo/commit/:sha', queryZodValidator(commitQuerySchema), async (c) => {
2576
- const { root: repoRoot } = c.get('project');
2577
- c.header('vary', 'Accept');
2578
- const { structured } = c.req.valid('query');
2579
- const wantsJson = structured !== undefined
2580
- ? structured === '1'
2581
- : negotiate(c.req.header('accept'), COMMIT_FORMATS) === 'application/json';
2582
- const info = await getRepoInfo(repoRoot);
2583
- if (wantsJson) {
2584
- if (!info)
2585
- return c.json({ error: 'not a git repository' }, 409);
2586
- const result = await collectCommitChanges(info.root, c.req.param('sha'));
2587
- if (!result.ok)
2588
- return c.json({ error: result.error }, 409);
2589
- return c.json(result.commit);
2590
- }
2591
- if (!info)
2592
- return c.text('not a git repository');
2593
- try {
2594
- return c.text(await getCommit(info.root, c.req.param('sha')));
2595
- }
2596
- catch (err) {
2597
- return c.text(`(git show failed: ${err instanceof Error ? err.message : String(err)})`);
2598
- }
2599
- })
2600
- // Structured sibling of the text-blob /api/repo/diff above (protected
2601
- // surface, untouched): the same {files, stat} shape the session /changes
2602
- // route serves, here for the MAIN working tree's uncommitted changes vs
2603
- // HEAD (redesign R5 Step 1.3 — §"Git/session API additions").
2604
- .get('/repo/changes', async (c) => {
2605
- const { root: repoRoot } = c.get('project');
2606
- const info = await getRepoInfo(repoRoot);
2607
- if (!info)
2608
- return c.json({ error: 'not a git repository' }, 409);
2609
- // The user's REAL working tree — never stage into their index (a GET must not write).
2610
- const result = await collectChanges(info.root, 'HEAD', {
2611
- intentToAdd: false,
2612
- });
2613
- if (!result.ok)
2614
- return c.json({ error: result.error }, 409);
2615
- return c.json(result.changes);
2616
- })
2617
- .get('/repo/pull', async (c) => {
2618
- const { root } = c.get('project');
2619
- const result = await localPullBranches(root);
2620
- if ('error' in result)
2621
- return c.json(result, 409);
2622
- return c.json(result);
2623
- })
2624
- .post('/repo/pull', jsonZodValidator(repoPullInputSchema), async (c) => {
2625
- const { root, store, manager } = c.get('project');
2626
- const info = await getRepoInfo(root);
2627
- if (!info)
2628
- return c.json({ error: 'not a git repository' }, 409);
2629
- const config = await loadConfig(root, deps.home);
2630
- const result = await pullRepoCheckout(info.root, c.req.valid('json'), config.baseBranch,
2631
- // Every id, not the live set: the manager may still hold a run whose record already
2632
- // settled (a worker's execution winding down). Ids only, nothing decoded.
2633
- () => store.queries.listRunIds().some((id) => manager.isActive(id)));
2634
- forgetRepoRead(info.root);
2635
- if (!result.ok)
2636
- return c.json(result.value, 409);
2637
- return c.json(result.value, 200);
2638
- })
2639
- .post('/repo/branch', jsonZodValidator(() => repoBranchSchema), async (c) => {
2640
- const { root: repoRoot } = c.get('project');
2641
- const info = await getRepoInfo(repoRoot);
2642
- if (!info)
2643
- return c.json({ error: 'not a git repository' }, 409);
2644
- const release = claimRepoGitMutation(info.root);
2645
- if (!release)
2646
- return c.json({ error: 'A Git operation is already in progress for this repository.' }, 409);
2647
- try {
2648
- const input = c.req.valid('json');
2649
- const result = await createOrSwitchBranch(info.root, input.name, input.from);
2650
- forgetRepoBranches(info.root);
2651
- forgetRepoRead(info.root);
2652
- if (!result.ok)
2653
- return c.json({ error: result.error }, 409);
2654
- return c.json({ branch: result.branch, created: result.created });
2655
- }
2656
- finally {
2657
- release();
2658
- }
2659
- });
2660
- /** #917, hearsay-tools/squawk#914: setup and teardown commands run on the host. */
2661
- const WORKTREE_COMMANDS_HOSTED_ERROR = `Worktree setup and teardown commands are read-only on this remote cockpit. To allow remote edits, run \`${productIdentity().command} remote-settings enable\` on the machine running Squawk.`;
2662
- // The Settings → Agent defaults knobs in one read (R6 Step 1.5) — an ADDITIVE
2663
- // sibling of PUT /api/config below; /api/health keeps its protected shape.
2664
- const configAnswer = async (repoRoot, config) => {
2665
- const archive = resolveArchiveOnMerge(config, await loadWorkspaceConfig(deps.home.workspaceConfig));
2666
- const nativeModels = await readAgentModelDefaults(repoRoot);
2667
- const setup = reportWorktreeCommands(config.worktreeSetup);
2668
- const teardown = reportWorktreeCommands(config.worktreeTeardown);
2669
- const modelsLocked = agentModelsLocked(repoRoot, process.env, deps.home);
2670
- return {
2671
- archiveOnMerge: config.archiveOnMerge ?? null,
2672
- effectiveArchiveOnMerge: archive.enabled,
2673
- archiveOnMergeSource: archive.source,
2674
- baseBranch: config.baseBranch ?? null,
2675
- defaultRunner: config.defaultRunner,
2676
- systemPrompt: config.systemPrompt ?? null,
2677
- // Native defaults seed each runner independently. A Squawk preset remains
2678
- // selectable unless the operator opts into the fixed-model policy.
2679
- defaultModels: modelsLocked
2680
- ? nativeModels
2681
- : { ...nativeModels, ...config.defaultModels },
2682
- modelsLocked,
2683
- maxParallel: config.maxParallel,
2684
- memoryLimitMb: config.memoryLimitMb ?? null,
2685
- // Count-based worktree retention (#483): keep the last N finished worktrees
2686
- // on disk. 0 = unlimited. Always materialized (schema default 10).
2687
- worktreeRetention: config.worktreeRetention,
2688
- // Live title updates (task auto-naming spec): tri-state — null means "no
2689
- // config key, the CEZ_TITLE_UPDATES env default (ON) decides".
2690
- liveTitleUpdates: config.liveTitleUpdates ?? null,
2691
- // Optional review gate (#489): tri-state — null means "no config key, the
2692
- // CEZ_REVIEW_GATE env default (OFF) decides".
2693
- reviewGate: config.reviewGate ?? null,
2694
- // Worktree setup (#917) and teardown (hearsay-tools/squawk#914): an invalid value is reported.
2695
- worktreeSetup: setup.value, worktreeSetupIssue: setup.issue,
2696
- worktreeTeardown: teardown.value, worktreeTeardownIssue: teardown.issue,
2697
- };
2698
- };
2699
- // ---- chained family: per-repo config (project-scoped) ----
2700
- const configRoutes = new Hono()
2701
- .get('/config', async (c) => {
2702
- const repoRoot = c.get('project').root;
2703
- return c.json(await configAnswer(repoRoot, await loadConfig(repoRoot, deps.home)));
2704
- })
2705
- .put('/config', jsonZodValidator(() => setConfigSchema, { runners: { ids: ['defaultRunner'], keys: ['defaultModels'] } }), async (c) => {
2706
- const { root: repoRoot, dataDir } = c.get('project');
2707
- const parsed = { data: c.req.valid('json') };
2708
- if (agentModelsLocked(repoRoot, process.env, deps.home) && parsed.data.defaultModels !== undefined) {
2709
- return c.json({ error: AGENT_MODELS_LOCKED_ERROR }, 409);
2710
- }
2711
- // Host commands need settings administration (hearsay-tools/cezarion#2428), checked before any write.
2712
- if ([parsed.data.worktreeSetup, parsed.data.worktreeTeardown].some((v) => v !== undefined) && !capabilities().settingsAdmin) {
2713
- return c.json({ error: WORKTREE_COMMANDS_HOSTED_ERROR }, 409);
2714
- }
2715
- const refused = await writeMergedConfig(dataDir, parsed.data).catch((err) => ({ failed: err instanceof Error ? err.message : String(err) }));
2716
- if (typeof refused === 'object')
2717
- return c.json({ error: refused.failed }, 500);
2718
- if (refused !== undefined)
2719
- return c.json({ error: refused }, 409);
2720
- if (parsed.data.archiveOnMerge !== undefined)
2721
- deps.archiveOnMergeChanged?.();
2722
- // Pre-R6 answer shape ({baseBranch, defaultRunner}) + additive R6 fields.
2723
- return c.json(await configAnswer(repoRoot, await loadConfig(repoRoot, deps.home)));
2724
- });
2725
- // ---- chained family: agent-config (project-scoped) -----------------------
2726
- // Agent config is project-scoped (spec #404, adapted to the multi-project
2727
- // route seam from #521): handlers resolve the selected repo through the
2728
- // same ProjectContext as every other mirrored route. Chained (not statements)
2729
- // so `AppType` carries it — see `healthRoutes`.
2730
- const agentConfigRoutes = new Hono()
2731
- .get('/agent-config', async (c) => {
2732
- const editable = capabilities().settingsAdmin;
2733
- return c.json(await listAgentConfig(c.get('project').root, process.env, editable));
2734
- })
2735
- .get('/agent-config/:id', async (c) => {
2736
- const id = c.req.param('id');
2737
- const def = findConfigFile(id);
2738
- if (!def)
2739
- return c.json({ error: 'unknown config file' }, 404);
2740
- if (def.tracked === 'outside-repo' && !capabilities().settingsAdmin) {
2741
- const error = `this file lives in your home directory and is not served on a remote cockpit — run \`${productIdentity().command} remote-settings enable\` on the host to allow it`;
2742
- return c.json({ error }, 409);
2743
- }
2744
- const read = await readConfigFile(id, c.get('project').root);
2745
- if (read === null)
2746
- return c.json({ error: 'unknown config file' }, 404);
2747
- if ('error' in read)
2748
- return c.json({ error: read.error }, 500);
2749
- return c.json(read);
2750
- })
2751
- .put('/agent-config/:id', jsonZodValidator(setAgentConfigSchema), async (c) => {
2752
- // Hooks and MCP commands run on the host: writes need settings administration (ADR 0055),
2753
- // re-gated on every request.
2754
- if (!capabilities().settingsAdmin) {
2755
- return c.json({
2756
- error: `editing agent config is disabled on this remote cockpit — run \`${productIdentity().command} remote-settings enable\` on the host to allow it`,
2757
- }, 409);
2758
- }
2759
- const parsed = { data: c.req.valid('json') };
2760
- const out = await writeConfigFile(c.req.param('id'), parsed.data.content, parsed.data.version, c.get('project').root);
2761
- if (out === null)
2762
- return c.json({ error: 'unknown config file' }, 404);
2763
- if (!out.ok)
2764
- return c.json({ error: out.error }, out.status);
2765
- return c.json(out.read);
2766
- });
2767
- // ---- assemble the chained families --------------------------------------
2768
- // Every chained family is registered ONCE and mounted into the versioned table. There is no
2769
- // second, unversioned spelling: `/api/*` was removed once the whole API was reachable under
2770
- // `/api/v1`. One surface means one thing to keep working, and
2771
- // it is the one the typed client describes.
2772
- //
2773
- // MOUNT ORDER IS REGISTRATION ORDER. Hono matches in the order routes were added, so each
2774
- // family keeps its internal order and the families keep theirs relative to each other.
2775
- //
2776
- // Written as ONE chained expression because that is the only shape Hono can infer route types
2777
- // from — it is what puts these routes in `AppType`, and so in the typed client.
2778
- // ---- chained family: agent webhooks (hearsay-tools/cezarion#1576, project-scoped) ----
2779
- // What `cez webhook` calls from inside a task: list the webhooks the owner exposed to agents in
2780
- // this project, and send one report through one of them. A webhook closed to agents answers
2781
- // the same 404 as an unknown one, so this interface cannot even confirm it exists.
2782
- const agentWebhooksRoutes = new Hono()
2783
- .get('/agent-webhooks', async (c) => {
2784
- const project = c.get('project');
2785
- const body = { webhooks: agentWebhooks(await registryEntry(project.id, project.root, deps.home).catch(() => undefined)) };
2786
- return c.json(body);
2787
- })
2788
- .post('/agent-webhooks/:webhook', paramZodValidator(agentWebhookParamsSchema.pick({ webhook: true })), jsonZodValidator(sendAgentReportInputSchema), async (c) => {
2789
- const project = c.get('project');
2790
- const { webhook: ref } = c.req.valid('param');
2791
- const entry = await registryEntry(project.id, project.root, deps.home).catch(() => undefined);
2792
- const webhook = agentWebhook(entry, ref);
2793
- if (!entry || !webhook)
2794
- return c.json({ error: `no webhook named "${ref}" is open to agents in this project — run \`${productIdentity().command} webhook list\`` }, 404);
2795
- const outcome = await sendAgentReport({
2796
- projectId: entry.id,
2797
- webhook,
2798
- input: c.req.valid('json'),
2799
- store: project.store,
2800
- origin: taskWebhooks.currentOrigin(),
2801
- fetch: deps.taskWebhookFetch,
2802
- });
2803
- const body = { ...outcome, webhook: { id: webhook.id, name: webhook.name } };
2804
- return c.json(body);
622
+ const runsRoutes = createRunsRoutes({
623
+ home: deps.home,
624
+ forgeFactory: deps.forgeFactory,
625
+ delegation: deps.delegation,
626
+ workerCleanup: deps.workerCleanup,
627
+ previewHost: deps.previewHost,
628
+ capabilities,
629
+ modelCatalog,
630
+ providerStatus,
631
+ providerActionError,
632
+ resolveWorkspaceProfile,
633
+ projectRegistryEntry,
634
+ taskWebhooks,
635
+ openTerminal,
636
+ openFile,
637
+ openApp,
638
+ });
639
+ const openTargetsRoutes = createOpenTargetsRoutes({ capabilities, openApp });
640
+ const worktreesRoutes = createWorktreesRoutes({ home: deps.home, previewHost: deps.previewHost });
641
+ const sseRoutes = createSseRoutes();
642
+ const workspaceEventsRoutes = createWorkspaceEventsRoutes({
643
+ serverGeneration,
644
+ resolveBootProject,
645
+ workspaceRunFeed,
646
+ workspaceEvents,
2805
647
  });
648
+ const githubRoutes = createGithubRoutes({ forgeFactory: deps.forgeFactory, resolveProjectForge });
649
+ const repoRoutes = createRepoRoutes({ home: deps.home, forgeFactory: deps.forgeFactory, branchForge: deps.branchForge });
650
+ const configRoutes = createConfigRoutes({ home: deps.home, capabilities, archiveOnMergeChanged: deps.archiveOnMergeChanged });
651
+ const agentConfigRoutes = createAgentConfigRoutes(capabilities);
652
+ const agentWebhooksRoutes = createAgentWebhooksRoutes({ home: deps.home, taskWebhooks, taskWebhookFetch: deps.taskWebhookFetch });
2806
653
  const v1 = new Hono()
2807
654
  .use('*', resolveProjectScope)
2808
655
  .route('/', skillsRoutes)
@@ -2823,173 +670,15 @@ export function createApp(deps) {
2823
670
  .route('/', agentConfigRoutes);
2824
671
  projectRoutePaths = new Set(v1.routes.filter((route) => route.method !== 'ALL')
2825
672
  .flatMap((route) => [V1_PREFIX, V1_SCOPED_PREFIX].map((prefix) => `${route.method} ${prefix}${route.path}`)));
2826
- // ---- chained family: the cross-project run index (workspace-level) -------
2827
- /**
2828
- * How many ARCHIVED root runs each project may contribute, newest first (#864). The index is a
2829
- * FINDER, not a listing: every unarchived ROOT run is in it (so a project's pills miss nothing
2830
- * live or unread), and older archived runs are reached through `GET /workspace/runs-search` and
2831
- * the project's own archived pages. Owned workers are never in it: the pills, ⌘K and the global
2832
- * Tasks page list no workers, and a parent's wait label comes from its own delegation. `truncated` names the projects this bit, so a consumer never
2833
- * has to pretend the list is complete.
2834
- */
2835
- const RUNS_INDEX_PER_PROJECT = ARCHIVED_WINDOW;
2836
- /**
2837
- * Every number a run MENTIONS — a superset of what its chip will show.
2838
- *
2839
- * Deliberately not `taskReference()`'s rule: which of a run's references is displayed is the
2840
- * cockpit's decision (#407, #526), and re-deriving it here would be a second rule that drifts
2841
- * from the first. This feeds a CACHE READ, which costs nothing per number, so asking about one
2842
- * the client will not paint is free and asking about one it will is the whole point.
2843
- */
2844
- const mentionedReferenceNumbers = (run) => {
2845
- const numbers = (run.pullRequests ?? []).map(pr => pr.number);
2846
- for (const url of [run.pullRequestUrl, run.referencedPullRequestUrl, run.referencedIssueUrl]) {
2847
- const number = url ? refNumberFromUrl(url) : null;
2848
- if (number !== null)
2849
- numbers.push(number);
2850
- }
2851
- for (const number of [run.prNumber, run.issueNumber, run.markerRefs?.pr, run.markerRefs?.issue]) {
2852
- if (typeof number === 'number' && Number.isInteger(number) && number > 0)
2853
- numbers.push(number);
2854
- }
2855
- return numbers;
2856
- };
2857
- /**
2858
- * `GET /workspace/runs-index` — every registered project's recent tasks in one slim answer, so
2859
- * ⌘K can find a task without knowing which project it lives in.
2860
- *
2861
- * Workspace-level and single-mount for the obvious reason: a project-scoped spelling of "all
2862
- * projects" is a contradiction. The per-project source is chosen the same way the automation
2863
- * coordinator's boot fan-out chooses it (`bootContext` for the boot project, `contexts.peek`
2864
- * for anything this process already owns, disk otherwise) — and never `contexts.context()`,
2865
- * which would build a context, prune worktrees and `recover()` running agents. Typing in a
2866
- * search box must not resume work; see `runs/run-index.ts`.
2867
- */
2868
- const coldRepoHandles = new ColdRepoHandles(deps.forgeFactory);
2869
- /**
2870
- * Every registered project whose runs can be read, and its owned store when this process holds
2871
- * one (`bootContext` for the boot project, `contexts.peek` otherwise) — never a built context.
2872
- * Without a store, the caller reads the project cold from `dataDir` with `handle`. The source
2873
- * rule both workspace run routes share, so the index and the search can never disagree on it.
2874
- */
2875
- const projectRunSources = async () => {
2876
- let projects = [];
2877
- try {
2878
- projects = await workspaceProjects.listProjects();
2879
- }
2880
- catch {
2881
- // unreadable workspace — no rows, never a 500. The palette degrades to the active
2882
- // project's own run list, which it holds either way.
2883
- }
2884
- const bootId = await resolveBootProject(projects);
2885
- coldRepoHandles.retainRoots(new Set(projects
2886
- .filter((project) => project.status !== 'missing' && project.id !== bootId && !contexts.peek(project.id))
2887
- .map((project) => project.root)));
2888
- // An unfinished migration finishes first. No folder or a fence: no runs. `not-git` still has an `.ai/cezar` worth indexing.
2889
- return (await prepareProjects(projects, { ownership: deps.ownership, homes: [deps.home] })).filter((project) => project.status !== 'missing' && !projectAdmissionRefusal(projectPaths(project.root).write)).map((project) => {
2890
- const owned = project.id === bootId ? bootContext : contexts.peek(project.id);
2891
- // A cold project's repository identity only: asking for an owned one starts a discovery
2892
- // nothing reads.
2893
- return { project, store: owned?.store, dataDir: projectPaths(project.root).write, handle: owned ? undefined : coldRepoHandles.get(project.root) };
2894
- });
2895
- };
2896
- /**
2897
- * One project's contribution to a workspace run route. An owned store throws what its database
2898
- * throws (busy, damaged); like a cold project that cannot be read, it then contributes nothing,
2899
- * so one project never fails every project's index or search (#864).
2900
- */
2901
- const readProjectRuns = (projectId, read) => {
2902
- try {
2903
- return read();
2904
- }
2905
- catch (error) {
2906
- console.warn(`[hsq] runs of project ${projectId} could not be read for the workspace run index: ${error instanceof Error ? error.message : String(error)}`);
2907
- return { runs: [], truncated: false };
2908
- }
2909
- };
2910
- const runsIndexRoutes = new Hono()
2911
- .get('/workspace/runs-index', async (c) => {
2912
- const runs = [];
2913
- const truncated = [];
2914
- // Statuses the server already holds, shipped WITH the rows that carry the references. The
2915
- // cockpit would otherwise ask for them a beat after the table paints — one round trip per
2916
- // project, and a visible flash of un-coloured chips before it lands. Cache-only, so this
2917
- // never touches `gh` and never slows the index down; anything cold stays absent and the
2918
- // lazy `/github/ref-status` route fills it in.
2919
- const referenceStatuses = {};
2920
- const sources = await projectRunSources();
2921
- // Read after the last await and before the synchronous reads below: every frame at or below
2922
- // it is in this snapshot, and a frame above it is newer (hearsay-tools/cezarion#2730).
2923
- const eventSeq = workspaceRunFeed.seq();
2924
- for (const { project, store: owned, dataDir, handle } of sources) {
2925
- // Both sources answer the same window, newest first: every unarchived run, plus the
2926
- // newest archived roots (#864). An owned project lays its held records over its rows; a
2927
- // cold one reads its stored summaries, at most one archived root past the window.
2928
- //
2929
- // Archived runs are INCLUDED. The active project's rows reach the palette through
2930
- // `GET /run-summaries`, which carries them too, and excluding them here would mean a task
2931
- // is findable while you stand in its project and vanishes the moment you leave — the
2932
- // exact asymmetry a cross-project finder exists to remove.
2933
- const window = readProjectRuns(project.id, () => owned
2934
- ? owned.queries.listRunSummaries({ archivedWindow: RUNS_INDEX_PER_PROJECT, roots: true })
2935
- : readRunIndexFromDisk(dataDir, { handle, archivedWindow: RUNS_INDEX_PER_PROJECT, roots: true }));
2936
- if (window.truncated)
2937
- truncated.push(project.id);
2938
- const recent = window.runs.map(withLiveUsage);
2939
- const mentioned = [];
2940
- for (const run of recent) {
2941
- runs.push({ projectId: project.id, ...run });
2942
- mentioned.push(...mentionedReferenceNumbers(run));
2943
- }
2944
- if (mentioned.length > 0) {
2945
- const cached = resolveForgeRoot(project.root, deps.forgeFactory).cachedRefStatuses(mentioned);
2946
- // Only when something was actually warm. A project key holding two empty maps is noise
2947
- // that every consumer would have to look past, and it would blur the one rule this
2948
- // payload has: absent means nothing is known.
2949
- if (Object.keys(cached.prs).length > 0 || Object.keys(cached.issues).length > 0) {
2950
- referenceStatuses[project.id] = cached;
2951
- }
2952
- }
2953
- }
2954
- runs.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
2955
- const body = {
2956
- runs,
2957
- perProjectLimit: RUNS_INDEX_PER_PROJECT,
2958
- truncated,
2959
- referenceStatuses,
2960
- generation: serverGeneration,
2961
- eventSeq,
2962
- };
2963
- return c.json(body);
2964
- })
2965
- /**
2966
- * `GET /workspace/runs-search` (#864) — every registered project's ROOT runs, archived or not,
2967
- * that match `q`, newest first: what lets ⌘K find a run past a project's window. Same source
2968
- * rule and the same side-effect-free contract as the index above.
2969
- */
2970
- .get('/workspace/runs-search', queryZodValidator(runsSearchQuerySchema), async (c) => {
2971
- const { q, limit = RUNS_SEARCH_PER_PROJECT_MAX } = c.req.valid('query');
2972
- const runs = [];
2973
- const truncated = [];
2974
- const tokens = searchTokens(q);
2975
- for (const { project, store: owned, dataDir, handle } of await projectRunSources()) {
2976
- // The palette filters its rows by project name too, so a token naming this project is
2977
- // already satisfied here: `shop database` searches shop for `database` (#864 review). A
2978
- // query that only names the project adds nothing past the index's rows for it.
2979
- const name = project.name.toLowerCase();
2980
- const rest = tokens.filter((token) => !name.includes(token));
2981
- if (rest.length === 0)
2982
- continue;
2983
- const scoped = rest.join(' ');
2984
- const found = readProjectRuns(project.id, () => owned ? owned.queries.searchRunSummaries(scoped, limit) : searchRunIndexFromDisk(dataDir, scoped, { handle, limit }));
2985
- if (found.truncated)
2986
- truncated.push(project.id);
2987
- for (const run of found.runs)
2988
- runs.push({ projectId: project.id, ...withLiveUsage(run) });
2989
- }
2990
- runs.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
2991
- const body = { runs, truncated };
2992
- return c.json(body);
673
+ const runsIndexRoutes = createRunsIndexRoutes({
674
+ loadPreparedProjects: (projects) => prepareProjects(projects, { ownership: deps.ownership, homes: [deps.home] }),
675
+ forgeFactory: deps.forgeFactory,
676
+ bootContext,
677
+ contexts,
678
+ workspaceProjects,
679
+ workspaceRunFeed,
680
+ serverGeneration,
681
+ withLiveUsage,
2993
682
  });
2994
683
  // Workspace-level families answer for the whole workspace, so they are single-mount: never a
2995
684
  // project-scoped spelling, which would be a second surface to protect with no consumer.