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

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,38 +1,14 @@
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';
1
+ import { runCheckout, preparePublishCheckout } from './run-checkout.js';
7
2
  import { adoptFallbackControl, protectFallbackRun, runArtifactDirectory } from './project-run-files.js';
8
- import { deleteSavedWorkflow } from './workflow-files.js';
9
3
  import { projectPaths, fallbackProjectWriteError } from '../project-paths.js';
10
- import { productIdentity } from '../home/identity.js';
11
- import { productEnv } from '../core/product-env.js';
12
4
  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
5
  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';
6
+ import { worktreeFilesQuerySchema } from '../contract/index.js';
7
+ import { gitCommitSchema } from '../contract/index.js';
25
8
  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
9
  import { imageMimeType } from '../contract/index.js';
32
10
  import { providerForActiveRun } from '../contract/index.js';
33
11
  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
12
  import { permissionDecisionSchema } from '../contract/index.js';
37
13
  import { runIdParamSchema as permissionRunIdParamSchema } from '../contract/index.js';
38
14
  import { CheckoutProgressCache } from './checkout-progress.js';
@@ -40,66 +16,37 @@ import { createWorkspaceLiveRoutes } from './workspace-live-routes.js';
40
16
  import { createActivityRoutes } from './activity-routes.js';
41
17
  import { createRunnersRoutes } from './runners-routes.js';
42
18
  import { createWorkspaceProjects, createWorkspaceProjectContexts, createTaskWebhooks } from './workspace-projects.js';
43
- import { subscribeRunFeed } from './run-event-feed.js';
44
19
  import { latestSession } from '../contract/index.js';
45
- import { probeWritableDir } from './probe-writable-dir.js';
46
20
  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';
21
+ import { archivedRunsQuerySchema, createRunInputSchema, runSummariesQuerySchema } from '../contract/index.js';
51
22
  import { DelegationService } from '../delegation/service.js';
52
23
  import { runRelationships } from './run-relationships.js';
53
24
  import { delegationFailure } from '../delegation/routes.js';
54
- import { githubItemParamsSchema } from '../contract/index.js';
55
25
  import { workerDestroyRequestSchema, workerEmptyRequestSchema, runRelationshipsSchema } from '../contract/index.js';
56
- import { existsSync } from 'node:fs';
57
26
  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';
27
+ import { readFile } from 'node:fs/promises';
66
28
  import { basename, dirname, join } from 'node:path';
67
29
  import { fileURLToPath } from 'node:url';
68
30
  import { Hono } from 'hono';
69
31
  import { bodyLimit } from 'hono/body-limit';
70
32
  import { matchedRoutes } from 'hono/route';
71
33
  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';
34
+ import { pinRunInputSchema, archiveFinishedRequestSchema, markAllReadRequestSchema, notifyRunInputSchema } from '../contract/index.js';
79
35
  // A contract VALUE, like `workspaceUiStateSchema` in workspace/migrations.ts — the request
80
36
  // schema this route validates with is the same one the client compiles against.
81
- import { openProjectInSchema } from '../contract/index.js';
82
37
  import { registeredRunnerId, registeredRunners, resolveRunnerId, runnerDefinition } from '../core/runner-registry.js';
83
- import { REMOVED_RUNNER_IDS } from '../runs/legacy-run-rows.js';
84
38
  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';
39
+ import { taskWebhooks as taskWebhookList } from '../workspace/webhooks.js';
87
40
  import { environmentStamp } from '../core/backend-detect.js';
88
41
  import { AGENT_MODELS_LOCKED_ERROR, agentModelsLocked } from '../core/agent-model-policy.js';
89
42
  import { createModelsRoutes } from './models-routes.js';
90
43
  import { createProviderSignInRoutes } from './provider-sign-in-routes.js';
91
44
  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
45
  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';
46
+ import { HistoryCursorError, deriveRunContextEvents, readRunHistoryPage } from '../runs/event-history.js';
47
+ import { ARCHIVED_WINDOW } from '../runs/run-index.js';
99
48
  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';
49
+ import { runHistoryQuerySchema, runIdParamSchema } from '../contract/index.js';
103
50
  import { resolveAttachmentPathAsync } from '../workflows/attachment-path.js';
104
51
  import { artifactParamsSchema, fileLinkQuerySchema } from '../contract/index.js';
105
52
  import { listArtifacts, readArtifact, readArtifactMetadata } from '../artifacts/store.js';
@@ -108,41 +55,27 @@ import { toPastedContent } from '../workflows/pasted-content.js';
108
55
  import { isUntouchedCancelledRun } from '../workflows/run/run-guards.js';
