@hearsay-tools/squawk 0.18.0-dev.6140 → 0.18.0-dev.6146

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.
Files changed (56) hide show
  1. package/dist/ci-wait/tools.d.ts +4 -4
  2. package/dist/core/agent-runner.d.ts +3 -0
  3. package/dist/core/agent-runner.js +1 -0
  4. package/dist/core/agent-runner.js.map +1 -1
  5. package/dist/core/claude-cli-runner.js +11 -9
  6. package/dist/core/claude-cli-runner.js.map +1 -1
  7. package/dist/core/codex-app-server-runner.js +7 -6
  8. package/dist/core/codex-app-server-runner.js.map +1 -1
  9. package/dist/core/codex-app-server-transport.d.ts +3 -1
  10. package/dist/core/codex-app-server-transport.js +7 -7
  11. package/dist/core/codex-app-server-transport.js.map +1 -1
  12. package/dist/core/cursor-print-process.d.ts +2 -0
  13. package/dist/core/cursor-print-process.js +4 -4
  14. package/dist/core/cursor-print-process.js.map +1 -1
  15. package/dist/core/cursor-print-runner.js +5 -3
  16. package/dist/core/cursor-print-runner.js.map +1 -1
  17. package/dist/core/managed-session.js +4 -3
  18. package/dist/core/managed-session.js.map +1 -1
  19. package/dist/core/omp-runner.js +7 -5
  20. package/dist/core/omp-runner.js.map +1 -1
  21. package/dist/core/opencode-server-runner.js +5 -4
  22. package/dist/core/opencode-server-runner.js.map +1 -1
  23. package/dist/core/pi-runner.js +8 -6
  24. package/dist/core/pi-runner.js.map +1 -1
  25. package/dist/core/runner-runtime.d.ts +9 -0
  26. package/dist/core/runner-runtime.js +7 -0
  27. package/dist/core/runner-runtime.js.map +1 -1
  28. package/dist/core/session-process.d.ts +2 -0
  29. package/dist/core/session-process.js +3 -3
  30. package/dist/core/session-process.js.map +1 -1
  31. package/dist/home/migration-boot.js +2 -2
  32. package/dist/home/migration-boot.js.map +1 -1
  33. package/dist/serve-boot.d.ts +1 -1
  34. package/dist/serve-command.d.ts +2 -1
  35. package/dist/serve-command.js +2 -1
  36. package/dist/serve-command.js.map +1 -1
  37. package/dist/server/reports-api.d.ts +2 -2
  38. package/dist/server/server.d.ts +452 -456
  39. package/dist/server/server.js +6 -334
  40. package/dist/server/server.js.map +1 -1
  41. package/dist/server/start-server.d.ts +6 -0
  42. package/dist/server/start-server.js +348 -0
  43. package/dist/server/start-server.js.map +1 -0
  44. package/dist/server-install/types.d.ts +3 -0
  45. package/dist/server-install/types.js +3 -0
  46. package/dist/server-install/types.js.map +1 -1
  47. package/dist/workflows/run/continuation-session.js +1 -0
  48. package/dist/workflows/run/continuation-session.js.map +1 -1
  49. package/dist/workflows/run/step-session.js +1 -0
  50. package/dist/workflows/run/step-session.js.map +1 -1
  51. package/dist/workflows/run/types.d.ts +1 -0
  52. package/dist/workflows/run.d.ts +1 -0
  53. package/dist/workflows/run.js +1 -1
  54. package/dist/workflows/run.js.map +1 -1
  55. package/package.json +4 -4
  56. package/scripts/measure-transcript-facts-health.mjs +1 -1
@@ -1,4 +1,3 @@
1
- import { reportsIndex } from '../artifacts/reports-index.js';
2
1
  import { runCheckout, preparePublishCheckout, reclaimCheckoutError } from './run-checkout.js';
3
2
  import { adoptFallbackControl, protectFallbackRun, runArtifactDirectory } from './project-run-files.js';
4
3
  import { deleteSavedWorkflow } from './workflow-files.js';
@@ -6,7 +5,6 @@ import { projectPaths, fallbackProjectWriteError } from '../project-paths.js';
6
5
  import { productIdentity } from '../home/identity.js';
7
6
  import { productName, logPrefix } from '../home/display.js';
8
7
  import { productEnv } from '../core/product-env.js';
