@tnunamak/dalan 0.0.0-stage → 0.5.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 (182) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/CONTRIBUTING.md +26 -0
  3. package/LICENSE +204 -0
  4. package/PROTOCOL.md +339 -0
  5. package/README.md +348 -2
  6. package/SECURITY.md +30 -0
  7. package/bin/dalan.mjs +38 -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 +755 -0
  14. package/docs/chatgpt-worker-onboarding.md +112 -0
  15. package/docs/claude-worker-onboarding.md +113 -0
  16. package/docs/connect-chatgpt.md +78 -0
  17. package/docs/connection-longevity.md +37 -0
  18. package/docs/dalan-upgrade.md +242 -0
  19. package/docs/deadman.md +59 -0
  20. package/docs/dot-pr-reviewer.config.example.json +9 -0
  21. package/docs/durability-audit.md +27 -0
  22. package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
  23. package/docs/keycloak-oauth-setup.md +30 -0
  24. package/docs/local-agent-mcp.md +39 -0
  25. package/docs/manual-setup.md +135 -0
  26. package/docs/mirror-fetch.md +98 -0
  27. package/docs/operations.md +751 -0
  28. package/docs/operator-duties.md +68 -0
  29. package/docs/owner-integrator.md +27 -0
  30. package/docs/portable-auth-profile.md +109 -0
  31. package/docs/pr-head-reviewer.md +54 -0
  32. package/docs/pr-preflight.md +26 -0
  33. package/docs/pull-workers.md +97 -0
  34. package/docs/redaction.md +27 -0
  35. package/docs/service-setup.md +166 -0
  36. package/docs/setup-reference.md +80 -0
  37. package/docs/t3-connector-icon.png +0 -0
  38. package/docs/t3-integration.md +49 -0
  39. package/docs/t3-result-retry-delivery.md +41 -0
  40. package/docs/t3-reverse-control.md +107 -0
  41. package/docs/usage.md +439 -0
  42. package/docs/worker-clients.md +285 -0
  43. package/integrations/t3/acp-kit/src/capability.mjs +25 -0
  44. package/integrations/t3/acp-kit/src/errors.mjs +13 -0
  45. package/integrations/t3/acp-kit/src/index.mjs +5 -0
  46. package/integrations/t3/acp-kit/src/lock.mjs +155 -0
  47. package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
  48. package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
  49. package/package.json +65 -4
  50. package/packages/job-core/README.md +18 -0
  51. package/packages/job-core/index.mjs +2 -0
  52. package/packages/job-core/package.json +8 -0
  53. package/packages/job-core/protocol/canonical.mjs +11 -0
  54. package/packages/job-core/protocol/v0/command.schema.json +1154 -0
  55. package/packages/job-core/protocol/v0/event.schema.json +77 -0
  56. package/packages/job-core/protocol/v0/reply.schema.json +59 -0
  57. package/packages/job-core/transitions.mjs +25 -0
  58. package/scripts/daily-selfcheck.mjs +135 -0
  59. package/scripts/lib/expose-tailscale.mjs +408 -0
  60. package/scripts/live-trial/common.mjs +272 -0
  61. package/scripts/monitor-targets.mjs +44 -0
  62. package/scripts/upgrade-drain.mjs +39 -0
  63. package/scripts/worker-bridge-setup.mjs +925 -0
  64. package/src/ack-ledger.mjs +37 -0
  65. package/src/acp-bridge.mjs +412 -0
  66. package/src/acp-context.mjs +138 -0
  67. package/src/admin-socket.mjs +14 -0
  68. package/src/alerts.mjs +147 -0
  69. package/src/artifact-journal.mjs +75 -0
  70. package/src/as-files.mjs +347 -0
  71. package/src/as-store.mjs +456 -0
  72. package/src/as.mjs +497 -0
  73. package/src/auth.mjs +166 -0
  74. package/src/builtin-http.mjs +22 -0
  75. package/src/check-coverage.mjs +38 -0
  76. package/src/check-lint.mjs +88 -0
  77. package/src/check-readiness.mjs +112 -0
  78. package/src/check-response.mjs +19 -0
  79. package/src/claim-command-ledger.mjs +51 -0
  80. package/src/cli-help.mjs +172 -0
  81. package/src/cli-name.mjs +16 -0
  82. package/src/connect-cli.mjs +126 -0
  83. package/src/consumers.mjs +61 -0
  84. package/src/deadman.mjs +329 -0
  85. package/src/delivery.mjs +19 -0
  86. package/src/demo-worker.mjs +150 -0
  87. package/src/destinations/index.mjs +23 -0
  88. package/src/destinations/none.mjs +15 -0
  89. package/src/destinations/t3.mjs +109 -0
  90. package/src/diagnostic.mjs +78 -0
  91. package/src/docs-url.mjs +9 -0
  92. package/src/drain-runner.mjs +9 -0
  93. package/src/drained-slot.mjs +53 -0
  94. package/src/drained.mjs +40 -0
  95. package/src/durable-waiters.mjs +236 -0
  96. package/src/env.mjs +19 -0
  97. package/src/execution.mjs +112 -0
  98. package/src/failure-type.mjs +28 -0
  99. package/src/get-summary.mjs +32 -0
  100. package/src/git-env.mjs +15 -0
  101. package/src/host-budget-receipts.mjs +154 -0
  102. package/src/host-budget-seccomp.py +33 -0
  103. package/src/host-budget-service.mjs +54 -0
  104. package/src/host-budget-stop.mjs +26 -0
  105. package/src/host-budget-storage.py +259 -0
  106. package/src/host-budget.mjs +149 -0
  107. package/src/host-cgroup.mjs +23 -0
  108. package/src/host-check-allowlist.mjs +42 -0
  109. package/src/host-execution-policy.mjs +38 -0
  110. package/src/host-health.mjs +34 -0
  111. package/src/host-stop-reverify.mjs +44 -0
  112. package/src/inbox.mjs +55 -0
  113. package/src/integrator.mjs +322 -0
  114. package/src/job-retention.mjs +69 -0
  115. package/src/legacy-names.mjs +8 -0
  116. package/src/lifecycle.mjs +291 -0
  117. package/src/limits.mjs +31 -0
  118. package/src/loopback.mjs +9 -0
  119. package/src/mcp-outcome.mjs +70 -0
  120. package/src/mcp-stdio.mjs +191 -0
  121. package/src/mirror-fetch-lock.py +164 -0
  122. package/src/mirror-fetch.mjs +174 -0
  123. package/src/notify-ledger.mjs +82 -0
  124. package/src/objectives.mjs +129 -0
  125. package/src/owner-report-artifact.mjs +66 -0
  126. package/src/patch-apply.mjs +84 -0
  127. package/src/path-syntax.mjs +16 -0
  128. package/src/paths.mjs +67 -0
  129. package/src/pr-head-reviewer.mjs +596 -0
  130. package/src/pr-preflight.mjs +51 -0
  131. package/src/prepared-node-modules.mjs +129 -0
  132. package/src/projects.mjs +480 -0
  133. package/src/protocol-artifact-commands.mjs +52 -0
  134. package/src/protocol-delivery-driver.mjs +167 -0
  135. package/src/protocol-finish.mjs +100 -0
  136. package/src/protocol-owner-command.mjs +35 -0
  137. package/src/protocol-owner-mutations.mjs +22 -0
  138. package/src/protocol-owner-waiters.mjs +67 -0
  139. package/src/protocol-retention.mjs +52 -0
  140. package/src/protocol-services.mjs +61 -0
  141. package/src/protocol-stop-observer.mjs +131 -0
  142. package/src/publish-plan.mjs +245 -0
  143. package/src/redaction.mjs +763 -0
  144. package/src/rejections.mjs +18 -0
  145. package/src/request-log.mjs +102 -0
  146. package/src/restore-check.mjs +90 -0
  147. package/src/result-binding.mjs +65 -0
  148. package/src/runtime-check.mjs +13 -0
  149. package/src/sandbox-supervisor.mjs +105 -0
  150. package/src/schema-subset.mjs +186 -0
  151. package/src/scopes.mjs +15 -0
  152. package/src/server.mjs +1340 -0
  153. package/src/shutdown-signal.mjs +12 -0
  154. package/src/signal-sandbox-processes.py +56 -0
  155. package/src/signal.mjs +119 -0
  156. package/src/status-evidence.mjs +47 -0
  157. package/src/status-summary.mjs +54 -0
  158. package/src/store.mjs +3057 -0
  159. package/src/submission-policy.mjs +623 -0
  160. package/src/subscription-storage.mjs +64 -0
  161. package/src/t3-audit.mjs +120 -0
  162. package/src/t3-control.mjs +102 -0
  163. package/src/t3-transport.mjs +158 -0
  164. package/src/t3.mjs +209 -0
  165. package/src/terminal-safe.mjs +19 -0
  166. package/src/tool-registry.mjs +451 -0
  167. package/src/try-command.mjs +11 -0
  168. package/src/try.mjs +589 -0
  169. package/src/webhooks.mjs +86 -0
  170. package/src/work-order.mjs +265 -0
  171. package/src/worker-instructions.mjs +26 -0
  172. package/src/worker-prompt.mjs +4 -0
  173. package/src/workers.mjs +622 -0
  174. package/src/workspace.mjs +1058 -0
  175. package/systemd/dot-bridge-heartbeat.service +18 -0
  176. package/systemd/dot-bridge-heartbeat.timer +10 -0
  177. package/systemd/dot-bridge-selfcheck.service +12 -0
  178. package/systemd/dot-bridge-selfcheck.timer +11 -0
  179. package/systemd/dot-bridge.service +17 -0
  180. package/systemd/dot-deadman.service +30 -0
  181. package/systemd/dot-pr-reviewer.service +11 -0
  182. package/systemd/dot-pr-reviewer.timer +10 -0
