@tnunamak/dalan 0.8.0 → 0.8.2

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 (130) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/CONTRIBUTING.md +2 -0
  3. package/PROTOCOL.md +6 -0
  4. package/README.md +8 -12
  5. package/bin/dalan.mjs +25 -4
  6. package/bin/dot-acp-agent.mjs +572 -76
  7. package/bin/dot-alert.mjs +9 -3
  8. package/bin/dot-deadman.mjs +3 -1
  9. package/bin/dot-heartbeat.mjs +14 -7
  10. package/bin/dot-pr-reviewer.mjs +3 -31
  11. package/bin/dot-worker.mjs +215 -40
  12. package/contracts/adapter-qualification.schema.json +94 -7
  13. package/docs/chatgpt-worker-onboarding.md +1 -1
  14. package/docs/codex-to-muse.md +2 -2
  15. package/docs/connect-chatgpt.md +1 -1
  16. package/docs/connection-longevity.md +2 -2
  17. package/docs/dalan-upgrade.md +8 -5
  18. package/docs/deadman.md +4 -0
  19. package/docs/design/authority-matrix.md +18 -0
  20. package/docs/design/failure-table.md +87 -0
  21. package/docs/design/identities.md +22 -0
  22. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  23. package/docs/design/reuse-ledger.md +75 -0
  24. package/docs/design/target-architecture-v2.md +434 -0
  25. package/docs/local-agent-mcp.md +14 -0
  26. package/docs/local-agent-requester.md +3 -2
  27. package/docs/manual-setup.md +1 -1
  28. package/docs/operations.md +78 -14
  29. package/docs/pull-workers.md +11 -0
  30. package/docs/relationships.md +13 -0
  31. package/docs/service-setup.md +10 -10
  32. package/docs/t3-integration.md +6 -2
  33. package/docs/t3-reverse-control.md +5 -5
  34. package/docs/t3-wake-fence-r4.md +1 -1
  35. package/docs/test-suite-isolation.md +8 -6
  36. package/docs/trials/chatgpt-agent.md +47 -0
  37. package/docs/trials/claude-code-requester.md +68 -0
  38. package/docs/trials/muse.md +46 -0
  39. package/docs/usage.md +35 -9
  40. package/docs/worker-clients.md +1 -1
  41. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  42. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  43. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  44. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  45. package/package.json +4 -3
  46. package/packages/job-core/protocol/canonical.mjs +45 -7
  47. package/packages/job-core/transitions.mjs +4 -2
  48. package/scripts/upgrade-drain.mjs +96 -8
  49. package/scripts/worker-bridge-setup.mjs +215 -120
  50. package/src/ack-ledger.mjs +7 -1
  51. package/src/acp-bridge.mjs +256 -28
  52. package/src/admin-socket.mjs +32 -3
  53. package/src/alerts.mjs +17 -8
  54. package/src/answer-journal-retention.mjs +82 -0
  55. package/src/answer-journal.mjs +6 -4
  56. package/src/as-store.mjs +51 -6
  57. package/src/as.mjs +27 -5
  58. package/src/catalog-switch-inventory.mjs +70 -0
  59. package/src/check-response.mjs +4 -1
  60. package/src/claim-command-ledger.mjs +3 -2
  61. package/src/cli-help.mjs +29 -10
  62. package/src/cli-name.mjs +13 -1
  63. package/src/connect-cli.mjs +159 -4
  64. package/src/deadman.mjs +8 -5
  65. package/src/delivery.mjs +2 -19
  66. package/src/destinations/index.mjs +75 -14
  67. package/src/drain-runner.mjs +5 -1
  68. package/src/follow-current.mjs +3 -1
  69. package/src/get-summary.mjs +11 -2
  70. package/src/git-env.mjs +1 -1
  71. package/src/gozar-routes.mjs +313 -94
  72. package/src/host-budget-storage.py +56 -6
  73. package/src/host-budget.mjs +98 -15
  74. package/src/host-execution-policy.mjs +17 -6
  75. package/src/inbox.mjs +13 -3
  76. package/src/legacy-names.mjs +0 -2
  77. package/src/lifecycle.mjs +104 -11
  78. package/src/loopback-probe.mjs +46 -0
  79. package/src/mcp-outcome.mjs +3 -1
  80. package/src/mcp-sse.mjs +2 -1
  81. package/src/mcp-stdio.mjs +192 -30
  82. package/src/patch-apply.mjs +285 -19
  83. package/src/phase-trace.mjs +73 -0
  84. package/src/prepared-go-modules.mjs +127 -0
  85. package/src/prepared-node-modules.mjs +225 -38
  86. package/src/prepared-pnpm.mjs +276 -0
  87. package/src/prepared-store-prune.mjs +52 -0
  88. package/src/projects.mjs +59 -7
  89. package/src/protocol-artifact-commands.mjs +28 -0
  90. package/src/protocol-finish.mjs +3 -2
  91. package/src/publication-authority.mjs +22 -0
  92. package/src/publish-plan.mjs +2 -2
  93. package/src/pull-queue.mjs +55 -20
  94. package/src/read-api.mjs +127 -0
  95. package/src/redaction.mjs +173 -0
  96. package/src/rejections.mjs +19 -3
  97. package/src/route-custody.mjs +90 -0
  98. package/src/route-publication.mjs +50 -0
  99. package/src/route-setup.mjs +184 -0
  100. package/src/schema-subset.mjs +5 -3
  101. package/src/server.mjs +619 -88
  102. package/src/service-launchd.mjs +5 -1
  103. package/src/service-update-lock.mjs +7 -4
  104. package/src/service-update-runtime.mjs +64 -19
  105. package/src/service-update.mjs +193 -48
  106. package/src/service.mjs +276 -77
  107. package/src/setup.mjs +48 -25
  108. package/src/signal.mjs +1 -1
  109. package/src/status-evidence.mjs +18 -5
  110. package/src/status-summary.mjs +3 -0
  111. package/src/store.mjs +1086 -127
  112. package/src/submission-policy.mjs +257 -56
  113. package/src/t3-control.mjs +1 -1
  114. package/src/t3.mjs +14 -8
  115. package/src/terminal-safe.mjs +9 -7
  116. package/src/tool-registry.mjs +134 -41
  117. package/src/try-exposure.mjs +53 -86
  118. package/src/try-hosted.mjs +257 -70
  119. package/src/try.mjs +48 -22
  120. package/src/work-order.mjs +11 -6
  121. package/src/worker-instructions.mjs +26 -4
  122. package/src/worker-runs.mjs +35 -0
  123. package/src/workers.mjs +49 -4
  124. package/src/workspace.mjs +354 -54
  125. package/systemd/dot-deadman.service +3 -1
  126. package/docs/dot-pr-reviewer.config.example.json +0 -9
  127. package/docs/pr-head-reviewer.md +0 -70
  128. package/src/pr-head-reviewer.mjs +0 -596
  129. package/systemd/dot-pr-reviewer.service +0 -11
  130. package/systemd/dot-pr-reviewer.timer +0 -10