9
- import { prepareHomeLifecycle } from '../home/entry.js';
10
8
  import { reportsRoutes } from './reports-api.js';
11
9
  import { writeMergedConfig } from './config-merge.js';
12
10
  import { applyWorkspaceConfigPatch } from './workspace-config-patch.js';
@@ -31,8 +29,6 @@ import { commitQuerySchema } from '../contract/index.js';
31
29
  import { imageMimeType } from '../contract/index.js';
32
30
  import { providerForActiveRun } from '../contract/index.js';
33
31
  import { defined } from '../core/defined.js';
34
- import { ArchiveOnMergeCoordinator } from './archive-on-merge.js';
35
- import { CompletionActionCoordinator } from './completion-actions.js';
36
32
  import { resolveArchiveOnMerge, resolveGlobalArchiveOnMerge } from '../archive-on-merge-setting.js';
37
33
  import { permissionDecisionSchema } from '../contract/index.js';
38
34
  import { runIdParamSchema as permissionRunIdParamSchema } from '../contract/index.js';
@@ -56,18 +52,15 @@ import { existsSync, readFileSync, statSync } from 'node:fs';
56
52
  import { randomUUID } from 'node:crypto';
57
53
  import { createAutomationService, onceCreateAnswer } from '../automations/service.js';
58
54
  import { createAutomationToolService } from '../automations/tool-adapter.js';
59
- import { AutomationCoordinator } from '../automations/coordinator.js';
60
55
  import { GithubPoller } from '../automations/github-poller.js';
61
56
  import { githubRepository } from '../automations/github-repository.js';
62
- import { ProjectAutomationScheduler, WorkspaceAutomationScheduler } from '../automations/scheduler.js';
63
- import { AutomationProjectUnavailableError } from '../automations/schedule-runner.js';
64
- import { launchAutomationRun, launchScheduledRun, rebaselineIdleAutomations, reconcileAutomationReceipts, } from '../automations/task-template.js';
57
+ import { ProjectAutomationScheduler } from '../automations/scheduler.js';
58
+ import { launchAutomationRun, launchScheduledRun, reconcileAutomationReceipts } from '../automations/task-template.js';
65
59
  import { isGithubAutomation, } from '../automations/types.js';
66
60
  import { access, constants as fsConstants, mkdir, readFile, realpath, stat, unlink, writeFile } from 'node:fs/promises';
67
61
  import { basename, dirname, join } from 'node:path';
68
62
  import { fileURLToPath } from 'node:url';
69
63
  import { Hono } from 'hono';
70
- import { getRequestListener, serve } from '@hono/node-server';
71
64
  import { bodyLimit } from 'hono/body-limit';
72
65
  import { streamSSE } from 'hono/streaming';
73
66
  import { matchedRoutes } from 'hono/route';
@@ -119,7 +112,7 @@ import { isUntouchedCancelledRun } from '../workflows/run/run-guards.js';
119
112
  import { worktreeDiff, worktreeSizeBytes } from '../git-worktree.js';
120
113
  import { releaseThenRemoveWorktree } from '../git-worktree-release.js';
121
114
  import { isReclaimable, reclaimWorktree, reclaimWorktrees, selectReclaimableWorktrees } from '../runs/retention.js';
122
- import { getBranches, getCommit, getDiff, getLogWithParents, getBranchHead, getRepoInfo, getStatus, getTracking } from './git.js';
115
+ import { getBranches, getCommit, getDiff, getLogWithParents, getRepoInfo, getStatus, getTracking } from './git.js';
123
116
  import { createGithubBranchForge } from './repo-branch-forge.js';
124
117
  import { attributeLog, classifyInputFor, deleteBranches, forgetRepoBranches, readRepoBranchCounts, readRepoBranches } from './repo-branches.js';
125
118
  import { claimRepoGitMutation, localPullBranches, pullRepoCheckout } from './repo-pull.js';
@@ -143,24 +136,19 @@ import { mergeWriteWorkspaceUiState, readWorkspaceUiState } from '../workspace/u
143
136
  import { checkoutRepo } from './checkout.js';
144
137
  import { createProject, listGithubOwners } from './create-project.js';
145
138
  import { createWorkspaceRunFeed } from './workspace-run-feed.js';
