@tnunamak/dalan 0.0.0-stage → 0.6.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 (199) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/CONTRIBUTING.md +26 -0
  3. package/LICENSE +204 -0
  4. package/PROTOCOL.md +351 -0
  5. package/README.md +215 -2
  6. package/SECURITY.md +30 -0
  7. package/bin/dalan.mjs +43 -0
  8. package/bin/dot-acp-agent.mjs +377 -0
  9. package/bin/dot-alert.mjs +9 -0
  10. package/bin/dot-deadman.mjs +82 -0
  11. package/bin/dot-heartbeat.mjs +29 -0
  12. package/bin/dot-pr-reviewer.mjs +32 -0
  13. package/bin/dot-worker.mjs +764 -0
  14. package/docs/chatgpt-worker-onboarding.md +112 -0
  15. package/docs/claude-worker-onboarding.md +113 -0
  16. package/docs/codex-to-muse.md +175 -0
  17. package/docs/connect-chatgpt.md +83 -0
  18. package/docs/connection-longevity.md +43 -0
  19. package/docs/dalan-upgrade.md +246 -0
  20. package/docs/deadman.md +61 -0
  21. package/docs/dot-pr-reviewer.config.example.json +9 -0
  22. package/docs/durability-audit.md +27 -0
  23. package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
  24. package/docs/keycloak-oauth-setup.md +30 -0
  25. package/docs/local-agent-mcp.md +41 -0
  26. package/docs/manual-setup.md +135 -0
  27. package/docs/mirror-fetch.md +97 -0
  28. package/docs/operations.md +799 -0
  29. package/docs/operator-duties.md +68 -0
  30. package/docs/owner-integrator.md +27 -0
  31. package/docs/portable-auth-profile.md +107 -0
  32. package/docs/pr-head-reviewer.md +70 -0
  33. package/docs/pr-preflight.md +28 -0
  34. package/docs/pull-queue.md +131 -0
  35. package/docs/pull-workers.md +94 -0
  36. package/docs/redaction.md +27 -0
  37. package/docs/service-setup.md +219 -0
  38. package/docs/setup-reference.md +80 -0
  39. package/docs/t3-connector-icon.png +0 -0
  40. package/docs/t3-integration.md +51 -0
  41. package/docs/t3-result-retry-delivery.md +41 -0
  42. package/docs/t3-reverse-control.md +107 -0
  43. package/docs/usage.md +443 -0
  44. package/docs/worker-clients.md +290 -0
  45. package/integrations/t3/acp-kit/src/capability.mjs +25 -0
  46. package/integrations/t3/acp-kit/src/errors.mjs +13 -0
  47. package/integrations/t3/acp-kit/src/index.mjs +5 -0
  48. package/integrations/t3/acp-kit/src/lock.mjs +155 -0
  49. package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
  50. package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
  51. package/package.json +67 -4
  52. package/packages/job-core/README.md +18 -0
  53. package/packages/job-core/index.mjs +2 -0
  54. package/packages/job-core/package.json +8 -0
  55. package/packages/job-core/protocol/canonical.mjs +11 -0
  56. package/packages/job-core/protocol/v0/command.schema.json +1154 -0
  57. package/packages/job-core/protocol/v0/event.schema.json +77 -0
  58. package/packages/job-core/protocol/v0/reply.schema.json +59 -0
  59. package/packages/job-core/transitions.mjs +25 -0
  60. package/scripts/daily-selfcheck.mjs +135 -0
  61. package/scripts/dalan-try-selfcheck.mjs +29 -0
  62. package/scripts/lib/expose-tailscale.mjs +408 -0
  63. package/scripts/live-trial/common.mjs +272 -0
  64. package/scripts/monitor-targets.mjs +44 -0
  65. package/scripts/upgrade-drain.mjs +39 -0
  66. package/scripts/worker-bridge-setup.mjs +925 -0
  67. package/src/ack-ledger.mjs +37 -0
  68. package/src/acp-bridge.mjs +418 -0
  69. package/src/acp-context.mjs +138 -0
  70. package/src/admin-socket.mjs +14 -0
  71. package/src/alerts.mjs +147 -0
  72. package/src/artifact-journal.mjs +75 -0
  73. package/src/as-files.mjs +347 -0
  74. package/src/as-store.mjs +456 -0
  75. package/src/as.mjs +538 -0
  76. package/src/auth.mjs +166 -0
  77. package/src/builtin-http.mjs +22 -0
  78. package/src/check-coverage.mjs +38 -0
  79. package/src/check-lint.mjs +88 -0
  80. package/src/check-readiness.mjs +112 -0
  81. package/src/check-response.mjs +19 -0
  82. package/src/child-exit.mjs +18 -0
  83. package/src/child-registry.mjs +94 -0
  84. package/src/claim-command-ledger.mjs +51 -0
  85. package/src/cli-help.mjs +186 -0
  86. package/src/cli-name.mjs +16 -0
  87. package/src/connect-cli.mjs +126 -0
  88. package/src/consumers.mjs +61 -0
  89. package/src/deadman.mjs +329 -0
  90. package/src/delivery.mjs +19 -0
  91. package/src/demo-worker.mjs +150 -0
  92. package/src/destinations/index.mjs +23 -0
  93. package/src/destinations/none.mjs +15 -0
  94. package/src/destinations/t3.mjs +109 -0
  95. package/src/diagnostic.mjs +78 -0
  96. package/src/docs-url.mjs +9 -0
  97. package/src/drain-runner.mjs +9 -0
  98. package/src/drained-owner.mjs +26 -0
  99. package/src/drained-slot.mjs +70 -0
  100. package/src/drained.mjs +40 -0
  101. package/src/durable-waiters.mjs +236 -0
  102. package/src/env.mjs +19 -0
  103. package/src/execution.mjs +112 -0
  104. package/src/failure-type.mjs +28 -0
  105. package/src/get-summary.mjs +32 -0
  106. package/src/git-env.mjs +15 -0
  107. package/src/host-budget-receipts.mjs +154 -0
  108. package/src/host-budget-seccomp.py +33 -0
  109. package/src/host-budget-service.mjs +54 -0
  110. package/src/host-budget-stop.mjs +26 -0
  111. package/src/host-budget-storage.py +259 -0
  112. package/src/host-budget.mjs +149 -0
  113. package/src/host-cgroup.mjs +23 -0
  114. package/src/host-check-allowlist.mjs +42 -0
  115. package/src/host-execution-policy.mjs +38 -0
  116. package/src/host-health.mjs +34 -0
  117. package/src/host-stop-reverify.mjs +44 -0
  118. package/src/inbox.mjs +55 -0
  119. package/src/integrator.mjs +322 -0
  120. package/src/job-retention.mjs +69 -0
  121. package/src/legacy-names.mjs +8 -0
  122. package/src/lifecycle.mjs +291 -0
  123. package/src/limits.mjs +31 -0
  124. package/src/loopback.mjs +9 -0
  125. package/src/mcp-outcome.mjs +79 -0
  126. package/src/mcp-sse.mjs +62 -0
  127. package/src/mcp-stdio.mjs +191 -0
  128. package/src/mirror-fetch-lock.py +164 -0
  129. package/src/mirror-fetch.mjs +174 -0
  130. package/src/notify-ledger.mjs +82 -0
  131. package/src/objectives.mjs +129 -0
  132. package/src/owner-report-artifact.mjs +66 -0
  133. package/src/patch-apply.mjs +84 -0
  134. package/src/path-syntax.mjs +16 -0
  135. package/src/paths.mjs +67 -0
  136. package/src/pr-head-reviewer.mjs +596 -0
  137. package/src/pr-preflight.mjs +51 -0
  138. package/src/prepared-node-modules.mjs +129 -0
  139. package/src/process-inspection.mjs +36 -0
  140. package/src/projects.mjs +480 -0
  141. package/src/protocol-artifact-commands.mjs +52 -0
  142. package/src/protocol-delivery-driver.mjs +167 -0
  143. package/src/protocol-finish.mjs +100 -0
  144. package/src/protocol-owner-command.mjs +35 -0
  145. package/src/protocol-owner-mutations.mjs +22 -0
  146. package/src/protocol-owner-waiters.mjs +67 -0
  147. package/src/protocol-retention.mjs +52 -0
  148. package/src/protocol-services.mjs +61 -0
  149. package/src/protocol-stop-observer.mjs +131 -0
  150. package/src/publish-plan.mjs +245 -0
  151. package/src/pull-queue.mjs +159 -0
  152. package/src/redaction.mjs +763 -0
  153. package/src/rejections.mjs +18 -0
  154. package/src/request-log.mjs +102 -0
  155. package/src/restore-check.mjs +90 -0
  156. package/src/result-binding.mjs +65 -0
  157. package/src/route-setting.mjs +24 -0
  158. package/src/runtime-check.mjs +13 -0
  159. package/src/sandbox-supervisor.mjs +105 -0
  160. package/src/schema-subset.mjs +186 -0
  161. package/src/scopes.mjs +15 -0
  162. package/src/server.mjs +1468 -0
  163. package/src/service-migrate-workers.mjs +113 -0
  164. package/src/service.mjs +388 -0
  165. package/src/setup.mjs +63 -0
  166. package/src/shutdown-signal.mjs +12 -0
  167. package/src/signal-sandbox-processes.py +56 -0
  168. package/src/signal.mjs +119 -0
  169. package/src/status-evidence.mjs +47 -0
  170. package/src/status-summary.mjs +54 -0
  171. package/src/store.mjs +3069 -0
  172. package/src/submission-policy.mjs +623 -0
  173. package/src/subscription-storage.mjs +64 -0
  174. package/src/t3-audit.mjs +120 -0
  175. package/src/t3-control.mjs +102 -0
  176. package/src/t3-transport.mjs +158 -0
  177. package/src/t3.mjs +209 -0
  178. package/src/terminal-safe.mjs +19 -0
  179. package/src/tool-registry.mjs +453 -0
  180. package/src/try-command.mjs +11 -0
  181. package/src/try-exposure.mjs +908 -0
  182. package/src/try-hosted-clients.mjs +46 -0
  183. package/src/try-hosted.mjs +444 -0
  184. package/src/try-selfcheck.mjs +168 -0
  185. package/src/try.mjs +635 -0
  186. package/src/webhooks.mjs +86 -0
  187. package/src/work-order.mjs +265 -0
  188. package/src/worker-instructions.mjs +26 -0
  189. package/src/worker-prompt.mjs +4 -0
  190. package/src/workers.mjs +632 -0
  191. package/src/workspace.mjs +1065 -0
  192. package/systemd/dot-bridge-heartbeat.service +18 -0
  193. package/systemd/dot-bridge-heartbeat.timer +10 -0
  194. package/systemd/dot-bridge-selfcheck.service +12 -0
  195. package/systemd/dot-bridge-selfcheck.timer +11 -0
  196. package/systemd/dot-bridge.service +17 -0
  197. package/systemd/dot-deadman.service +30 -0
  198. package/systemd/dot-pr-reviewer.service +11 -0
  199. package/systemd/dot-pr-reviewer.timer +10 -0
