@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,166 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { groupSyncDir, runDir, runDocFallbackPath, runDocSinkStatePath } from '../paths.js';
4
+ import { ensureRunDoc } from '../run-registry/index.js';
5
+ import { GroupSyncAutoDocArtifactSchema, GroupSyncAutoDocArtifactSetSchema, GroupSyncAutoDocInputSchema, } from './contracts.js';
6
+ function atomicWrite(path, content) {
7
+ mkdirSync(dirname(path), { recursive: true });
8
+ const temp = `${path}.tmp`;
9
+ writeFileSync(temp, content);
10
+ renameSync(temp, path);
11
+ }
12
+ function runGroupSyncAutoDocsPath(dataDir, runId, botId = 'default') {
13
+ return join(runDir(dataDir, runId, botId), 'group-sync-docs.json');
14
+ }
15
+ function readArtifactSet(path, input, nowIso) {
16
+ if (!existsSync(path)) {
17
+ return GroupSyncAutoDocArtifactSetSchema.parse({
18
+ session_id: input.session_id,
19
+ run_id: input.run_id,
20
+ last_revision: input.revision,
21
+ updated_at: nowIso,
22
+ artifacts: [],
23
+ });
24
+ }
25
+ return GroupSyncAutoDocArtifactSetSchema.parse(JSON.parse(readFileSync(path, 'utf8')));
26
+ }
27
+ function writeArtifactSet(path, state) {
28
+ atomicWrite(path, JSON.stringify(state, null, 2));
29
+ }
30
+ function sanitizeIdPart(value) {
31
+ const raw = value?.trim() ?? '';
32
+ if (raw.length === 0)
33
+ return 'none';
34
+ return raw.replace(/[^a-zA-Z0-9._-]+/g, '_');
35
+ }
36
+ function buildSyncId(input) {
37
+ return [
38
+ 'autodoc',
39
+ sanitizeIdPart(input.request_id),
40
+ sanitizeIdPart(input.artifact_id),
41
+ sanitizeIdPart(input.sink_run_id),
42
+ ].join(':');
43
+ }
44
+ function readDocSinkError(path) {
45
+ if (!existsSync(path))
46
+ return null;
47
+ try {
48
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
49
+ return typeof parsed.error_message === 'string' && parsed.error_message.length > 0 ? parsed.error_message : null;
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
55
+ function toArtifact(input, nowIso, patch = {}) {
56
+ return GroupSyncAutoDocArtifactSchema.parse({
57
+ request_id: input.request_id,
58
+ session_id: input.session_id,
59
+ run_id: input.run_id,
60
+ revision: input.revision,
61
+ artifact_id: input.artifact_id,
62
+ artifact_label: input.artifact_label,
63
+ artifact_path: input.artifact_path ?? null,
64
+ sink_run_id: input.sink_run_id,
65
+ terminal_status: input.terminal_status,
66
+ existing_doc_urls: input.existing_doc_urls,
67
+ sync_id: buildSyncId(input),
68
+ doc_urls: patch.doc_urls ?? [],
69
+ doc_sink_failed: patch.doc_sink_failed ?? false,
70
+ sync_failed: patch.sync_failed ?? false,
71
+ sink_reason: patch.sink_reason ?? 'not_longform',
72
+ doc_state_path: patch.doc_state_path ?? '',
73
+ fallback_path: patch.fallback_path ?? '',
74
+ created_at: patch.created_at ?? nowIso,
75
+ synced_at: patch.synced_at ?? null,
76
+ last_error: patch.last_error ?? null,
77
+ });
78
+ }
79
+ function mergeArtifactSet(state, artifact, nowIso) {
80
+ const artifacts = state.artifacts.filter((item) => item.sync_id !== artifact.sync_id);
81
+ artifacts.push(artifact);
82
+ artifacts.sort((left, right) => left.sync_id.localeCompare(right.sync_id));
83
+ return GroupSyncAutoDocArtifactSetSchema.parse({
84
+ session_id: state.session_id,
85
+ run_id: state.run_id,
86
+ last_revision: Math.max(state.last_revision, artifact.revision),
87
+ updated_at: nowIso,
88
+ artifacts,
89
+ });
90
+ }
91
+ export function groupSyncMockAutoDocLedgerPath(dataDir) {
92
+ return join(groupSyncDir(dataDir), 'mock-docs.ndjson');
93
+ }
94
+ export async function publishAutoDocArtifact(options) {
95
+ const input = GroupSyncAutoDocInputSchema.parse(options.doc);
96
+ const nowFn = options.nowFn ?? Date.now;
97
+ const nowIso = new Date(nowFn()).toISOString();
98
+ const botId = options.botId ?? 'default';
99
+ const statePath = runGroupSyncAutoDocsPath(options.dataDir, input.run_id, botId);
100
+ const current = readArtifactSet(statePath, input, nowIso);
101
+ const existing = current.artifacts.find((item) => item.sync_id === buildSyncId(input));
102
+ if (existing && existing.sync_failed === false) {
103
+ return {
104
+ sync_failed: false,
105
+ artifact: existing,
106
+ state: current,
107
+ statePath,
108
+ };
109
+ }
110
+ try {
111
+ const docResult = await ensureRunDoc({
112
+ dataDir: options.dataDir,
113
+ runId: input.sink_run_id,
114
+ botId,
115
+ status: input.terminal_status,
116
+ existingDocUrls: input.existing_doc_urls,
117
+ config: options.runRegistryConfig,
118
+ transport: options.transport,
119
+ env: options.env,
120
+ });
121
+ const lastError = docResult.doc_sink_failed ? readDocSinkError(docResult.statePath) : null;
122
+ const artifact = toArtifact(input, nowIso, {
123
+ created_at: existing?.created_at ?? nowIso,
124
+ doc_urls: docResult.produced_doc_urls,
125
+ doc_sink_failed: docResult.doc_sink_failed,
126
+ sync_failed: docResult.doc_sink_failed,
127
+ sink_reason: docResult.reason,
128
+ doc_state_path: docResult.statePath,
129
+ fallback_path: docResult.fallbackPath,
130
+ synced_at: docResult.doc_sink_failed ? null : nowIso,
131
+ last_error: lastError,
132
+ });
133
+ const nextState = mergeArtifactSet(current, artifact, nowIso);
134
+ writeArtifactSet(statePath, nextState);
135
+ return {
136
+ sync_failed: artifact.sync_failed,
137
+ artifact,
138
+ state: nextState,
139
+ statePath,
140
+ };
141
+ }
142
+ catch (error) {
143
+ const message = error instanceof Error ? error.message : String(error);
144
+ const docStatePath = runDocSinkStatePath(options.dataDir, input.sink_run_id, botId);
145
+ const fallbackPath = runDocFallbackPath(options.dataDir, input.sink_run_id, botId);
146
+ const artifact = toArtifact(input, nowIso, {
147
+ created_at: existing?.created_at ?? nowIso,
148
+ doc_urls: [],
149
+ doc_sink_failed: true,
150
+ sync_failed: true,
151
+ sink_reason: 'failed',
152
+ doc_state_path: docStatePath,
153
+ fallback_path: fallbackPath,
154
+ synced_at: null,
155
+ last_error: message,
156
+ });
157
+ const nextState = mergeArtifactSet(current, artifact, nowIso);
158
+ writeArtifactSet(statePath, nextState);
159
+ return {
160
+ sync_failed: true,
161
+ artifact,
162
+ state: nextState,
163
+ statePath,
164
+ };
165
+ }
166
+ }
@@ -0,0 +1,45 @@
1
+ import { existsSync, readFileSync, statSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { loadConfig } from '../config/registry.js';
4
+ import { configFile, legacyConfigJsonPath, resolveDataDir } from '../paths.js';
5
+ import { GroupSyncConfigSchema } from './contracts.js';
6
+ function validateMode(path) {
7
+ const stat = statSync(path);
8
+ if ((stat.mode & 0o077) !== 0) {
9
+ throw new Error(`${path} permissions are too open (${(stat.mode & 0o777).toString(8)}), expected 600`);
10
+ }
11
+ }
12
+ function readJson(path) {
13
+ return JSON.parse(readFileSync(path, 'utf8'));
14
+ }
15
+ function isRecord(value) {
16
+ return typeof value === 'object' && value !== null;
17
+ }
18
+ function parseLegacyConfig(path) {
19
+ const parsed = readJson(path);
20
+ if (!isRecord(parsed) || !isRecord(parsed['group_sync'])) {
21
+ throw new Error('config.json must contain a group_sync object');
22
+ }
23
+ return GroupSyncConfigSchema.parse(parsed['group_sync']);
24
+ }
25
+ export function resolveGroupSyncDataDir(env = process.env) {
26
+ return resolveDataDir({ dataDir: env['WB_DATA_DIR'] });
27
+ }
28
+ export function resolveGroupSyncConfigPath(env = process.env) {
29
+ return resolve(configFile(resolveGroupSyncDataDir(env), 'group-sync'));
30
+ }
31
+ export function loadGroupSyncConfig(options = {}) {
32
+ const env = options.env ?? process.env;
33
+ const dataDir = resolveGroupSyncDataDir(env);
34
+ const configPath = resolve(options.configPath ?? resolveGroupSyncConfigPath(env));
35
+ const legacyPath = resolve(legacyConfigJsonPath(dataDir));
36
+ if (existsSync(configPath)) {
37
+ validateMode(configPath);
38
+ return GroupSyncConfigSchema.parse(loadConfig(dataDir, 'group-sync', GroupSyncConfigSchema, {}));
39
+ }
40
+ if (existsSync(legacyPath)) {
41
+ validateMode(legacyPath);
42
+ return parseLegacyConfig(legacyPath);
43
+ }
44
+ return GroupSyncConfigSchema.parse({});
45
+ }
@@ -0,0 +1,126 @@
1
+ import { z } from 'zod';
2
+ export const GroupSyncConfigSchema = z.object({
3
+ enabled: z.boolean().default(false),
4
+ transport: z.enum(['disabled', 'mock', 'guarded']).default('disabled'),
5
+ rpc_timeout_ms: z.number().int().positive().default(15_000),
6
+ sweep_interval_ms: z.number().int().positive().default(15_000),
7
+ });
8
+ export const GroupSyncCommandReceivedSchema = z.object({
9
+ request_id: z.string().min(1),
10
+ session_id: z.string().min(1),
11
+ run_id: z.string().min(1),
12
+ revision: z.number().int().min(0),
13
+ text: z.string().min(1),
14
+ scheduled_at: z.string().datetime(),
15
+ user_open_id: z.string().optional(),
16
+ thread_id: z.string().optional(),
17
+ message_id: z.string().optional(),
18
+ });
19
+ export const GroupSyncStateSchema = z.object({
20
+ request_id: z.string().min(1),
21
+ session_id: z.string().min(1),
22
+ run_id: z.string().min(1),
23
+ revision: z.number().int().min(0),
24
+ thread_id: z.string().nullable().default(null),
25
+ message_id: z.string().nullable().default(null),
26
+ scheduled_at: z.string().datetime(),
27
+ last_synced_at: z.string().datetime().nullable().default(null),
28
+ sync_failed: z.boolean().default(false),
29
+ last_error: z.string().nullable().default(null),
30
+ updated_at: z.string().datetime(),
31
+ });
32
+ export const GroupSyncArtifactKindSchema = z.enum(['run', 'session', 'diff', 'doc']);
33
+ export const GroupSyncCrossGroupReferenceInputSchema = z.object({
34
+ request_id: z.string().min(1),
35
+ session_id: z.string().min(1),
36
+ run_id: z.string().min(1),
37
+ revision: z.number().int().min(0),
38
+ source_thread_id: z.string().min(1),
39
+ source_message_id: z.string().min(1).nullable().optional(),
40
+ target_thread_id: z.string().min(1),
41
+ target_message_id: z.string().min(1).nullable().optional(),
42
+ artifact_kind: GroupSyncArtifactKindSchema.default('run'),
43
+ artifact_label: z.string().min(1),
44
+ artifact_path: z.string().min(1).nullable().optional(),
45
+ });
46
+ export const GroupSyncCrossGroupReferenceSchema = GroupSyncCrossGroupReferenceInputSchema.extend({
47
+ reference_id: z.string().min(1),
48
+ created_at: z.string().datetime(),
49
+ synced_at: z.string().datetime().nullable().default(null),
50
+ sync_failed: z.boolean().default(false),
51
+ last_error: z.string().nullable().default(null),
52
+ });
53
+ export const GroupSyncCrossGroupReferenceSetSchema = z.object({
54
+ session_id: z.string().min(1),
55
+ run_id: z.string().min(1),
56
+ last_revision: z.number().int().min(0),
57
+ updated_at: z.string().datetime(),
58
+ references: z.array(GroupSyncCrossGroupReferenceSchema).default([]),
59
+ });
60
+ export const GroupSyncReviewDiffReplyInputSchema = z.object({
61
+ request_id: z.string().min(1),
62
+ session_id: z.string().min(1),
63
+ run_id: z.string().min(1),
64
+ revision: z.number().int().min(0),
65
+ source_thread_id: z.string().min(1),
66
+ source_message_id: z.string().min(1).nullable().optional(),
67
+ review_id: z.string().min(1),
68
+ title: z.string().min(1),
69
+ summary: z.string().min(1),
70
+ diff_paths: z.array(z.string().min(1)).default([]),
71
+ });
72
+ export const GroupSyncReviewDiffReplySchema = GroupSyncReviewDiffReplyInputSchema.extend({
73
+ reply_id: z.string().min(1),
74
+ created_at: z.string().datetime(),
75
+ synced_at: z.string().datetime().nullable().default(null),
76
+ sync_failed: z.boolean().default(false),
77
+ last_error: z.string().nullable().default(null),
78
+ });
79
+ export const GroupSyncReviewDiffReplySetSchema = z.object({
80
+ session_id: z.string().min(1),
81
+ run_id: z.string().min(1),
82
+ last_revision: z.number().int().min(0),
83
+ updated_at: z.string().datetime(),
84
+ replies: z.array(GroupSyncReviewDiffReplySchema).default([]),
85
+ });
86
+ export const GroupSyncAutoDocTerminalStatusSchema = z.enum(['succeeded', 'failed', 'cancelled']);
87
+ export const GroupSyncAutoDocInputSchema = z.object({
88
+ request_id: z.string().min(1),
89
+ session_id: z.string().min(1),
90
+ run_id: z.string().min(1),
91
+ revision: z.number().int().min(0),
92
+ artifact_id: z.string().min(1),
93
+ artifact_label: z.string().min(1),
94
+ artifact_path: z.string().min(1).nullable().optional(),
95
+ sink_run_id: z.string().min(1),
96
+ terminal_status: GroupSyncAutoDocTerminalStatusSchema,
97
+ existing_doc_urls: z.array(z.string().url()).default([]),
98
+ });
99
+ export const GroupSyncAutoDocReasonSchema = z.enum([
100
+ 'already_succeeded',
101
+ 'existing_registry_url',
102
+ 'not_terminal',
103
+ 'not_longform',
104
+ 'created',
105
+ 'failed',
106
+ 'locked',
107
+ ]);
108
+ export const GroupSyncAutoDocArtifactSchema = GroupSyncAutoDocInputSchema.extend({
109
+ sync_id: z.string().min(1),
110
+ doc_urls: z.array(z.string().url()).default([]),
111
+ doc_sink_failed: z.boolean().default(false),
112
+ sync_failed: z.boolean().default(false),
113
+ sink_reason: GroupSyncAutoDocReasonSchema,
114
+ doc_state_path: z.string().min(1),
115
+ fallback_path: z.string().min(1),
116
+ created_at: z.string().datetime(),
117
+ synced_at: z.string().datetime().nullable().default(null),
118
+ last_error: z.string().nullable().default(null),
119
+ });
120
+ export const GroupSyncAutoDocArtifactSetSchema = z.object({
121
+ session_id: z.string().min(1),
122
+ run_id: z.string().min(1),
123
+ last_revision: z.number().int().min(0),
124
+ updated_at: z.string().datetime(),
125
+ artifacts: z.array(GroupSyncAutoDocArtifactSchema).default([]),
126
+ });
@@ -0,0 +1,163 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { z } from 'zod';
4
+ import { groupSyncDir, runDir } from '../paths.js';
5
+ import { appendNdjsonLine } from '../util/ndjson-rotation.js';
6
+ import { GroupSyncCommandReceivedSchema } from './contracts.js';
7
+ const GroupSyncDispatchRecordSchema = GroupSyncCommandReceivedSchema.extend({
8
+ dispatch_id: z.string().min(1),
9
+ created_at: z.string().datetime(),
10
+ dispatched_at: z.string().datetime().nullable().default(null),
11
+ dispatch_failed: z.boolean().default(false),
12
+ last_error: z.string().nullable().default(null),
13
+ });
14
+ const GroupSyncDispatchStateSchema = z.object({
15
+ session_id: z.string().min(1),
16
+ run_id: z.string().min(1),
17
+ last_revision: z.number().int().min(0),
18
+ updated_at: z.string().datetime(),
19
+ commands: z.array(GroupSyncDispatchRecordSchema).default([]),
20
+ });
21
+ function atomicWrite(path, content) {
22
+ mkdirSync(dirname(path), { recursive: true });
23
+ const temp = `${path}.tmp`;
24
+ writeFileSync(temp, content);
25
+ renameSync(temp, path);
26
+ }
27
+ function runGroupSyncDispatchPath(dataDir, runId, botId = 'default') {
28
+ return join(runDir(dataDir, runId, botId), 'group-sync-dispatch.json');
29
+ }
30
+ function readDispatchSet(path, input, nowIso) {
31
+ if (!existsSync(path)) {
32
+ return GroupSyncDispatchStateSchema.parse({
33
+ session_id: input.session_id,
34
+ run_id: input.run_id,
35
+ last_revision: input.revision,
36
+ updated_at: nowIso,
37
+ commands: [],
38
+ });
39
+ }
40
+ return GroupSyncDispatchStateSchema.parse(JSON.parse(readFileSync(path, 'utf8')));
41
+ }
42
+ function writeDispatchSet(path, state) {
43
+ atomicWrite(path, JSON.stringify(state, null, 2));
44
+ }
45
+ function sanitizeIdPart(value) {
46
+ const raw = value?.trim() ?? '';
47
+ if (raw.length === 0)
48
+ return 'none';
49
+ return raw.replace(/[^a-zA-Z0-9._-]+/g, '_');
50
+ }
51
+ function buildDispatchId(input) {
52
+ return [
53
+ 'dispatch',
54
+ sanitizeIdPart(input.request_id),
55
+ sanitizeIdPart(input.run_id),
56
+ sanitizeIdPart(String(input.revision)),
57
+ ].join(':');
58
+ }
59
+ function toDispatchRecord(input, nowIso, patch = {}) {
60
+ return GroupSyncDispatchRecordSchema.parse({
61
+ request_id: input.request_id,
62
+ session_id: input.session_id,
63
+ run_id: input.run_id,
64
+ revision: input.revision,
65
+ text: input.text,
66
+ scheduled_at: input.scheduled_at,
67
+ user_open_id: input.user_open_id,
68
+ thread_id: input.thread_id,
69
+ message_id: input.message_id,
70
+ dispatch_id: buildDispatchId(input),
71
+ created_at: patch.created_at ?? nowIso,
72
+ dispatched_at: patch.dispatched_at ?? null,
73
+ dispatch_failed: patch.dispatch_failed ?? false,
74
+ last_error: patch.last_error ?? null,
75
+ });
76
+ }
77
+ function mergeDispatchSet(state, record, nowIso) {
78
+ const commands = state.commands.filter((item) => item.dispatch_id !== record.dispatch_id);
79
+ commands.push(record);
80
+ commands.sort((left, right) => left.dispatch_id.localeCompare(right.dispatch_id));
81
+ return GroupSyncDispatchStateSchema.parse({
82
+ session_id: state.session_id,
83
+ run_id: state.run_id,
84
+ last_revision: Math.max(state.last_revision, record.revision),
85
+ updated_at: nowIso,
86
+ commands,
87
+ });
88
+ }
89
+ export function groupSyncMockDispatchLedgerPath(dataDir) {
90
+ return join(groupSyncDir(dataDir), 'mock-dispatch.ndjson');
91
+ }
92
+ export function createInlineGroupSyncDispatchTransport(handler) {
93
+ return {
94
+ async dispatchCommand(input) {
95
+ await handler(input);
96
+ },
97
+ };
98
+ }
99
+ export function createMockGroupSyncDispatchTransport(dataDir) {
100
+ const ledgerPath = groupSyncMockDispatchLedgerPath(dataDir);
101
+ return {
102
+ async dispatchCommand(input) {
103
+ mkdirSync(dirname(ledgerPath), { recursive: true });
104
+ appendNdjsonLine(ledgerPath, JSON.stringify(GroupSyncCommandReceivedSchema.parse(input)));
105
+ },
106
+ };
107
+ }
108
+ export function createGuardedCliGroupSyncDispatchTransport() {
109
+ return {
110
+ async dispatchCommand() {
111
+ throw new Error('group sync dispatch egress requires explicit real-device authorization');
112
+ },
113
+ };
114
+ }
115
+ export async function dispatchGroupSyncCommand(options) {
116
+ const command = GroupSyncCommandReceivedSchema.parse(options.command);
117
+ const nowFn = options.nowFn ?? Date.now;
118
+ const nowIso = new Date(nowFn()).toISOString();
119
+ const statePath = runGroupSyncDispatchPath(options.dataDir, command.run_id, options.botId ?? 'default');
120
+ const current = readDispatchSet(statePath, command, nowIso);
121
+ const existing = current.commands.find((item) => item.dispatch_id === buildDispatchId(command));
122
+ if (existing && existing.dispatch_failed === false) {
123
+ return {
124
+ dispatch_failed: false,
125
+ record: existing,
126
+ state: current,
127
+ statePath,
128
+ };
129
+ }
130
+ try {
131
+ await options.transport.dispatchCommand(command);
132
+ const record = toDispatchRecord(command, nowIso, {
133
+ created_at: existing?.created_at ?? nowIso,
134
+ dispatched_at: nowIso,
135
+ dispatch_failed: false,
136
+ last_error: null,
137
+ });
138
+ const nextState = mergeDispatchSet(current, record, nowIso);
139
+ writeDispatchSet(statePath, nextState);
140
+ return {
141
+ dispatch_failed: false,
142
+ record,
143
+ state: nextState,
144
+ statePath,
145
+ };
146
+ }
147
+ catch (error) {
148
+ const record = toDispatchRecord(command, nowIso, {
149
+ created_at: existing?.created_at ?? nowIso,
150
+ dispatched_at: null,
151
+ dispatch_failed: true,
152
+ last_error: error instanceof Error ? error.message : String(error),
153
+ });
154
+ const nextState = mergeDispatchSet(current, record, nowIso);
155
+ writeDispatchSet(statePath, nextState);
156
+ return {
157
+ dispatch_failed: true,
158
+ record,
159
+ state: nextState,
160
+ statePath,
161
+ };
162
+ }
163
+ }
@@ -0,0 +1,9 @@
1
+ export * from './contracts.js';
2
+ export { loadGroupSyncConfig, resolveGroupSyncConfigPath, resolveGroupSyncDataDir } from './config.js';
3
+ export { createGuardedCliGroupSyncDispatchTransport, createInlineGroupSyncDispatchTransport, createMockGroupSyncDispatchTransport, dispatchGroupSyncCommand, groupSyncMockDispatchLedgerPath, } from './dispatch.js';
4
+ export { syncGroupCommand } from './service.js';
5
+ export { createGuardedCliGroupSyncAutoDocTransport, createGuardedCliGroupSyncReferenceTransport, createGuardedCliGroupSyncReviewDiffTransport, createGuardedCliGroupSyncTransport, createMockGroupSyncAutoDocTransport, createMockGroupSyncReferenceTransport, createMockGroupSyncReviewDiffTransport, createMockGroupSyncTransport, } from './transport.js';
6
+ export { startGroupSyncScheduler } from './scheduler.js';
7
+ export { groupSyncMockAutoDocLedgerPath, publishAutoDocArtifact, } from './autodoc.js';
8
+ export { groupSyncMockReferenceLedgerPath, publishCrossGroupReference, } from './xref.js';
9
+ export { groupSyncMockReviewDiffLedgerPath, publishReviewDiffReply, } from './revdiff.js';
@@ -0,0 +1,138 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { groupSyncDir, runDir } from '../paths.js';
4
+ import { GroupSyncReviewDiffReplyInputSchema, GroupSyncReviewDiffReplySchema, GroupSyncReviewDiffReplySetSchema, } from './contracts.js';
5
+ function atomicWrite(path, content) {
6
+ mkdirSync(dirname(path), { recursive: true });
7
+ const temp = `${path}.tmp`;
8
+ writeFileSync(temp, content);
9
+ renameSync(temp, path);
10
+ }
11
+ function withTimeout(promise, timeoutMs, message) {
12
+ return new Promise((resolve, reject) => {
13
+ const timer = setTimeout(() => reject(new Error(message)), timeoutMs);
14
+ void promise.then((value) => {
15
+ clearTimeout(timer);
16
+ resolve(value);
17
+ }, (error) => {
18
+ clearTimeout(timer);
19
+ reject(error);
20
+ });
21
+ });
22
+ }
23
+ function runGroupSyncReviewDiffPath(dataDir, runId, botId = 'default') {
24
+ return join(runDir(dataDir, runId, botId), 'group-sync-review-diffs.json');
25
+ }
26
+ function readReplySet(path, input, nowIso) {
27
+ if (!existsSync(path)) {
28
+ return GroupSyncReviewDiffReplySetSchema.parse({
29
+ session_id: input.session_id,
30
+ run_id: input.run_id,
31
+ last_revision: input.revision,
32
+ updated_at: nowIso,
33
+ replies: [],
34
+ });
35
+ }
36
+ return GroupSyncReviewDiffReplySetSchema.parse(JSON.parse(readFileSync(path, 'utf8')));
37
+ }
38
+ function writeReplySet(path, state) {
39
+ atomicWrite(path, JSON.stringify(state, null, 2));
40
+ }
41
+ function sanitizeIdPart(value) {
42
+ const raw = value?.trim() ?? '';
43
+ if (raw.length === 0)
44
+ return 'none';
45
+ return raw.replace(/[^a-zA-Z0-9._-]+/g, '_');
46
+ }
47
+ function buildReplyId(input) {
48
+ return [
49
+ 'revdiff',
50
+ sanitizeIdPart(input.request_id),
51
+ sanitizeIdPart(input.review_id),
52
+ sanitizeIdPart(input.source_thread_id),
53
+ sanitizeIdPart(input.source_message_id ?? null),
54
+ ].join(':');
55
+ }
56
+ function toReply(input, nowIso, patch = {}) {
57
+ return GroupSyncReviewDiffReplySchema.parse({
58
+ request_id: input.request_id,
59
+ session_id: input.session_id,
60
+ run_id: input.run_id,
61
+ revision: input.revision,
62
+ source_thread_id: input.source_thread_id,
63
+ source_message_id: input.source_message_id ?? null,
64
+ review_id: input.review_id,
65
+ title: input.title,
66
+ summary: input.summary,
67
+ diff_paths: input.diff_paths,
68
+ reply_id: buildReplyId(input),
69
+ created_at: patch.created_at ?? nowIso,
70
+ synced_at: patch.synced_at ?? null,
71
+ sync_failed: patch.sync_failed ?? false,
72
+ last_error: patch.last_error ?? null,
73
+ });
74
+ }
75
+ function mergeReplySet(state, reply, nowIso) {
76
+ const replies = state.replies.filter((item) => item.reply_id !== reply.reply_id);
77
+ replies.push(reply);
78
+ replies.sort((left, right) => left.reply_id.localeCompare(right.reply_id));
79
+ return GroupSyncReviewDiffReplySetSchema.parse({
80
+ session_id: state.session_id,
81
+ run_id: state.run_id,
82
+ last_revision: Math.max(state.last_revision, reply.revision),
83
+ updated_at: nowIso,
84
+ replies,
85
+ });
86
+ }
87
+ export function groupSyncMockReviewDiffLedgerPath(dataDir) {
88
+ return join(groupSyncDir(dataDir), 'mock-review-diffs.ndjson');
89
+ }
90
+ export async function publishReviewDiffReply(options) {
91
+ const input = GroupSyncReviewDiffReplyInputSchema.parse(options.reply);
92
+ const nowFn = options.nowFn ?? Date.now;
93
+ const nowIso = new Date(nowFn()).toISOString();
94
+ const statePath = runGroupSyncReviewDiffPath(options.dataDir, input.run_id, options.botId ?? 'default');
95
+ const current = readReplySet(statePath, input, nowIso);
96
+ const existing = current.replies.find((item) => item.reply_id === buildReplyId(input));
97
+ if (existing && existing.sync_failed === false) {
98
+ return {
99
+ sync_failed: false,
100
+ reply: existing,
101
+ state: current,
102
+ statePath,
103
+ };
104
+ }
105
+ try {
106
+ const reply = toReply(input, nowIso, {
107
+ created_at: existing?.created_at ?? nowIso,
108
+ synced_at: nowIso,
109
+ sync_failed: false,
110
+ last_error: null,
111
+ });
112
+ await withTimeout(options.transport.publishReviewDiff(reply), options.config.rpc_timeout_ms, 'group sync review diff timeout');
113
+ const nextState = mergeReplySet(current, reply, nowIso);
114
+ writeReplySet(statePath, nextState);
115
+ return {
116
+ sync_failed: false,
117
+ reply,
118
+ state: nextState,
119
+ statePath,
120
+ };
121
+ }
122
+ catch (error) {
123
+ const reply = toReply(input, nowIso, {
124
+ created_at: existing?.created_at ?? nowIso,
125
+ synced_at: null,
126
+ sync_failed: true,
127
+ last_error: error instanceof Error ? error.message : String(error),
128
+ });
129
+ const nextState = mergeReplySet(current, reply, nowIso);
130
+ writeReplySet(statePath, nextState);
131
+ return {
132
+ sync_failed: true,
133
+ reply,
134
+ state: nextState,
135
+ statePath,
136
+ };
137
+ }
138
+ }