109
56
  import { worktreeDiff } from '../git-worktree.js';
110
57
  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';
58
+ import { getRepoInfo } from './git.js';
113
59
  import { createHealthCache, HEALTH_TTL_MS } from './health-cache.js';
114
- import { COMMIT_FORMATS, FILE_FORMATS, negotiate } from './accept-negotiation.js';
60
+ import { FILE_FORMATS, negotiate } from './accept-negotiation.js';
115
61
  import { authorityOfHost, authorityOfOrigin, hostnameOfHost, hostnameOfOrigin } from './host-authority.js';
116
62
  import { pluginHealth, pluginLoadReport } from '../plugin/loader.js';
117
63
  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';
64
+ import { collectChanges, collectCommitChanges, collectRunCommits, commitAll, pushCurrentBranch, readWorktreePath } from './git-changes.js';
65
+ import { healthConfig, loadConfig } from '../config.js';
66
+ import { defaultWorkspaceConfig, loadWorkspaceConfig } from '../workspace/config.js';
129
67
  import { DEFAULT_AGENT_ACCOUNT_ID, defaultAgentAccountStore, loadAgentAccounts } from '../workspace/agent-accounts.js';
130
68
  import { defaultAgentProfile, listAgentProfiles, resolveStoredProfile } from '../workspace/agent-profiles.js';
131
69
  import { profileEnv } from '../core/agent-profiles.js';
132
70
  import { shellQuote, withEnvPrefix } from '../core/shell-env.js';
133
71
  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';
72
+ import { createWorkspaceRunFeed } from './workspace-run-feed.js';
138
73
  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';
74
+ import { resolveForge, forgeWebRoot, resolveForgeRoot } from './forge/index.js';
75
+ import { withProjectAdmission } from './cockpit-ownership.js';
143
76
  import { prepareProjects } from '../project-migration/auto.js';
144
77
  import { freshCliHandoff, openRunApp, openRunCli, openRunDefaultApp } from './open-in-targets.js';
145
- import { agentCliRunner, detectOpenTargets } from './open-in-app.js';
78
+ import { agentCliRunner } from './open-in-app.js';
146
79
  import { ProviderRuntimeAuthObserver } from './provider-auth-runtime.js';
147
80
  import { continueRunProviders } from './provider-action-gate.js';
148
81
  import { attachProjectWebhooks, createBootContext, createProviderStatus, resolveServerDeps, watchProviderRuntimeAuth } from './server-deps.js';
@@ -152,7 +85,12 @@ import { compression, createStaticAssets, isFile } from './static-assets.js';
152
85
  import { registerBrandFileRoutes } from './brand-file-routes.js';
153
86
  import { createProjectsRoutes } from './projects-routes.js';
154
87
  import { createAgentProfilesRoutes, createProvidersRoutes } from './providers-routes.js';
155
- import { hostedProfileRefusal, streamSSENoBuffer, UI_STATE_BODY_LIMIT, WorkspaceEventBus } from './server-types.js';
88
+ import { hostedProfileRefusal, WorkspaceEventBus } from './server-types.js';
89
+ import { createAutomationsRouteBundles } from './automations-routes.js';
90
+ import { createGithubRoutes } from './github-routes.js';
91
+ import { createOpenTargetsRoutes, createRepoRoutes, createWorktreesRoutes } from './repo-routes.js';
92
+ import { createFsBrowseRoutes, createRunsIndexRoutes, createWorkspaceConfigRoutes, createWorkspaceEventsRoutes } from './workspace-routes.js';
93
+ import { createAgentConfigRoutes, createAgentWebhooksRoutes, createConfigRoutes, createPlanRoutes, createSkillsRoutes, createSseRoutes, createUiStateRoutes, createWorkflowsRoutes } from './project-settings-routes.js';
156
94
  // ---- project-scoped routing (multi-project spec, step 2.2) -----------------
157
95
  export { WorkspaceEventBus } from './server-types.js';
158
96
  /**
@@ -190,7 +128,6 @@ export function projectRouteManifest(app) {
190
128
  return manifest;
191
129
  }
192
130
  /** 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
131
  /** 404 body for a run whose row is in runs.db but whose record this Squawk cannot decode (#779). */
195
132
  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
133
  // ---- workspace SSE (multi-project spec, step 2.8) --------------------------
