@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,200 @@
1
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { buildDocBody, classifyDocSink } from './doc-sink-classifier.js';
4
+ import { createLarkDocTransport } from './doc-sink-transport.js';
5
+ import { replayEventsFromNdjson } from '../runner/event-replay.js';
6
+ import { runDocFallbackPath, runDocSinkLockPath, runDocSinkStatePath, runEventsPath } from '../paths.js';
7
+ import { RUN_REGISTRY_ERROR_CODES } from './contracts.js';
8
+ function readState(path) {
9
+ if (!existsSync(path))
10
+ return null;
11
+ try {
12
+ return JSON.parse(readFileSync(path, 'utf8'));
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ }
18
+ function atomicWrite(path, content) {
19
+ mkdirSync(dirname(path), { recursive: true });
20
+ const temp = `${path}.tmp`;
21
+ writeFileSync(temp, content);
22
+ renameSync(temp, path);
23
+ }
24
+ function writeState(path, value) {
25
+ atomicWrite(path, JSON.stringify(value, null, 2));
26
+ }
27
+ function writeFallback(path, content) {
28
+ atomicWrite(path, content);
29
+ }
30
+ function buildFailureState(runId, message) {
31
+ return {
32
+ run_id: runId,
33
+ status: 'failed',
34
+ doc_url: null,
35
+ error_code: RUN_REGISTRY_ERROR_CODES.E_DOC_SINK_WRITE,
36
+ error_message: message,
37
+ updated_at: new Date().toISOString(),
38
+ };
39
+ }
40
+ function mergeProducedDocUrls(existing, next) {
41
+ return [...new Set([...existing, ...next])];
42
+ }
43
+ function acquireLock(path) {
44
+ mkdirSync(dirname(path), { recursive: true });
45
+ try {
46
+ return openSync(path, 'wx');
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ function releaseLock(path, fd) {
53
+ if (fd === null)
54
+ return;
55
+ try {
56
+ closeSync(fd);
57
+ }
58
+ finally {
59
+ try {
60
+ unlinkSync(path);
61
+ }
62
+ catch {
63
+ // ignore stale cleanup failure
64
+ }
65
+ }
66
+ }
67
+ export function buildRunRecordFromUpserted(input) {
68
+ const spec = input.entry.spec;
69
+ const threadId = spec?.threadId ?? '';
70
+ return {
71
+ run_id: input.event.run_id,
72
+ created_at: spec?.startedAt ?? new Date().toISOString(),
73
+ operator: spec?.userOpenId ?? 'unknown',
74
+ project: threadId ? `${spec?.botId ?? 'default'}_${threadId.split('/')[0] ?? ''}` : null,
75
+ cwd: spec?.cwd ?? '',
76
+ scope: spec?.consentLevel ?? 'normal',
77
+ agent: spec?.agentId ?? 'claude-code',
78
+ cmd: spec?.model ? `${spec?.agentId ?? 'claude-code'} --model ${spec.model}` : (spec?.agentId ?? 'claude-code'),
79
+ status: input.event.status,
80
+ cost_tokens: input.event.cost_tokens,
81
+ cost_minutes: input.event.cost_minutes,
82
+ produced_doc_urls: input.event.produced_doc_urls,
83
+ commit_shas: input.event.commit_shas,
84
+ risk_level: 'unknown',
85
+ home_group_id: threadId || null,
86
+ entry_form: threadId ? 'im' : 'cli',
87
+ doc_sink_failed: input.entry.doc_sink_failed ?? false,
88
+ calendar_block_id: input.event.calendar_block_id ?? null,
89
+ calendar_hook_failed: input.entry.calendar_hook_failed ?? false,
90
+ };
91
+ }
92
+ export async function ensureRunDoc(options) {
93
+ const botId = options.botId ?? 'default';
94
+ const statePath = runDocSinkStatePath(options.dataDir, options.runId, botId);
95
+ const fallbackPath = runDocFallbackPath(options.dataDir, options.runId, botId);
96
+ const lockPath = runDocSinkLockPath(options.dataDir, options.runId, botId);
97
+ if (options.status !== 'succeeded' && options.status !== 'failed' && options.status !== 'cancelled') {
98
+ return {
99
+ produced_doc_urls: options.existingDocUrls ?? [],
100
+ doc_sink_failed: false,
101
+ statePath,
102
+ fallbackPath,
103
+ reason: 'not_terminal',
104
+ };
105
+ }
106
+ const existingState = readState(statePath);
107
+ if (existingState?.status === 'succeeded' && existingState.doc_url) {
108
+ return {
109
+ produced_doc_urls: mergeProducedDocUrls(options.existingDocUrls ?? [], [existingState.doc_url]),
110
+ doc_sink_failed: false,
111
+ statePath,
112
+ fallbackPath,
113
+ reason: 'already_succeeded',
114
+ };
115
+ }
116
+ const eventsPath = runEventsPath(options.dataDir, options.runId, botId);
117
+ const replay = replayEventsFromNdjson(eventsPath);
118
+ if (replay.skipped) {
119
+ const message = replay.errors.join('; ') || 'event replay skipped';
120
+ writeState(statePath, buildFailureState(options.runId, message));
121
+ writeFallback(fallbackPath, `Run ID: ${options.runId}\n\n${message}`);
122
+ return {
123
+ produced_doc_urls: [],
124
+ doc_sink_failed: true,
125
+ statePath,
126
+ fallbackPath,
127
+ reason: 'failed',
128
+ };
129
+ }
130
+ const classification = classifyDocSink(replay.events, options.runId);
131
+ if (!classification.shouldSink) {
132
+ return {
133
+ produced_doc_urls: [],
134
+ doc_sink_failed: false,
135
+ statePath,
136
+ fallbackPath,
137
+ reason: 'not_longform',
138
+ };
139
+ }
140
+ const lockFd = acquireLock(lockPath);
141
+ if (lockFd === null) {
142
+ const refreshedState = readState(statePath);
143
+ if (refreshedState?.status === 'succeeded' && refreshedState.doc_url) {
144
+ return {
145
+ produced_doc_urls: [refreshedState.doc_url],
146
+ doc_sink_failed: false,
147
+ statePath,
148
+ fallbackPath,
149
+ reason: 'already_succeeded',
150
+ };
151
+ }
152
+ return {
153
+ produced_doc_urls: [],
154
+ doc_sink_failed: false,
155
+ statePath,
156
+ fallbackPath,
157
+ reason: 'locked',
158
+ };
159
+ }
160
+ const transport = options.transport ?? createLarkDocTransport();
161
+ const body = buildDocBody(options.runId, classification.text);
162
+ try {
163
+ const created = await transport.create({
164
+ runId: options.runId,
165
+ title: classification.title,
166
+ body,
167
+ env: options.env,
168
+ });
169
+ writeState(statePath, {
170
+ run_id: options.runId,
171
+ status: 'succeeded',
172
+ doc_url: created.url,
173
+ error_code: null,
174
+ error_message: null,
175
+ updated_at: new Date().toISOString(),
176
+ });
177
+ return {
178
+ produced_doc_urls: [created.url],
179
+ doc_sink_failed: false,
180
+ statePath,
181
+ fallbackPath,
182
+ reason: 'created',
183
+ };
184
+ }
185
+ catch (error) {
186
+ const message = error instanceof Error ? error.message : String(error);
187
+ writeState(statePath, buildFailureState(options.runId, message));
188
+ writeFallback(fallbackPath, body);
189
+ return {
190
+ produced_doc_urls: [],
191
+ doc_sink_failed: true,
192
+ statePath,
193
+ fallbackPath,
194
+ reason: 'failed',
195
+ };
196
+ }
197
+ finally {
198
+ releaseLock(lockPath, lockFd);
199
+ }
200
+ }
@@ -0,0 +1,40 @@
1
+ import { deriveApprovalRiskLevel } from '../approval-gate/audit.js';
2
+ const SHA_PATTERN = /\b[0-9a-f]{40}\b/g;
3
+ function matchesAllowlist(url, rule) {
4
+ if (rule.startsWith('*.')) {
5
+ const suffix = rule.slice(1);
6
+ return url.hostname.endsWith(suffix);
7
+ }
8
+ return url.hostname === rule || url.hostname.endsWith(`.${rule}`);
9
+ }
10
+ export function extractUrls(records, allowlist) {
11
+ const urls = new Set();
12
+ for (const record of records) {
13
+ if (record.action !== 'network_call')
14
+ continue;
15
+ try {
16
+ const parsed = new URL(record.resource);
17
+ if (allowlist.some((rule) => matchesAllowlist(parsed, rule))) {
18
+ urls.add(parsed.toString());
19
+ }
20
+ }
21
+ catch {
22
+ continue;
23
+ }
24
+ }
25
+ return [...urls];
26
+ }
27
+ export function extractShas(records) {
28
+ const shas = new Set();
29
+ for (const record of records) {
30
+ if (record.action !== 'git_op')
31
+ continue;
32
+ for (const sha of record.resource.match(SHA_PATTERN) ?? []) {
33
+ shas.add(sha);
34
+ }
35
+ }
36
+ return [...shas];
37
+ }
38
+ export function extractRiskLevel(records) {
39
+ return deriveApprovalRiskLevel(records);
40
+ }
@@ -0,0 +1,11 @@
1
+ export * from './contracts.js';
2
+ export { createRunRegistryWriter, } from './bitable-writer.js';
3
+ export { loadRunRegistryConfig, resolveRunRegistryConfigPath, resolveRunRegistryDataDir } from './config.js';
4
+ export { ensureRunDoc, buildRunRecordFromUpserted } from './doc-sink.js';
5
+ export { buildDocBody, classifyDocSink, collectLongformText, sanitizeDocSinkText } from './doc-sink-classifier.js';
6
+ export { createLarkDocTransport } from './doc-sink-transport.js';
7
+ export { extractShas, extractUrls } from './extractor.js';
8
+ export { RUN_INHERIT_FIELDS, buildRunInheritanceSnapshot } from './inherit.js';
9
+ export { startRunRegistry } from './orchestrator.js';
10
+ export { RunTailer } from './tailer.js';
11
+ export { createRunRegistryWal } from './wal.js';
@@ -0,0 +1,11 @@
1
+ export const RUN_INHERIT_FIELDS = ['project', 'cwd', 'scope', 'agent', 'home_group_id', 'entry_form'];
2
+ export function buildRunInheritanceSnapshot(source) {
3
+ return {
4
+ project: source.project,
5
+ cwd: source.cwd,
6
+ scope: source.scope,
7
+ agent: source.agent,
8
+ home_group_id: source.home_group_id,
9
+ entry_form: source.entry_form,
10
+ };
11
+ }
@@ -0,0 +1,86 @@
1
+ import { configFile } from '../paths.js';
2
+ import { buildRunRecordFromUpserted } from './doc-sink.js';
3
+ import { loadRunRegistryConfig, resolveRunRegistryDataDir } from './config.js';
4
+ import { createRunRegistryWriter } from './bitable-writer.js';
5
+ import { RunTailer } from './tailer.js';
6
+ function countWalPending(writer) {
7
+ return writer?.wal.listFiles().length ?? 0;
8
+ }
9
+ async function startRuntime(state, options) {
10
+ const config = loadRunRegistryConfig({ configPath: state.configPath, env: state.env });
11
+ const writer = createRunRegistryWriter(options);
12
+ await writer.validateSchema();
13
+ writer.startSyncWorker();
14
+ const nextTailer = new RunTailer({
15
+ dataDir: resolveRunRegistryDataDir(state.env),
16
+ runFinalizeGraceMs: config.run_finalize_grace_ms,
17
+ config,
18
+ env: state.env,
19
+ docSinkTransport: options.docSinkTransport,
20
+ batchFlushIntervalMs: options._tailerBatchFlushIntervalMs,
21
+ pollIntervalMs: options._tailerPollIntervalMs,
22
+ finalizeIntervalMs: options._tailerFinalizeIntervalMs,
23
+ onRunUpserted: async (event, entry) => {
24
+ const record = buildRunRecordFromUpserted({ event, entry });
25
+ const result = await writer.upsert(record);
26
+ if (result.ok)
27
+ state.lastWriteOk = new Date().toISOString();
28
+ },
29
+ });
30
+ const previousTailer = state.tailer;
31
+ const previousWriter = state.writer;
32
+ previousTailer?.stop();
33
+ await previousTailer?.waitForIdle();
34
+ previousWriter?.stopSyncWorker();
35
+ state.writer = writer;
36
+ state.tailer = nextTailer;
37
+ nextTailer.start();
38
+ }
39
+ export async function startRunRegistry(options = {}) {
40
+ const env = options.env ?? process.env;
41
+ const dataDir = resolveRunRegistryDataDir(env);
42
+ const state = {
43
+ configPath: options.configPath ?? configFile(dataDir, 'run-registry'),
44
+ env,
45
+ writer: null,
46
+ tailer: null,
47
+ stopped: false,
48
+ lastWriteOk: null,
49
+ onSighup: null,
50
+ onSigterm: null,
51
+ };
52
+ await startRuntime(state, options);
53
+ const controller = {
54
+ async reload() {
55
+ if (state.stopped)
56
+ return;
57
+ await startRuntime(state, options);
58
+ },
59
+ async stop() {
60
+ if (state.stopped)
61
+ return;
62
+ state.stopped = true;
63
+ state.tailer?.stop();
64
+ state.writer?.stopSyncWorker();
65
+ if (state.onSighup)
66
+ process.removeListener('SIGHUP', state.onSighup);
67
+ if (state.onSigterm)
68
+ process.removeListener('SIGTERM', state.onSigterm);
69
+ },
70
+ status() {
71
+ return {
72
+ walPending: countWalPending(state.writer),
73
+ lastWriteOk: state.lastWriteOk,
74
+ };
75
+ },
76
+ };
77
+ state.onSighup = () => {
78
+ void controller.reload();
79
+ };
80
+ state.onSigterm = () => {
81
+ void controller.stop();
82
+ };
83
+ process.on('SIGHUP', state.onSighup);
84
+ process.on('SIGTERM', state.onSigterm);
85
+ return controller;
86
+ }
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { startRunRegistry } from './orchestrator.js';
4
+ import { isEntryModule } from '../util/entry-module.js';
5
+ export function resolveRunRegistryCommand(argv) {
6
+ const parsed = parseArgs({
7
+ args: argv,
8
+ allowPositionals: false,
9
+ options: {
10
+ once: { type: 'boolean', default: false },
11
+ interval: { type: 'string' },
12
+ },
13
+ });
14
+ const intervalRaw = parsed.values.interval;
15
+ return { once: parsed.values.once, intervalMs: intervalRaw ? Number.parseInt(intervalRaw, 10) : undefined };
16
+ }
17
+ async function main() {
18
+ const command = resolveRunRegistryCommand(process.argv.slice(2));
19
+ const controller = await startRunRegistry();
20
+ if (command.once) {
21
+ const waitMs = command.intervalMs && command.intervalMs > 0 ? Math.min(command.intervalMs, 1_000) : 1_000;
22
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
23
+ await controller.stop();
24
+ return;
25
+ }
26
+ await new Promise((resolve) => {
27
+ const shutdown = () => { void controller.stop().finally(resolve); };
28
+ process.once('SIGINT', shutdown);
29
+ process.once('SIGTERM', shutdown);
30
+ });
31
+ }
32
+ const isEntry = isEntryModule(import.meta.url);
33
+ if (isEntry) {
34
+ void main().catch((error) => {
35
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
36
+ process.exit(1);
37
+ });
38
+ }