@@ -0,0 +1,37 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { createHash } from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ const digest=value=>createHash('sha256').update(value).digest('hex');
7
+
8
+ // This ledger is deliberately outside bridge.db so a main-database rollback
9
+ // cannot erase positive transport acknowledgments.
10
+ export class AckLedger {
11
+ constructor(file) {
12
+ fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});
13
+ const existed=fs.existsSync(file);
14
+ if(existed&&(fs.statSync(file).mode&0o777)!==0o600) throw new Error('acknowledgment ledger must be mode 0600');
15
+ if(!existed) { const fd=fs.openSync(file,'wx',0o600); fs.closeSync(fd); }
16
+ this.db=new DatabaseSync(file);
17
+ try {
18
+ if((fs.statSync(file).mode&0o777)!==0o600) throw new Error('acknowledgment ledger must be mode 0600');
19
+ this.db.exec('PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS acknowledgments(event_id TEXT NOT NULL,body_sha256 TEXT NOT NULL,binding_sha256 TEXT NOT NULL,acknowledged_at TEXT NOT NULL,PRIMARY KEY(event_id,body_sha256,binding_sha256)) WITHOUT ROWID;');
20
+ if(this.db.prepare('PRAGMA integrity_check').get().integrity_check!=='ok') throw new Error('acknowledgment ledger integrity check failed');
21
+ } catch(error) { this.db.close(); throw new Error(`acknowledgment ledger unavailable: ${error.message}`,{cause:error}); }
22
+ }
23
+ key(eventId,body,binding) {
24
+ return {eventId,bodySha256:digest(body),bindingSha256:digest(binding)};
25
+ }
26
+ has(key) {
27
+ return !!this.db.prepare('SELECT 1 FROM acknowledgments WHERE event_id=? AND body_sha256=? AND binding_sha256=?').get(key.eventId,key.bodySha256,key.bindingSha256);
28
+ }
29
+ record(key,at=new Date().toISOString()) {
30
+ this.db.exec('BEGIN IMMEDIATE');
31
+ try {
32
+ this.db.prepare('INSERT INTO acknowledgments(event_id,body_sha256,binding_sha256,acknowledged_at) VALUES(?,?,?,?) ON CONFLICT DO NOTHING').run(key.eventId,key.bodySha256,key.bindingSha256,at);
33
+ this.db.exec('COMMIT');
34
+ } catch(error) { this.db.exec('ROLLBACK'); throw new Error(`acknowledgment ledger write failed: ${error.message}`,{cause:error}); }
35
+ }
36
+ close() { this.db.close(); }
37
+ }
@@ -0,0 +1,412 @@
1
+ import { defaultPath } from './paths.mjs';
2
+ // Bridge-facing pieces of the ACP adapter (bin/dot-acp-agent.mjs): the admin-socket client, the owner token, brief and
3
+ // request-id rules, submit eligibility and the payload builder. Nothing here speaks ACP.
4
+ import http from 'node:http';
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { createHash } from 'node:crypto';
9
+ import { execFile, execFileSync, spawn } from 'node:child_process';
10
+ import { promisify } from 'node:util';
11
+ import { packRepoDiff, stripPacked } from './acp-context.mjs';
12
+ import { hostCheckRefusal } from './host-execution-policy.mjs';
13
+ import { redactLogEntry } from './redaction.mjs';
14
+ import { submissionLimits } from './submission-policy.mjs';
15
+ import { readOrCreateSecret, ownerToken } from '../integrations/t3/acp-kit/src/capability.mjs';
16
+ import { CONTINUE_PROMPT, promptText, unwrapUserRequest, isT3RuntimeBlock, parseIdentity } from '../integrations/t3/acp-kit/src/t3-envelope.mjs';
17
+ import { adminSocketPathError } from './admin-socket.mjs';
18
+
19
+ // Shared with external ACP adapters: integrations/t3/acp-kit.
20
+ export { readOrCreateSecret, ownerToken, CONTINUE_PROMPT, promptText, unwrapUserRequest, isT3RuntimeBlock };
21
+
22
+ export const sha256 = text => createHash('sha256').update(text).digest('hex');
23
+ const idPattern = /^[-\w]{8,128}$/;
24
+
25
+ export function paths(env = process.env) {
26
+ const home = os.homedir();
27
+ return {
28
+ socket: env.DOT_ACP_SOCKET || defaultPath(home,'.local/share/dot-bridge/admin.sock'),
29
+ secretFile: env.DOT_ACP_SECRET_FILE || defaultPath(home,'.config/dot-bridge/acp-secret'),
30
+ stateDir: env.DOT_ACP_STATE_DIR || defaultPath(home,'.local/state/dot-bridge/acp'),
31
+ };
32
+ }
33
+
34
+ // ---------------------------------------------------------------- admin socket
35
+ export class BridgeError extends Error {
36
+ constructor(message, kind, httpStatus) { super(message); this.kind = kind; this.http_status = httpStatus ?? null; }
37
+ }
38
+ export const transient = e => e.kind === 'transport' || e.http_status >= 500;
39
+
40
+ export function adminRequest(socket, route, { method = 'GET', payload, token, signal, timeoutMs } = {}) {
41
+ const positive = (value, fallback) => Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : fallback;
42
+ const baseMs = positive(process.env.DOT_ACP_HTTP_TIMEOUT_MS, 5000);
43
+ const graceMs = positive(process.env.DOT_ACP_HTTP_GRACE_MS, 1000);
44
+ const url = new URL(route, 'http://localhost');
45
+ const pollMs = url.pathname === '/wait' ? positive(url.searchParams.get('timeout'), 30) * 1000 : 0;
46
+ const deadlineMs = timeoutMs ?? (pollMs ? pollMs + graceMs : baseMs);
47
+ return new Promise((resolve, reject) => {
48
+ const socketPathError = adminSocketPathError(socket);
49
+ if (socketPathError) return reject(Object.assign(new BridgeError(socketPathError.message, 'local'), { code: socketPathError.code, fix: socketPathError.fix }));
50
+ const bytes = payload ? JSON.stringify(payload) : '';
51
+ let timer;
52
+ const fail = error => { clearTimeout(timer); reject(error instanceof BridgeError ? error : Object.assign(new BridgeError(error.message, 'transport'), { name: error.name })); };
53
+ const headers = { 'content-type': 'application/json', 'content-length': Buffer.byteLength(bytes), ...(token ? { 'x-owner-capability': token } : {}) };
54
+ const req = http.request({ socketPath: socket, path: route, method, headers, signal }, res => {
55
+ let out = '';
56
+ res.on('data', b => { out += b; });
57
+ res.on('error', fail);
58
+ res.on('aborted', () => fail(new Error('admin response aborted')));
59
+ res.on('end', () => {
60
+ clearTimeout(timer);
61
+ let value;
62
+ try { value = JSON.parse(out); } catch { return fail(new Error('invalid admin response')); }
63
+ if (res.statusCode < 200 || res.statusCode >= 300) reject(Object.assign(new BridgeError(value?.error || `HTTP ${res.statusCode}`, 'http', res.statusCode), value?.verdict ? { verdict: value.verdict, reasons: value.reasons, bytes: value.bytes, retry_after_seconds: value.retry_after_seconds } : {}));
64
+ else resolve(value);
65
+ });
66
+ });
67
+ req.on('error', fail);
68
+ timer = setTimeout(() => req.destroy(new BridgeError(`admin request deadline exceeded (${deadlineMs} ms)`, 'transport')), deadlineMs);
69
+ req.end(bytes);
70
+ });
71
+ }
72
+
73
+ // Raw artifact bytes (the admin route answers octet-stream, not JSON). Resolves null on any failure: evidence is best effort.
74
+ export function adminArtifact(socket, artifactId, token, timeoutMs = 5000) {
75
+ return new Promise(resolve => {
76
+ const req = http.request({ socketPath: socket, path: `/artifact?id=${encodeURIComponent(artifactId)}`, headers: { 'x-owner-capability': token } }, res => {
77
+ const chunks = [];
78
+ res.on('data', b => chunks.push(b));
79
+ res.on('error', () => resolve(null));
80
+ res.on('end', () => {
81
+ const data = Buffer.concat(chunks);
82
+ resolve(res.statusCode === 200 && sha256(data) === res.headers['x-artifact-sha256'] ? data : null);
83
+ });
84
+ });
85
+ req.on('error', () => resolve(null));
86
+ req.setTimeout(timeoutMs, () => req.destroy());
87
+ req.end();
88
+ });
89
+ }
90
+
91
+ // ---------------------------------------------------------------- brief and ids
92
+ // The brief the worker sees is the prompt without the router's token line. The root decision id keys the bridge request.
93
+ // T3's delegate_task puts `Act as the <role> sub-agent for this task.\n\n` before the task for every role except general
94
+ // (and none); parseIdentity strips it, because otherwise the token line and a [dot-build] line are no longer first.
95
+ export function parsePrompt(prompt) {
96
+ const { id: root, text, brief } = parseIdentity(prompt, { prefix: 'dot-decision', idPattern });
97
+ // Without a token the identity is the text after the T3 preamble, so a resend with or without a role maps to one request.
98
+ return { brief, root, requestRoot: root ?? `acp-${sha256(text).slice(0, 24)}` };
99
+ }
100
+ // Attempt 1 is the root itself. After a cancelled or expired row the next attempt is `<root>_r<n>` (the bridge accepts only
101
+ // [-\w] in a request id, so the doc's `#` separator cannot be used).
102
+ export const attemptId = (root, n) => {
103
+ const id = n === 1 ? root : `${root}_r${n}`;
104
+ return idPattern.test(id) ? id : `acp-${sha256(id).slice(0, 24)}`;
105
+ };
106
+
107
+ // ---------------------------------------------------------------- eligibility
108
+ // failure_type is the closed vocabulary of src/failure-type.mjs; verdict/reasons come from the bridge's work-order compiler.
109
+ export class Refusal extends Error {
110
+ constructor(message, failure_type = 'admission_refused', extra = {}) { super(message); this.failure_type = failure_type; Object.assign(this, extra); }
111
+ }
112
+ // The words a requester reads for a typed refusal: each reason with its fix, plus the byte accounting when a limit is the cause.
113
+ export function verdictRefusal(order) {
114
+ const lines = (order.reasons ?? []).map(r => `${r.message}${r.candidates?.length ? ` (did you mean ${r.candidates.join(' or ')}?)` : ''}. Fix: ${r.fix}`);
115
+ const retry = order.verdict === 'defer' && order.retry_after_seconds ? ` Retry in about ${Math.round(order.retry_after_seconds / 60) || 1} min.` : '';
116
+ const failure_type=order.verdict==='defer'?'deferred':order.verdict==='clarify'?'clarification_required':'admission_refused';
117
+ return new Refusal(`${lines.join(' | ')}${retry}`, failure_type, { verdict: order.verdict, reasons: order.reasons, bytes: order.bytes, failure_type_source:'bridge_work_order_verdict' });
118
+ }
119
+
120
+ // The router's checks repeated as a backstop: the worker must be able to take work now.
121
+ export function bridgeRefusal(status, inFlightCap) {
122
+ if (status.paused) return `worker paused${status.pause_reason ? `: ${status.pause_reason}` : ''}`;
123
+ // Only evidence holds work: an owner-confirmed break. An inferred break is silence; estimated limits are metrics.
124
+ if (status.worker_break?.active && status.worker_break.source === 'owner') return `worker_break active since ${status.worker_break.since}`;
125
+ const queued = status.counts?.find(c => c.status === 'queued')?.count ?? 0;
126
+ if (queued >= inFlightCap) return `worker queue is full (${queued} queued, in-flight cap ${inFlightCap})`;
127
+ return null;
128
+ }
129
+
130
+ const execFileAsync = promisify(execFile);
131
+ // Async so a slow git never blocks the event loop (ACP notifications, the cancel window); each call is killed after the timeout.
132
+ async function git(cwd, args) {
133
+ try {
134
+ const r = await execFileAsync('git', ['-C', cwd, ...args], { encoding: 'utf8', timeout: 15000, killSignal: 'SIGKILL', maxBuffer: 4 * 1024 * 1024 });
135
+ return { ok: true, out: r.stdout.trim(), err: r.stderr.trim() };
136
+ } catch (e) { return { ok: false, out: (e.stdout || '').trim(), err: (e.stderr || e.message).trim() }; }
137
+ }
138
+ export function githubRepoOf(url) {
139
+ const m = /^(?:https?:\/\/(?:[^/@]+@)?github\.com\/|ssh:\/\/git@github\.com\/|git@github\.com:)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(url || '');
140
+ return m ? `${m[1]}/${m[2]}` : null;
141
+ }
142
+ // A clean, pushed GitHub checkout gives the worker that commit. Local work can be packed against an origin branch's
143
+ // pushed ancestor; without one, the worker gets text only, so it never reviews a revision the requester has moved past.
144
+ // Refusing instead would cost the parent a wake and a re-route for work that may need no code at all.
145
+ // repoOf is injectable for local bare-repo tests; production accepts only GitHub origins.
146
+ export const NO_REPO_NOTE = "No repository access: the requester's checkout has unpushed or uncommitted work. Answer from this brief alone; if you need code that is not quoted here, finish with BLOCKED: and name what is missing.";
147
+ // Added when the checkout differs from its pushed HEAD only by untracked files: the worker reads HEAD, not those files.
148
+ export const UNTRACKED_NOTE = 'Untracked local files in the requester\'s checkout are not included: the repository is the pushed commit, without them. If you need one, finish with BLOCKED: and name it.';
149
+ const NOTES = [NO_REPO_NOTE, UNTRACKED_NOTE];
150
+ export const withoutNote = brief => {
151
+ const note = NOTES.find(n => brief.startsWith(`${n}\n\n`));
152
+ return stripPacked(note ? brief.slice(note.length + 2) : brief);
153
+ };
154
+ export async function repoInputs(cwd, { repoOf = githubRepoOf } = {}) {
155
+ if (!cwd || !fs.existsSync(cwd)) return { inputs: [] };
156
+ if (!(await git(cwd, ['rev-parse', '--is-inside-work-tree'])).ok) return { inputs: [] };
157
+ // Untracked, non-ignored files do not change the pushed commit, so only tracked changes make the checkout dirty.
158
+ // An unreadable or commit-less checkout never refuses the job: a text-only job needs no repository, and a build
159
+ // is refused later for having no pinned input.
160
+ const status = await git(cwd, ['status', '--porcelain']);
161
+ if (!status.ok) return { inputs: [], note: NO_REPO_NOTE };
162
+ const lines = status.out.split('\n').filter(Boolean);
163
+ const dirty = { out: lines.filter(line => !line.startsWith('?? ')).join('\n') };
164
+ const untracked = lines.some(line => line.startsWith('?? '));
165
+ const head = await git(cwd, ['rev-parse', 'HEAD']);
166
+ if (!head.ok) return { inputs: [], note: NO_REPO_NOTE };
167
+ // Containment is checked on origin only: a commit that exists only under another remote must not be sent as origin evidence.
168
+ const remote = await git(cwd, ['for-each-ref', '--contains', head.out, '--format=%(refname) %(symref)', 'refs/remotes/origin/']);
169
+ const onOrigin = remote.ok && remote.out.split('\n').some(line => /^refs\/remotes\/origin\/(?!HEAD(?:\s|$))\S+\s*$/.test(line));
170
+ const repo = repoOf((await git(cwd, ['remote', 'get-url', 'origin'])).out);
171
+ if (!dirty.out && onOrigin) return { inputs: repo ? [{ github_repo: repo, base_sha: head.out, head_sha: head.out }] : [], ...(repo && untracked ? { untracked: true } : {}) };
172
+ if (!repo) return { inputs: [], note: NO_REPO_NOTE };
173
+ // Newest ancestors reachable from an origin branch (boundary commits). Only refs of the origin remote count.
174
+ // No fetch and no change to the requester's index.
175
+ const history = await git(cwd, ['rev-list', '--topo-order', '--boundary', 'HEAD', '--not', '--remotes=origin']);
176
+ const base = onOrigin ? head.out : history.ok && history.out.split('\n').find(line => /^-[a-f0-9]{40}$/.test(line))?.slice(1);
177
+ return base ? { inputs: [{ github_repo: repo, base_sha: base, head_sha: base }], packBase: base } : { inputs: [], note: NO_REPO_NOTE };
178
+ }
179
+
180
+ // Async end to end (git runs as child processes with timeouts), so packing never blocks ACP notifications or the cancel window.
181
+ // A text-only worker (DOT_ACP_TEXT_ONLY=1) never gets repository inputs; builds are then refused by the no-inputs rule below.
182
+ export const TEXT_ONLY_NOTE = 'Text-only job: there is no repository or file access. Answer from this brief alone.';
183
+ // A size error from the packer or the bridge (`brief: N UTF-8 bytes exceeds L`) rewritten to say which part is over and by how
184
+ // much. `requestBytes` is the requester's own text; the rest of the total is what the adapter and bridge added. Null when the
185
+ // message is not a size error.
186
+ const fmt = n => Number(n).toLocaleString('en-US');
187
+ export function sizeRefusal(message, requestBytes) {
188
+ const m = /^(brief|task instructions): (\d+) UTF-8 bytes exceeds (\d+)/.exec(message ?? '');
189
+ if (!m) return null;
190
+ const what = m[1], total = Number(m[2]), limit = Number(m[3]), extra = total - requestBytes, cut = total - limit;
191
+ const split = extra > 0 ? `your request ${fmt(requestBytes)} + context added by the adapter and bridge ${fmt(extra)}` : `your request alone`;
192
+ const head = what === 'brief' ? `brief is ${fmt(total)} bytes` : `task instructions (brief, expected output and scope) are ${fmt(total)} bytes`;
193
+ return `${head}: ${split}; the limit is ${fmt(limit)}; cut at least ${fmt(cut)} bytes from your request${extra > 0 ? ' (pushing your local work drops the added context)' : ''}`;
194
+ }
195
+ export async function prepareAssignment(request, options, env = process.env) {
196
+ try {
197
+ const assignment = await prepareUnexplained(request, options, env);
198
+ // The bridge repeats this check; making it here too refuses before the round trip, with the same numbers.
199
+ const total = Buffer.byteLength(assignment.brief);
200
+ if (total > submissionLimits.brief) throw new Error(`brief: ${total} UTF-8 bytes exceeds ${submissionLimits.brief}`);
201
+ return assignment;
202
+ } catch (error) {
203
+ const text = sizeRefusal(error.message, Buffer.byteLength(request.brief));
204
+ if (text) throw new Refusal(text);
205
+ throw error;
206
+ }
207
+ }
208
+ async function prepareUnexplained({ cwd, ...request }, options, env) {
209
+ // A text-only worker cannot open host files, so a brief that names one would end BLOCKED after a wake-up cycle. Refuse
210
+ // at submit, while the sender can still paste the content. URLs and repository-relative names are allowed.
211
+ if (env.DOT_ACP_TEXT_ONLY === '1') {
212
+ const hostPath = request.brief.match(/(?<![\w:/.-])(?:~\/|\/(?:home|Users|tmp|root|var|etc|mnt|opt)\/)[^\s'"`)<>]+/);
213
+ if (hostPath) throw new Refusal(`text-only worker: the brief names a local path (${hostPath[0].slice(0, 80)}) that the worker cannot read; paste the needed content into the brief instead`);
214
+ }
215
+ const context = env.DOT_ACP_TEXT_ONLY === '1' ? { inputs: [], note: TEXT_ONLY_NOTE } : await repoInputs(cwd, options);
216
+ const build = isBuild(request.brief);
217
+ // A build patch must apply to the requester's own commit: no packed local diff and no text-only fallback.
218
+ if (build && !buildScope(request.brief).length) throw new Refusal(BUILD_NEEDS_SCOPE);
219
+ if (build && (!context.inputs.length || context.packBase || context.note)) throw new Refusal(BUILD_NEEDS_PUSHED);
220
+ if (build) {
221
+ const why = buildIneligible(context.inputs[0].github_repo, buildScope(request.brief));
222
+ if (why) throw new Refusal(why);
223
+ // Each listed path is a file at HEAD or a new file; a directory would widen the scope past the file bound and path terms.
224
+ for (const p of buildScope(request.brief)) if ((await git(cwd, ['cat-file', '-t', `HEAD:${p}`])).out === 'tree') throw new Refusal(`[dot-build] lists a directory (${p}); list files`);
225
+ }
226
+ // Identity is the requester's brief only; packed context and notes are presentation and never enter this hash.
227
+ const assignment = { ...buildAssignment({ ...request, inputs: context.inputs, build }), acp_brief_hash: sha256(request.brief) };
228
+ if (context.packBase) return packRepoDiff(cwd, assignment, context.packBase, NO_REPO_NOTE);
229
+ if (context.untracked && !build) return { ...assignment, brief: `${UNTRACKED_NOTE}\n\n${assignment.brief}` };
230
+ return context.note ? { ...assignment, brief: `${context.note}\n\n${assignment.brief}` } : assignment;
231
+ }
232
+
233
+ // ---------------------------------------------------------------- build tasks
234
+ // A brief whose first line is exactly BUILD_MARKER asks the worker for a patch: implementation scope (apply_patch, run_check)
235
+ // on the requester's pushed HEAD, task_kind "build" (the delegation gate measures acceptance of these), and a result that
236
+ // carries the patch evidence and the verdict commands. Any other brief keeps read-only scope.
237
+ // The marker line names the repository paths the worker may read and change: `[dot-build] src/a.py tests/test_a.py`. Implementation
238
+ // scope admits no sensitive file in scope (--exclude-sensitive is for read-only work), so a whole-repo scope fails on any
239
+ // repository with a .env.example; an explicit list also keeps the worker's reads, and so its usage, small.
240
+ export const BUILD_MARKER = '[dot-build]';
241
+ const buildLine = /^\[dot-build\]((?:[ \t]+\S+)*)[ \t]*$/;
242
+ export const isBuild = brief => typeof brief === 'string' && buildLine.test(brief.split('\n', 1)[0].trim());
243
+ export const buildScope = brief => (buildLine.exec(brief.split('\n', 1)[0].trim())?.[1] ?? '').trim().split(/[ \t]+/).filter(Boolean);
244
+ export const BUILD_NEEDS_PUSHED = 'a [dot-build] task needs a clean checkout whose HEAD is pushed to a GitHub origin; push first, or use dalan submit with an explicit base_sha';
245
+ export const BUILD_NEEDS_SCOPE = 'a [dot-build] line must name the files the worker may read and change, e.g. "[dot-build] src/a.py tests/test_a.py"';
246
+ // Who may receive a build comes from the operator's owner allowlist because a parent can send a [dot-build] task without
247
+ // the delegation gate's offer. The repo exclusion config and credential path terms add further restrictions.
248
+ // The current and legacy environment variable names are supported; a missing owner list refuses every build.
249
+ export const BUILD_MAX_FILES = 5;
250
+ const glob = pattern => new RegExp(`^${pattern.toLowerCase().replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`);
251
+ function configuredOwners(value) {
252
+ if (typeof value !== 'string' || !value.trim()) return null;
253
+ const owners = value.split(',').map(owner => owner.trim().toLowerCase());
254
+ if (owners.some(owner => !/^[a-z0-9_.-]+$/.test(owner))) return null;
255
+ return owners;
256
+ }
257
+ export function buildIneligible(repo, files, env = process.env) {
258
+ const owners = configuredOwners(env.DALAN_ACP_BUILD_OWNERS || env.DOT_ACP_BUILD_OWNERS);
259
+ if (!owners) return '[dot-build] refused: DALAN_ACP_BUILD_OWNERS or DOT_ACP_BUILD_OWNERS must list authorized repository owners';
260
+ const name = String(repo || '').toLowerCase();
261
+ if (!owners.includes(name.split('/')[0])) return `[dot-build] refused: ${repo} is outside the configured owner allowlist`;
262
+ if (files.length > BUILD_MAX_FILES) return `[dot-build] names ${files.length} paths; at most ${BUILD_MAX_FILES}`;
263
+ let cfg;
264
+ try { cfg = JSON.parse(fs.readFileSync(env.DALAN_ACP_REPO_CONFIG || env.DOT_ACP_REPO_CONFIG || defaultPath(os.homedir(),'.config/dot-bridge/producer.json'), 'utf8')); }
265
+ catch { return '[dot-build] refused: the repo exclusion config is unreadable'; }
266
+ const exclude = cfg?.repo_selection?.exclude, terms = cfg?.deny_path_terms;
267
+ if (!Array.isArray(exclude) || !Array.isArray(terms) || ![...exclude, ...terms].every(x => typeof x === 'string' && x)) return '[dot-build] refused: the repo exclusion config is malformed';
268
+ if (exclude.some(g => glob(g).test(name))) return `[dot-build] refused: ${repo} is excluded by the repo exclusion config`;
269
+ const hit = files.find(f => terms.some(t => f.toLowerCase().includes(t.toLowerCase())));
270
+ if (hit) return `[dot-build] refused: ${hit} matches a credential path term`;
271
+ return null;
272
+ }
273
+ const BUILD_OUTPUT = 'A patch: make the change with apply_patch, run the named check with run_check, then finish with a short summary, the check result and anything you could not do.';
274
+
275
+ export function buildAssignment({ requestId, brief, inputs, validUntil, build = false }) {
276
+ return {
277
+ schema_version: 1, request_id: requestId, brief, inputs,
278
+ ...(inputs.length ? { scope_paths: build ? buildScope(brief) : ['.'] } : {}),
279
+ expected_output: build ? BUILD_OUTPUT : 'A complete answer as plain text. Put the result in the finish call.',
280
+ execution_scope: build ? 'implementation' : 'read-only', valid_until: validUntil,
281
+ };
282
+ }
283
+
284
+ const PREVIEW_BYTES = 3072;
285
+ const CODE_COMMENT = /^(?:\/\/|\/\*|\*|#(?!\s*(?:include\b|!\/))|--|<!--)/;
286
+ function addedProse(patch) {
287
+ const prose = [];
288
+ let file = null;
289
+ for (const line of patch.split('\n')) {
290
+ const header = /^\+\+\+ b\/(.+)$/.exec(line);
291
+ if (header) { file = header[1]; continue; }
292
+ if (!line.startsWith('+') || line.startsWith('+++') || !file) continue;
293
+ const content = line.slice(1);
294
+ if (/\.md$/i.test(file) || CODE_COMMENT.test(content.trim())) prose.push(`${file}: ${content}`);
295
+ }
296
+ return prose.join('\n');
297
+ }
298
+ // Redact first, then clip, so a token cut by the clip cannot leave a prefix behind.
299
+ const clip = (value, max) => redactLogEntry(String(value)).slice(0, max);
300
+ const SEVERITIES = new Set(['info', 'low', 'minor', 'medium', 'warning', 'high', 'major', 'error', 'critical']);
301
+ const FINDING_TEXT_KEYS = ['text', 'message', 'description', 'suggestion'];
302
+ const FINDING_LABEL_KEYS = ['rule', 'type'];
303
+ // Keep only known string fields of a finding. Arrays, objects and unknown severities are dropped, so nothing reaches
304
+ // the result text without passing through the redactor as one string.
305
+ function sanitizeFinding(f) {
306
+ if (!f || typeof f !== 'object' || Array.isArray(f)) return {};
307
+ const out = {};
308
+ if (typeof f.severity === 'string' && SEVERITIES.has(f.severity.toLowerCase())) out.severity = f.severity.toLowerCase();
309
+ for (const k of FINDING_LABEL_KEYS) if (typeof f[k] === 'string') out[k] = clip(f[k], 80);
310
+ for (const k of FINDING_TEXT_KEYS) if (typeof f[k] === 'string') out[k] = clip(f[k], 4000);
311
+ return out;
312
+ }
313
+ // The checker gets only what it needs to start: no inherited credentials, a throwaway HOME, and a fixed PATH
314
+ // (the running node's directory plus the system directories) so the host PATH text and entries are not inherited.
315
+ const checkerPath = () => [path.dirname(process.execPath), '/usr/bin', '/bin'].join(path.delimiter);
316
+ const checkerEnv = home => ({ PATH: checkerPath(), HOME: home, TMPDIR: home, LANG: 'C.UTF-8', LC_ALL: 'C.UTF-8', TZ: 'UTC' });
317
+ // Containment guarantee (not a sandbox): on timeout or completion the checker's process group is killed, and so is
318
+ // every descendant still linked to it by parent pid at that moment, even one that started its own session. A
319
+ // descendant that was already orphaned (its parent exited first), or that forks during the kill, can escape. There is
320
+ // no sound containment without a sandbox or cgroup, so the checker also runs only when the host-check policy allows
321
+ // unsandboxed host execution, and it must be a trusted local data-only command, not a security boundary.
322
+ function descendantPids(rootPid) {
323
+ try {
324
+ const rows = execFileSync('ps', ['-eo', 'pid=,ppid='], { encoding: 'utf8', timeout: 2000 }).trim().split('\n').map(l => l.trim().split(/\s+/).map(Number));
325
+ const kids = new Map();
326
+ for (const [pid, ppid] of rows) { if (!kids.has(ppid)) kids.set(ppid, []); kids.get(ppid).push(pid); }
327
+ const found = [], queue = [rootPid];
328
+ while (queue.length) for (const pid of kids.get(queue.pop()) ?? []) { found.push(pid); queue.push(pid); }
329
+ return found;
330
+ } catch { return []; }
331
+ }
332
+ // Optional prose check of a build patch: pipes the added prose lines to an owner-configured linter command.
333
+ export function runBuildProseCheck(repo, patch, env = process.env, { refusal = hostCheckRefusal, timeoutMs = 30000 } = {}) {
334
+ const ownersName = 'DALAN_ACP_PROSE_CHECK_OWNERS';
335
+ const command = env.DALAN_ACP_PROSE_CHECK;
336
+ const owners = configuredOwners(env[ownersName]);
337
+ if (env[ownersName] && !owners) return Promise.resolve({ status: 'ERROR', detail: `invalid ${ownersName}` });
338
+ if (!owners || !owners.includes(String(repo || '').toLowerCase().split('/')[0])) return Promise.resolve(null);
339
+ if (patch === null || patch === undefined) return Promise.resolve({ status: 'ERROR', detail: 'patch unavailable' });
340
+ if (!command) return Promise.resolve({ status: 'ERROR', detail: 'prose check command not configured' });
341
+ const refused = refusal();
342
+ if (refused) return Promise.resolve({ status: 'ERROR', detail: `skipped: host checks refused (${clip(refused, 160)})` });
343
+ const prose = addedProse(Buffer.from(patch).toString('utf8'));
344
+ return new Promise(resolve => {
345
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'prose-check-'));
346
+ const child = spawn(command, ['check', '--stdin', '--kind', 'doc', '--json'], { env: checkerEnv(home), stdio: ['pipe', 'pipe', 'pipe'], detached: true });
347
+ const killTree = () => {
348
+ const tracked = descendantPids(child.pid);
349
+ try { process.kill(-child.pid, 'SIGKILL'); } catch { child.kill('SIGKILL'); }
350
+ for (const pid of tracked) { try { process.kill(pid, 'SIGKILL'); } catch {} }
351
+ };
352
+ let stdout = '', stderr = '', settled = false;
353
+ const finish = result => { if (settled) return; settled = true; clearTimeout(timer); killTree(); fs.rmSync(home, { recursive: true, force: true }); resolve(result); };
354
+ const timer = setTimeout(() => finish({ status: 'ERROR', detail: 'timed out' }), timeoutMs);
355
+ child.stdout.setEncoding('utf8').on('data', chunk => { if (stdout.length < 256000) stdout += chunk; });
356
+ child.stderr.setEncoding('utf8').on('data', chunk => { if (stderr.length < 4000) stderr += chunk; });
357
+ child.on('error', error => finish({ status: 'ERROR', detail: error.code === 'ENOENT' ? 'command not found' : clip(error.message, 300) }));
358
+ child.on('close', code => {
359
+ let result;
360
+ try { result = JSON.parse(stdout); }
361
+ catch { finish({ status: 'ERROR', detail: `invalid JSON output${stderr.trim() ? ' (checker stderr withheld: the shared redactor does not recognize every opaque credential shape)' : ''}` }); return; }
362
+ const findings = Array.isArray(result.findings) ? result.findings : [];
363
+ finish({ status: code === 0 ? 'PASS' : 'FAIL', findings: findings.slice(0, 3).map(sanitizeFinding), detail: code === 0 ? null : `exit ${code}` });
364
+ });
365
+ child.stdin.on('error', () => {});
366
+ child.stdin.end(prose);
367
+ });
368
+ }
369
+ function proseCheckText(verdict) {
370
+ if (!verdict) return null;
371
+ if (verdict.status === 'ERROR') return `prose check: ERROR (${verdict.detail})`;
372
+ const findings = verdict.findings?.length
373
+ ? `; top findings: ${verdict.findings.map(sanitizeFinding).map(f => {
374
+ const detail = f.text ?? f.message ?? f.description ?? f.suggestion;
375
+ return `${f.severity ?? 'medium'} ${f.rule ?? f.type ?? 'finding'}${detail ? `: ${clip(detail, 240)}` : ''}`;
376
+ }).join(' | ')}`
377
+ : '; no findings';
378
+ return `prose check: ${verdict.status}${verdict.detail ? ` (${verdict.detail})` : ''}${findings}`;
379
+ }
380
+ function diffstat(patch) {
381
+ const files = new Map();
382
+ let file = null;
383
+ for (const line of patch.split('\n')) {
384
+ const head = /^diff --git a\/(\S+) b\/(\S+)/.exec(line);
385
+ if (head) { file = head[2]; files.set(file, { add: 0, del: 0 }); continue; }
386
+ if (!file || line.startsWith('+++') || line.startsWith('---')) continue;
387
+ if (line.startsWith('+')) files.get(file).add++;
388
+ else if (line.startsWith('-')) files.get(file).del++;
389
+ }
390
+ return [...files].map(([f, n]) => ` ${f} +${n.add} -${n.del}`);
391
+ }
392
+ // One line that asks the requester for the one word that records what the result was worth.
393
+ export const decideHint = rid => `decide: dalan decide ${rid} accepted|applied|useful_no_change|useful_negative|not_useful`;
394
+ // The text a build task returns to its T3 parent: the worker's own result, then what to apply and how to record the verdict.
395
+ // patch is the artifact's bytes (Buffer or string) or null when it could not be read.
396
+ export function buildResultText(row, text, patch, proseCheck = null) {
397
+ const rid = row.request_id, ev = row.report?.workspace_evidence ?? {}, input = row.assignment?.inputs?.[0] ?? {};
398
+ const art = ev.patch_artifact, lines = [text, '', `--- worker build evidence (request ${rid}) ---`, `base: ${input.github_repo ?? '?'}@${ev.base_sha ?? input.base_sha ?? '?'}`];
399
+ const checks = (ev.checks ?? []).map(c => `${c.check_id} ${c.status}${c.exit_code === null || c.exit_code === undefined ? '' : ` exit ${c.exit_code}`} on diff ${String(c.diff_sha256 ?? '').slice(0, 12)}${c.check_summary?`; ${c.check_summary}`:''}`);
400
+ lines.push(`worker checks: ${checks.length ? checks.join('; ') : 'none run'}`);
401
+ if (proseCheck) lines.push(proseCheckText(proseCheck));
402
+ if (!art?.artifact_id || !art.size) lines.push('patch: none (empty diff). Nothing to apply.');
403
+ else {
404
+ const body = patch === null || patch === undefined ? null : Buffer.from(patch).toString('utf8');
405
+ lines.push(`patch: ${art.size} bytes, sha256 ${art.sha256}, artifact ${art.artifact_id}`);
406
+ if (body !== null) lines.push(...diffstat(body), body.length <= PREVIEW_BYTES ? `\`\`\`diff\n${body}\`\`\`` : `(preview omitted: over ${PREVIEW_BYTES} bytes)`);
407
+ lines.push(`Fetch: dalan get ${rid} --json >/dev/null && dalan artifact ${art.artifact_id} --output <file>`);
408
+ }
409
+ lines.push(`Next: on a clean checkout of that base, git apply the patch, re-run the tests yourself, push only if they pass. Then record the verdict: dalan accept ${rid}, or dalan reject ${rid} --note '<why>'. The delegation gate offers the worker builds only while these verdicts stay good.`);
410
+ lines.push(`Or apply it for you: dalan apply ${rid} [--dir <checkout>] (checks the digest and base, then records applied). ${decideHint(rid)}`);
411
+ return lines.join('\n');
412
+ }
@@ -0,0 +1,138 @@
1
+ // Local context is evidence for a pinned checkout, never a second repository revision or a change to request identity.
2
+ import { execFile } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
4
+ import { validateSubmission, submissionLimits, allowListHeading, outputPathsHeading } from './submission-policy.mjs';
5
+
6
+ const hash = text => createHash('sha256').update(text).digest('hex');
7
+ const endContext = '\n<!-- dot-context end -->\n\n';
8
+ function withContext(brief, context) {
9
+ return `<!-- dot-context v1 ${hash(brief)} ${brief.length} -->\n${context}${endContext}${brief}`;
10
+ }
11
+
12
+ // What the bridge may append to a brief at admission: the sensitive-file scope note, then the scope_paths allow-list, then the output_paths list.
13
+ const escape=text=>text.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
14
+ const bridgeSuffix=new RegExp(`(?:\\n\\nBridge scope note: \\d+ sensitive file\\(s\\) are outside scope_paths; do not read them: [^\\n]+\\.)?(?:\\n\\n${escape(allowListHeading)}\\n[^\\n]+(?:\\n[^\\n]+)*)?(?:\\n\\n${escape(outputPathsHeading)}\\n[^\\n]+(?:\\n[^\\n]+)*)?$`);
15
+ // The requester's brief without the bridge-added suffixes.
16
+ export const withoutBridgeSuffix=brief=>brief.replace(bridgeSuffix,'');
17
+ export function stripPacked(brief) {
18
+ const header = /^<!-- dot-context v1 ([a-f0-9]{64}) (\d+) -->\n/.exec(brief);
19
+ if (!header) return withoutBridgeSuffix(brief);
20
+ const end = brief.indexOf(endContext, header[0].length);
21
+ if (end < 0) return brief;
22
+ const start = end + endContext.length, original = brief.slice(start, start + Number(header[2]));
23
+ const tail = brief.slice(start + original.length);
24
+ // The bridge can append its scope note and allow-list after admission. Verify the stored requester slice, and accept
25
+ // only those known suffixes; arbitrary trailing text must still fail the attach guard.
26
+ if (tail && withoutBridgeSuffix(tail) !== '') return brief;
27
+ return hash(original) === header[1] ? original : brief;
28
+ }
29
+
30
+ // Async git with a per-call timeout and an overall packing deadline, so a slow or hung git never blocks the
31
+ // event loop (ACP notifications, the cancel window) and never runs unbounded across many files.
32
+ const GIT_CALL_MS = 15000, PACK_DEADLINE_MS = 120000;
33
+ function git(cwd, args, { maxBuffer = 4 * 1024 * 1024, diff = false, deadline } = {}) {
34
+ const remaining = deadline - Date.now();
35
+ if (remaining <= 0) return Promise.reject(new Error('context packer deadline exceeded'));
36
+ return new Promise((resolve, reject) => {
37
+ execFile('git', ['-C', cwd, ...args], { encoding: 'buffer', timeout: Math.min(GIT_CALL_MS, remaining), killSignal: 'SIGKILL', maxBuffer }, (error, stdout) => {
38
+ if (error?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' || error?.code === 'ENOBUFS') return reject(Object.assign(new Error('local diff exceeds brief limit'), { oversize: true }));
39
+ if (error && !(diff && error.code === 1)) return reject(new Error('context packer cannot read git state'));
40
+ resolve(stdout);
41
+ });
42
+ });
43
+ }
44
+ const names = buffer => new TextDecoder('utf-8', { fatal: true }).decode(buffer).split('\0').filter(Boolean);
45
+ const sensitiveError = error => /^(?:hard sensitive (?:path|content|patch content) exclusion|sensitive scope path):?/.test(error.message);
46
+ const sizeError = error => /^(?:brief|task instructions): \d+ UTF-8 bytes exceeds/.test(error.message);
47
+
48
+ export async function packRepoDiff(cwd, assignment, base, noRepoNote) {
49
+ const deadline = Date.now() + PACK_DEADLINE_MS;
50
+ const run = (dir, args, options) => git(dir, args, { ...options, deadline });
51
+ // Validate requester text independently: an unsafe brief must not become acceptable by dropping local context.
52
+ const textOnly = { ...assignment, inputs: [] };
53
+ delete textOnly.scope_paths;
54
+ validateSubmission(textOnly);
55
+ cwd = (await run(cwd, ['rev-parse', '--show-toplevel'])).toString('utf8').trim();
56
+ const diffArgs = ['diff', '--no-ext-diff', '--no-textconv', '--no-renames', '--no-color', '--src-prefix=a/', '--dst-prefix=b/'];
57
+ const tracked = names(await run(cwd, [...diffArgs, '--name-only', '-z', base, '--']));
58
+ const untracked = names(await run(cwd, ['ls-files', '--others', '--exclude-standard', '-z']));
59
+ const changed = [...new Set([...tracked, ...untracked])].sort();
60
+ const untrackedSet = new Set(untracked), trackedSet = new Set(tracked), omitted = new Set();
61
+ const probe = (file, diff = '') => validateSubmission({ ...assignment, brief: 'Review the local change.', scope_paths: [file] }, {
62
+ scanInput: () => ({ files: [file], diffFiles: [file], diff, symlinks: [] }),
63
+ });
64
+ // Check paths before asking git for their contents; never collect an env/key/signing file's hunk.
65
+ for (const file of changed) {
66
+ try { probe(file); }
67
+ catch (error) { if (!sensitiveError(error)) throw error;omitted.add(file); }
68
+ }
69
+ const diagnostics = () => changed.map(file => omitted.has(file) ? `omitted: ${file} (sensitive)` : `changed: ${file}`);
70
+ const fallback = reason => {
71
+ let context = `Context not packed: ${reason}.\nChanged files:`;
72
+ // File lists can themselves be larger than a brief. Keep complete names, then report the number left out.
73
+ let listed = 0;
74
+ for (const line of diagnostics()) {
75
+ const next = `${context}\n${line}`;
76
+ const candidate = { ...textOnly, brief: `${noRepoNote}\n\n${withContext(assignment.brief, next + `\n${changed.length} more changed file names exceed the brief limit.`)}` };
77
+ try { validateSubmission(candidate); }
78
+ catch (error) { if (sizeError(error)) break;throw error; }
79
+ context = next;listed++;
80
+ }
81
+ if (listed < changed.length) context += `\n${changed.length - listed} more changed file names exceed the brief limit.`;
82
+ const out = { ...textOnly, brief: `${noRepoNote}\n\n${withContext(assignment.brief, context)}` };
83
+ validateSubmission(out);
84
+ return out;
85
+ };
86
+ const chunks = [], skipped = [];
87
+ try {
88
+ for (const file of changed) {
89
+ if (omitted.has(file)) continue;
90
+ let raw = await run(cwd, untrackedSet.has(file)
91
+ ? [...diffArgs, '--no-index', '--', '/dev/null', file]
92
+ : [...diffArgs, base, '--', `:(literal)${file}`], { maxBuffer: submissionLimits.brief, diff: untrackedSet.has(file) });
93
+ // A staged deletion can leave a recreated untracked file at the same path. Preserve the deletion before its
94
+ // addition so the patch applies to a base where that path already exists.
95
+ if (untrackedSet.has(file) && trackedSet.has(file)) raw = Buffer.concat([
96
+ await run(cwd, [...diffArgs, base, '--', `:(literal)${file}`], { maxBuffer: submissionLimits.brief }), raw,
97
+ ]);
98
+ let diff;
99
+ try { diff = new TextDecoder('utf-8', { fatal: true }).decode(raw); }
100
+ catch { skipped.push(`omitted: ${file} (binary)`);continue; }
101
+ if (raw.includes(0) || /^Binary files /m.test(diff)) { skipped.push(`omitted: ${file} (binary)`);continue; }
102
+ if (/^(?:new (?:file )?mode|old mode|deleted file mode) 120000$/m.test(diff)) { skipped.push(`omitted: ${file} (symlink)`);continue; }
103
+ try { probe(file, diff); }
104
+ catch (error) {
105
+ if (sensitiveError(error)) { omitted.add(file);continue; }
106
+ if (error.code === 'DOT_BRIDGE_INFRASTRUCTURE') throw error;
107
+ return fallback('submission policy rejected local context');
108
+ }
109
+ chunks.push(diff);
110
+ if (Buffer.byteLength(chunks.join('')) > submissionLimits.brief) return fallback('diff exceeds assignment limits');
111
+ }
112
+ } catch (error) {
113
+ if (error.oversize) return fallback('diff exceeds assignment limits');
114
+ throw error;
115
+ }
116
+ const diff = chunks.join('');
117
+ // Choose a fence longer than any run in repository text, so source Markdown cannot close the diff fence.
118
+ const fence = '`'.repeat(Math.max(3, ...[...diff.matchAll(/`+/g)].map(m => m[0].length + 1)));
119
+ const context = [
120
+ `The repository checkout is at pushed base ${base}. Apply this unified diff mentally to see the requester's state.`,
121
+ 'For checks, use apply_patch if implementation scope permits it; otherwise return a proposed patch/check plan. Binary and sensitive files are omitted.',
122
+ ...[...omitted].map(file => `omitted: ${file} (sensitive)`), ...skipped,
123
+ `${fence}diff\n${diff}${fence}`,
124
+ ].join('\n');
125
+ const out = { ...assignment, brief: withContext(assignment.brief, context) };
126
+ const tree = names(await run(cwd, ['ls-tree', '-r', '-z', base]));
127
+ const files = tree.map(entry => entry.slice(entry.indexOf('\t') + 1));
128
+ const symlinks = tree.filter(entry => entry.startsWith('120000 ')).map(entry => entry.slice(entry.indexOf('\t') + 1));
129
+ try {
130
+ // Match the bridge's pinned-base scan, including its scope narrowing and the bytes of its appended note.
131
+ validateSubmission(out, { excludeSensitive: true, scanInput: () => ({ files, diffFiles: [], diff: '', symlinks }) });
132
+ } catch (error) {
133
+ if (error.code === 'DOT_BRIDGE_INFRASTRUCTURE') throw error;
134
+ return fallback(sizeError(error) ? 'diff exceeds assignment limits' : 'submission policy rejected local context');
135
+ }
136
+ // The bridge owns scope_excluded and will repeat admission itself; never send the locally narrowed result.
137
+ return out;
138
+ }
@@ -0,0 +1,14 @@
1
+ // The bridge's admin socket lives in the bridge home. A Unix socket path has a fixed size limit (108 bytes on Linux and
2
+ // 104 on macOS, including the terminating NUL), so a long bridge home cannot hold it. The server and every client check
3
+ // the path first and say so, in place of the system's bare EINVAL.
4
+ export const SOCKET_PATH_LIMIT = process.platform === 'darwin' ? 103 : 107; // usable bytes, excluding the terminating NUL
5
+
6
+ // Null when the path fits; otherwise the error to report.
7
+ export function adminSocketPathError(socket) {
8
+ const bytes = Buffer.byteLength(socket);
9
+ if (bytes <= SOCKET_PATH_LIMIT) return null;
10
+ return Object.assign(
11
+ new Error(`the bridge home path is too long for the admin socket: ${socket} is ${bytes} bytes, and the limit on this system is ${SOCKET_PATH_LIMIT}`),
12
+ { code: 'ADMIN_SOCKET_PATH_TOO_LONG', fix: ['use a bridge home with a shorter path (DALAN_HOME)'] },
13
+ );
14
+ }