@zyaochen/weaverbird 0.0.0-stage → 0.1.0

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 (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +418 -0
  3. package/README.md +418 -2
  4. package/apps/wb-bot/README.md +118 -0
  5. package/dist/apps/wb-bot/src/agent-display.js +24 -0
  6. package/dist/apps/wb-bot/src/agent-registry.js +188 -0
  7. package/dist/apps/wb-bot/src/approval-gate/audit.js +37 -0
  8. package/dist/apps/wb-bot/src/approval-gate/cards.js +94 -0
  9. package/dist/apps/wb-bot/src/approval-gate/hook-env.js +15 -0
  10. package/dist/apps/wb-bot/src/approval-gate/hook-files.js +311 -0
  11. package/dist/apps/wb-bot/src/approval-gate/hook-main.js +147 -0
  12. package/dist/apps/wb-bot/src/approval-gate/notifier.js +29 -0
  13. package/dist/apps/wb-bot/src/approval-gate/store.js +157 -0
  14. package/dist/apps/wb-bot/src/binding/migration-runner.js +35 -0
  15. package/dist/apps/wb-bot/src/binding/migrations/001-add-run-id-agent-id.js +8 -0
  16. package/dist/apps/wb-bot/src/binding/migrations/002-add-bot-id.js +34 -0
  17. package/dist/apps/wb-bot/src/binding/migrations/003-inflight-card-agent-id-pk.js +31 -0
  18. package/dist/apps/wb-bot/src/binding/migrations/004-thread-alias-topic-key.js +31 -0
  19. package/dist/apps/wb-bot/src/binding/migrations/005-card-entity.js +21 -0
  20. package/dist/apps/wb-bot/src/binding/migrations/006-group-setting.js +17 -0
  21. package/dist/apps/wb-bot/src/binding/schema.js +58 -0
  22. package/dist/apps/wb-bot/src/binding/sleep-sync.js +5 -0
  23. package/dist/apps/wb-bot/src/binding/store.js +270 -0
  24. package/dist/apps/wb-bot/src/binding/task-index.js +127 -0
  25. package/dist/apps/wb-bot/src/boot/entry-path.js +9 -0
  26. package/dist/apps/wb-bot/src/boot/integrity.js +47 -0
  27. package/dist/apps/wb-bot/src/boot/logger.js +44 -0
  28. package/dist/apps/wb-bot/src/captain/bot-discovery.js +42 -0
  29. package/dist/apps/wb-bot/src/captain/captain-context.js +26 -0
  30. package/dist/apps/wb-bot/src/captain/captain-gate.js +9 -0
  31. package/dist/apps/wb-bot/src/captain/captain-status.js +101 -0
  32. package/dist/apps/wb-bot/src/captain/captain-stop-all.js +72 -0
  33. package/dist/apps/wb-bot/src/captain/list-bots.js +39 -0
  34. package/dist/apps/wb-bot/src/cli/doctor.js +105 -0
  35. package/dist/apps/wb-bot/src/cli/init.js +122 -0
  36. package/dist/apps/wb-bot/src/cli/parse-args.js +31 -0
  37. package/dist/apps/wb-bot/src/cli/preflight.js +9 -0
  38. package/dist/apps/wb-bot/src/cli/setup-checklist.js +10 -0
  39. package/dist/apps/wb-bot/src/commands/health.js +328 -0
  40. package/dist/apps/wb-bot/src/commands/history.js +100 -0
  41. package/dist/apps/wb-bot/src/commands/logs.js +91 -0
  42. package/dist/apps/wb-bot/src/commands/parser.js +43 -0
  43. package/dist/apps/wb-bot/src/commands/queue-metrics.js +24 -0
  44. package/dist/apps/wb-bot/src/commands/resume.js +48 -0
  45. package/dist/apps/wb-bot/src/commands/router.js +299 -0
  46. package/dist/apps/wb-bot/src/commands/status.js +77 -0
  47. package/dist/apps/wb-bot/src/commands/tasks.js +106 -0
  48. package/dist/apps/wb-bot/src/commands/wb-approval.js +86 -0
  49. package/dist/apps/wb-bot/src/commands/wb-audit.js +46 -0
  50. package/dist/apps/wb-bot/src/commands/wb-mute.js +84 -0
  51. package/dist/apps/wb-bot/src/commands/wb-sync.js +58 -0
  52. package/dist/apps/wb-bot/src/config/approval-code-owners.js +95 -0
  53. package/dist/apps/wb-bot/src/config/bot-env.js +80 -0
  54. package/dist/apps/wb-bot/src/config/config-paths.js +16 -0
  55. package/dist/apps/wb-bot/src/config/env.js +43 -0
  56. package/dist/apps/wb-bot/src/config/lark-credentials.js +14 -0
  57. package/dist/apps/wb-bot/src/e2e/preflight-env.js +147 -0
  58. package/dist/apps/wb-bot/src/e2e/preflight-main.js +12 -0
  59. package/dist/apps/wb-bot/src/feishu/admin-alert.js +94 -0
  60. package/dist/apps/wb-bot/src/feishu/artifacts.js +95 -0
  61. package/dist/apps/wb-bot/src/feishu/bot-identity.js +38 -0
  62. package/dist/apps/wb-bot/src/feishu/card-pipeline.js +121 -0
  63. package/dist/apps/wb-bot/src/feishu/card-renderer.js +360 -0
  64. package/dist/apps/wb-bot/src/feishu/card-transport.js +294 -0
  65. package/dist/apps/wb-bot/src/feishu/chat-mode-cache.js +47 -0
  66. package/dist/apps/wb-bot/src/feishu/completion-push.js +30 -0
  67. package/dist/apps/wb-bot/src/feishu/doc-comment.js +183 -0
  68. package/dist/apps/wb-bot/src/feishu/event-handler.js +2634 -0
  69. package/dist/apps/wb-bot/src/feishu/events-file-reader.js +162 -0
  70. package/dist/apps/wb-bot/src/feishu/inbound-context.js +53 -0
  71. package/dist/apps/wb-bot/src/feishu/keepalive.js +85 -0
  72. package/dist/apps/wb-bot/src/feishu/log-redact.js +20 -0
  73. package/dist/apps/wb-bot/src/feishu/markdown-style.js +95 -0
  74. package/dist/apps/wb-bot/src/feishu/media-cache.js +92 -0
  75. package/dist/apps/wb-bot/src/feishu/message-parser.js +126 -0
  76. package/dist/apps/wb-bot/src/feishu/pending-queue.js +133 -0
  77. package/dist/apps/wb-bot/src/feishu/reaction.js +44 -0
  78. package/dist/apps/wb-bot/src/feishu/reverse-at-im-handler.js +345 -0
  79. package/dist/apps/wb-bot/src/feishu/run-state.js +30 -0
  80. package/dist/apps/wb-bot/src/feishu/session-short-id.js +9 -0
  81. package/dist/apps/wb-bot/src/feishu/stream-state.js +72 -0
  82. package/dist/apps/wb-bot/src/feishu/topic-key.js +34 -0
  83. package/dist/apps/wb-bot/src/feishu/transport.js +768 -0
  84. package/dist/apps/wb-bot/src/feishu/wb-runner-spawner.js +84 -0
  85. package/dist/apps/wb-bot/src/heartbeat/bot-heartbeat.js +20 -0
  86. package/dist/apps/wb-bot/src/main.js +144 -0
  87. package/dist/apps/wb-bot/src/multi/discovery.js +53 -0
  88. package/dist/apps/wb-bot/src/multi/main.js +57 -0
  89. package/dist/apps/wb-bot/src/multi/parse-args.js +17 -0
  90. package/dist/apps/wb-bot/src/multi/supervisor.js +288 -0
  91. package/dist/apps/wb-bot/src/run-observability/orchestrator.js +61 -0
  92. package/dist/apps/wb-bot/src/security/bot-id-validator.js +18 -0
  93. package/dist/apps/wb-bot/src/security/cwd-guard.js +72 -0
  94. package/dist/apps/wb-bot/src/security/env-whitelist.js +94 -0
  95. package/dist/apps/wb-bot/src/server/wire-up.js +125 -0
  96. package/dist/apps/wb-cli/src/commands/approval.js +101 -0
  97. package/dist/apps/wb-cli/src/commands/attach.js +31 -0
  98. package/dist/apps/wb-cli/src/commands/audit.js +71 -0
  99. package/dist/apps/wb-cli/src/commands/captain.js +72 -0
  100. package/dist/apps/wb-cli/src/commands/debug.js +22 -0
  101. package/dist/apps/wb-cli/src/commands/history.js +75 -0
  102. package/dist/apps/wb-cli/src/commands/list.js +24 -0
  103. package/dist/apps/wb-cli/src/commands/logs.js +122 -0
  104. package/dist/apps/wb-cli/src/commands/resume.js +50 -0
  105. package/dist/apps/wb-cli/src/commands/runs.js +75 -0
  106. package/dist/apps/wb-cli/src/commands/status.js +35 -0
  107. package/dist/apps/wb-cli/src/commands/watch.js +73 -0
  108. package/dist/apps/wb-cli/src/main.js +312 -0
  109. package/dist/packages/core/src/agent/claude-code.js +354 -0
  110. package/dist/packages/core/src/agent/cli-subprocess.js +244 -0
  111. package/dist/packages/core/src/agent/codex.js +231 -0
  112. package/dist/packages/core/src/agent/index.js +5 -0
  113. package/dist/packages/core/src/agent/registry.js +47 -0
  114. package/dist/packages/core/src/agent/types.js +1 -0
  115. package/dist/packages/core/src/approval-gate/audit.js +16 -0
  116. package/dist/packages/core/src/approval-gate/contracts.js +26 -0
  117. package/dist/packages/core/src/approval-gate/matcher.js +112 -0
  118. package/dist/packages/core/src/audit-pipe/audit-pipe-main.js +38 -0
  119. package/dist/packages/core/src/audit-pipe/bitable-sink.js +156 -0
  120. package/dist/packages/core/src/audit-pipe/config.js +105 -0
  121. package/dist/packages/core/src/audit-pipe/contracts.js +33 -0
  122. package/dist/packages/core/src/audit-pipe/index.js +2 -0
  123. package/dist/packages/core/src/audit-pipe/mirror-sink.js +21 -0
  124. package/dist/packages/core/src/audit-pipe/normalizer.js +129 -0
  125. package/dist/packages/core/src/audit-pipe/orchestrator.js +252 -0
  126. package/dist/packages/core/src/audit-pipe/parser.js +24 -0
  127. package/dist/packages/core/src/audit-pipe/tailer.js +46 -0
  128. package/dist/packages/core/src/audit-pipe/wal.js +71 -0
  129. package/dist/packages/core/src/calendar-hook/config.js +45 -0
  130. package/dist/packages/core/src/calendar-hook/contracts.js +66 -0
  131. package/dist/packages/core/src/calendar-hook/index.js +5 -0
  132. package/dist/packages/core/src/calendar-hook/scheduler.js +169 -0
  133. package/dist/packages/core/src/calendar-hook/service.js +189 -0
  134. package/dist/packages/core/src/calendar-hook/transport.js +66 -0
  135. package/dist/packages/core/src/captain/captain-service.js +160 -0
  136. package/dist/packages/core/src/captain/command-catalog.js +41 -0
  137. package/dist/packages/core/src/captain/concurrency-config.js +10 -0
  138. package/dist/packages/core/src/captain/concurrency-queue-index.js +94 -0
  139. package/dist/packages/core/src/captain/concurrency-queue-store.js +43 -0
  140. package/dist/packages/core/src/captain/contracts.js +102 -0
  141. package/dist/packages/core/src/captain/cwd-inference.js +29 -0
  142. package/dist/packages/core/src/captain/enqueue-or-spawn.js +63 -0
  143. package/dist/packages/core/src/captain/index.js +27 -0
  144. package/dist/packages/core/src/captain/queue-metrics/aggregator.js +98 -0
  145. package/dist/packages/core/src/captain/queue-metrics/contracts.js +42 -0
  146. package/dist/packages/core/src/captain/queue-metrics/event-store.js +26 -0
  147. package/dist/packages/core/src/captain/session-store.js +429 -0
  148. package/dist/packages/core/src/captain/toml-loader.js +86 -0
  149. package/dist/packages/core/src/config/errors.js +15 -0
  150. package/dist/packages/core/src/config/registry.js +34 -0
  151. package/dist/packages/core/src/errors/codes.js +98 -0
  152. package/dist/packages/core/src/group-sync/autodoc.js +166 -0
  153. package/dist/packages/core/src/group-sync/config.js +45 -0
  154. package/dist/packages/core/src/group-sync/contracts.js +126 -0
  155. package/dist/packages/core/src/group-sync/dispatch.js +163 -0
  156. package/dist/packages/core/src/group-sync/index.js +9 -0
  157. package/dist/packages/core/src/group-sync/revdiff.js +138 -0
  158. package/dist/packages/core/src/group-sync/scheduler.js +93 -0
  159. package/dist/packages/core/src/group-sync/service.js +79 -0
  160. package/dist/packages/core/src/group-sync/transport.js +97 -0
  161. package/dist/packages/core/src/group-sync/xref.js +139 -0
  162. package/dist/packages/core/src/index.js +23 -0
  163. package/dist/packages/core/src/minutes/adapter.js +187 -0
  164. package/dist/packages/core/src/minutes/client.js +46 -0
  165. package/dist/packages/core/src/minutes/contracts.js +36 -0
  166. package/dist/packages/core/src/minutes/index.js +3 -0
  167. package/dist/packages/core/src/paths.js +158 -0
  168. package/dist/packages/core/src/periodic-tasks/config.js +45 -0
  169. package/dist/packages/core/src/periodic-tasks/contracts.js +75 -0
  170. package/dist/packages/core/src/periodic-tasks/index.js +4 -0
  171. package/dist/packages/core/src/periodic-tasks/orchestrator.js +249 -0
  172. package/dist/packages/core/src/periodic-tasks/state.js +29 -0
  173. package/dist/packages/core/src/reverse-channel/attach-handler.js +108 -0
  174. package/dist/packages/core/src/reverse-channel/audit-encoder.js +61 -0
  175. package/dist/packages/core/src/reverse-channel/contracts.js +136 -0
  176. package/dist/packages/core/src/reverse-channel/echo-tailer.js +36 -0
  177. package/dist/packages/core/src/reverse-channel/handoff.js +238 -0
  178. package/dist/packages/core/src/reverse-channel/index.js +5 -0
  179. package/dist/packages/core/src/reverse-channel/ipc-client.js +110 -0
  180. package/dist/packages/core/src/reverse-channel/ipc-control-handler.js +27 -0
  181. package/dist/packages/core/src/reverse-channel/ipc-server.js +127 -0
  182. package/dist/packages/core/src/reverse-channel/mute-registry.js +113 -0
  183. package/dist/packages/core/src/reverse-channel/pid-resolver.js +41 -0
  184. package/dist/packages/core/src/reverse-channel/reverse-at-handler.js +19 -0
  185. package/dist/packages/core/src/reverse-channel/sla-tracker.js +51 -0
  186. package/dist/packages/core/src/run-observability/alert-card-renderer.js +24 -0
  187. package/dist/packages/core/src/run-observability/alert-pusher.js +47 -0
  188. package/dist/packages/core/src/run-observability/card-refresher.js +31 -0
  189. package/dist/packages/core/src/run-observability/card-renderer-progress.js +33 -0
  190. package/dist/packages/core/src/run-observability/config-loader.js +23 -0
  191. package/dist/packages/core/src/run-observability/contracts.js +107 -0
  192. package/dist/packages/core/src/run-observability/exit-code-detector.js +16 -0
  193. package/dist/packages/core/src/run-observability/finalizer.js +114 -0
  194. package/dist/packages/core/src/run-observability/index.js +12 -0
  195. package/dist/packages/core/src/run-observability/obs-toggle-handler.js +29 -0
  196. package/dist/packages/core/src/run-observability/progress-collector.js +53 -0
  197. package/dist/packages/core/src/run-observability/progress-store.js +100 -0
  198. package/dist/packages/core/src/run-observability/silent-timeout-detector.js +12 -0
  199. package/dist/packages/core/src/run-registry/bitable-writer.js +308 -0
  200. package/dist/packages/core/src/run-registry/config.js +77 -0
  201. package/dist/packages/core/src/run-registry/contracts.js +114 -0
  202. package/dist/packages/core/src/run-registry/doc-sink-classifier.js +0 -0
  203. package/dist/packages/core/src/run-registry/doc-sink-transport.js +63 -0
  204. package/dist/packages/core/src/run-registry/doc-sink.js +200 -0
  205. package/dist/packages/core/src/run-registry/extractor.js +40 -0
  206. package/dist/packages/core/src/run-registry/index.js +11 -0
  207. package/dist/packages/core/src/run-registry/inherit.js +11 -0
  208. package/dist/packages/core/src/run-registry/orchestrator.js +86 -0
  209. package/dist/packages/core/src/run-registry/run-registry-main.js +38 -0
  210. package/dist/packages/core/src/run-registry/tailer.js +390 -0
  211. package/dist/packages/core/src/run-registry/wal.js +106 -0
  212. package/dist/packages/core/src/runner/event-replay.js +65 -0
  213. package/dist/packages/core/src/runner/wb-runner-main.js +27 -0
  214. package/dist/packages/core/src/runner/wb-runner.js +237 -0
  215. package/dist/packages/core/src/util/entry-module.js +21 -0
  216. package/dist/packages/core/src/util/ndjson-rotation.js +99 -0
  217. package/package.json +76 -4
@@ -0,0 +1,102 @@
1
+ /**
2
+ * W3.2.5 Captain 权威化基建 — SPEC contracts
3
+ * ≤250 lines · zod schemas + derived TS types · no runtime imports
4
+ *
5
+ * Import-only from W3.1/W3.2 (do NOT modify):
6
+ * ENTRY_FORMS, DEFAULT_RETRY_POLICY ← audit-pipe
7
+ * RUN_STATUS, RunRecord ← run-registry
8
+ */
9
+ import { z } from 'zod';
10
+ import { RUN_STATUS, ENTRY_FORMS } from '../run-registry/contracts.js';
11
+ import { DEFAULT_RETRY_POLICY } from '../audit-pipe/contracts.js';
12
+ export { RUN_STATUS, ENTRY_FORMS, DEFAULT_RETRY_POLICY };
13
+ export const SESSION_STATUS = {
14
+ IDLE: 'idle',
15
+ ACTIVE: 'active',
16
+ SUSPENDED: 'suspended',
17
+ CLOSED: 'closed',
18
+ };
19
+ const SessionStatusSchema = z.enum(['idle', 'active', 'suspended', 'closed']);
20
+ export const SessionRecordSchema = z.object({
21
+ session_id: z.string().min(1),
22
+ captain_id: z.string().min(1),
23
+ created_at: z.string().datetime(),
24
+ last_active_at: z.string().datetime(),
25
+ closed_at: z.string().datetime().nullable(),
26
+ status: SessionStatusSchema,
27
+ cwd: z.string(),
28
+ scope: z.enum(['dev', 'staging', 'prod']),
29
+ project: z.enum(['weaverbird', 'other']),
30
+ home_group_id: z.string().nullable(),
31
+ agent: z.enum(['claude-code', 'codex', 'other']),
32
+ latest_run_id: z.string().nullable(),
33
+ operator: z.string(),
34
+ entry_form: z.enum(ENTRY_FORMS),
35
+ // M11-D D1 (2026-08-04 owner-authorized): additive revision for optimistic
36
+ // concurrency. Reader treats missing as 0. Cross-device attach uses this to
37
+ // detect "my write reached the store before yours" instead of wealth wins.
38
+ revision: z.number().int().min(0).default(0),
39
+ });
40
+ export const CaptainMappingSchema = z.object({
41
+ git_remote: z.string(),
42
+ cwd_prefix: z.string().optional(),
43
+ captain_id: z.string(),
44
+ home_group_id: z.string().optional(),
45
+ });
46
+ export const CaptainTomlSchema = z.object({
47
+ version: z.number().int().positive().default(1),
48
+ mapping: z.array(CaptainMappingSchema),
49
+ });
50
+ export const CaptainConfigSchema = z.object({
51
+ bitable_base_id: z.string().min(1),
52
+ sessions_table_id: z.string().min(1),
53
+ app_id: z.string().min(1),
54
+ app_secret: z.string().min(1),
55
+ lark_domain: z.enum(['Lark', 'LarkSuite', 'LarkOffice']).default('LarkSuite'),
56
+ captain_state_path: z.string().min(1),
57
+ captain_toml_path: z.string().min(1),
58
+ });
59
+ export const CaptainStoreConfigSchema = CaptainConfigSchema;
60
+ export const CwdInferenceResultSchema = z.discriminatedUnion('outcome', [
61
+ z.object({
62
+ outcome: z.literal('hit'),
63
+ captain_id: z.string(),
64
+ matched_by: z.enum(['git_remote', 'cwd_prefix']),
65
+ }),
66
+ z.object({
67
+ outcome: z.literal('miss'),
68
+ candidates: z.array(z.string()),
69
+ suggestion: z.string(),
70
+ }),
71
+ ]);
72
+ export const CommandCatalogEntrySchema = z.object({
73
+ name: z.string(),
74
+ aliases: z.array(z.string()).default([]),
75
+ belongs_to: z.enum(['bot', 'cli', 'both']),
76
+ capability_tags: z.array(z.string()).default([]),
77
+ im_visible: z.boolean(),
78
+ cli_visible: z.boolean(),
79
+ description: z.string(),
80
+ });
81
+ export const CAPTAIN_ERROR_CODES = {
82
+ E_TOML_MISSING: 'captain.toml.missing',
83
+ E_TOML_INVALID: 'captain.toml.invalid',
84
+ E_INFERENCE_MISS: 'captain.cwd.inference_miss',
85
+ E_SESSION_NOT_FOUND: 'captain.session.not_found',
86
+ E_STORE_WRITE: 'captain.store.write_failed',
87
+ E_STORE_RETRY_EXHAUSTED: 'captain.store.retry_exhausted',
88
+ E_CATALOG_INCOMPLETE: 'captain.catalog.incomplete',
89
+ E_CONFIG_MISSING: 'captain.config.missing',
90
+ E_CONFIG_INCOMPLETE: 'captain.config.incomplete',
91
+ E_REVISION_MISMATCH: 'captain.session.revision_mismatch',
92
+ };
93
+ export class CaptainError extends Error {
94
+ code;
95
+ cause;
96
+ constructor(code, message, cause) {
97
+ super(`[${code}] ${message}`);
98
+ this.code = code;
99
+ this.cause = cause;
100
+ this.name = 'CaptainError';
101
+ }
102
+ }
@@ -0,0 +1,29 @@
1
+ import { execSync } from 'node:child_process';
2
+ import { CwdInferenceResultSchema } from './contracts.js';
3
+ function readGitRemote(cwd) {
4
+ try {
5
+ return execSync('git remote get-url origin', { cwd, encoding: 'utf8' }).trim();
6
+ }
7
+ catch {
8
+ return '';
9
+ }
10
+ }
11
+ export function inferCaptain(cwd, config, gitRemote = readGitRemote(cwd)) {
12
+ for (const mapping of config.mapping) {
13
+ if (new RegExp(mapping.git_remote).test(gitRemote)) {
14
+ return CwdInferenceResultSchema.parse({ outcome: 'hit', captain_id: mapping.captain_id, matched_by: 'git_remote' });
15
+ }
16
+ }
17
+ const hits = config.mapping
18
+ .filter((mapping) => mapping.cwd_prefix && cwd.startsWith(mapping.cwd_prefix))
19
+ .sort((left, right) => (right.cwd_prefix?.length ?? 0) - (left.cwd_prefix?.length ?? 0));
20
+ if (hits.length > 0) {
21
+ return CwdInferenceResultSchema.parse({ outcome: 'hit', captain_id: hits[0].captain_id, matched_by: 'cwd_prefix' });
22
+ }
23
+ const candidates = [...new Set(config.mapping.map((mapping) => mapping.captain_id))];
24
+ return CwdInferenceResultSchema.parse({
25
+ outcome: 'miss',
26
+ candidates,
27
+ suggestion: candidates.length > 0 ? `run: wb captain use ${candidates[0]}` : 'no captains configured; run: wb captain init',
28
+ });
29
+ }
@@ -0,0 +1,63 @@
1
+ import { ConcurrencyQueueEntryStatus, } from './concurrency-queue-store.js';
2
+ export async function enqueueOrSpawn(deps, input) {
3
+ const runId = deps.genRunId();
4
+ const ts = deps.now();
5
+ const runningCount = deps.index.countRunning(input.session_id);
6
+ deps.metrics?.record({
7
+ metric: 'captain_queue_decisions_total',
8
+ value: 1,
9
+ labels: { session_id: input.session_id, decision: 'incoming' },
10
+ });
11
+ if (runningCount < deps.config.max_concurrent_runs) {
12
+ deps.store.append({
13
+ session_id: input.session_id,
14
+ run_id: runId,
15
+ status: ConcurrencyQueueEntryStatus.RUNNING,
16
+ ts,
17
+ });
18
+ deps.index.markRunning(input.session_id, runId, ts);
19
+ deps.metrics?.record({
20
+ metric: 'captain_queue_decisions_total',
21
+ value: 1,
22
+ labels: { session_id: input.session_id, decision: 'spawn' },
23
+ });
24
+ return { kind: 'spawn', run_id: runId };
25
+ }
26
+ const queuedCount = deps.index.countQueued(input.session_id);
27
+ if (queuedCount >= deps.config.queue_max_depth) {
28
+ deps.metrics?.record({
29
+ metric: 'captain_queue_decisions_total',
30
+ value: 1,
31
+ labels: { session_id: input.session_id, decision: 'rejected', reason: 'queue_full' },
32
+ });
33
+ deps.metrics?.record({
34
+ metric: 'captain_queue_rejections_total',
35
+ value: 1,
36
+ labels: { session_id: input.session_id, reason: 'queue_full' },
37
+ });
38
+ return { kind: 'rejected', reason: 'queue_full' };
39
+ }
40
+ deps.store.append({
41
+ session_id: input.session_id,
42
+ run_id: runId,
43
+ status: ConcurrencyQueueEntryStatus.QUEUED,
44
+ ts,
45
+ });
46
+ deps.index.enqueue(input.session_id, runId, ts);
47
+ const position = deps.index.countQueued(input.session_id);
48
+ deps.metrics?.record({
49
+ metric: 'captain_queue_decisions_total',
50
+ value: 1,
51
+ labels: { session_id: input.session_id, decision: 'queued' },
52
+ });
53
+ deps.metrics?.record({
54
+ metric: 'captain_queue_enqueue_position',
55
+ value: position,
56
+ labels: { session_id: input.session_id },
57
+ });
58
+ return {
59
+ kind: 'queued',
60
+ run_id: runId,
61
+ position,
62
+ };
63
+ }
@@ -0,0 +1,27 @@
1
+ import { loadConcurrencyConfig } from './concurrency-config.js';
2
+ import { createConcurrencyQueueIndex } from './concurrency-queue-index.js';
3
+ import { createConcurrencyQueueStore } from './concurrency-queue-store.js';
4
+ import { createQueueMetricsAggregator } from './queue-metrics/aggregator.js';
5
+ import { createQueueMetricsEventStore } from './queue-metrics/event-store.js';
6
+ export * from './contracts.js';
7
+ export { CaptainService } from './captain-service.js';
8
+ export { createCaptainSessionStore } from './session-store.js';
9
+ export { validateCatalog, COMMAND_CATALOG } from './command-catalog.js';
10
+ export { inferCaptain } from './cwd-inference.js';
11
+ export { loadCaptainConfig } from './toml-loader.js';
12
+ let processQueueMetricsAggregator;
13
+ export function getCaptainProcessQueueMetrics() {
14
+ return processQueueMetricsAggregator;
15
+ }
16
+ export function createCaptainConcurrencyContainer(dataDir) {
17
+ const metrics = createQueueMetricsAggregator({
18
+ eventStore: createQueueMetricsEventStore(dataDir),
19
+ });
20
+ processQueueMetricsAggregator = metrics;
21
+ return {
22
+ config: loadConcurrencyConfig(dataDir),
23
+ index: createConcurrencyQueueIndex(metrics),
24
+ store: createConcurrencyQueueStore(dataDir),
25
+ metrics,
26
+ };
27
+ }
@@ -0,0 +1,98 @@
1
+ import { QUEUE_HISTOGRAM_BUCKETS, QUEUE_METRIC_NAMES, QUEUE_METRIC_TYPES, } from './contracts.js';
2
+ function emptyState() {
3
+ return { counters: {}, gauges: {}, histograms: {} };
4
+ }
5
+ function ensureState(map, sessionId) {
6
+ const existing = map.get(sessionId);
7
+ if (existing)
8
+ return existing;
9
+ const created = emptyState();
10
+ map.set(sessionId, created);
11
+ return created;
12
+ }
13
+ function observeHistogram(state, metric, value) {
14
+ const existing = state.histograms[metric] ?? { values: [] };
15
+ existing.values.push(value);
16
+ state.histograms[metric] = existing;
17
+ }
18
+ function percentile(values, p) {
19
+ if (values.length === 0)
20
+ return 0;
21
+ const sorted = [...values].sort((a, b) => a - b);
22
+ const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * p) - 1));
23
+ return sorted[index] ?? 0;
24
+ }
25
+ function histogramSnapshot(metric, values) {
26
+ const buckets = QUEUE_HISTOGRAM_BUCKETS[metric] ?? [];
27
+ const bucketCounts = {};
28
+ for (const bucket of buckets) {
29
+ bucketCounts[String(bucket)] = values.filter((value) => value <= bucket).length;
30
+ }
31
+ return {
32
+ count: values.length,
33
+ sum: values.reduce((total, value) => total + value, 0),
34
+ p50: percentile(values, 0.5),
35
+ p95: percentile(values, 0.95),
36
+ buckets: bucketCounts,
37
+ };
38
+ }
39
+ function snapshotState(state) {
40
+ const histograms = {};
41
+ for (const [metric, histogram] of Object.entries(state.histograms)) {
42
+ histograms[metric] = histogramSnapshot(metric, histogram.values);
43
+ }
44
+ return {
45
+ counters: { ...state.counters },
46
+ gauges: { ...state.gauges },
47
+ histograms,
48
+ };
49
+ }
50
+ export function createQueueMetricsAggregator(options = {}) {
51
+ const globalState = emptyState();
52
+ const sessionStates = new Map();
53
+ function apply(state, event) {
54
+ const type = QUEUE_METRIC_TYPES[event.metric];
55
+ if (type === 'counter') {
56
+ state.counters[event.metric] = (state.counters[event.metric] ?? 0) + event.value;
57
+ return;
58
+ }
59
+ if (type === 'gauge') {
60
+ state.gauges[event.metric] = event.value;
61
+ return;
62
+ }
63
+ observeHistogram(state, event.metric, event.value);
64
+ }
65
+ function recordInternal(event) {
66
+ apply(globalState, event);
67
+ if (event.labels?.session_id) {
68
+ apply(ensureState(sessionStates, event.labels.session_id), event);
69
+ }
70
+ }
71
+ function recordStoreError(sessionId) {
72
+ const errorEvent = {
73
+ metric: 'captain_queue_store_read_errors_total',
74
+ value: 1,
75
+ ...(sessionId ? { labels: { session_id: sessionId } } : {}),
76
+ };
77
+ recordInternal(errorEvent);
78
+ }
79
+ return {
80
+ record(event) {
81
+ if (!QUEUE_METRIC_NAMES.includes(event.metric))
82
+ return;
83
+ recordInternal(event);
84
+ try {
85
+ options.eventStore?.append(event);
86
+ }
87
+ catch {
88
+ recordStoreError(event.labels?.session_id);
89
+ }
90
+ },
91
+ snapshot(opts) {
92
+ if (opts?.session_id) {
93
+ return snapshotState(sessionStates.get(opts.session_id) ?? emptyState());
94
+ }
95
+ return snapshotState(globalState);
96
+ },
97
+ };
98
+ }
@@ -0,0 +1,42 @@
1
+ export const QUEUE_METRIC_NAMES = [
2
+ 'captain_queue_decisions_total',
3
+ 'captain_queue_rejections_total',
4
+ 'captain_queue_enqueue_position',
5
+ 'captain_queue_depth',
6
+ 'captain_queue_running_total',
7
+ 'captain_queue_wait_duration_seconds',
8
+ 'captain_queue_promotions_total',
9
+ 'captain_run_ended_total',
10
+ 'captain_queue_commands_total',
11
+ 'captain_queue_cancelled_runs_total',
12
+ 'captain_queue_preempted_runs_total',
13
+ 'captain_queue_promoted_by_preempt_total',
14
+ 'captain_queue_promotion_failures_total',
15
+ 'captain_queue_entries_appended_total',
16
+ 'captain_queue_store_read_errors_total',
17
+ 'captain_queue_config_max_concurrent_runs',
18
+ 'captain_queue_config_max_depth',
19
+ ];
20
+ export const QUEUE_METRIC_TYPES = {
21
+ captain_queue_decisions_total: 'counter',
22
+ captain_queue_rejections_total: 'counter',
23
+ captain_queue_enqueue_position: 'histogram',
24
+ captain_queue_depth: 'gauge',
25
+ captain_queue_running_total: 'gauge',
26
+ captain_queue_wait_duration_seconds: 'histogram',
27
+ captain_queue_promotions_total: 'counter',
28
+ captain_run_ended_total: 'counter',
29
+ captain_queue_commands_total: 'counter',
30
+ captain_queue_cancelled_runs_total: 'counter',
31
+ captain_queue_preempted_runs_total: 'counter',
32
+ captain_queue_promoted_by_preempt_total: 'counter',
33
+ captain_queue_promotion_failures_total: 'counter',
34
+ captain_queue_entries_appended_total: 'counter',
35
+ captain_queue_store_read_errors_total: 'counter',
36
+ captain_queue_config_max_concurrent_runs: 'gauge',
37
+ captain_queue_config_max_depth: 'gauge',
38
+ };
39
+ export const QUEUE_HISTOGRAM_BUCKETS = {
40
+ captain_queue_enqueue_position: [1, 2, 3, 5, 8, 13],
41
+ captain_queue_wait_duration_seconds: [1, 5, 10, 30, 60, 120, 300],
42
+ };
@@ -0,0 +1,26 @@
1
+ import { captainQueueMetricsPath } from '../../paths.js';
2
+ import { appendNdjsonLine } from '../../util/ndjson-rotation.js';
3
+ import { QUEUE_METRIC_TYPES, } from './contracts.js';
4
+ function toRecord(event) {
5
+ const labels = {};
6
+ if (event.labels?.session_id)
7
+ labels.session_id = event.labels.session_id;
8
+ if (event.labels?.command)
9
+ labels.command = event.labels.command;
10
+ return {
11
+ ts: new Date().toISOString(),
12
+ metric: event.metric,
13
+ type: QUEUE_METRIC_TYPES[event.metric],
14
+ value: event.value,
15
+ ...(Object.keys(labels).length > 0 ? { labels } : {}),
16
+ };
17
+ }
18
+ export function createQueueMetricsEventStore(dataDir) {
19
+ const path = captainQueueMetricsPath(dataDir);
20
+ return {
21
+ path,
22
+ append(event) {
23
+ appendNdjsonLine(path, JSON.stringify(toRecord(event)));
24
+ },
25
+ };
26
+ }