146
- import { armPreview, projectWarmupEnabled, sweepRegisteredPreviewLeftovers } from './project-context.js';
147
139
  import { readProjectUiState, readUiState, writeProjectUiState } from '../ui-state.js';
148
140
  import { agentHomePaths, expandTilde } from '../paths.js';
149
141
  import { isLoopbackHostHeader, normalizeHostname, resolveCapabilities } from './capabilities.js';
150
- import { createSocketHub, socketHubRoute } from './ws.js';
151
- import { attachUpgradeRouter } from './upgrade-router.js';
152
- import { createPreviewSockets } from './preview-sockets.js';
153
142
  import { browseDirectory, isInsideBrowseRoot, isLexicallyInsideBrowseRoot, resolveBrowseRoot } from './fs-browse.js';
154
- import { forgeRepositoryUrl, resolveForge, forgeWebRoot, resolveForgeRoot, GithubPrNotFoundError, GH_CHECKS_MAX, GH_REF_STATUS_MAX } from './forge/index.js';
143
+ import { resolveForge, forgeWebRoot, resolveForgeRoot, GithubPrNotFoundError, GH_CHECKS_MAX, GH_REF_STATUS_MAX } from './forge/index.js';
155
144
  import { refNumberFromUrl } from '../contract/index.js';
156
145
  import { projectAdmissionRefusal, withProjectAdmission } from './cockpit-ownership.js';
157
- import { closingSignal, prepareBeforeTicks, prepareProject, prepareProjects } from '../project-migration/auto.js';
158
- import { RunStoreOpenError } from '../runs/store-open-error.js';
146
+ import { prepareProjects } from '../project-migration/auto.js';
159
147
  import { freshCliHandoff, openRunApp, openRunCli, openRunDefaultApp } from './open-in-targets.js';
160
148
  import { agentCliRunner, detectOpenTargets } from './open-in-app.js';
161
149
  import { ProviderRuntimeAuthObserver } from './provider-auth-runtime.js';
162
150
  import { providerForExistingRun, providersRequiredByWorkflow, } from './provider-action-gate.js';
163
- import { attachProjectWebhooks, cockpitOriginFor, createBootContext, createProviderStatus, emitProviderRow, resolveServerDeps, watchProviderRuntimeAuth, } from './server-deps.js';
151
+ import { attachProjectWebhooks, createBootContext, createProviderStatus, emitProviderRow, resolveServerDeps, watchProviderRuntimeAuth, } from './server-deps.js';
164
152
  import { NO_WEBHOOK_ERROR, agentProfileRefusal, clientRequestOf, launchRun, modelLockRefusal, notifyRefusal, providerGateRefusal, replayedRun, resolveStartWorkflow, startRunInput, } from './start-run-options.js';
165
153
  import { ASSET_CACHE_CONTROL, BUILD_HINT_HTML, assetContentType, isSafeAssetFilename, resolveGetRequest, } from './static-ui.js';
166
154
  /** The hosted-mode refusal, worded like the agent-config one it mirrors. */
@@ -4537,322 +4525,6 @@ function builtinSkillsOf(manager) {
4537
4525
  }
4538
4526
  export { cockpitOriginFor } from './server-deps.js';
4539
4527
  const webhookNameTakenError = (name) => `this project already has a webhook named "${name.trim()}" — pick another name`;
