@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,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
+ }