@@ -280,12 +217,6 @@ export function createApp(deps) {
280
217
  const serverGeneration = randomUUID();
281
218
  const checkoutProgress = new CheckoutProgressCache();
282
219
  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
220
  const automationsChanged = () => deps.automationsChanged?.();
290
221
  const providerRuntimeAuth = deps.providerRuntimeAuth
291
222
  ?? new ProviderRuntimeAuthObserver(providerAuth, (status) => {
@@ -757,454 +688,26 @@ export function createApp(deps) {
757
688
  // events on the workspace stream. `checkoutId` is the cockpit's own
758
689
  // correlation token, echoed on every event so two tabs cloning at once never
759
690
  // 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);
691
+ const workspaceConfigRoutes = createWorkspaceConfigRoutes({
692
+ home: deps.home,
693
+ semaphore: deps.semaphore,
694
+ archiveOnMergeChanged: deps.archiveOnMergeChanged,
1198
695
  });
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);
696
+ const fsBrowseRoutes = createFsBrowseRoutes(workspaceBrowseRoot);
697
+ const skillsRoutes = createSkillsRoutes({ home: deps.home, capabilities, skillCatalog, resolveWorkspaceProfile });
698
+ const uiStateRoutes = createUiStateRoutes();
699
+ const workflowsRoutes = createWorkflowsRoutes();
700
+ const planRoutes = createPlanRoutes({ home: deps.home, skillCatalog, providerActionError, resolveWorkspaceProfile });
701
+ const { automationsRoutes, automationChecksRoutes } = createAutomationsRouteBundles({
702
+ home: deps.home,
703
+ capabilities,
704
+ modelCatalog,
705
+ providerStatus,
706
+ bootContext,
707
+ contexts,
708
+ workspaceEvents,
709
+ automationsChanged,
710
+ resolveProjectForge,
1208
711
  });
1209
712
  // ---- runs ----------------------------------------------------------------
1210
713
  // Additive `usage` field (#348): the latest CPU/RSS/proc-count sample of the
@@ -2075,33 +1578,7 @@ export function createApp(deps) {
2075
1578
  release();
2076
1579
  }
2077
1580
  });
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
- });
1581
+ const openTargetsRoutes = createOpenTargetsRoutes({ capabilities, openApp });
2105
1582
  // Agent screenshots and user attachments — what the run manager persisted out of tool
2106
1583
  // results and pasted messages (`persistAttachment`). `basename` pins reads inside the
2107
1584
  // run's own dir.
@@ -2124,685 +1601,19 @@ export function createApp(deps) {
2124
1601
  txt: 'text/plain; charset=utf-8',
2125
1602
  md: 'text/plain; charset=utf-8',
2126
1603
  };
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);
1604
+ const worktreesRoutes = createWorktreesRoutes({ home: deps.home, previewHost: deps.previewHost });
1605
+ const sseRoutes = createSseRoutes();
1606
+ const workspaceEventsRoutes = createWorkspaceEventsRoutes({
1607
+ serverGeneration,
1608
+ resolveBootProject,
1609
+ workspaceRunFeed,
1610
+ workspaceEvents,
2805
1611
  });
1612
+ const githubRoutes = createGithubRoutes({ forgeFactory: deps.forgeFactory, resolveProjectForge });
1613
+ const repoRoutes = createRepoRoutes({ home: deps.home, forgeFactory: deps.forgeFactory, branchForge: deps.branchForge });
1614
+ const configRoutes = createConfigRoutes({ home: deps.home, capabilities, archiveOnMergeChanged: deps.archiveOnMergeChanged });
1615
+ const agentConfigRoutes = createAgentConfigRoutes(capabilities);
1616
+ const agentWebhooksRoutes = createAgentWebhooksRoutes({ home: deps.home, taskWebhooks, taskWebhookFetch: deps.taskWebhookFetch });
2806
1617
  const v1 = new Hono()
2807
1618
  .use('*', resolveProjectScope)
2808
1619
  .route('/', skillsRoutes)
@@ -2823,173 +1634,15 @@ export function createApp(deps) {
2823
1634
  .route('/', agentConfigRoutes);
2824
1635
  projectRoutePaths = new Set(v1.routes.filter((route) => route.method !== 'ALL')
2825
1636
  .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);
1637
+ const runsIndexRoutes = createRunsIndexRoutes({
1638
+ loadPreparedProjects: (projects) => prepareProjects(projects, { ownership: deps.ownership, homes: [deps.home] }),
1639
+ forgeFactory: deps.forgeFactory,
1640
+ bootContext,
1641
+ contexts,
1642
+ workspaceProjects,
1643
+ workspaceRunFeed,
1644
+ serverGeneration,
1645
+ withLiveUsage,
2993
1646
  });
2994
1647
  // Workspace-level families answer for the whole workspace, so they are single-mount: never a
2995
1648
  // project-scoped spelling, which would be a second surface to protect with no consumer.