4540
- export function startServer(deps, port, listener) {
4541
- const attachHomeLifecycle = prepareHomeLifecycle(deps.home);
4542
- const workspaceEvents = deps.workspaceEvents ?? new WorkspaceEventBus();
4543
- // The subscription hub rides the same HTTP server (one port, zero config):
4544
- // createApp registers the topics, the `upgrade` hook below owns the socket.
4545
- const socketHub = deps.socketHub ?? createSocketHub();
4546
- // `cezar_preview_serve` refuses the cockpit's own port: the one the listener BOUND (`--port 0`).
4547
- let listeningPort;
4548
- const squawkPort = deps.squawkPort ?? (() => listeningPort);
4549
- const workspaceProjects = deps.workspaceProjects ?? createWorkspaceProjects({ bootRoot: deps.repoRoot, bootProjectId: deps.bootProjectId, bindHost: deps.bindHost, home: deps.home });
4550
- // Every registry reader below sees what createApp sees: single-project mode hides other projects.
4551
- const visibleProjects = () => workspaceProjects.listVisibleProjects();
4552
- const automationCoordinator = new AutomationCoordinator({ listProjects: () => visibleProjects().then((projects) => prepareProjects(projects, { ownership: deps.ownership, homes: [deps.home], rebrand: deps.legacyCanary })) }); // projects arrive prepared
4553
- const bootProjectId = deps.bootProjectId ?? 'default';
4554
- const bootAutomationStore = () => automationCoordinator.store(bootProjectId, deps.repoRoot); // resolve after preparation
4555
- const taskWebhooks = createTaskWebhooks(deps);
4556
- // #774: the bound origin every agent env carries (`CEZ_COCKPIT_URL`), so `cez automation` calls
4557
- // this cockpit instead of probing ports. Unset until `listening`; a project built after that is
4558
- // addressed in `prepareManager`, before its recovery resumes anything.
4559
- let cockpitOrigin;
4560
- const addressManager = (project) => {
4561
- if (cockpitOrigin)
4562
- project.manager.setCockpitAddress?.({ origin: cockpitOrigin, projectId: project.id });
4563
- };
4564
- const sharedContexts = createWorkspaceProjectContexts(deps, taskWebhooks, {
4565
- ownership: deps.ownership,
4566
- listProjects: visibleProjects,
4567
- squawkPort,
4568
- automationStore: (projectId, root) => automationCoordinator.store(projectId, root),
4569
- addressManager,
4570
- });
4571
- const archiveDeps = prepareBeforeTicks({ ownership: deps.ownership, homes: [deps.home], rebrand: deps.legacyCanary }, {
4572
- projects: async () => {
4573
- const boot = { id: bootProjectId, root: deps.repoRoot, status: 'ok' };
4574
- return [boot, ...(await visibleProjects()).filter(project => project.id !== bootProjectId && project.root !== deps.repoRoot)];
4575
- },
4576
- enabled: async (project) => resolveArchiveOnMerge(await loadConfig(project.root, deps.home), await loadWorkspaceConfig(deps.home.workspaceConfig)).enabled,
4577
- repository: async (project) => {
4578
- const repository = await resolveForgeRoot(project.root, deps.forgeFactory).discoverRepository();
4579
- return repository.status === 'resolved' ? forgeRepositoryUrl('github', repository.handle.owner, repository.handle.name) : undefined;
4580
- },
4581
- withStore: (project, work) => withProjectAdmission(projectPaths(project.root).write, function admittedStore() {
4582
- if (project.root === deps.repoRoot)
4583
- return work(deps.store, id => deps.manager.isActive?.(id) ?? false, () => server.listening);
4584
- return sharedContexts.withMaintenanceStore(project.id, (store, valid) => work(store, id => sharedContexts.peek(project.id)?.manager.isActive(id) ?? false, valid));
4585
- }, () => undefined),
4586
- lookup: (root, identities, signal) => resolveForgeRoot(root, deps.forgeFactory).mergedPullRequests(identities, signal),
4587
- });
4588
- const archiveOnMerge = new ArchiveOnMergeCoordinator(archiveDeps);
4589
- const completionActions = new CompletionActionCoordinator({
4590
- projects: archiveDeps.projects,
4591
- withStore: (project, work) => archiveDeps.withStore(project, (store, _active, valid) => work(store, valid)),
4592
- forge: async (project) => {
4593
- const info = await getRepoInfo(project.root);
4594
- const driver = resolveForge(info, deps.forgeFactory);
4595
- const repository = info?.remote ? forgeWebRoot(info.remote) : null;
4596
- return driver && repository ? { driver, repository } : undefined;
4597
- },
4598
- head: (project, branch) => getBranchHead(project.root, branch),
4599
- });
4600
- // Injected contexts (tests) skip `prepareManager`.
4601
- sharedContexts.onContextBuilt(addressManager);
4602
- // #801: Automations can be disabled. Off, the flag must remove the BEHAVIOR and not merely
4603
- // the UI — no scheduler, no GitHub polling, no launched runs — so every entry point into the
4604
- // workspace scheduler below is gated on it. Read per call rather than captured, for the same
4605
- // reason `capabilities()` is inside `createApp`: tests flip the variable between apps.
4606
- const automationsEnabled = () => resolveCapabilities(process.env, deps.bindHost).automations;
4607
- let rescheduleAutomations = () => { };
4608
- const app = createApp({
4609
- ...deps,
4610
- taskWebhooks,
4611
- contexts: sharedContexts,
4612
- automationStore: bootAutomationStore,
4613
- workspaceEvents,
4614
- socketHub,
4615
- squawkPort,
4616
- workspaceProjects,
4617
- archiveOnMergeChanged: () => archiveOnMerge.invalidate(),
4618
- automationsChanged: () => rescheduleAutomations(),
4619
- });
4620
- // SECURITY: default to loopback. This server executes agents locally and its endpoints are
4621
- // same-origin-trusted (only /api/health is CORS-open); binding to a non-loopback host would
4622
- // expose an agent-executing box to the network. `bindHost` exists only for a deliberate
4623
- // hosted/VPS deployment (which also flips CEZ_REMOTE to gate the local-handoff endpoints) —
4624
- // The CLI passes it only when explicitly requested; normal startup stays on loopback.
4625
- const serverOptions = {
4626
- fetch: (request, env) => app.fetch(request, env),
4627
- port,
4628
- hostname: deps.bindHost ?? '127.0.0.1',
4629
- };
4630
- // The CLI already owns this listener before recovery. Replace its temporary 503
4631
- // handler without closing/rebinding; direct server callers retain normal startup.
4632
- if (listener) {
4633
- listener.removeAllListeners('request');
4634
- listener.on('request', getRequestListener(serverOptions.fetch, defined({ hostname: serverOptions.hostname })));
4635
- }
4636
- const server = listener ?? serve(serverOptions);
4637
- attachHomeLifecycle(server);
4638
- // EVERY registered project, remote or not: a schedule needs none. `github` is present only for
4639
- // a github.com remote, and only then does the project's handle poll.
4640
- const automationProjects = new Map();
4641
- const rememberAutomationProject = async (id, root) => {
4642
- const github = githubRepository(root, (await getRepoInfo(root))?.remote);
4643
- automationProjects.set(id, { root, ...(github ? { github } : {}) });
4644
- };
4645
- const emitWorkspaceAutomationChange = (projectId) => (automationId, revision) => workspaceEvents.emit('automation-change', { project: projectId, automationId, revision });
4646
- /**
4647
- * The boot brake for one project, at boot and for a project registered after it: an enabled
4648
- * poll idle past its lookback is re-baselined rather than resumed from a stale cursor. Only a
4649
- * project with a github.com remote: its polls are the only ones the timer arms, so a poll
4650
- * without one never succeeds and would be re-baselined on every boot, forever.
4651
- */
4652
- const brakeIdleAutomations = (id, automationStore) => {
4653
- if (!automationStore || !automationProjects.get(id)?.github)
4654
- return;
4655
- rebaselineIdleAutomations(automationStore, emitWorkspaceAutomationChange(id));
4656
- };
4657
- const automationScheduler = new WorkspaceAutomationScheduler({
4658
- coordinator: automationCoordinator,
4659
- handle: (projectId, store) => {
4660
- const project = automationProjects.get(projectId);
4661
- if (!project)
4662
- return undefined;
4663
- const timeZone = localTimeZone();
4664
- const launchContext = async () => projectId === (deps.bootProjectId ?? 'default')
4665
- ? { root: deps.repoRoot, manager: deps.manager, store: deps.store }
4666
- : await sharedContexts.context(projectId);
4667
- return {
4668
- projectId,
4669
- store,
4670
- timeZone,
4671
- ...(project.github ? { github: { ...project.github, poller: new GithubPoller() } } : {}),
4672
- onChange: emitWorkspaceAutomationChange(projectId),
4673
- // Building a lazy project's context reconciles on its own; the explicit call covers the
4674
- // boot project and a context built before another process left the reservation.
4675
- reconcileReceipts: async () => { reconcileAutomationReceipts(store, (await launchContext()).store); },
4676
- // A run store that cannot open (#779) launches nothing. Firing anyway would count every
4677
- // refusal towards the auto-pause, and the pause would outlive the restart that fixed it.
4678
- ready: async () => {
4679
- try {
4680
- const { store: runs } = await launchContext();
4681
- if (runs.unavailable)
4682
- throw runs.unavailable;
4683
- }
4684
- catch (error) {
4685
- if (error instanceof RunStoreOpenError)
4686
- throw new AutomationProjectUnavailableError(error.message, { cause: error });
4687
- throw error;
4688
- }
4689
- },
4690
- launchSchedule: async (definition, occurrence, receiptId) => {
4691
- const context = await launchContext();
4692
- return launchScheduledRun({
4693
- root: context.root,
4694
- manager: context.manager,
4695
- store: context.store,
4696
- definition,
4697
- occurrence,
4698
- receiptId,
4699
- projectName: basename(context.root),
4700
- timeZone,
4701
- });
4702
- },
4703
- launch: async (definition, candidate, receiptId) => {
4704
- const context = await launchContext();
4705
- return launchAutomationRun({
4706
- root: context.root,
4707
- manager: context.manager,
4708
- store: context.store,
4709
- definition,
4710
- candidate,
4711
- receiptId,
4712
- });
4713
- },
4714
- };
4715
- },
4716
- });
4717
- // The scheduler is inert until `start()` anyway (it constructs `stopped`), but the gate is
4718
- // stated here rather than inherited from that detail: a definition saved while the flag is off
4719
- // must not even ask the coordinator to refresh.
4720
- rescheduleAutomations = () => {
4721
- if (!automationsEnabled())
4722
- return;
4723
- void automationScheduler.reschedule();
4724
- };
4725
- const unsubscribe = workspaceEvents.on((event, data) => {
4726
- if (event === 'project-added') {
4727
- const project = data.project;
4728
- if (project && typeof project.id === 'string' && typeof project.root === 'string' && project.status !== 'missing') {
4729
- const { id, root } = project;
4730
- void prepareProject(root, { ownership: deps.ownership, homes: [deps.home], rebrand: deps.legacyCanary }).then(() => rememberAutomationProject(id, root)).then(() => {
4731
- if (!automationsEnabled())
4732
- return;
4733
- brakeIdleAutomations(id, automationCoordinator.store(id, root));
4734
- return rescheduleAutomations();
4735
- }).catch(() => undefined);
4736
- }
4737
- }
4738
- else if (event === 'project-removed') {
4739
- const id = data.id;
4740
- if (typeof id === 'string') {
4741
- automationCoordinator.remove(id);
4742
- automationProjects.delete(id);
4743
- rescheduleAutomations();
4744
- }
4745
- }
4746
- });
4747
- const lifecycle = closingSignal(server);
4748
- const startBackgroundServices = () => {
4749
- if (!deps.store.unavailable)
4750
- reportsIndex(deps.store).start();
4751
- void visibleProjects().then(async (projects) => {
4752
- const all = projects.some((project) => project.root === deps.repoRoot)
4753
- ? projects : [{ id: deps.bootProjectId ?? 'default', root: deps.repoRoot, status: 'ok' }, ...projects];
4754
- await prepareProjects(all, { ownership: deps.ownership, homes: [deps.home], rebrand: deps.legacyCanary, stopped: lifecycle.stopped }); // before any touch below
4755
- if (!lifecycle.stopped()) {
4756
- archiveOnMerge.start();
4757
- completionActions.start();
4758
- }
4759
- // #781: every registered project's preview leftovers, not only the boot project's.
4760
- void sweepRegisteredPreviewLeftovers(all, deps.previewHost).catch(() => 0);
4761
- // #667: build every other project's context now, so the first click on one does not pay
4762
- // its store open, worktree sweeps and recovery. The boot project is built already.
4763
- // Not after a close that landed while the registry was being read: `disposeAll` has run, and
4764
- // a warm-up started now would build contexts nothing will ever dispose.
4765
- // Not in single-project mode either: every other project is out of reach there, and
4766
- // building one would resume its interrupted runs behind the operator's back.
4767
- if (projectWarmupEnabled() && server.listening && !resolveCapabilities(process.env, deps.bindHost).singleProject) {
4768
- const bootId = deps.bootProjectId ?? 'default';
4769
- void sharedContexts.warmAll(all.filter((project) => project.id !== bootId && project.root !== deps.repoRoot))
4770
- .catch(() => undefined);
4771
- }
4772
- // No automation warmup while opted out, or after discovery outlives the listener; the final continuation also checks for close during Git inspection.
4773
- if (!automationsEnabled() || !server.listening)
4774
- return;
4775
- void Promise.all(all.map(async (project) => {
4776
- await rememberAutomationProject(project.id, project.root);
4777
- if (!server.listening)
4778
- return;
4779
- const automationStore = automationCoordinator.store(project.id, project.root);
4780
- const runStore = project.id === (deps.bootProjectId ?? 'default')
4781
- ? deps.store
4782
- : sharedContexts.peek(project.id)?.store;
4783
- // A run store that could not open (#779) cannot say which receipts launched a run.
4784
- if (automationStore && runStore && !runStore.unavailable)
4785
- reconcileAutomationReceipts(automationStore, runStore);
4786
- brakeIdleAutomations(project.id, automationStore);
4787
- })).then(() => server.listening ? automationScheduler.start() : undefined).catch(() => undefined);
4788
- }).catch(() => undefined);
4789
- };
4790
- if (server.listening)
4791
- startBackgroundServices();
4792
- else
4793
- server.once('listening', startBackgroundServices);
4794
- armPreview(deps.store, projectPaths(deps.repoRoot).write, deps.previewHost);
4795
- const previewSockets = createPreviewSockets({
4796
- host: deps.previewHost, cockpitOrigin: () => cockpitOrigin,
4797
- verify: (req) => verifyWsUpgrade(req, deps.bindHost),
4798
- resolveProject: (projectId) => workspaceProjects.lookupProject(projectId),
4799
- });
4800
- server.once('close', () => {
4801
- unsubscribe();
4802
- archiveOnMerge.stop();
4803
- completionActions.stop();
4804
- automationScheduler.stop();
4805
- sharedContexts.disposeAll();
4806
- void deps.delegation?.close();
4807
- socketHub.close();
4808
- previewSockets.close();
4809
- void deps.previewHost?.close().catch(() => undefined);
4810
- });
4811
- // The one `upgrade` listener: the subscription bus and the preview's sockets (hearsay-tools/cezarion#781).
4812
- attachUpgradeRouter(server, [socketHubRoute(socketHub, (req) => verifyWsUpgrade(req, deps.bindHost)), ...previewSockets.routes]);
4813
- const shutdownForRestart = async () => {
4814
- lifecycle.stop();
4815
- archiveOnMerge.stop();
4816
- completionActions.stop();
4817
- sharedContexts.disposeAll(); // close every built secondary project before old process exits
4818
- deps.store.flush();
4819
- socketHub.close();
4820
- // Dev servers run in their own process groups: they outlive Squawk unless stopped here.
4821
- // A failed release must not abort the restart halfway, with the store flushed and the port still bound.
4822
- await deps.previewHost?.close().catch(() => undefined);
4823
- previewSockets.close();
4824
- await deps.delegation?.close();
4825
- await new Promise((resolve) => {
4826
- server.close(() => resolve());
4827
- if ('closeAllConnections' in server)
4828
- server.closeAllConnections();
4829
- });
4830
- // Last, with no request left to serve: write what is still pending and release every claim,
4831
- // so the replacement process finds the live runs nobody's, as a clean stop leaves them (#779).
4832
- deps.store.close();
4833
- };
4834
- // The task webhook's thread links name the port the listener BOUND (#594 review): `--port 0`
4835
- // asks for an ephemeral one, so the requested number is not an address. Deliveries queue
4836
- // behind this, so none goes out before it is set.
4837
- const setTaskWebhookOrigin = () => {
4838
- const address = server.address();
4839
- const bound = address && typeof address === 'object' ? address.port : port;
4840
- listeningPort = bound;
4841
- cockpitOrigin = cockpitOriginFor(deps.bindHost, bound);
4842
- taskWebhooks.setOrigin(cockpitOrigin);
4843
- addressManager({ id: bootProjectId, manager: deps.manager });
4844
- for (const id of sharedContexts.ids()) {
4845
- const context = sharedContexts.peek(id);
4846
- if (context)
4847
- addressManager(context);
4848
- }
4849
- };
4850
- if (server.listening)
4851
- setTaskWebhookOrigin();
4852
- else
4853
- server.once('listening', setTaskWebhookOrigin);
4854
- return Object.assign(server, { shutdownForRestart });
4855
- }
4856
4528
  /**
4857
4529
  * Validate topic-bus upgrades before handshake. Local Host must be loopback. Same-authority or
4858
4530
  * native clients are trusted; verified dev proxies are trusted. Metadata-free foreign loopback