@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.
- package/CHANGELOG.md +176 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +351 -0
- package/README.md +215 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +43 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +764 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/codex-to-muse.md +175 -0
- package/docs/connect-chatgpt.md +83 -0
- package/docs/connection-longevity.md +43 -0
- package/docs/dalan-upgrade.md +246 -0
- package/docs/deadman.md +61 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +41 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +97 -0
- package/docs/operations.md +799 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +107 -0
- package/docs/pr-head-reviewer.md +70 -0
- package/docs/pr-preflight.md +28 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +94 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +219 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +51 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +443 -0
- package/docs/worker-clients.md +290 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +67 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/dalan-try-selfcheck.mjs +29 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +418 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +538 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +186 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-owner.mjs +26 -0
- package/src/drained-slot.mjs +70 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +79 -0
- package/src/mcp-sse.mjs +62 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/process-inspection.mjs +36 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/pull-queue.mjs +159 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/route-setting.mjs +24 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1468 -0
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +388 -0
- package/src/setup.mjs +63 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3069 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +453 -0
- package/src/try-command.mjs +11 -0
- package/src/try-exposure.mjs +908 -0
- package/src/try-hosted-clients.mjs +46 -0
- package/src/try-hosted.mjs +444 -0
- package/src/try-selfcheck.mjs +168 -0
- package/src/try.mjs +635 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +632 -0
- package/src/workspace.mjs +1065 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { defaultPath } from './paths.mjs';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
|
|
8
|
+
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
9
|
+
const runtime = () => ({ node: process.version, abi: process.versions.modules, platform: process.platform, arch: process.arch });
|
|
10
|
+
const store = options => path.resolve(options.cacheDir ?? defaultPath(os.homedir(),'.dot-bridge/prepared-node-modules'));
|
|
11
|
+
const failure = (code, message) => Object.assign(new Error(`${code}: ${message}`), { code });
|
|
12
|
+
const recovery = source => `dalan prepare-deps ${shellQuote(path.resolve(source))}`;
|
|
13
|
+
|
|
14
|
+
function readRegular(file, optional = false) {
|
|
15
|
+
let fd;
|
|
16
|
+
try {
|
|
17
|
+
fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
18
|
+
if (!fs.fstatSync(fd).isFile()) throw failure('dependencies_invalid', 'manifest must be a regular file');
|
|
19
|
+
return fs.readFileSync(fd);
|
|
20
|
+
} catch (e) {
|
|
21
|
+
if (optional && e.code === 'ENOENT') return null;
|
|
22
|
+
if (e.code === 'dependencies_invalid') throw e;
|
|
23
|
+
throw failure('dependencies_invalid', 'cannot read regular manifest or lock');
|
|
24
|
+
} finally { if (fd !== undefined) fs.closeSync(fd); }
|
|
25
|
+
}
|
|
26
|
+
function inputs(source) {
|
|
27
|
+
const root = path.resolve(source);
|
|
28
|
+
if (fs.realpathSync(root) !== root || !fs.lstatSync(root).isDirectory()) throw failure('dependencies_invalid', 'source directory must be canonical');
|
|
29
|
+
const lock = readRegular(path.join(root, 'package-lock.json'), true);
|
|
30
|
+
if (!lock) return null;
|
|
31
|
+
const manifest = readRegular(path.join(root, 'package.json'));
|
|
32
|
+
let pkg, data;
|
|
33
|
+
try { pkg = JSON.parse(manifest); data = JSON.parse(lock); } catch { throw failure('dependencies_invalid', 'invalid manifest or lock JSON'); }
|
|
34
|
+
if (pkg.workspaces || ![2, 3].includes(data.lockfileVersion) || !data.packages || typeof data.packages !== 'object') throw failure('dependencies_unsupported', 'only root npm lockfiles without workspaces are supported');
|
|
35
|
+
for (const [name, entry] of Object.entries(data.packages)) {
|
|
36
|
+
if (entry?.link || (name && !name.startsWith('node_modules/')) || /^(file:|link:|workspace:)/i.test(entry?.resolved ?? '')) throw failure('dependencies_unsupported', 'local or workspace dependencies are unsupported');
|
|
37
|
+
for (const group of ['dependencies','devDependencies','optionalDependencies']) for (const value of Object.values(entry?.[group] ?? {})) if (typeof value === 'string' && /^(file:|link:|workspace:)/i.test(value)) throw failure('dependencies_unsupported', 'local or workspace dependencies are unsupported');
|
|
38
|
+
}
|
|
39
|
+
const identity = { lock_sha256: hash(lock), manifest_sha256: hash(manifest), runtime: runtime() };
|
|
40
|
+
return { root, lock, manifest, identity, key: hash(JSON.stringify(identity.runtime)) };
|
|
41
|
+
}
|
|
42
|
+
function checkDirectory(dir, privateMode = false) {
|
|
43
|
+
const s = fs.lstatSync(dir);
|
|
44
|
+
if (!s.isDirectory() || s.uid !== process.getuid() || (s.mode & (privateMode ? 0o077 : 0o022))) throw failure('dependencies_invalid', 'unsafe cache directory ownership or mode');
|
|
45
|
+
}
|
|
46
|
+
function checkParents(dir) {
|
|
47
|
+
for (let p = dir; ; p = path.dirname(p)) {
|
|
48
|
+
const s = fs.lstatSync(p);
|
|
49
|
+
if (!s.isDirectory() || (s.uid !== process.getuid() && s.uid !== 0) || (s.mode & 0o022)) throw failure('dependencies_invalid', 'unsafe cache parent');
|
|
50
|
+
if (p === '/') break;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function validateTree(root) {
|
|
54
|
+
const walk = dir => {
|
|
55
|
+
const st = fs.lstatSync(dir);
|
|
56
|
+
if (st.uid !== process.getuid() || (!st.isSymbolicLink() && (st.mode & 0o222))) throw failure('dependencies_invalid', 'dependency tree ownership or mode invalid');
|
|
57
|
+
if (st.isSymbolicLink()) {
|
|
58
|
+
const target = fs.realpathSync(dir);
|
|
59
|
+
if (!target.startsWith(root + path.sep)) throw failure('dependencies_invalid', 'dependency link escapes tree');
|
|
60
|
+
} else if (st.isDirectory()) for (const name of fs.readdirSync(dir)) walk(path.join(dir, name));
|
|
61
|
+
else if (!st.isFile()) throw failure('dependencies_invalid', 'special file in dependency tree');
|
|
62
|
+
};
|
|
63
|
+
walk(root);
|
|
64
|
+
}
|
|
65
|
+
function entryPath(base, input) { return path.join(base, input.identity.lock_sha256, input.key); }
|
|
66
|
+
const shellQuote = value => "'" + value.replaceAll("'", "'\\''") + "'";
|
|
67
|
+
function lookup(input, base) {
|
|
68
|
+
const entry = entryPath(base, input);
|
|
69
|
+
try {
|
|
70
|
+
checkParents(base); checkDirectory(base, true); checkDirectory(path.dirname(entry), true); checkDirectory(entry, true);
|
|
71
|
+
const metaPath = path.join(entry, 'metadata.json'), st = fs.lstatSync(metaPath);
|
|
72
|
+
if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o222)) throw new Error('bad metadata');
|
|
73
|
+
const metadata = JSON.parse(readRegular(metaPath));
|
|
74
|
+
if (JSON.stringify(metadata.identity) !== JSON.stringify(input.identity)) throw new Error('identity mismatch');
|
|
75
|
+
const treePath = path.join(entry, 'node_modules'); validateTree(treePath);
|
|
76
|
+
return { treePath, ...input.identity };
|
|
77
|
+
} catch (e) {
|
|
78
|
+
throw failure('dependencies_unprepared', `missing or invalid preparation; owner recovery: ${recovery(input.root)} --replace-invalid`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export function resolvePreparedNodeModules(sourceDir, options = {}) {
|
|
82
|
+
const input = inputs(sourceDir);
|
|
83
|
+
return input ? lookup(input, store(options)) : null;
|
|
84
|
+
}
|
|
85
|
+
export function prepareNodeModules(sourceDir, options = {}) {
|
|
86
|
+
const input = inputs(sourceDir);
|
|
87
|
+
if (!input) throw failure('dependencies_invalid', 'root package-lock.json required');
|
|
88
|
+
const base = store(options);
|
|
89
|
+
fs.mkdirSync(base, { recursive: true, mode: 0o700 });
|
|
90
|
+
checkParents(base); checkDirectory(base, true);
|
|
91
|
+
const lockDir = path.join(base, input.identity.lock_sha256);
|
|
92
|
+
fs.mkdirSync(lockDir, { mode: 0o700, recursive: true }); checkDirectory(lockDir, true);
|
|
93
|
+
const destination = entryPath(base, input);
|
|
94
|
+
if (fs.existsSync(destination)) {
|
|
95
|
+
try { return lookup(input, base); }
|
|
96
|
+
catch(error) { if(!options.replaceInvalid)throw error; }
|
|
97
|
+
}
|
|
98
|
+
const stage = fs.mkdtempSync(path.join(base, '.stage-'));
|
|
99
|
+
try {
|
|
100
|
+
fs.writeFileSync(path.join(stage, 'package.json'), input.manifest, { mode: 0o600 });
|
|
101
|
+
fs.writeFileSync(path.join(stage, 'package-lock.json'), input.lock, { mode: 0o600 });
|
|
102
|
+
const npm = path.join(path.dirname(process.execPath), 'npm');
|
|
103
|
+
const run = spawnSync(process.execPath, [npm, 'ci', '--ignore-scripts', '--no-audit', '--no-fund'], { cwd: stage, env: { ...process.env, npm_config_ignore_scripts: 'true' }, stdio: 'ignore' });
|
|
104
|
+
if (run.error || run.status !== 0) {
|
|
105
|
+
const exit = run.error ? `error: ${run.error.message}` : run.signal ? `signal ${run.signal}` : `exit status ${run.status}`;
|
|
106
|
+
throw failure('dependencies_install_failed', `npm ci failed (ran ${npm}; ${exit}); no preparation published`);
|
|
107
|
+
}
|
|
108
|
+
const tree = path.join(stage, 'node_modules');
|
|
109
|
+
if (!fs.existsSync(tree)) fs.mkdirSync(tree, { mode: 0o700 });
|
|
110
|
+
const freeze = dir => { const s = fs.lstatSync(dir); if (s.isSymbolicLink()) return; if (s.isDirectory()) for (const name of fs.readdirSync(dir)) freeze(path.join(dir, name)); else if (!s.isFile()) throw failure('dependencies_invalid', 'special file in dependency tree'); fs.chmodSync(dir, s.mode & 0o555); };
|
|
111
|
+
freeze(tree); validateTree(tree);
|
|
112
|
+
fs.rmSync(path.join(stage, 'package.json')); fs.rmSync(path.join(stage, 'package-lock.json'));
|
|
113
|
+
fs.writeFileSync(path.join(stage, 'metadata.json'), JSON.stringify({ identity: input.identity }) + '\n', { mode: 0o400 });
|
|
114
|
+
if(fs.existsSync(destination)) {
|
|
115
|
+
// Recheck after npm: a concurrent owner preparation may have finished.
|
|
116
|
+
try { return lookup(input,base); }
|
|
117
|
+
catch(error) { if(!options.replaceInvalid)throw error; }
|
|
118
|
+
// Preserve old inodes for any active read-only mount. An explicit owner
|
|
119
|
+
// repair publishes new bytes without modifying a running check's input.
|
|
120
|
+
fs.renameSync(destination,path.join(base,'.replaced-'+randomUUID()));
|
|
121
|
+
}
|
|
122
|
+
// The private publication directory remains owner-writable for explicit recovery.
|
|
123
|
+
fs.renameSync(stage, destination);
|
|
124
|
+
return lookup(input, base);
|
|
125
|
+
} finally { if (fs.existsSync(stage)) {
|
|
126
|
+
const thaw = dir => { const st=fs.lstatSync(dir); if (!st.isDirectory() || st.isSymbolicLink()) return; fs.chmodSync(dir, 0o700); for (const name of fs.readdirSync(dir)) thaw(path.join(dir,name)); };
|
|
127
|
+
thaw(stage); fs.rmSync(stage, { recursive: true, force: true });
|
|
128
|
+
} }
|
|
129
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
|
|
4
|
+
// Inspection failure is not evidence of exit. Read Linux start ticks on both sides of ps so command and identity belong
|
|
5
|
+
// to the same process. macOS supplies its start timestamp and command in one ps snapshot, with a fixed locale and timezone.
|
|
6
|
+
export const processCommand = (pid, { platform = process.platform, run = spawnSync, readFile = fs.readFileSync, probe = pid => process.kill(pid, 0) } = {}) => {
|
|
7
|
+
const unknown = { state: 'unknown' }, absent = { state: 'absent' };
|
|
8
|
+
if (!Number.isInteger(pid) || pid <= 0) return unknown;
|
|
9
|
+
const startTicks = () => {
|
|
10
|
+
const stat = readFile(`/proc/${pid}/stat`, 'utf8');
|
|
11
|
+
const fields = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/);
|
|
12
|
+
if (!/^\d+$/.test(fields[19] ?? '')) throw new Error('invalid process start time');
|
|
13
|
+
return fields[19];
|
|
14
|
+
};
|
|
15
|
+
try {
|
|
16
|
+
const before = platform === 'linux' ? startTicks() : null;
|
|
17
|
+
if (!['linux', 'darwin'].includes(platform)) return unknown;
|
|
18
|
+
const out = run('ps', ['-p', String(pid), '-o', platform === 'darwin' ? 'lstart=,command=' : 'command='], { encoding: 'utf8', timeout: 5000, env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' } });
|
|
19
|
+
if (out.error || out.status !== 0 || !out.stdout?.trim()) {
|
|
20
|
+
// Even ps exit 1 can be an inspection failure; only ESRCH confirms absence.
|
|
21
|
+
try { probe(pid); } catch (error) { if (error.code === 'ESRCH') return absent; }
|
|
22
|
+
return unknown;
|
|
23
|
+
}
|
|
24
|
+
if (platform === 'linux') {
|
|
25
|
+
const after = startTicks();
|
|
26
|
+
return before === after ? { state: 'present', command: out.stdout.trim(), start: before } : unknown;
|
|
27
|
+
}
|
|
28
|
+
const match = /^(\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.+)$/.exec(out.stdout.trim());
|
|
29
|
+
return match ? { state: 'present', command: match[2], start: match[1].replace(/\s+/g, ' ') } : unknown;
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if (['ENOENT', 'ESRCH'].includes(error.code)) {
|
|
32
|
+
try { probe(pid); } catch (probeError) { if (probeError.code === 'ESRCH') return absent; }
|
|
33
|
+
}
|
|
34
|
+
return unknown;
|
|
35
|
+
}
|
|
36
|
+
};
|
package/src/projects.mjs
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
import { defaultPath,workspaceRoot } from './paths.mjs';
|
|
2
|
+
import { readEnv } from './env.mjs';
|
|
3
|
+
import { fetchMirror } from './mirror-fetch.mjs';
|
|
4
|
+
import { gitEnv } from './git-env.mjs';
|
|
5
|
+
import { parseHostBudget } from './host-budget.mjs';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { execFileSync, spawnSync } from 'node:child_process';
|
|
10
|
+
|
|
11
|
+
const fullSha = /^[a-f0-9]{40}$/;
|
|
12
|
+
const repoName = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
13
|
+
const mirrorRoot = worker => worker ? path.join(workspaceRoot(), 'mirrors', 'workers', safeWorker(worker)) : path.join(workspaceRoot(), 'mirrors');
|
|
14
|
+
function safeWorker(worker) { if(typeof worker!=='string'||!/^[a-z][a-z0-9_-]{0,31}$/.test(worker)) throw new Error('invalid verified worker');return worker; }
|
|
15
|
+
const overrideFile = () => readEnv('DALAN_CHECKS_FILE') || defaultPath(os.homedir(),'.config/dot-bridge/checks.json');
|
|
16
|
+
// Discovery reads only this allowlist. The integrator shares it so changes to
|
|
17
|
+
// discovery inputs or ecosystem lockfiles always require owner approval.
|
|
18
|
+
export const CHECK_INPUT_FILES = Object.freeze(['.dalan.json','.dot-bridge.json','package.json','package-lock.json','npm-shrinkwrap.json','pnpm-lock.yaml','yarn.lock','pyproject.toml','pytest.ini','uv.lock','Cargo.toml','Cargo.lock','go.mod','go.sum','Makefile']);
|
|
19
|
+
const checkMetadataFiles = new Set(CHECK_INPUT_FILES);
|
|
20
|
+
const CHECK_METADATA_MAX_BYTES = 1024 * 1024;
|
|
21
|
+
|
|
22
|
+
function runGit(args, opts = {}) {
|
|
23
|
+
const result = spawnSync('git', args, { encoding: 'utf8', timeout: 30000, maxBuffer: 12 * 1024 * 1024, ...opts, env: gitEnv(opts.env) });
|
|
24
|
+
if (result.error || result.status !== 0) throw new Error(`git failed: ${redact((result.stderr || result.error?.message || '').slice(0, 500))}`);
|
|
25
|
+
return result.stdout.trim();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Check definitions and detected project metadata come only from regular files directly inside the checkout. O_NOFOLLOW closes
|
|
29
|
+
// the lstat/open race for symlinks; reads are capped so discovery cannot allocate based on untrusted file size.
|
|
30
|
+
function openCheckMetadata(dir, name) {
|
|
31
|
+
if (!checkMetadataFiles.has(name)) throw new Error('invalid check metadata path');
|
|
32
|
+
let checkout;
|
|
33
|
+
try { checkout = fs.realpathSync(dir); } catch { throw new Error('check metadata directory unavailable'); }
|
|
34
|
+
const file = path.join(checkout, name);
|
|
35
|
+
if (path.dirname(file) !== checkout) throw new Error('invalid check metadata path');
|
|
36
|
+
let entry;
|
|
37
|
+
try { entry = fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') return null; throw new Error('cannot inspect check metadata'); }
|
|
38
|
+
if (entry.isSymbolicLink()) throw new Error('check metadata symlinks are not allowed');
|
|
39
|
+
if (!entry.isFile()) throw new Error('check metadata must be a regular file');
|
|
40
|
+
let fd;
|
|
41
|
+
try {
|
|
42
|
+
const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
|
|
43
|
+
fd = fs.openSync(file, flags);
|
|
44
|
+
const stat = fs.fstatSync(fd);
|
|
45
|
+
if (!stat.isFile()) throw new Error('check metadata must be a regular file');
|
|
46
|
+
return { fd, size: stat.size };
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
49
|
+
if (error.code === 'ELOOP') throw new Error('check metadata symlinks are not allowed');
|
|
50
|
+
if (error.message === 'check metadata must be a regular file') throw error;
|
|
51
|
+
throw new Error('cannot open check metadata');
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function hasCheckMetadata(dir, name) {
|
|
56
|
+
const opened = openCheckMetadata(dir, name);
|
|
57
|
+
if (!opened) return false;
|
|
58
|
+
fs.closeSync(opened.fd);
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function readCheckMetadata(dir, name, maxBytes = CHECK_METADATA_MAX_BYTES) {
|
|
63
|
+
const opened = openCheckMetadata(dir, name);
|
|
64
|
+
if (!opened) return null;
|
|
65
|
+
try {
|
|
66
|
+
if (opened.size > maxBytes) throw new Error('check metadata exceeds the size limit');
|
|
67
|
+
const bytes = Buffer.allocUnsafe(maxBytes + 1);
|
|
68
|
+
const count = fs.readSync(opened.fd, bytes, 0, bytes.length, 0);
|
|
69
|
+
if (count > maxBytes) throw new Error('check metadata exceeds the size limit');
|
|
70
|
+
return bytes.subarray(0, count).toString('utf8');
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (error.message === 'check metadata exceeds the size limit') throw error;
|
|
73
|
+
throw new Error('cannot read check metadata');
|
|
74
|
+
} finally { fs.closeSync(opened.fd); }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function parseCheckMetadata(text) {
|
|
78
|
+
try { return JSON.parse(text); } catch { throw new Error('invalid check metadata JSON'); }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function githubAuthRecovery(error) {
|
|
82
|
+
if (!/could not read (?:Username|Password)|authentication failed|terminal prompts disabled|repository not found|gh:\s*(?:not found|not installed)|not logged in|no oauth token|not authenticated/i.test(error?.message ?? '')) return null;
|
|
83
|
+
return Object.assign(new Error('GitHub authentication failed. Install GitHub CLI, run `gh auth login` as the bridge service user, or set GH_TOKEN in the bridge service environment; confirm `gh` is on the service PATH, then retry the job.'), { code: 'DOT_BRIDGE_INFRASTRUCTURE' });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function redact(value) {
|
|
87
|
+
return String(value).replace(/https:\/\/[^/@\s]+@/g, 'https://<redacted>@');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function loadCapacity(file = defaultPath(os.homedir(),'.config/dot-bridge/limits.json')) {
|
|
91
|
+
if (!fs.existsSync(file)) return 1;
|
|
92
|
+
if ((fs.statSync(file).mode & 0o777) !== 0o600) throw new Error('limits policy must be mode 0600');
|
|
93
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8')).max_claimed_outer_assignments ?? 1;
|
|
94
|
+
if (!Number.isInteger(value) || value < 1 || value > 10) throw new Error('invalid max_claimed_outer_assignments');
|
|
95
|
+
return value;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function assignmentInput(assignment) {
|
|
99
|
+
if (!['read-only', 'implementation'].includes(assignment.execution_scope)) throw new Error('invalid execution scope');
|
|
100
|
+
if (assignment.inputs?.length !== 1) throw new Error('one pinned GitHub input required');
|
|
101
|
+
const input = assignment.inputs[0];
|
|
102
|
+
if (!validRepo(input.github_repo) || !fullSha.test(input.base_sha || '')) throw new Error('github_repo and full base_sha required');
|
|
103
|
+
if (input.head_sha && !fullSha.test(input.head_sha)) throw new Error('invalid head SHA');
|
|
104
|
+
if (input.input_patch !== undefined && (typeof input.input_patch !== 'string' || Buffer.byteLength(input.input_patch) > 262144)) throw new Error('invalid input patch');
|
|
105
|
+
// A read-only input_patch is a local patch under review: the workspace applies it, read_file sees the patched tree and
|
|
106
|
+
// workspace_result shows the diff, without publishing the patch to GitHub.
|
|
107
|
+
return input;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function cloneUrl(repo) {
|
|
111
|
+
const key = `DALAN_GITHUB_URL_${repo.toUpperCase().replace(/[^A-Z0-9]/g, '_')}`;
|
|
112
|
+
const value = readEnv(key) || `${process.env.GITHUB_CLONE_BASE_URL || 'https://github.com'}/${repo}.git`;
|
|
113
|
+
if (/^https:\/\/[^/@\s]+@/.test(value)) throw new Error('GitHub clone URL must not embed credentials');
|
|
114
|
+
return value;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function hostGitEnv() {
|
|
118
|
+
const askpass = path.join(workspaceRoot(), 'github-askpass');
|
|
119
|
+
fs.mkdirSync(workspaceRoot(), { recursive: true, mode: 0o700 });
|
|
120
|
+
fs.writeFileSync(askpass, '#!/bin/sh\ncase "$1" in\n *Username*) printf "x-access-token\\n" ;;\n *Password*) exec gh auth token ;;\nesac\n', { mode: 0o700 });
|
|
121
|
+
fs.chmodSync(askpass, 0o700);
|
|
122
|
+
return { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: askpass };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function mirrorPath(repo,{worker}={}) {
|
|
126
|
+
if (!validRepo(repo)) throw new Error('invalid github_repo');
|
|
127
|
+
const [owner, name] = repo.split('/');
|
|
128
|
+
return path.join(mirrorRoot(worker), owner, `${name}.git`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function validRepo(repo) {
|
|
132
|
+
return repoName.test(repo || '') && repo.split('/').every(part => part !== '.' && part !== '..' && !part.includes('..'));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const COMPLETENESS_MAX_BUFFER = 32 * 1024 * 1024;
|
|
136
|
+
|
|
137
|
+
// Proves the pinned commit and every tree and blob under it are present in the mirror. A commit object alone is not
|
|
138
|
+
// enough: a mirror can hold the commit and lack an object below it, and the job then fails later in the scope scan.
|
|
139
|
+
export function verifyFetchedCommit(mirror, sha, label) {
|
|
140
|
+
// A promisor remote must not fetch lazily inside admission; a missing object stays missing.
|
|
141
|
+
const options = { encoding: 'utf8', timeout: 30000, maxBuffer: COMPLETENESS_MAX_BUFFER, env: { ...gitEnv(), GIT_NO_LAZY_FETCH: '1' } };
|
|
142
|
+
const result = spawnSync('git', ['-C', mirror, 'rev-parse', '--quiet', '--verify', `${sha}^{commit}`], { ...options, maxBuffer: 1024 });
|
|
143
|
+
if (!result.error && (result.status === 1 || result.status === 0 && result.stdout.trim() !== sha)) throw Object.assign(new Error(`${label} SHA does not identify a fetched GitHub commit`), { code: 'DOT_BRIDGE_INVALID_INPUT' });
|
|
144
|
+
if (result.error || result.status !== 0) throw Object.assign(new Error('GitHub revision verification unavailable'), { code: 'DOT_BRIDGE_INFRASTRUCTURE' });
|
|
145
|
+
const unavailable = error => Object.assign(new Error(error?.code === 'ENOBUFS' || error?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER'
|
|
146
|
+
? `GitHub mirror completeness verification unavailable: the ${label} tree listing exceeds ${COMPLETENESS_MAX_BUFFER / 1024 / 1024} MiB`
|
|
147
|
+
: error?.code === 'ETIMEDOUT' ? `GitHub mirror completeness verification unavailable: the ${label} check timed out`
|
|
148
|
+
: 'GitHub mirror completeness verification unavailable'), { code: 'DOT_BRIDGE_INFRASTRUCTURE' });
|
|
149
|
+
// The requester cannot repair the bridge's mirror, so this is an infrastructure fault, not an input error.
|
|
150
|
+
const missing = (type, oid, file) => Object.assign(new Error(`${label} SHA ${sha}: the bridge's mirror is incomplete: missing ${type} ${oid} for ${file} under the pinned commit.`), { code: 'DOT_BRIDGE_INFRASTRUCTURE', mirrorIncomplete: true });
|
|
151
|
+
// -z preserves paths with whitespace; -t includes tree OIDs for diagnostics. Gitlinks belong to another repository;
|
|
152
|
+
// symlinks are ordinary blob objects, never filesystem targets to follow.
|
|
153
|
+
const listing = spawnSync('git', ['-C', mirror, 'ls-tree', '-r', '-t', '-z', sha], options);
|
|
154
|
+
if (listing.error) throw unavailable(listing.error);
|
|
155
|
+
const entries = (listing.stdout || '').split('\0').filter(Boolean).map(entry => {
|
|
156
|
+
const match = /^(\d{6}) (blob|tree|commit) ([a-f0-9]{40})\t([\s\S]*)$/.exec(entry);
|
|
157
|
+
if (!match) throw unavailable();
|
|
158
|
+
return { type: match[2], oid: match[3], file: match[4] };
|
|
159
|
+
}).filter(entry => entry.type !== 'commit');
|
|
160
|
+
if (listing.status !== 0) {
|
|
161
|
+
// Git versions word this differently: "Could not read <oid>", "unable to read tree (<oid>)", "not a tree object".
|
|
162
|
+
const oid = /(?:unable to read tree|not a tree object|could not read)\s*\(?([a-f0-9]{40})\)?/i.exec(listing.stderr || '')?.[1];
|
|
163
|
+
if (!oid) throw unavailable();
|
|
164
|
+
const entry = entries.find(entry => entry.oid === oid);
|
|
165
|
+
throw missing('tree', oid, entry?.file || 'the root tree');
|
|
166
|
+
}
|
|
167
|
+
// Identical files share one object; check each object once.
|
|
168
|
+
const unique = [...new Map(entries.map(entry => [entry.oid, entry])).values()];
|
|
169
|
+
if (!unique.length) return;
|
|
170
|
+
// One batch process, fed through stdin rather than one process per object.
|
|
171
|
+
const batch = spawnSync('git', ['-C', mirror, 'cat-file', '--batch-check'], { ...options, input: unique.map(entry => entry.oid).join('\n') + '\n' });
|
|
172
|
+
if (batch.error || batch.status !== 0) throw unavailable(batch.error);
|
|
173
|
+
const lines = batch.stdout.trimEnd().split('\n');
|
|
174
|
+
if (lines.length !== unique.length) throw unavailable();
|
|
175
|
+
for (let i = 0; i < unique.length; i++) {
|
|
176
|
+
const entry = unique[i];
|
|
177
|
+
if (lines[i] === `${entry.oid} missing`) throw missing(entry.type, entry.oid, entry.file);
|
|
178
|
+
if (!lines[i].startsWith(`${entry.oid} ${entry.type} `) || !/^\d+$/.test(lines[i].split(' ')[2] || '')) throw unavailable();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function prepareGithubRepo(input,{worker}={}) {
|
|
183
|
+
requireGithubAvailable();
|
|
184
|
+
const mirror = mirrorPath(input.github_repo,{worker});
|
|
185
|
+
fs.mkdirSync(path.dirname(mirror), { recursive: true, mode: 0o700 });
|
|
186
|
+
const env = hostGitEnv();
|
|
187
|
+
// Fetch attempts isolate temporary packs and publish complete objects before refs.
|
|
188
|
+
// Leave time for pin/tree validation inside the 180-second admission scan.
|
|
189
|
+
// The fetch and its corruption retry share this budget and settle all writers.
|
|
190
|
+
// The completeness repair below fetches a second time; both fetches share one 120-second budget.
|
|
191
|
+
const pins=[['base',input.base_sha],...(input.head_sha?[['head',input.head_sha]]:[])];
|
|
192
|
+
const deadline=performance.now()+120000;
|
|
193
|
+
const fetch = options => {
|
|
194
|
+
const budget=Math.floor(deadline-performance.now());
|
|
195
|
+
if(budget<=0) throw Object.assign(new Error('GitHub mirror fetch timed out before the incomplete mirror could be refetched'),{code:'DOT_BRIDGE_INFRASTRUCTURE'});
|
|
196
|
+
try { fetchMirror(mirror, cloneUrl(input.github_repo), env, budget, pins.map(([,sha])=>sha), options); }
|
|
197
|
+
catch (error) {
|
|
198
|
+
const lines=String(error.message).split(/\r?\n/);
|
|
199
|
+
const missing=pins.find(([,sha])=>lines.some(line=>line.endsWith(`not our ref ${sha}`)||line.endsWith(`couldn't find remote ref ${sha}`)));
|
|
200
|
+
if(missing) throw Object.assign(new Error(`${missing[0]} SHA cannot be fetched from the GitHub repository`),{code:'DOT_BRIDGE_INVALID_INPUT'});
|
|
201
|
+
throw githubAuthRecovery(error) || error;
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
const verify = () => { for (const [label, sha] of pins) verifyFetchedCommit(mirror, sha, label); };
|
|
205
|
+
fetch();
|
|
206
|
+
try { verify(); }
|
|
207
|
+
catch (error) {
|
|
208
|
+
if (!error.mirrorIncomplete) throw error;
|
|
209
|
+
// A fetch of pins the mirror already claims to have transfers nothing, so an object lost from the mirror
|
|
210
|
+
// stays lost. Refetch once, ignoring what the mirror claims, then verify again.
|
|
211
|
+
fetch({ refetch: true });
|
|
212
|
+
try { verify(); }
|
|
213
|
+
catch (again) {
|
|
214
|
+
if (again.mirrorIncomplete) again.message += ' A refetch did not repair it. Operator: repair or recreate this repository\'s bridge mirror, then resubmit.';
|
|
215
|
+
throw again;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return mirror;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function projectFor(assignment) {
|
|
222
|
+
const input = assignmentInput(assignment);
|
|
223
|
+
return { input, mirror: prepareGithubRepo(input), policy: { artifact_retention_days: 14 } };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const argvOk = v => Array.isArray(v) && v.length && v.every(x => typeof x === 'string' && x && !x.includes('\0'));
|
|
227
|
+
const relPath = p => typeof p === 'string' && p && !p.includes('\0') && !p.includes('\\') && !p.startsWith('/') && !p.split('/').some(x => x === '..');
|
|
228
|
+
const runtimeSpec = /^[a-z][a-z0-9_.-]*>=\d+(?:\.\d+)*$/;
|
|
229
|
+
// Prerequisites are all-or-nothing per field: null means unknown, an empty binaries list means "needs nothing beyond the runtime".
|
|
230
|
+
function normalizePrerequisites(p, id) {
|
|
231
|
+
if (p === undefined || p === null) return null;
|
|
232
|
+
if (typeof p !== 'object' || Array.isArray(p)) throw new Error(`invalid prerequisites ${id}`);
|
|
233
|
+
const { binaries = null, lockfile = null, runtime = null } = p;
|
|
234
|
+
if (binaries !== null && (!Array.isArray(binaries) || binaries.some(b => typeof b !== 'string' || !/^[A-Za-z0-9._+-]+$/.test(b)))) throw new Error(`invalid prerequisite binaries ${id}`);
|
|
235
|
+
if (lockfile !== null && lockfile !== true && !(relPath(lockfile))) throw new Error(`invalid prerequisite lockfile ${id}`);
|
|
236
|
+
if (runtime !== null && !(typeof runtime === 'string' && runtimeSpec.test(runtime))) throw new Error(`invalid prerequisite runtime ${id}`);
|
|
237
|
+
return binaries === null && lockfile === null && runtime === null ? null : { binaries, lockfile, runtime };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// A declared test path counts as named when argv holds it as a whole element or as a whole word inside one (a `bash -c` script).
|
|
241
|
+
export function argvNamesPath(argv, p) {
|
|
242
|
+
const bare = p.replace(/^\.\//, '').replace(/\/$/, '');
|
|
243
|
+
const re = new RegExp(`(?:^|[\\s'"=]|\\./)${bare.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/?(?=$|[\\s'";&|)/])`);
|
|
244
|
+
return argv.some(x => re.test(x));
|
|
245
|
+
}
|
|
246
|
+
// Test-file-like tokens an argv names (for `bash -c` scripts: words inside the script text).
|
|
247
|
+
export const testFileName = /(?:\.(?:test|spec)\.[cm]?[jt]sx?|_test\.(?:py|go|sh)|(?:^|\/)test_[^/]+\.py)$/;
|
|
248
|
+
export function argvTestFiles(argv) {
|
|
249
|
+
const found = [];
|
|
250
|
+
for (const el of argv) for (const tok of String(el).split(/[\s'"=;&|()<>]+/)) {
|
|
251
|
+
const t = tok.replace(/^\.\//, '');
|
|
252
|
+
if (t && !t.startsWith('-') && !t.startsWith('/') && !t.includes('$') && testFileName.test(t)) found.push(t);
|
|
253
|
+
}
|
|
254
|
+
return [...new Set(found)];
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function normalizeCheck(check, id = 'default', derived = {}) {
|
|
258
|
+
if (!argvOk(check.argv)) throw new Error(`invalid check ${id}`);
|
|
259
|
+
if (check.install_argv && !argvOk(check.install_argv)) throw new Error(`invalid install ${id}`);
|
|
260
|
+
const timeout_ms = check.timeout_ms ?? 120000;
|
|
261
|
+
const output_bytes = check.output_bytes ?? 262144;
|
|
262
|
+
if (!Number.isInteger(timeout_ms) || timeout_ms < 100 || timeout_ms > 900000) throw new Error(`invalid timeout ${id}`);
|
|
263
|
+
if (!Number.isInteger(output_bytes) || output_bytes < 1024 || output_bytes > 1048576) throw new Error(`invalid output cap ${id}`);
|
|
264
|
+
if (check.readiness_argv !== undefined && !argvOk(check.readiness_argv)) throw new Error(`invalid readiness ${id}`);
|
|
265
|
+
if (check.test_paths !== undefined && (!Array.isArray(check.test_paths) || !check.test_paths.length || !check.test_paths.every(relPath))) throw new Error(`invalid test_paths ${id}`);
|
|
266
|
+
// A declared test file is a promise about what argv runs: it must be named in argv, so the id, the list and the command cannot drift apart.
|
|
267
|
+
// Directories stay informational because a command like `npm run test:sandbox` reaches them through a script.
|
|
268
|
+
for (const p of check.test_paths ?? []) if (testFileName.test(p) && !argvNamesPath(check.argv, p)) throw new Error(`test_paths ${id}: ${p} is not named in argv`);
|
|
269
|
+
const prerequisites = normalizePrerequisites(check.prerequisites ?? derived.prerequisites, id);
|
|
270
|
+
const test_paths = (check.test_paths ?? derived.test_paths)?.map(p => p === './...' ? p : p.replace(/^\.\//, '').replace(/\/$/, '')) ?? null;
|
|
271
|
+
return {
|
|
272
|
+
id, argv: check.argv, install_argv: check.install_argv || null, timeout_ms, output_bytes,
|
|
273
|
+
...(check.host_budget === undefined ? {} : { host_budget: parseHostBudget(check.host_budget) }),
|
|
274
|
+
prerequisites, prerequisites_reason: prerequisites ? null : derived.prerequisites_reason || 'not declared',
|
|
275
|
+
readiness_argv: check.readiness_argv || null,
|
|
276
|
+
test_paths, test_paths_reason: test_paths ? null : derived.test_paths_reason || 'not declared',
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// Paths a package.json test script names (files or directories); null when it names none.
|
|
281
|
+
function scriptTestPaths(script) {
|
|
282
|
+
const found = [];
|
|
283
|
+
for (const token of String(script).split(/\s+/)) {
|
|
284
|
+
if (!/^[\w@.\/-]+$/.test(token) || token.startsWith('-') || token.startsWith('..') || token.startsWith('/') || /^[a-z]+:\/\//.test(token)) continue;
|
|
285
|
+
if (token.includes('/') || /\.(?:[cm]?[jt]sx?|py|sh)$/.test(token)) found.push(token.replace(/^\.\//, '').replace(/\/$/, ''));
|
|
286
|
+
}
|
|
287
|
+
return found.length ? [...new Set(found)].slice(0, 200) : null;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function pytestPaths(dir) {
|
|
291
|
+
const ini = /^\s*testpaths\s*[=:]\s*(.+)$/m.exec(readCheckMetadata(dir, 'pytest.ini') ?? '');
|
|
292
|
+
if (ini) return ini[1].trim().split(/\s+/).filter(relPath);
|
|
293
|
+
const toml = /^\s*testpaths\s*=\s*\[([^\]]*)\]/m.exec(readCheckMetadata(dir, 'pyproject.toml') ?? '');
|
|
294
|
+
if (toml) return [...toml[1].matchAll(/["']([^"']+)["']/g)].map(m => m[1]).filter(relPath);
|
|
295
|
+
return [];
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function packageManager(dir) {
|
|
299
|
+
if (hasCheckMetadata(dir, 'pnpm-lock.yaml')) return 'pnpm';
|
|
300
|
+
if (hasCheckMetadata(dir, 'yarn.lock')) return 'yarn';
|
|
301
|
+
return 'npm';
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function hasPackageDependencies(pkg) {
|
|
305
|
+
return ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'].some(key => pkg[key] && Object.keys(pkg[key]).length);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// The owner's checks.json parsed from an owner-owned mode-0600 regular file; {} when absent.
|
|
309
|
+
export function ownerChecks() {
|
|
310
|
+
const file = overrideFile();
|
|
311
|
+
let entry;
|
|
312
|
+
try { entry = fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') return {}; throw new Error('cannot read check override configuration'); }
|
|
313
|
+
if (!entry.isFile() || entry.isSymbolicLink() || entry.uid !== process.getuid() || (entry.mode & 0o777) !== 0o600) throw new Error('check override file must be an owner-owned mode-0600 regular file');
|
|
314
|
+
let fd;
|
|
315
|
+
try {
|
|
316
|
+
fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
|
|
317
|
+
const stat = fs.fstatSync(fd);
|
|
318
|
+
if (!stat.isFile() || stat.uid !== process.getuid() || (stat.mode & 0o777) !== 0o600 || stat.dev !== entry.dev || stat.ino !== entry.ino || stat.size > CHECK_METADATA_MAX_BYTES) throw new Error('cannot read check override configuration');
|
|
319
|
+
return parseCheckMetadata(fs.readFileSync(fd, 'utf8'));
|
|
320
|
+
} catch (error) { throw new Error(error.message === 'invalid check metadata JSON' ? error.message : 'cannot read check override configuration'); }
|
|
321
|
+
finally { if (fd !== undefined) fs.closeSync(fd); }
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// Return only a fresh owner-configured definition. Repository metadata can
|
|
325
|
+
// describe checks, but it cannot supply this authority or an owner budget.
|
|
326
|
+
export function ownerCheck(repo, checkId) {
|
|
327
|
+
const data = ownerChecks();
|
|
328
|
+
const check = data?.[repo]?.checks?.[checkId];
|
|
329
|
+
if (!check) return null;
|
|
330
|
+
try { return normalizeCheck(check, checkId); } catch { return null; }
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const repoCheckFile=dir=>hasCheckMetadata(dir,'.dalan.json')?'.dalan.json':'.dot-bridge.json';
|
|
334
|
+
|
|
335
|
+
function overrideCheck(repo, dir, checkId) {
|
|
336
|
+
const ownerFile = overrideFile();
|
|
337
|
+
for (const file of [ownerFile, path.join(dir, repoCheckFile(dir))]) {
|
|
338
|
+
const ownerConfig = file === ownerFile;
|
|
339
|
+
let text;
|
|
340
|
+
if (ownerConfig) {
|
|
341
|
+
if (!fs.existsSync(file)) continue;
|
|
342
|
+
if ((fs.statSync(file).mode & 0o777) !== 0o600) throw new Error('check override file must be mode 0600');
|
|
343
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch { throw new Error('cannot read check override configuration'); }
|
|
344
|
+
} else {
|
|
345
|
+
text = readCheckMetadata(dir, repoCheckFile(dir));
|
|
346
|
+
if (text === null) continue;
|
|
347
|
+
}
|
|
348
|
+
const data = parseCheckMetadata(text);
|
|
349
|
+
const source = ownerConfig ? data[repo] : data;
|
|
350
|
+
if (source?.checks?.[checkId]) {
|
|
351
|
+
try { return { spec: normalizeCheck(source.checks[checkId], checkId), from: ownerConfig ? 'owner_config' : 'workspace_file' }; }
|
|
352
|
+
catch { throw new Error('invalid check metadata'); }
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
return null;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
export function detectCheck(repo, dir, checkId = 'default') { return detectCheckWithOrigin(repo, dir, checkId)?.spec ?? null; }
|
|
359
|
+
|
|
360
|
+
// A repository definition can tighten an owner budget, but its command never
|
|
361
|
+
// supplies host execution authority when an owner definition is required.
|
|
362
|
+
export function workspaceCheck(repo, dir, checkId) {
|
|
363
|
+
const text = readCheckMetadata(dir, repoCheckFile(dir));
|
|
364
|
+
if (text === null) return null;
|
|
365
|
+
const check = parseCheckMetadata(text)?.checks?.[checkId];
|
|
366
|
+
if (!check) return null;
|
|
367
|
+
try { return normalizeCheck(check, checkId); } catch { throw new Error('invalid check metadata'); }
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// Where the resolved definition came from: the owner's checks.json, the checkout's own .dot-bridge.json, or detection from repo files.
|
|
371
|
+
export function detectCheckWithOrigin(repo, dir, checkId = 'default') {
|
|
372
|
+
const override = overrideCheck(repo, dir, checkId);
|
|
373
|
+
if (override) return override;
|
|
374
|
+
const spec = detectFromFiles(dir, checkId);
|
|
375
|
+
return spec ? { spec, from: 'detected' } : null;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function detectFromFiles(dir, checkId) {
|
|
379
|
+
if (checkId !== 'default') return null;
|
|
380
|
+
const packageText = readCheckMetadata(dir, 'package.json');
|
|
381
|
+
if (packageText !== null) {
|
|
382
|
+
const pkg = parseCheckMetadata(packageText);
|
|
383
|
+
if (pkg.scripts?.test) {
|
|
384
|
+
const manager = packageManager(dir);
|
|
385
|
+
const hasLockfile = ['package-lock.json', 'pnpm-lock.yaml', 'yarn.lock'].some(file => hasCheckMetadata(dir, file));
|
|
386
|
+
const install_argv = hasPackageDependencies(pkg) || hasLockfile
|
|
387
|
+
? manager === 'pnpm' ? ['pnpm', 'install', '--frozen-lockfile', '--ignore-scripts']
|
|
388
|
+
: manager === 'yarn' ? ['yarn', 'install', '--frozen-lockfile', '--ignore-scripts']
|
|
389
|
+
: hasCheckMetadata(dir, 'package-lock.json') ? ['/runtime/node', '/runtime/npm/bin/npm-cli.js', 'ci', '--ignore-scripts']
|
|
390
|
+
: ['/runtime/node', '/runtime/npm/bin/npm-cli.js', 'install', '--ignore-scripts', '--package-lock=false']
|
|
391
|
+
: null;
|
|
392
|
+
const engines = /^\s*>=\s*(\d+(?:\.\d+)*)\s*$/.exec(pkg.engines?.node ?? '');
|
|
393
|
+
const lockfile = manager === 'pnpm' ? 'pnpm-lock.yaml' : manager === 'yarn' ? 'yarn.lock' : install_argv?.includes('ci') ? 'package-lock.json' : null;
|
|
394
|
+
const paths = scriptTestPaths(pkg.scripts.test);
|
|
395
|
+
return normalizeCheck({ argv: manager === 'npm' ? ['/runtime/node', '/runtime/npm/bin/npm-cli.js', 'test'] : [manager, 'test'], install_argv }, 'default', {
|
|
396
|
+
prerequisites: { binaries: manager === 'npm' ? [] : [manager], lockfile, runtime: engines ? `node>=${engines[1]}` : null },
|
|
397
|
+
test_paths: paths, test_paths_reason: 'package.json test script names no files or directories' });
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
const pyproject = readCheckMetadata(dir, 'pyproject.toml');
|
|
401
|
+
const pytest = readCheckMetadata(dir, 'pytest.ini');
|
|
402
|
+
if (pyproject !== null || pytest !== null) {
|
|
403
|
+
const paths = pytestPaths(dir);
|
|
404
|
+
return normalizeCheck({ install_argv: ['uv', 'sync'], argv: ['uv', 'run', 'pytest'] }, 'default', { prerequisites: { binaries: ['uv'], lockfile: null, runtime: null }, test_paths: paths.length ? paths : null, test_paths_reason: 'no pytest testpaths configured' });
|
|
405
|
+
}
|
|
406
|
+
if (hasCheckMetadata(dir, 'Cargo.toml')) return normalizeCheck({ install_argv: ['cargo', 'fetch'], argv: ['cargo', 'test'] }, 'default', { prerequisites: { binaries: ['cargo'], lockfile: null, runtime: null }, test_paths: ['tests'] });
|
|
407
|
+
if (hasCheckMetadata(dir, 'go.mod')) return normalizeCheck({ install_argv: ['go', 'mod', 'download'], argv: ['go', 'test', './...'] }, 'default', { prerequisites: { binaries: ['go'], lockfile: null, runtime: null }, test_paths: ['./...'] });
|
|
408
|
+
const makefile = readCheckMetadata(dir, 'Makefile');
|
|
409
|
+
if (makefile !== null && /^test:/m.test(makefile)) return normalizeCheck({ argv: ['make', 'test'] }, 'default', { prerequisites: { binaries: ['make'], lockfile: null, runtime: null }, test_paths_reason: 'Makefile test target does not name test paths' });
|
|
410
|
+
return null;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
export function availableChecks(repo, dir) {
|
|
414
|
+
const ids = new Set();
|
|
415
|
+
const ownerFile = overrideFile();
|
|
416
|
+
for (const file of [ownerFile, path.join(dir, repoCheckFile(dir))]) {
|
|
417
|
+
const ownerConfig = file === ownerFile;
|
|
418
|
+
let text;
|
|
419
|
+
if (ownerConfig) {
|
|
420
|
+
if (!fs.existsSync(file)) continue;
|
|
421
|
+
if ((fs.statSync(file).mode & 0o777) !== 0o600) throw new Error('check override file must be mode 0600');
|
|
422
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch { throw new Error('cannot read check override configuration'); }
|
|
423
|
+
} else {
|
|
424
|
+
text = readCheckMetadata(dir, repoCheckFile(dir));
|
|
425
|
+
if (text === null) continue;
|
|
426
|
+
}
|
|
427
|
+
let source;
|
|
428
|
+
try {
|
|
429
|
+
const data = parseCheckMetadata(text);
|
|
430
|
+
source = ownerConfig ? data[repo] : data;
|
|
431
|
+
for (const [id, check] of Object.entries(source?.checks || {})) {
|
|
432
|
+
normalizeCheck(check, id);
|
|
433
|
+
ids.add(id);
|
|
434
|
+
}
|
|
435
|
+
} catch {
|
|
436
|
+
throw new Error('invalid check metadata');
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
if (detectCheck(repo, dir, 'default')) ids.add('default');
|
|
440
|
+
return [...ids].sort();
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// Check metadata at a pinned commit, read with `git show` into a temp dir (no worktree). Calls fn(dir).
|
|
444
|
+
export function withCheckMetadata(mirror, sha, fn) {
|
|
445
|
+
const caches = path.join(workspaceRoot(), 'caches');
|
|
446
|
+
fs.mkdirSync(caches, { recursive: true, mode: 0o700 });
|
|
447
|
+
const dir = fs.mkdtempSync(path.join(caches, 'check-metadata-'));
|
|
448
|
+
try {
|
|
449
|
+
const entries = spawnSync('git', ['-C', mirror, 'ls-tree', '-z', '--full-tree', sha, '--', ...checkMetadataFiles], { encoding: 'utf8', timeout: 10000, maxBuffer: 1024 * 1024, env: gitEnv() });
|
|
450
|
+
if (entries.error || entries.status !== 0) throw new Error('cannot inspect pinned check metadata');
|
|
451
|
+
const pinnedFiles = new Set();
|
|
452
|
+
for (const entry of entries.stdout.split('\0')) {
|
|
453
|
+
if (!entry) continue;
|
|
454
|
+
const separator = entry.indexOf('\t');
|
|
455
|
+
if (separator < 0) throw new Error('cannot inspect pinned check metadata');
|
|
456
|
+
const [mode] = entry.slice(0, separator).split(' ');
|
|
457
|
+
const file = entry.slice(separator + 1);
|
|
458
|
+
if (!checkMetadataFiles.has(file)) continue;
|
|
459
|
+
if (mode !== '100644' && mode !== '100755') throw new Error('check metadata must be a regular file');
|
|
460
|
+
pinnedFiles.add(file);
|
|
461
|
+
}
|
|
462
|
+
for (const file of checkMetadataFiles) {
|
|
463
|
+
if (!pinnedFiles.has(file)) continue;
|
|
464
|
+
const found = spawnSync('git', ['-C', mirror, 'show', `${sha}:${file}`], { encoding: 'utf8', timeout: 10000, maxBuffer: 1024 * 1024, env: gitEnv() });
|
|
465
|
+
if (found.status === 0) fs.writeFileSync(path.join(dir, file), found.stdout);
|
|
466
|
+
else throw new Error(`cannot read check metadata: ${file}`);
|
|
467
|
+
}
|
|
468
|
+
return fn(dir);
|
|
469
|
+
} finally { fs.rmSync(dir, { recursive: true, force: true }); }
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// Every check spec (id -> normalized spec) at a pinned commit.
|
|
473
|
+
export function checkSpecsAt(repo, mirror, sha) {
|
|
474
|
+
return withCheckMetadata(mirror, sha, dir => Object.fromEntries(availableChecks(repo, dir).map(id => [id, detectCheck(repo, dir, id)])));
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
export function requireGithubAvailable() {
|
|
478
|
+
try { execFileSync('git', ['--version'], { stdio: 'ignore', timeout: 5000 }); }
|
|
479
|
+
catch { throw new Error('git unavailable for GitHub workspace operation'); }
|
|
480
|
+
}
|