@@ -1,596 +0,0 @@
1
- import { defaultPath } from './paths.mjs';
2
- import { parseJsonBody, safeDiagnostic } from './diagnostic.mjs';
3
- import { redactLogEntry } from './redaction.mjs';
4
- // PR-head reviewer: one scoped, read-only review assignment per open PR head that has no worker review yet.
5
- // Deterministic (no model calls). Pure helpers first, then `run`, which takes its I/O (gh, dalan, databases, clock) as
6
- // dependencies so the whole flow is testable. See docs/pr-head-reviewer.md.
7
- import fs from 'node:fs';
8
- import os from 'node:os';
9
- import path from 'node:path';
10
- import { DatabaseSync } from 'node:sqlite';
11
- import { spawn } from 'node:child_process';
12
- import { validateSubmission } from './submission-policy.mjs';
13
- import { legacyReportThreadKey } from './legacy-names.mjs';
14
-
15
- const home = os.homedir();
16
- export const paths = {
17
- config: path.join(home, '.config/dot-pr-reviewer/config.json'),
18
- stateDir: path.join(home, '.local/state/dot-pr-reviewer'),
19
- bridgeDb: defaultPath(home,'.local/share/dot-bridge/bridge.db'),
20
- t3Db: path.join(home, '.t3/userdata/statev2.sqlite'),
21
- };
22
-
23
- export const DEFAULTS = Object.freeze({
24
- owners: [],
25
- repos: [],
26
- exclude_owners: [],
27
- exclude_repos: [],
28
- include_forks: false,
29
- skip_bots: true,
30
- max_submits_per_run: 10,
31
- headroom: 6,
32
- draft_days: 7,
33
- max_age_days: 30,
34
- max_changed_files: 200,
35
- max_scope_paths: 150,
36
- max_scope_bytes: 8000,
37
- ttl_hours: 4,
38
- refusal_cooldown_hours: 6,
39
- report_thread_id: null,
40
- dot_worker: 'dalan',
41
- gh_concurrency: 6,
42
- max_closed_checks: 40,
43
- });
44
-
45
- export function loadConfig(file = paths.config) {
46
- let user = {};
47
- if (fs.existsSync(file)) {
48
- user = JSON.parse(fs.readFileSync(file, 'utf8'));
49
- if (!user || typeof user !== 'object' || Array.isArray(user)) throw new Error(`invalid config ${file}`);
50
- // The report thread key had another name in earlier releases; it is still read, and the new key wins when both are set.
51
- if (legacyReportThreadKey in user) {
52
- if (user.report_thread_id == null) user.report_thread_id = user[legacyReportThreadKey];
53
- delete user[legacyReportThreadKey];
54
- }
55
- for (const k of Object.keys(user)) if (!(k in DEFAULTS) && !['bridge_db', 't3_db'].includes(k)) throw new Error(`unknown config key ${k}`);
56
- }
57
- return { ...DEFAULTS, bridge_db: paths.bridgeDb, t3_db: paths.t3Db, ...user };
58
- }
59
-
60
- const threadId = /^[A-Za-z0-9._:%-]{8,1024}$/;
61
- const lower = s => String(s).toLowerCase();
62
- export const prKey = (repo, number) => `${lower(repo)}#${number}`;
63
-
64
- export function parseOnly(value) {
65
- const match = typeof value === 'string' && !value.startsWith('-') && /^([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#([1-9][0-9]*)$/.exec(value);
66
- if (!match || match[0] !== value || !Number.isSafeInteger(Number(match[2]))) throw new Error('invalid --only: expected owner/repo#number');
67
- return { repo: match[1], number: Number(match[2]) };
68
- }
69
-
70
- // ---- repository selection --------------------------------------------------------------------------------------------
71
-
72
- export function reviewRepos(listed, cfg) {
73
- const owners = new Set(cfg.exclude_owners.map(lower)), repos = new Set(cfg.exclude_repos.map(lower));
74
- const all = [...listed, ...cfg.repos];
75
- return [...new Map(all.map(r => [lower(r), r])).values()]
76
- .filter(r => /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(r) && !owners.has(lower(r.split('/')[0])) && !repos.has(lower(r)));
77
- }
78
-
79
- // Open PRs worth a review now: bots skipped, a draft only when recently updated, anything else only when not stale.
80
- // Ready PRs first, then newest.
81
- export function selectPrs(prs, cfg, now) {
82
- const day = 86400000;
83
- return prs.filter(pr => {
84
- const age = now - Date.parse(pr.updatedAt);
85
- if (cfg.skip_bots && (pr.author?.is_bot || pr.author?.type === 'Bot' || /\[bot\]$/i.test(pr.author?.login ?? ''))) return false;
86
- if (pr.isDraft) return age <= cfg.draft_days * day;
87
- return cfg.max_age_days == null || age <= cfg.max_age_days * day;
88
- }).sort((a, b) => (a.isDraft - b.isDraft) || Date.parse(b.updatedAt) - Date.parse(a.updatedAt));
89
- }
90
-
91
- // ---- identity --------------------------------------------------------------------------------------------------------
92
-
93
- export function requestId(repo, number, head) {
94
- const [owner, name] = repo.split('/'), suffix = `-${number}-${head.slice(0, 12)}`;
95
- const id = `${`prh-${owner}-${name}`.slice(0, 128 - suffix.length)}${suffix}`.replace(/[^-\w]/g, '_');
96
- if (!/^[-\w]{8,128}$/.test(id)) throw new Error(`request id out of bounds: ${id}`);
97
- return id;
98
- }
99
- export const objectiveKey = (repo, number) => `pr:${repo}#${number}`;
100
-
101
- // ---- scope and brief -------------------------------------------------------------------------------------------------
102
-
103
- const byteLength = list => Buffer.byteLength(list.join('\n'));
104
- // The PR's files as they are, or, past the limits, the deepest directory level at which they fit.
105
- export function collapseScope(files, { maxPaths, maxBytes }) {
106
- const unique = [...new Set(files)];
107
- const fits = list => list.length <= maxPaths && byteLength(list) <= maxBytes;
108
- if (fits(unique)) return unique;
109
- const deepest = Math.max(...unique.map(f => f.split('/').length));
110
- let level = [];
111
- for (let depth = deepest - 1; depth >= 1; depth--) {
112
- level = [...new Set(unique.map(f => { const parts = f.split('/'); return parts.length <= depth ? f : parts.slice(0, depth).join('/'); }))];
113
- if (fits(level)) return level;
114
- }
115
- return level;
116
- }
117
-
118
- export function buildBrief({ repo, number, head, base, diff }) {
119
- const where = diff
120
- ? `The workspace is pinned at that head; workspace_result shows the PR diff against its merge base ${base.slice(0, 12)}. The allow-list is exactly the files the PR changes.`
121
- : 'The workspace is pinned at that head. The PR diff is not available here; the allow-list holds the files the PR changes (files that look sensitive are withheld), so read them as they stand at the head.';
122
- return `Review only; make no changes. Review ${repo} pull request #${number} at head ${head}. ${where} `
123
- + 'Review design and architecture before lines. '
124
- + '(1) goal: does the design serve the real goal, or a proxy such as passing tests? '
125
- + '(2) simplicity as separation of independent concerns: what is braided that should be independent (state and value, time and identity, policy and mechanism, domain logic and input-output, waiting and error, unrelated reasons for change)? Moving code into more files is not decomplecting. '
126
- + '(3) invariant owners: which single component owns each invariant (completeness, ordering, identity, authorization, durability), do two places decide the same thing, and are modules deep rather than shallow wrappers? '
127
- + '(4) explicit state and information flow: are effects, retries and caching visible, and does each decision see the state it needs, or is state hidden, dropped or reported as success when partial? '
128
- + '(5) feedback loops and real data: can retries, polling or cursors stall or run away, and does the code fit real data sizes and shapes? '
129
- + 'Report a finding or an explicit no-issue for each of (1) to (4), and say whether a simpler design would remove several findings at once. '
130
- + 'Then find correctness, data-loss, security and regression defects in the changed behavior, and missing or vacuous tests for it. '
131
- + 'For each finding give severity (P1 = wrong results, data loss or security; P2 = real bug or missing test for a risky path; P3 = minor), the file and line, the concrete failing scenario, and the fix. '
132
- + 'Return NONE if you find nothing real. Do not report style.';
133
- }
134
-
135
- // A bridge or transport failure, not a verdict on the assignment.
136
- const transient = /"http_status":5\d\d|unavailable|timeout|ECONN|ENOTFOUND|exit 127|\bdeferred:/i;
137
- const deferredSubmit = error => {
138
- if (/^deferred:/i.test(error ?? '')) return true;
139
- try { const value=JSON.parse(error); return value?.verdict==='defer'||/^deferred:/i.test(value?.error ?? ''); }
140
- catch { return false; }
141
- };
142
- const sensitiveRefusal = /^(?:sensitive scope path|hard sensitive path exclusion): (.+?)(?: \(.*)?$/;
143
-
144
- // The assignment, built to pass the bridge's submit lint. The same `validateSubmission` the bridge runs checks it here,
145
- // against the PR's own file list instead of a clone. A changed file the lint calls sensitive leaves the scope, and the PR is
146
- // then reviewed at its head without the diff (the bridge refuses any diff that touches a sensitive name).
147
- // Returns {assignment, scope, excluded, diff, warnings} or {skip: reason}.
148
- export function planReview(pr, { files, mergeBase }, cfg, now, validate = validateSubmission) {
149
- let live = [...new Set(files)], diff = Boolean(mergeBase);
150
- const excluded = [];
151
- for (let attempt = 0; attempt <= files.length + 1; attempt++) {
152
- if (!live.length) return { skip: files.length ? 'every changed file is excluded as sensitive' : 'the PR changes no files' };
153
- const scope = collapseScope(live, { maxPaths: cfg.max_scope_paths, maxBytes: cfg.max_scope_bytes });
154
- const input = diff ? { github_repo: pr.repo, base_sha: mergeBase, head_sha: pr.head } : { github_repo: pr.repo, base_sha: pr.head };
155
- const assignment = {
156
- schema_version: 1,
157
- request_id: requestId(pr.repo, pr.number, pr.head),
158
- inputs: [input],
159
- scope_paths: scope,
160
- brief: buildBrief({ repo: pr.repo, number: pr.number, head: pr.head, base: mergeBase, diff }),
161
- expected_output: 'Ranked findings with severity, file and line, and the failing scenario, or NONE.',
162
- execution_scope: 'read-only',
163
- prepared_at: new Date(now).toISOString().replace(/\.\d+Z$/, 'Z'),
164
- valid_until: new Date(now + cfg.ttl_hours * 3600000).toISOString().replace(/\.\d+Z$/, 'Z'),
165
- };
166
- const warnings = [];
167
- try {
168
- validate(assignment, { scanInput: () => ({ files: live, diffFiles: diff ? live : [], diff: '', symlinks: [] }), warnings, excludeSensitive: true });
169
- return { assignment, scope, excluded, diff, warnings };
170
- } catch (error) {
171
- const m = sensitiveRefusal.exec(error.message);
172
- if (!m || !live.includes(m[1])) return { skip: `lint: ${error.message}` };
173
- excluded.push(m[1]);
174
- live = live.filter(f => f !== m[1]);
175
- diff = false;
176
- }
177
- }
178
- return { skip: 'lint: sensitive-file exclusion did not converge' };
179
- }
180
-
181
- // ---- gating ----------------------------------------------------------------------------------------------------------
182
-
183
- // {hold: reason} while the worker must not be fed, else {slots}: lanes plus headroom, minus what is claimed or live-queued.
184
- export function gate(status, cfg, now) {
185
- if (status.paused) return { hold: `paused (${status.pause_reason ?? 'no reason'})` };
186
- if (status.worker_break?.active && status.worker_break.source === 'owner') return { hold: 'owner-confirmed worker_break active' };
187
- const until = status.claim_denied?.capacity_hold_until;
188
- if (until) { const t = Date.parse(until); if (Number.isNaN(t) || t > now) return { hold: `capacity hold until ${until}` }; }
189
- const count = s => status.counts?.find(c => c.status === s)?.count ?? 0;
190
- const claimed = count('claimed'), queued = Math.max(0, count('queued') - (status.queued_expired?.count ?? 0));
191
- const lanes = status.max_claimed_outer_assignments ?? 6;
192
- return { slots: Math.max(0, lanes + cfg.headroom - (claimed + queued)), claimed, queued, lanes };
193
- }
194
-
195
- // ---- dedupe ----------------------------------------------------------------------------------------------------------
196
-
197
- // request_id of an assignment that already covers this PR head: same repository, head pinned as head_sha (or as the lone
198
- // base_sha), or the same objective at this revision. Queued, claimed and finished cover it; a cancelled one does not.
199
- export function findCovered(db, repo, number, head) {
200
- const rows = db.prepare(`select request_id, status from assignments
201
- where status != 'cancelled' and (
202
- (objective_key = ? and revision = ?)
203
- or (lower(json_extract(payload,'$.inputs[0].github_repo')) = ? and coalesce(json_extract(payload,'$.inputs[0].head_sha'), json_extract(payload,'$.inputs[0].base_sha')) = ?))
204
- order by created_at desc limit 1`).all(objectiveKey(repo, number), head, lower(repo), head);
205
- return rows[0] ?? null;
206
- }
207
-
208
- // ---- closed PRs ------------------------------------------------------------------------------------------------------
209
-
210
- // Queued and claimed assignments that target a PR, grouped by PR: {repo, number, ids}. The PR comes from the objective key
211
- // pr:<owner>/<repo>#<n> (this producer, and any submitter that sets it) or from inputs[0] github_repo plus pr_number.
212
- export function trackedPrs(db) {
213
- const prs = new Map();
214
- for (const r of db.prepare(`select request_id, objective_key, json_extract(payload,'$.inputs[0].github_repo') as repo,
215
- json_extract(payload,'$.inputs[0].pr_number') as number from assignments where status in ('queued','claimed') order by created_at`).all()) {
216
- const key = /^pr:([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#([1-9][0-9]*)$/.exec(r.objective_key ?? '');
217
- const repo = key?.[1] ?? r.repo, number = key ? Number(key[2]) : r.number;
218
- if (typeof repo !== 'string' || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo) || !Number.isSafeInteger(number) || number <= 0) continue;
219
- const k = prKey(repo, number);
220
- (prs.get(k) ?? prs.set(k, { repo, number, ids: [] }).get(k)).ids.push(r.request_id);
221
- }
222
- return [...prs.values()];
223
- }
224
-
225
- // ---- T3 thread links -------------------------------------------------------------------------------------------------
226
-
227
- // "repo#number" -> thread id. A live thread beats an archived one; then the most recent link wins.
228
- export function threadIndex(db) {
229
- const rows = db.prepare(`select t.thread_id as id, t.archived_at as archived, json_extract(j.value,'$.repository') as repo,
230
- json_extract(j.value,'$.number') as number, json_extract(j.value,'$.linkedAt') as linked
231
- from orchestration_v2_projection_threads t, json_each(t.payload_json, '$.pullRequests') j where t.deleted_at is null`).all();
232
- const best = new Map();
233
- for (const r of rows) {
234
- if (!r.repo || !Number.isInteger(r.number) || !threadId.test(r.id)) continue;
235
- const key = prKey(r.repo, r.number), rank = [r.archived ? 0 : 1, r.linked ?? ''];
236
- const cur = best.get(key);
237
- if (!cur || rank[0] > cur.rank[0] || (rank[0] === cur.rank[0] && rank[1] > cur.rank[1])) best.set(key, { id: r.id, rank });
238
- }
239
- return new Map([...best].map(([k, v]) => [k, v.id]));
240
- }
241
-
242
- export function deliveryFor(index, repo, number, cfg) {
243
- const linked = index.get(prKey(repo, number));
244
- if (linked) return { delivery: `t3:${linked}`, via: 'pr-link' };
245
- if (cfg.report_thread_id && threadId.test(cfg.report_thread_id)) return { delivery: `t3:${cfg.report_thread_id}`, via: 'report-thread' };
246
- return { delivery: 'none', via: 'none' };
247
- }
248
-
249
- // Follow the delegated child's lineage, choosing the nearest owner that can receive a result.
250
- export function delegateOwner(db, id) {
251
- const get = db.prepare(`select thread_id as id, archived_at as archived, deleted_at as deleted,
252
- json_extract(payload_json,'$.settledAt') as settled,
253
- json_extract(payload_json,'$.settledOverride') as settled_override,
254
- json_extract(payload_json,'$.lineage.parentThreadId') as parent,
255
- json_extract(payload_json,'$.lineage.rootThreadId') as root
256
- from orchestration_v2_projection_threads where thread_id = ?`);
257
- const seen = new Set(), first = get.get(id);
258
- let next = first?.parent;
259
- while (next && !seen.has(next)) {
260
- seen.add(next);
261
- const row = get.get(next);
262
- if (!row) break;
263
- if (!next.startsWith('thread:delegated-task:') && threadId.test(next)
264
- && !row.archived && !row.deleted && !row.settled && row.settled_override !== 'settled') return next;
265
- next = row.parent;
266
- }
267
- const root = first?.root;
268
- if (root && !seen.has(root)) {
269
- const row = get.get(root);
270
- if (row && !root.startsWith('thread:delegated-task:') && threadId.test(root)
271
- && !row.archived && !row.deleted && !row.settled && row.settled_override !== 'settled') return root;
272
- }
273
- return null;
274
- }
275
-
276
- function fallbackDelivery(cfg, current) {
277
- const report = cfg.report_thread_id;
278
- return report && threadId.test(report) && current !== `t3:${report}`
279
- ? { delivery: `t3:${report}`, via: 'report-thread' } : { delivery: 'none', via: 'none' };
280
- }
281
-
282
- // ---- state and log ---------------------------------------------------------------------------------------------------
283
-
284
- export class State {
285
- constructor(dir) {
286
- this.dir = dir; this.file = path.join(dir, 'state.json');
287
- this.data = fs.existsSync(this.file) ? JSON.parse(fs.readFileSync(this.file, 'utf8')) : {};
288
- this.data.refused ??= {};
289
- this.data.covered ??= [];
290
- }
291
- // A covered head is logged once, not on every run for as long as the PR stays open.
292
- firstCovered(id) { if (this.data.covered.includes(id)) return false; this.data.covered.push(id); return true; }
293
- recentlyRefused(id, now, hours) { const at = this.data.refused[id]; return at !== undefined && now - Date.parse(at) < hours * 3600000; }
294
- refuse(id, now, reason) { this.data.refused[id] = new Date(now).toISOString(); this.data.reasons = { ...this.data.reasons, [id]: reason }; }
295
- save(now, hours) {
296
- for (const [id, at] of Object.entries(this.data.refused)) if (now - Date.parse(at) >= hours * 3600000) { delete this.data.refused[id]; delete this.data.reasons?.[id]; }
297
- this.data.covered = this.data.covered.slice(-2000);
298
- fs.mkdirSync(this.dir, { recursive: true });
299
- const tmp = `${this.file}.tmp`; fs.writeFileSync(tmp, JSON.stringify(this.data, null, 1) + '\n'); fs.renameSync(tmp, this.file);
300
- }
301
- }
302
-
303
- // ---- real I/O --------------------------------------------------------------------------------------------------------
304
-
305
- const exec = (cmd, args, { input, timeout = 120000 } = {}) => new Promise(resolve => {
306
- const child = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'pipe'] });
307
- let stdout = '', stderr = '', done = false;
308
- const finish = code => { if (!done) { done = true; clearTimeout(timer); resolve({ code, stdout, stderr }); } };
309
- const timer = setTimeout(() => { child.kill('SIGKILL'); stderr += 'timeout'; finish(124); }, timeout);
310
- child.stdout.on('data', d => { stdout += d; });
311
- child.stderr.on('data', d => { stderr += d; });
312
- child.on('error', e => { stderr += e.message; finish(127); });
313
- child.on('close', finish);
314
- child.stdin.on('error', () => {});
315
- child.stdin.end(input ?? '');
316
- });
317
-
318
- // gh -i may emit one response per page. Never attach a collection's first-page ETag
319
- // to every page: cache validators only for single-response resources.
320
- function apiResponses(text) {
321
- const starts = [...text.matchAll(/^HTTP\/[\d.]+\s+(\d{3})[^\r\n]*\r?$/gm)];
322
- if (!starts.length) throw new Error('gh api: missing HTTP response headers');
323
- return starts.map((m, i) => {
324
- const chunk = text.slice(m.index, starts[i + 1]?.index ?? text.length);
325
- const split = /\r?\n\r?\n/.exec(chunk);
326
- if (!split) throw new Error('gh api: incomplete response headers');
327
- const headers = Object.fromEntries(chunk.slice(0, split.index).split(/\r?\n/).slice(1).map(line => {
328
- const colon = line.indexOf(':'); return [line.slice(0, colon).toLowerCase(), line.slice(colon + 1).trim()];
329
- }));
330
- const body = chunk.slice(split.index + split[0].length).trim();
331
- return { status: Number(m[1]), headers, body };
332
- });
333
- }
334
-
335
- export class GitHubRateLimit extends Error {
336
- // `text` is the original response (its headers drive the backoff); `message` is the sanitized human-readable line.
337
- constructor(text, now, message = text) {
338
- super('GitHub rate limit: ' + message.trim().split('\n')[0]);
339
- const reset = /x-ratelimit-reset:\s*(\d+)/i.exec(text);
340
- const retry = /retry-after:\s*([^\r\n]+)/i.exec(text);
341
- const retryAt = retry ? (/^\d+$/.test(retry[1].trim()) ? now + Number(retry[1]) * 1000 : Date.parse(retry[1])) : NaN;
342
- const resetAt = reset ? Number(reset[1]) * 1000 : NaN;
343
- this.until = new Date(Math.max(now + 60000, ...[resetAt, retryAt].filter(Number.isFinite),
344
- ...(!Number.isFinite(resetAt) && !Number.isFinite(retryAt) ? [now + 3600000] : []))).toISOString();
345
- }
346
- }
347
-
348
- // Only the application policy refusal is eligible, never an authorization/Guardian denial.
349
- function protectedDestination(error) {
350
- let reason = error;
351
- try { reason = JSON.parse(error)?.error ?? error; } catch { /* plain policy reason */ }
352
- return typeof reason === 'string' && /^protected T3 destination(?:$|:)/i.test(reason)
353
- && !/guardian|authorization|permission denied|user cancel/i.test(reason);
354
- }
355
-
356
- export function realDeps(cfg, runCommand = exec) {
357
- let state, dryRun = false;
358
- const counts = {};
359
- const gh = async (kind, args) => {
360
- counts[kind] = (counts[kind] ?? 0) + 1;
361
- const r = await runCommand('gh', args, { timeout: 120000 });
362
- const text = r.stdout + '\n' + r.stderr;
363
- // Only the status line, the remaining-quota header and gh's own stderr can signal a limit. A PR body or diff that
364
- // mentions "rate limit" must not trigger a backoff.
365
- const status = /^HTTP\/[\d.]+\s+(\d{3})/.exec(r.stdout)?.[1], remaining = /^x-ratelimit-remaining:\s*(\d+)/im.exec(r.stdout)?.[1];
366
- if (status === '429' || (status === '403' && remaining === '0') || /rate limit exceeded|secondary rate limit/i.test(r.stderr)) throw new GitHubRateLimit(text, Date.now(), safeDiagnostic(text, 2000));
367
- if (r.code !== 0 && !/^HTTP\/[\d.]+\s+304\b/m.test(r.stdout)) throw new Error('gh ' + args.slice(0, 3).join(' ') + ': ' + safeDiagnostic((r.stderr || r.stdout).trim().split('\n')[0], 2000));
368
- return r.stdout;
369
- };
370
- const api = async (url, paginate = false) => {
371
- const cache = state?.data.api_cache ?? {};
372
- const saved = cache[url];
373
- const raw = await gh(paginate ? 'files' : 'pull', ['api', url, '-i', ...(paginate ? ['--paginate'] : []),
374
- ...(saved?.etag ? ['-H', 'If-None-Match: ' + saved.etag] : [])]);
375
- const pages = apiResponses(raw);
376
- let body;
377
- if (pages[0].status === 304) {
378
- if (!saved || !Object.hasOwn(saved, 'body')) throw new Error('gh api: 304 without cached body for ' + url);
379
- counts.not_modified = (counts.not_modified ?? 0) + 1;
380
- return saved.body;
381
- }
382
- for (const page of pages) if (page.status < 200 || page.status >= 300) throw new Error('gh api HTTP ' + page.status + ' for ' + url);
383
- body = paginate ? pages.flatMap(p => parseJsonBody(p.body, 'gh api page')) : parseJsonBody(pages[0].body, 'gh api response');
384
- if (state && !dryRun) {
385
- state.data.api_cache ??= {};
386
- state.data.api_cache[url] = { body, etag: pages.length === 1 && !/rel="next"/.test(pages[0].headers.link ?? '') ? pages[0].headers.etag : null };
387
- }
388
- return body;
389
- };
390
- return {
391
- now: () => Date.now(),
392
- beginRun: (s, dry) => { state = s; dryRun = dry; for (const key of Object.keys(counts)) delete counts[key]; },
393
- ghCounts: () => ({ ...counts }),
394
- status: async () => { const r = await runCommand(cfg.dot_worker, ['status', '--json']); if (r.code !== 0) throw new Error('status: ' + safeDiagnostic(r.stderr.trim(), 2000)); return parseJsonBody(r.stdout, 'status output'); },
395
- searchPrs: async ({ owner, repo }, since) => parseJsonBody(await gh('search', ['search', 'prs', ...(owner ? ['--owner', owner] : ['--repo', repo]),
396
- '--state', 'open', '--json', 'number,repository,url,updatedAt,isDraft,author', '--limit', '200', ...(since ? ['updated:>=' + since] : [])])),
397
- prDetails: async (repo, number) => api('repos/' + repo + '/pulls/' + number),
398
- prFiles: async (repo, number) => api('repos/' + repo + '/pulls/' + number + '/files', true),
399
- openBridge: () => new DatabaseSync(cfg.bridge_db, { readOnly: true }),
400
- cancel: async (id, reason) => {
401
- const r = await runCommand(cfg.dot_worker, ['cancel', id, '--reason', reason]);
402
- if (r.code !== 0) throw new Error('cancel ' + id + ': ' + safeDiagnostic((r.stderr || r.stdout).trim().split('\n').pop(), 2000));
403
- },
404
- openT3: () => new DatabaseSync(cfg.t3_db, { readOnly: true }),
405
- submit: async (assignment, { delivery, objective, head }) => {
406
- const args = ['submit', '--stdin', '--json', '--background', '--exclude-sensitive', '--allow-scope-prune', '--deliver', delivery,
407
- '--objective-key', objective, '--revision', head, '--task-kind', 'review', '--source', 'agent'] // assignments.source is CHECK-constrained to drainer|fix-loop|agent|unknown; prh- ids and pr: objective keys mark this producer;
408
- const r = await runCommand(cfg.dot_worker, args, { input: JSON.stringify(assignment), timeout: 180000 });
409
- const text = (r.stderr + r.stdout).trim();
410
- let error = null;
411
- if (r.code !== 0) error = safeDiagnostic(text.split('\n').filter(Boolean).pop() ?? `exit ${r.code}`, 2000);
412
- else { try { const out = JSON.parse(r.stdout); if (out?.error) error = safeDiagnostic(String(out.error), 2000); } catch { /* plain output is fine */ } }
413
- return { ok: error === null, error, output: r.stdout.trim() };
414
- },
415
- };
416
- }
417
-
418
- // ---- one run ---------------------------------------------------------------------------------------------------------
419
-
420
- export async function run({ cfg, deps, stateDir = paths.stateDir, dryRun = false, only = null, maxSubmits = null, ignoreCapacity = false, print = () => {} }) {
421
- if (only !== null) {
422
- if (!only || typeof only !== 'object' || typeof only.repo !== 'string' || !Number.isSafeInteger(only.number) || only.number <= 0) throw new Error('invalid --only: expected owner/repo#number');
423
- parseOnly(`${only.repo}#${only.number}`);
424
- }
425
- const logFile = path.join(stateDir, 'log.jsonl');
426
- const log = (event, fields = {}) => {
427
- const line = redactLogEntry({ at: new Date(deps.now()).toISOString(), event, dry_run: dryRun || undefined, ...fields });
428
- print(JSON.stringify(line));
429
- if (!dryRun) { fs.mkdirSync(stateDir, { recursive: true }); fs.appendFileSync(logFile, JSON.stringify(line) + '\n'); }
430
- };
431
- const summary = { submitted: 0, skipped: 0, refused: 0, errors: 0, cancelled: 0, hold: null, slots: null };
432
- const now = deps.now(), state = new State(stateDir);
433
- deps.beginRun?.(state, dryRun);
434
- let complete = true;
435
- try {
436
- if (Date.parse(state.data.backoff_until) > now) {
437
- summary.hold = 'GitHub backoff until ' + state.data.backoff_until;
438
- log('hold', { reason: summary.hold }); return summary;
439
- }
440
- // A merged or closed PR no longer needs its review: cancel its queued and claimed requests so they free their lanes. Runs
441
- // before the capacity gate, since a full or held queue is when stale work costs the most. One REST pulls call per tracked
442
- // PR (conditional on the saved ETag, so an unchanged PR is a 304), never GraphQL, and at most max_closed_checks per run.
443
- if (!only) {
444
- let tracked = [];
445
- const bridge = deps.openBridge();
446
- try { tracked = trackedPrs(bridge); } finally { bridge.close(); }
447
- for (const pr of tracked.slice(0, cfg.max_closed_checks ?? DEFAULTS.max_closed_checks)) {
448
- try {
449
- if ((await deps.prDetails(pr.repo, pr.number)).state !== 'closed') continue;
450
- for (const id of pr.ids) {
451
- if (dryRun) { log('would-cancel', { repo: pr.repo, pr: pr.number, request_id: id, reason: 'pr_closed' }); continue; }
452
- await deps.cancel(id, 'pr_closed'); summary.cancelled++;
453
- log('cancel', { repo: pr.repo, pr: pr.number, request_id: id, reason: 'pr_closed' });
454
- }
455
- } catch (e) {
456
- if (e instanceof GitHubRateLimit) throw e;
457
- log('error', { repo: pr.repo, pr: pr.number, stage: 'pr-closed-check', error: e.message });
458
- }
459
- }
460
- }
461
- const status = await deps.status(), g = gate(status, cfg, now);
462
- if (g.hold) { summary.hold = g.hold; log('hold', { reason: g.hold }); return summary; }
463
- const limit = Math.min(maxSubmits ?? cfg.max_submits_per_run, ignoreCapacity ? Infinity : g.slots);
464
- summary.slots = g.slots;
465
- log('capacity', { claimed: g.claimed, queued: g.queued, lanes: g.lanes, headroom: cfg.headroom, slots: g.slots, limit: Number.isFinite(limit) ? limit : null });
466
- if (limit <= 0) return summary;
467
-
468
- const excludedOwners = new Set(cfg.exclude_owners.map(lower));
469
- const owners = [...new Set(cfg.owners.map(lower))].filter(o => !excludedOwners.has(o));
470
- const sources = only ? reviewRepos([], { ...cfg, repos: [only.repo] }).map(repo => ({ repo }))
471
- : [...owners.map(owner => ({ owner })), ...reviewRepos([], cfg).filter(repo => !owners.includes(lower(repo.split('/')[0]))).map(repo => ({ repo }))];
472
- const previous = Date.parse(state.data.last_successful_run);
473
- const since = !only && Number.isFinite(previous) ? new Date(previous - 600000).toISOString() : null;
474
- const listing = [];
475
- // Sequential gh calls ensure a rate-limit response cannot leave more work running.
476
- for (const source of sources) {
477
- try {
478
- const rows = await deps.searchPrs(source, since);
479
- if (rows.length >= 200) { complete = false; log('note', { reason: 'search limit reached; incremental watermark retained', ...source }); }
480
- for (const row of rows) {
481
- const repo = row.repository?.nameWithOwner ?? row.repository?.fullName ?? row.repository?.full_name ?? source.repo;
482
- if (!repo || !reviewRepos([], { ...cfg, repos: [repo] }).length) continue;
483
- if (row.repository?.isArchived || row.repository?.archived) continue;
484
- if (!cfg.include_forks && (row.repository?.isFork || row.repository?.fork)) continue;
485
- if (only && row.number !== only.number) continue;
486
- listing.push({ ...row, repo });
487
- }
488
- } catch (e) {
489
- if (e instanceof GitHubRateLimit) throw e;
490
- summary.errors++; complete = false; log('error', { stage: 'search-prs', ...source, error: e.message });
491
- }
492
- }
493
- const prs = selectPrs([...new Map(listing.map(pr => [prKey(pr.repo, pr.number), pr])).values()], cfg, now);
494
- let bridge, t3;
495
- try {
496
- bridge = deps.openBridge(); t3 = deps.openT3();
497
- const index = threadIndex(t3);
498
- for (const row of prs) {
499
- if (summary.submitted >= limit) { complete = false; break; }
500
- let pr;
501
- try {
502
- const detail = await deps.prDetails(row.repo, row.number);
503
- if (detail.state === 'closed' || detail.base?.repo?.archived || (!cfg.include_forks && detail.base?.repo?.fork)) continue;
504
- const head = String(detail.head?.sha ?? '').toLowerCase(), base = detail.base?.sha;
505
- if (!/^[a-f0-9]{40}$/.test(head) || !/^[a-f0-9]{40}$/i.test(base ?? '')) throw new Error('invalid PR head/base SHA');
506
- pr = { repo: row.repo, number: row.number, head, base, isDraft: row.isDraft };
507
- } catch (e) {
508
- if (e instanceof GitHubRateLimit) throw e;
509
- summary.errors++; complete = false; log('error', { repo: row.repo, pr: row.number, stage: 'pr-details', error: e.message }); continue;
510
- }
511
- const id = requestId(pr.repo, pr.number, pr.head), ident = { repo: pr.repo, pr: pr.number, head: pr.head, request_id: id };
512
- const covered = findCovered(bridge, pr.repo, pr.number, pr.head);
513
- if (covered) { summary.skipped++; if (state.firstCovered(id)) log('skip', { ...ident, reason: 'covered', by: covered.request_id, status: covered.status }); continue; }
514
- const protectedReason = protectedDestination(state.data.reasons?.[id] ?? '') ? state.data.reasons[id] : null;
515
- if (!protectedReason && state.recentlyRefused(id, now, cfg.refusal_cooldown_hours)) { complete = false; summary.skipped++; log('skip', { ...ident, reason: 'refused earlier', detail: state.data.reasons?.[id] }); continue; }
516
- let files;
517
- try {
518
- files = await deps.prFiles(pr.repo, pr.number);
519
- const latest = await deps.prDetails(pr.repo, pr.number);
520
- const latestHead = String(latest.head?.sha ?? '').toLowerCase();
521
- if (latestHead !== pr.head) {
522
- complete = false; summary.skipped++;
523
- log('skip', { ...ident, reason: 'PR head changed while fetching files', latest_head: latestHead });
524
- continue;
525
- }
526
- }
527
- catch (e) {
528
- if (e instanceof GitHubRateLimit) throw e;
529
- summary.errors++; complete = false; log('error', { ...ident, stage: 'pr-files', error: e.message }); continue;
530
- }
531
- const liveFiles = files.filter(f => typeof f === 'string' || f.status !== 'removed').map(f => typeof f === 'string' ? f : f.filename);
532
- if (files.length && !liveFiles.length) { summary.skipped++; log('skip', { ...ident, reason: 'only deletions' }); continue; }
533
- if (files.length > (cfg.max_changed_files ?? DEFAULTS.max_changed_files)) { summary.skipped++; log('skip', { ...ident, reason: 'too many changed files', changed_files: files.length, max_changed_files: cfg.max_changed_files ?? DEFAULTS.max_changed_files }); continue; }
534
- // REST pulls supplies the base tip, not the merge base. Never claim it is a merge base.
535
- const plan = planReview(pr, { files: liveFiles, mergeBase: null }, cfg, now);
536
- if (plan.skip) { complete = false; summary.skipped++; state.refuse(id, now, plan.skip); log('skip', { ...ident, reason: plan.skip, excluded: plan.excluded }); continue; }
537
- const target = deliveryFor(index, pr.repo, pr.number, cfg);
538
- const delegate = target.via === 'pr-link' && target.delivery.startsWith('t3:thread:delegated-task:');
539
- const fallbackReason = delegate
540
- ? 'delegate thread' : protectedReason;
541
- if (fallbackReason && target.delivery.startsWith('t3:')) {
542
- const owner = delegate ? delegateOwner(t3, target.delivery.slice(3)) : null;
543
- const next = owner
544
- ? { delivery: `t3:${owner}`, via: 'owner' }
545
- : fallbackDelivery(cfg, target.delivery);
546
- log('delivery-fallback', { ...ident, reason: fallbackReason, from: target.delivery, delivery: next.delivery });
547
- Object.assign(target, next);
548
- }
549
- const detail = { ...ident, scope_paths: plan.scope.length, changed_files: files.length, excluded: plan.excluded, diff: plan.diff, delivery: target.delivery, delivery_via: target.via, warnings: plan.warnings };
550
- if (target.via === 'none') log('note', { ...ident, reason: 'no deliverable T3 thread or report_thread_id; delivery none' });
551
- if (dryRun) { summary.submitted++; log('would-submit', detail); continue; }
552
- const meta = { delivery: target.delivery, objective: objectiveKey(pr.repo, pr.number), head: pr.head };
553
- let result = await deps.submit(plan.assignment, meta);
554
- while (!result.ok && meta.delivery.startsWith('t3:') && protectedDestination(result.error ?? '')) {
555
- const next = fallbackDelivery(cfg, meta.delivery);
556
- log('delivery-fallback', { ...ident, reason: result.error, from: meta.delivery, delivery: next.delivery });
557
- meta.delivery = detail.delivery = next.delivery; detail.delivery_via = next.via;
558
- result = await deps.submit(plan.assignment, meta);
559
- }
560
- if (result.ok) { summary.submitted++; log('submit', detail); }
561
- else if (deferredSubmit(result.error)) { complete = false; summary.hold = result.error; log('hold', { ...detail, reason: result.error }); break; }
562
- else if (transient.test(result.error)) { complete = false; summary.errors++; state.refuse(id, now, result.error); log('error', { ...detail, stage: 'submit', error: result.error }); break; }
563
- else { complete = false; summary.refused++; state.refuse(id, now, result.error); log('refused', { ...detail, error: result.error }); }
564
- }
565
- } finally { bridge?.close(); t3?.close(); }
566
- if (complete && !summary.errors && !only) state.data.last_successful_run = new Date(now).toISOString();
567
- } catch (e) {
568
- summary.errors++;
569
- if (e instanceof GitHubRateLimit) {
570
- state.data.backoff_until = e.until; summary.hold = 'GitHub rate limit';
571
- log('rate-limit', { error: e.message, backoff_until: e.until });
572
- } else { log('error', { stage: 'run', error: e.message }); }
573
- } finally {
574
- if (!dryRun) state.save(now, cfg.refusal_cooldown_hours);
575
- summary.gh_calls = deps.ghCounts?.() ?? {};
576
- log('gh-calls', { counts: summary.gh_calls });
577
- log('run', summary);
578
- }
579
- return summary;
580
- }
581
-
582
- export function acquireLock(dir) {
583
- fs.mkdirSync(dir, { recursive: true });
584
- const file = path.join(dir, 'run.lock');
585
- for (let i = 0; i < 2; i++) {
586
- try { fs.writeFileSync(file, String(process.pid), { flag: 'wx' }); return () => { try { fs.unlinkSync(file); } catch { /* gone */ } }; }
587
- catch (e) {
588
- if (e.code !== 'EEXIST') throw e;
589
- const raw = fs.readFileSync(file, 'utf8').trim();
590
- if (!/^[1-9]\d*$/.test(raw) || !Number.isSafeInteger(Number(raw))) return null;
591
- try { process.kill(Number(raw), 0); return null; } catch (err) { if (err.code !== 'ESRCH') return null; }
592
- try { fs.unlinkSync(file); } catch { /* raced */ }
593
- }
594
- }
595
- return null;
596
- }
@@ -1,11 +0,0 @@
1
- [Unit]
2
- Description=Submit one read-only worker review per open PR head that has none (no LLM calls)
3
- After=dot-bridge.service
4
-
5
- [Service]
6
- Type=oneshot
7
- WorkingDirectory=/ABSOLUTE/PATH/TO/DALAN
8
- Environment=PATH=/ABSOLUTE/PATH/TO/NODE/BIN:%h/.local/bin:/usr/local/bin:/usr/bin:/bin
9
- ExecStart=/usr/bin/env node /ABSOLUTE/PATH/TO/DALAN/bin/dot-pr-reviewer.mjs
10
- TimeoutStartSec=900
11
- NoNewPrivileges=true
@@ -1,10 +0,0 @@
1
- [Unit]
2
- Description=Run the Dalan PR head reviewer every 10 minutes
3
-
4
- [Timer]
5
- OnCalendar=*:0/10
6
- Persistent=true
7
- Unit=dot-pr-reviewer.service
8
-
9
- [Install]
10
- WantedBy=timers.target