@@ -0,0 +1,129 @@
1
+ // Objective identity of an assignment: objective_key, revision, task_kind and the submitter (source). Live submitters send
2
+ // it with /submit; older rows get it only from a tuple that the request_id itself proves (see docs/usage.md, "Metrics").
3
+ import { createHash } from 'node:crypto';
4
+ import { legacyFixLoopName } from './legacy-names.mjs';
5
+
6
+ // Submitter identity stored next to (not inside) the payload. Every manifest is submitted by the drainer, so there is no
7
+ // separate producer source; 'unknown' is for a caller that declares it cannot say.
8
+ // The fix loop was first called by an older name: it is accepted as input and normalized to `fix-loop`, and it stays the
9
+ // stored form of `assignments.source` in databases created before the rename (their CHECK constraint lists it), so no
10
+ // stored row changes there. A database created after the rename stores and allows only `fix-loop`.
11
+ export const fixLoopSource='fix-loop';
12
+ export const objectiveSources=['drainer',fixLoopSource,'agent','unknown'];
13
+ // A database whose stored schema was created before the rename keeps the earlier spelling (its CHECK constraint lists it and
14
+ // SQLite cannot change a CHECK without rebuilding the table). A newer database stores the neutral spelling. `legacy` says which.
15
+ export const toStoredSource=(source,legacy=true)=>legacy&&source===fixLoopSource?legacyFixLoopName:source;
16
+ export const fromStoredSource=source=>source===legacyFixLoopName?fixLoopSource:source;
17
+ // The earlier spelling also prefixes stored objective keys and task kinds. Rows keep what they were written with; every
18
+ // comparison and report reads both spellings as one.
19
+ export const canonicalObjectiveKey=key=>typeof key==='string'&&key.startsWith(`${legacyFixLoopName}:`)?`${fixLoopSource}${key.slice(legacyFixLoopName.length)}`:key;
20
+ export const canonicalTaskKind=kind=>kind===legacyFixLoopName?fixLoopSource:kind;
21
+ // A "kind/priority" label (or a bare kind) as the metrics report it.
22
+ export const canonicalKindLabel=label=>typeof label==='string'&&(label===legacyFixLoopName||label.startsWith(`${legacyFixLoopName}/`))?`${fixLoopSource}${label.slice(legacyFixLoopName.length)}`:label;
23
+ // SQL for the same mapping over a kind expression.
24
+ export const canonicalKindSql=expr=>`CASE WHEN (${expr})='${legacyFixLoopName}' THEN '${fixLoopSource}' ELSE (${expr}) END`;
25
+ // The reverse mapping, for hashes that were persisted under the earlier spelling.
26
+ export const storedObjectiveKey=(key,legacy=true)=>legacy&&typeof key==='string'&&key.startsWith(`${fixLoopSource}:`)?`${legacyFixLoopName}${key.slice(fixLoopSource.length)}`:key;
27
+ export const storedTaskKind=(kind,legacy=true)=>legacy&&kind===fixLoopSource?legacyFixLoopName:kind;
28
+ export function canonicalMetaValue(field,value) {
29
+ if(value==null) return value;
30
+ return field==='source'?fromStoredSource(value):field==='objective_key'?canonicalObjectiveKey(value):field==='task_kind'?canonicalTaskKind(value):value;
31
+ }
32
+ export const metaFields=['objective_key','revision','task_kind','source'];
33
+ export function normalizeMeta(meta) {
34
+ const out=Object.fromEntries(metaFields.map(k=>[k,null]));
35
+ if(meta===undefined||meta===null) return out;
36
+ if(typeof meta!=='object'||Array.isArray(meta)||Object.keys(meta).some(k=>!metaFields.includes(k))) throw new Error('invalid meta');
37
+ for(const k of metaFields) {
38
+ const v=meta[k];
39
+ if(v===undefined||v===null) continue;
40
+ if(typeof v!=='string'||!v||Buffer.byteLength(v)>512) throw new Error(`invalid meta.${k}`);
41
+ out[k]=k==='source'?fromStoredSource(v):v;
42
+ }
43
+ if(out.source!==null&&!objectiveSources.includes(out.source)) throw new Error('invalid meta.source');
44
+ return out;
45
+ }
46
+
47
+ const hash = value => createHash('sha256').update(value).digest('hex');
48
+ // The drainer's deterministic identity: the request_id commits to the whole tuple, so a matching hash proves it. A
49
+ // re-preparation (the producer prepares the objective again after the bridge cancelled attempt n-1 as expired) appends
50
+ // `-r<n>`, as fix-loop reopen attempts do; the first preparation keeps the bare id, so existing ids are unchanged.
51
+ export const maxPreparationAttempt = 3;
52
+ export const drainerRequestId = (repo, objectiveKey, revision, taskKind, policyVersion = 1, attempt = 0) => `dot_${hash(JSON.stringify([repo ?? '', objectiveKey, revision, taskKind, policyVersion]))}${attempt ? `-r${attempt}` : ''}`;
53
+ export const preparationAttemptOf = requestId => Number(/-r(\d+)$/.exec(requestId)?.[1] ?? 0);
54
+ // fix-loop: one request id per candidate and reopen attempt (`-r<n>`); the objective is the candidate, the revision the pinned head.
55
+ // The request id prefix is persisted in existing request ids and receipts, so it does not change.
56
+ export const fixLoopRequestId = (candidate, attempt = 0) => `dotfix-${candidate.id}-${hash(`${candidate.repo}:${candidate.id}`).slice(0, 8)}${attempt ? `-r${attempt}` : ''}`.slice(0, 128);
57
+ export const fixLoopObjective = candidate => `${fixLoopSource}:${candidate.repo}#${candidate.id}`;
58
+ export const fixLoopTaskKind = fixLoopSource;
59
+ // Producers of earlier releases send the old name in the objective key and task kind; both spellings verify.
60
+ const fixLoopObjectivePattern = new RegExp(`^(?:${fixLoopSource}|${legacyFixLoopName}):([^#]+)#(.+)$`);
61
+ const fixLoopTaskKinds = [fixLoopTaskKind, legacyFixLoopName];
62
+
63
+ const firstInput = payload => (Array.isArray(payload?.inputs) ? payload.inputs[0] : null) ?? null;
64
+
65
+ // Null when the tuple is proven for this row (request_id + stored payload), else the reason it is not.
66
+ export function verifyObjective(row, tuple) {
67
+ let meta;
68
+ try { meta = normalizeMeta(tuple); } catch (error) { return error.message; }
69
+ if (metaFields.some(k => meta[k] === null)) return 'incomplete tuple';
70
+ const payload = typeof row.payload === 'string' ? JSON.parse(row.payload) : row.payload, input = firstInput(payload);
71
+ if (meta.source === 'drainer') {
72
+ if (row.request_id !== drainerRequestId(input?.github_repo ?? '', meta.objective_key, meta.revision, meta.task_kind, 1, preparationAttemptOf(row.request_id))) return 'request_id does not match the drainer identity of this tuple';
73
+ if (input && meta.revision !== (input.head_sha ?? input.base_sha)) return 'revision differs from the pinned input';
74
+ return null;
75
+ }
76
+ if (meta.source === fixLoopSource) {
77
+ const m = fixLoopObjectivePattern.exec(meta.objective_key);
78
+ if (!m || !fixLoopTaskKinds.includes(meta.task_kind)) return 'not a fix-loop objective';
79
+ const candidate = { repo: m[1], id: m[2] }, attempt = Number(/-r(\d+)$/.exec(row.request_id)?.[1] ?? 0);
80
+ if (row.request_id !== fixLoopRequestId(candidate, 0) && row.request_id !== fixLoopRequestId(candidate, attempt)) return 'request_id does not match the fix-loop candidate';
81
+ if (input?.github_repo !== candidate.repo || input?.base_sha !== meta.revision) return 'revision or repo differs from the pinned input';
82
+ return null;
83
+ }
84
+ return `source ${meta.source} cannot be verified`;
85
+ }
86
+
87
+ // Lens names the producer has used for audit objectives, including retired ones; a guess counts only if the hash matches.
88
+ const auditLenses = ['correctness', 'errors', 'tests', 'concurrency', 'clarity'];
89
+ function guesses(payload) {
90
+ const input = firstInput(payload), repo = input?.github_repo;
91
+ if (!repo) return [];
92
+ const out = [];
93
+ if (input.head_sha && input.pr_number) out.push({ objective_key: `pr-review:${repo}#${input.pr_number}`, revision: input.head_sha, task_kind: 'review' });
94
+ const module = Array.isArray(payload.scope_paths) && typeof payload.scope_paths[0] === 'string' && payload.scope_paths[0].includes('/') ? payload.scope_paths[0].split('/')[0] : null;
95
+ if (module && input.base_sha && !input.head_sha) {
96
+ const part = /\(part (\d+) of \d+/.exec(payload.brief ?? '');
97
+ const indexes = part ? [Number(part[1]) - 1] : [];
98
+ for (const lens of auditLenses) for (const index of indexes) out.push({ objective_key: `audit:${repo}:${module}:${lens}:${index}`, revision: input.base_sha, task_kind: 'audit-review' });
99
+ for (const kind of ['audit-review', 'audit']) out.push({ objective_key: `audit:${repo}:${module}`, revision: input.base_sha, task_kind: kind });
100
+ }
101
+ return out.map(t => ({ ...t, source: 'drainer' }));
102
+ }
103
+
104
+ // Host-side derivation for `dalan backfill-objectives`: receipts are the rows (their body is the submitted payload);
105
+ // manifests and the fix ledger supply exact tuples, and payload-shaped guesses cover consumed manifests. Only tuples
106
+ // that verifyObjective proves are returned; the server verifies again against its own stored payload.
107
+ export function deriveObjectives({ receipts = [], manifests = [], ledger = [] }) {
108
+ const fromManifest = new Map(), fromLedger = new Map();
109
+ for (const m of manifests) {
110
+ if (!m || typeof m !== 'object' || m.policy_version !== 1) continue;
111
+ const input = firstInput(m.assignment);
112
+ fromManifest.set(drainerRequestId(input?.github_repo ?? '', m.objective_key, m.revision, m.task_kind, 1, m.preparation_attempt ?? 0), { objective_key: m.objective_key, revision: m.revision, task_kind: m.task_kind, source: 'drainer' });
113
+ }
114
+ for (const e of ledger) if (e?.stage === 'assigned' && typeof e.request_id === 'string' && e.request_id.startsWith('dotfix-') && e.id && e.repo && e.base_sha)
115
+ fromLedger.set(e.request_id, { objective_key: fixLoopObjective(e), revision: e.base_sha, task_kind: fixLoopTaskKind, source: fixLoopSource });
116
+ const tuples = [], counts = { receipts: 0, verified: { manifest: 0, ledger: 0, payload: 0 }, unverified: 0 };
117
+ for (const r of receipts) {
118
+ let payload;
119
+ try { payload = JSON.parse(r.body); } catch { continue; }
120
+ if (!payload || payload.request_id !== r.request_id) continue;
121
+ counts.receipts++;
122
+ const row = { request_id: r.request_id, payload };
123
+ const tried = [['manifest', fromManifest.get(r.request_id)], ['ledger', fromLedger.get(r.request_id)], ...guesses(payload).map(t => ['payload', t])];
124
+ const hit = tried.find(([, t]) => t && verifyObjective(row, t) === null);
125
+ if (hit) { counts.verified[hit[0]]++; tuples.push({ request_id: r.request_id, ...hit[1] }); }
126
+ else counts.unverified++;
127
+ }
128
+ return { tuples, counts };
129
+ }
@@ -0,0 +1,66 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import {createHash,randomUUID} from 'node:crypto';
4
+ import {redactSinkText,splitFields} from './redaction.mjs';
5
+
6
+ export const OWNER_REPORT_ARTIFACT_LIMIT=8*1024*1024;
7
+ const clean=value=>redactSinkText(value);
8
+
9
+ const preparedReports=new WeakMap();
10
+ // Preparing a document performs redaction exactly once. Storage accepts only
11
+ // this process-local capability, not arbitrary bytes claiming to be prepared.
12
+ // New documents carry the neutral id; the original id is still accepted so documents written earlier stay valid.
13
+ export const ownerReportFormat='dalan-owner-report';
14
+ const ownerReportFormats=[ownerReportFormat,'dot-bridge-owner-report'];
15
+ export function prepareOwnerReportArtifact(doc) {
16
+ const invalid=()=>{throw new Error('invalid owner report artifact document');};
17
+ const closed=(value,keys)=>value&&Object.getPrototypeOf(value)===Object.prototype&&
18
+ Object.keys(value).length===keys.length&&keys.every(key=>Object.hasOwn(value,key));
19
+ if(!closed(doc,['format','version','summary','result','progress'])||!ownerReportFormats.includes(doc.format)||doc.version!==1||
20
+ typeof doc.summary!=='string'||typeof doc.result!=='string'||!Array.isArray(doc.progress))invalid();
21
+ for(const row of doc.progress) if(!closed(row,['sequence','at','text'])||!Number.isSafeInteger(row.sequence)||row.sequence<1||typeof row.at!=='string'||typeof row.text!=='string')invalid();
22
+ // A report whose raw text is already over the limit is refused before the split check, which reads all of it.
23
+ const rawTexts=[doc.summary,doc.result,...doc.progress.flatMap(row=>[row.at,row.text])];
24
+ if(rawTexts.reduce((n,text)=>n+Buffer.byteLength(text),0)>OWNER_REPORT_ARTIFACT_LIMIT)throw new Error('owner report artifact exceeds 8 MiB');
25
+ // One split check over every text the worker wrote: a credential split between summary, result and progress is
26
+ // masked. Timestamps come from the bridge and take no part.
27
+ const [summary,result,...texts]=splitFields([doc.summary,doc.result,...doc.progress.map(row=>row.text)]).map(clean);
28
+ const progress=doc.progress.map((row,i)=>({sequence:row.sequence,at:clean(row.at),text:texts[i]}));
29
+ const encoded=Buffer.from(JSON.stringify({format:doc.format,version:doc.version,summary,result,progress})+'\n');
30
+ if(encoded.length>OWNER_REPORT_ARTIFACT_LIMIT)throw new Error('owner report artifact exceeds 8 MiB');
31
+ const prepared=Object.freeze({size:encoded.length,sha256:createHash('sha256').update(encoded).digest('hex')});
32
+ preparedReports.set(prepared,encoded);
33
+ return prepared;
34
+ }
35
+ export function ownerReportArtifactBytes(prepared) {
36
+ const bytes=preparedReports.get(prepared);
37
+ if(!bytes)throw new Error('owner report artifact requires a prepared document');
38
+ return Buffer.from(bytes);
39
+ }
40
+
41
+ // Called only from a trusted finish transaction. Workspace remains the owner of
42
+ // artifact storage, sealing, retention, and ordinary rollback cleanup.
43
+ export function captureOwnerReportArtifact(store,workspace,{requestId,claimId,outcome,summary,result,onRollback}) {
44
+ if(outcome!=='completed') return null;
45
+ if(!store.db.isTransaction||typeof onRollback!=='function') throw new Error('owner report artifact requires finish transaction');
46
+ const progress=store.db.prepare('SELECT id,note,created_at FROM progress WHERE request_id=? ORDER BY id').all(requestId)
47
+ .map(row=>({sequence:row.id,at:row.created_at,text:row.note}));
48
+ const document={format:ownerReportFormat,version:1,summary,result,progress};
49
+ const prepared=prepareOwnerReportArtifact(document);
50
+ const artifactId=`art_${randomUUID()}`;
51
+ const saved=workspace.saveArtifactInTransaction(requestId,claimId,'owner-report',prepared,artifactId,onRollback);
52
+ const row=store.db.prepare('SELECT path,size,sha256 FROM artifacts WHERE id=? AND request_id=? AND kind=\'owner-report\' AND sealed=1').get(artifactId,requestId);
53
+ if(!row||row.size!==prepared.size||row.sha256!==prepared.sha256) throw new Error('owner report artifact integrity failure');
54
+ const fd=fs.openSync(row.path,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
55
+ try {
56
+ const stat=fs.fstatSync(fd);
57
+ if(!stat.isFile()||stat.size!==row.size) throw new Error('owner report artifact integrity failure');
58
+ const actual=Buffer.alloc(row.size);let offset=0;
59
+ while(offset<actual.length){const count=fs.readSync(fd,actual,offset,actual.length-offset,offset);if(!count)throw new Error('owner report artifact integrity failure');offset+=count;}
60
+ if(createHash('sha256').update(actual).digest('hex')!==row.sha256) throw new Error('owner report artifact integrity failure');
61
+ fs.fsyncSync(fd);
62
+ } finally {fs.closeSync(fd);}
63
+ const dirfd=fs.openSync(path.dirname(row.path),fs.constants.O_RDONLY|fs.constants.O_DIRECTORY);
64
+ try {fs.fsyncSync(dirfd);} finally {fs.closeSync(dirfd);}
65
+ return {artifact_id:saved.artifact_id,kind:saved.kind,size:saved.size,sha256:saved.sha256};
66
+ }
@@ -0,0 +1,84 @@
1
+ // Apply a worker build patch to a checkout, or observe a matching tree. Used by `dalan apply` and by the ACP
2
+ // adapter's read-only check. Nothing here talks to the bridge.
3
+ import { spawnSync } from 'node:child_process';
4
+ import { createHash } from 'node:crypto';
5
+
6
+ const git = (dir, args, input, env) => spawnSync('git', ['-C', dir, ...args], { input, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, env });
7
+
8
+ // git apply from a subdirectory can silently skip root-relative paths.
9
+ function worktreeRoot(dir, env) {
10
+ const root = git(dir, ['rev-parse', '--show-toplevel'], undefined, env);
11
+ return root.status === 0 ? root.stdout.replace(/\r?\n$/, '') : null;
12
+ }
13
+
14
+ // The patch must apply onto the job's base or a descendant of it, so HEAD has to contain base. Returns null when it does,
15
+ // else the reason in one sentence.
16
+ export function baseProblem(dir, baseSha, env) {
17
+ if (!/^[0-9a-f]{40,64}$/.test(baseSha ?? '')) return 'the job records no base commit';
18
+ const head = git(dir, ['rev-parse', '--verify', 'HEAD'], undefined, env);
19
+ if (head.status !== 0) return `${dir} is not a git checkout with a HEAD`;
20
+ const known = git(dir, ['cat-file', '-e', `${baseSha}^{commit}`], undefined, env);
21
+ if (known.status !== 0) return `base ${baseSha.slice(0, 12)} is not in this checkout; use a checkout that already contains it`;
22
+ const anc = git(dir, ['merge-base', '--is-ancestor', baseSha, 'HEAD'], undefined, env);
23
+ if (anc.status === 1) return `base ${baseSha.slice(0, 12)} is not an ancestor of HEAD ${head.stdout.trim().slice(0, 12)}; the patch was built on a different line of history`;
24
+ return anc.status === 0 ? null : `could not compare base and HEAD: ${anc.stderr.trim()}`;
25
+ }
26
+
27
+ // Checks the digest, the base and `git apply --check`, then applies. Preflight failures touch nothing; a failed apply
28
+ // process may have partially changed the checkout. Returns Git's NUL-delimited list of touched file names.
29
+ export function applyPatch({ dir, patch, sha256, baseSha, env }) {
30
+ const body = Buffer.from(patch);
31
+ if (sha256 && createHash('sha256').update(body).digest('hex') !== sha256) throw new Error('patch sha256 does not match the recorded evidence; not applied');
32
+ const problem = baseProblem(dir, baseSha, env);
33
+ if (problem) throw new Error(`not applied: ${problem}`);
34
+ dir = worktreeRoot(dir, env);
35
+ if (!dir) throw new Error('not applied: could not resolve the repository worktree top level');
36
+ const check = git(dir, ['apply', '--check', '-'], body, env);
37
+ if (check.status !== 0) throw new Error(`not applied: git apply --check failed: ${(check.stderr || '').trim().slice(0, 300)}`);
38
+ const numstat = git(dir, ['apply', '--numstat', '-z', '-'], body, env);
39
+ if (numstat.error || numstat.status !== 0) throw new Error(`git apply --numstat failed: ${(numstat.stderr || numstat.error?.message || '').trim().slice(0, 300)}`);
40
+ const records = numstat.stdout.split('\0');
41
+ const files = [];
42
+ for (let index = 0; index < records.length; index++) {
43
+ const record = records[index];
44
+ if (!record) continue;
45
+ const firstTab = record.indexOf('\t'), secondTab = record.indexOf('\t', firstTab + 1);
46
+ if (firstTab < 0 || secondTab < 0) throw new Error('git apply --numstat returned an invalid path record');
47
+ const file = record.slice(secondTab + 1);
48
+ if (file) files.push(file);
49
+ else {
50
+ const oldPath = records[index + 1], newPath = records[index + 2];
51
+ if (!oldPath || !newPath) throw new Error('git apply --numstat returned an incomplete rename record');
52
+ files.push(oldPath, newPath);
53
+ index += 2;
54
+ }
55
+ }
56
+ const run = git(dir, ['apply', '-'], body, env);
57
+ if (run.status !== 0) throw new Error(`git apply failed after a clean check; the checkout may be partially changed: ${(run.stderr || '').trim().slice(0, 300)}`);
58
+ return files;
59
+ }
60
+
61
+ // Read-only reverse-applicability check. A match does not establish who applied
62
+ // the change, its origin or its value. Empty patches never count as a match.
63
+ export function patchMatchesWorktree(dir, patch) {
64
+ const body = Buffer.from(patch);
65
+ if (!body.length) return false;
66
+ dir = worktreeRoot(dir);
67
+ if (!dir) return false;
68
+ return git(dir, ['apply', '--check', '--reverse', '-'], body).status === 0;
69
+ }
70
+
71
+ // Observe reverse applicability once per remembered patch. This cannot identify who
72
+ // applied a change or whether it was useful, and never records an owner decision.
73
+ export async function detectPresentPatches(builds, cwd, { fetchPatch, onError = () => {} }) {
74
+ const done = [];
75
+ for (const b of builds.filter(x => !x.observed)) {
76
+ try {
77
+ const patch = cwd ? await fetchPatch(b) : null;
78
+ if (!patch || !patchMatchesWorktree(cwd, patch)) continue;
79
+ b.observed = true;
80
+ done.push(b.rid);
81
+ } catch (e) { onError(b, e); }
82
+ }
83
+ return done;
84
+ }
@@ -0,0 +1,16 @@
1
+ // Which repository path text the bridge reads as one path. Used by the submission scanner (src/submission-policy.mjs).
2
+ //
3
+ // A segment is plain characters [A-Za-z0-9_.@-], or router groups followed by plain characters. Router groups are whole bracket or
4
+ // parenthesis forms only: `[id]`, `[...slug]`, `[[...slug]]`, `[[lang]]`, `[slug=matcher]`, `(group)`, and the interception markers
5
+ // `(.)`, `(..)`, `(...)`. `@slot` is plain. A segment after a `/` may start with `+` (SvelteKit `+page.svelte`); the first segment
6
+ // may not, because a diff line starts with `+` and `+README.md` must still read as `README.md`. Spaces, `$`, backticks, quotes,
7
+ // `;|&<>`, `~`, `*`, `?`, backslash and control characters are never path characters. `[..]` is no group.
8
+ export const plainChar = '[A-Za-z0-9_.@-]';
9
+ const group = '\\[\\[(?:\\.\\.\\.)?[A-Za-z0-9_-]+\\]\\]|\\[(?:\\.\\.\\.)?[A-Za-z0-9_=-]+\\]|\\((?:[A-Za-z0-9_-]+|\\.{1,3})\\)';
10
+ export const firstSegment = `(?:(?:${group})+${plainChar}*|${plainChar}+)`;
11
+ export const laterSegment = `(?:(?:${group})+${plainChar}*|\\+?${plainChar}+)`;
12
+ const wholePath = new RegExp(`^${laterSegment}(?:\\/${laterSegment})*$`);
13
+ // True when `file` is a repository-relative path made only of the segments above, with no `.` or `..` segment.
14
+ export const readablePath = file => typeof file === 'string' && wholePath.test(file) && !file.split('/').some(part => part === '.' || part === '..');
15
+ // Router syntax present: a bracket or parenthesis anywhere in the path.
16
+ export const hasRouterSyntax = file => /[[\]()]/.test(file);
package/src/paths.mjs ADDED
@@ -0,0 +1,67 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import {readEnv} from './env.mjs';
5
+
6
+ const areas=['.config','.local/share','.local/state'];
7
+ const components={
8
+ '.config':['env','operator.key','workers.json','workers-repos.json','workers-audit.jsonl','limits.json','alerts.env','acp-secret','oauth.env','as.json','as-jwks.json','as-cookie-keys.json','as-storage.key','as.sqlite'],
9
+ '.local/share':['bridge.db','delivery-acks.db','notify-sent.db','bridge.db.secrets/storage.key','receipts','artifact-index'],
10
+ '.local/state':['requests.jsonl'],
11
+ '.tmp':['artifacts','host-receipts'],
12
+ };
13
+ function info(file) {
14
+ try {return fs.lstatSync(file);} catch(error) {if(error.code==='ENOENT')return null;throw error;}
15
+ }
16
+ function populated(file) {
17
+ const stat=info(file);
18
+ if(!stat)return false;
19
+ if(['.keep','.gitkeep','.DS_Store'].includes(path.basename(file))||/^as-owner\.sqlite(?:-(?:wal|shm))?$/.test(path.basename(file)))return false;
20
+ if(stat.isDirectory())return fs.readdirSync(file).some(name=>populated(path.join(file,name)));
21
+ // Empty placeholder files and directory scaffolding do not initialize a root.
22
+ // Do not follow symlinks: an explicitly linked root is an operator choice.
23
+ return !stat.isFile()||stat.size>0;
24
+ }
25
+ // Signal tokens rotate between the shared signal-token and per-worker signal-token.<worker> files, and stale copies can
26
+ // remain. A root that had any signal token needs at least one in its replacement, not the same file names.
27
+ const signalToken=/^signal-token(?:\.[a-z][a-z0-9_-]{0,31})?$/;
28
+ function hasSignalToken(dir) {
29
+ try {return fs.readdirSync(dir).some(name=>signalToken.test(name)&&populated(path.join(dir,name)));}
30
+ catch(error) {if(error.code==='ENOENT'||error.code==='ENOTDIR')return false;throw error;}
31
+ }
32
+ function initialized(current,legacy,area) {
33
+ return populated(current)&&(components[area]??[]).every(name=>!populated(path.join(legacy,name))||populated(path.join(current,name)))
34
+ &&(area!=='.config'||!hasSignalToken(legacy)||hasSignalToken(current));
35
+ }
36
+ // Choose one complete root; never fill missing keys or databases from its sibling.
37
+ // Empty new scaffolding cannot hide an existing installation's durable state.
38
+ export function defaultPath(home, relative, ...tail) {
39
+ const parts=relative.split('/'),index=parts.findIndex(part=>/^\.?dot-bridge(?:\.|$)/.test(part));
40
+ if(index<0)throw new Error('defaultPath requires a legacy product path');
41
+ const oldRoot=path.join(home,...parts.slice(0,index+1));
42
+ const newRoot=path.join(home,...parts.slice(0,index),parts[index].replace('dot-bridge','dalan'));
43
+ let root=newRoot;
44
+ const area=parts.slice(0,index).join('/');
45
+ if(!initialized(newRoot,oldRoot,area)) {
46
+ const legacyInstall=areas.some(area=>info(path.join(home,area,'dot-bridge')));
47
+ const currentInstall=areas.some(area=>initialized(path.join(home,area,'dalan'),path.join(home,area,'dot-bridge'),area));
48
+ if(populated(oldRoot)||info(oldRoot)&&!info(newRoot)||legacyInstall&&!currentInstall)root=oldRoot;
49
+ }
50
+ return path.join(root,...parts.slice(index+1),...tail);
51
+ }
52
+ export function workspaceRoot(home=os.homedir(),env=process.env) {
53
+ return readEnv('DALAN_WORKSPACE_ROOT',env)||defaultPath(home,'.tmp/dot-bridge');
54
+ }
55
+ // Observe the existing choice without merging roots or reading private file contents.
56
+ export function rootWarnings(home=os.homedir()) {
57
+ return areas.flatMap((parent,index)=>{
58
+ const legacy=path.join(home,parent,'dot-bridge'),current=path.join(home,parent,'dalan');
59
+ const chosen=defaultPath(home,parent+'/dot-bridge');
60
+ if(chosen!==legacy||!populated(current))return [];
61
+ const missing=components[parent].filter(name=>populated(path.join(legacy,name))&&!populated(path.join(current,name)));
62
+ if(parent==='.config'&&hasSignalToken(legacy)&&!hasSignalToken(current)) {
63
+ missing.push(...fs.readdirSync(legacy).filter(name=>signalToken.test(name)&&populated(path.join(legacy,name))).sort());
64
+ }
65
+ return [{area:['config','data','state'][index],chosen,passed_over:current,missing}];
66
+ });
67
+ }