@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.
- package/CHANGELOG.md +172 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +339 -0
- package/README.md +348 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +38 -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 +755 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/connect-chatgpt.md +78 -0
- package/docs/connection-longevity.md +37 -0
- package/docs/dalan-upgrade.md +242 -0
- package/docs/deadman.md +59 -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 +39 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +98 -0
- package/docs/operations.md +751 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +109 -0
- package/docs/pr-head-reviewer.md +54 -0
- package/docs/pr-preflight.md +26 -0
- package/docs/pull-workers.md +97 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +166 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +49 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +439 -0
- package/docs/worker-clients.md +285 -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 +65 -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/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 +412 -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 +497 -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/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +172 -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-slot.mjs +53 -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 +70 -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/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/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/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 +1340 -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 +3057 -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 +451 -0
- package/src/try-command.mjs +11 -0
- package/src/try.mjs +589 -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 +622 -0
- package/src/workspace.mjs +1058 -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,164 @@
|
|
|
1
|
+
"""Kernel ownership and platform-specific settlement for a private mirror fetch.
|
|
2
|
+
|
|
3
|
+
The lock inode is permanent. Never unlink it: another opener may already hold it.
|
|
4
|
+
The single-threaded guardian never reaps a child between enumerating and signaling
|
|
5
|
+
it, so a child PID cannot be recycled in that interval.
|
|
6
|
+
"""
|
|
7
|
+
import ctypes
|
|
8
|
+
import fcntl
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import shutil
|
|
12
|
+
import signal
|
|
13
|
+
import select
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def run():
|
|
20
|
+
request = sys.stdin.buffer.read()
|
|
21
|
+
mirror = json.loads(request)['mirror']
|
|
22
|
+
attempt = mirror + '.fetch-lock'
|
|
23
|
+
fd = os.open(mirror + '.fetch-mutex', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
|
24
|
+
try:
|
|
25
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
26
|
+
except BlockingIOError:
|
|
27
|
+
raise RuntimeError('mirror fetch already in progress (kernel lock held)')
|
|
28
|
+
expected = json.dumps({'version': 1, 'mirror': mirror}).encode()
|
|
29
|
+
receipt_path = mirror + '.fetch-owner.json'
|
|
30
|
+
try:
|
|
31
|
+
with open(receipt_path, 'rb') as source:
|
|
32
|
+
receipt = source.read(4096)
|
|
33
|
+
except FileNotFoundError:
|
|
34
|
+
receipt = None
|
|
35
|
+
if receipt is None and not os.path.exists(attempt):
|
|
36
|
+
# Publish atomically before creating any disposable state. An interrupted
|
|
37
|
+
# publication has no attempt to clean; the next owner can repeat it.
|
|
38
|
+
with open(receipt_path + '.new', 'wb') as target:
|
|
39
|
+
os.chmod(target.fileno(), 0o600)
|
|
40
|
+
target.write(expected)
|
|
41
|
+
target.flush()
|
|
42
|
+
os.fsync(target.fileno())
|
|
43
|
+
os.replace(receipt_path + '.new', receipt_path)
|
|
44
|
+
parent_fd = os.open(os.path.dirname(mirror), os.O_RDONLY | os.O_DIRECTORY)
|
|
45
|
+
os.fsync(parent_fd)
|
|
46
|
+
os.close(parent_fd)
|
|
47
|
+
elif receipt != expected:
|
|
48
|
+
raise RuntimeError('mirror fetch ownership receipt missing or corrupt; private attempt left untouched')
|
|
49
|
+
# Acquiring flock proves all previous cooperating owners have closed it.
|
|
50
|
+
# Set subreaper BEFORE spawning: orphan Git descendants become our children.
|
|
51
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
52
|
+
if sys.platform == 'linux' and libc.prctl(36, 1, 0, 0, 0) != 0: # PR_SET_CHILD_SUBREAPER
|
|
53
|
+
raise OSError(ctypes.get_errno(), 'cannot establish mirror fetch subreaper')
|
|
54
|
+
# The live anchor and actual Git stderr descriptors retain this separate
|
|
55
|
+
# barrier even if both the guardian and Node die. Never clean a live writer.
|
|
56
|
+
settle(mirror, nonblocking=True)
|
|
57
|
+
if os.path.exists(attempt):
|
|
58
|
+
shutil.rmtree(attempt)
|
|
59
|
+
child = subprocess.Popen([sys.argv[1], sys.argv[2], '--owned-fetch', str(fd)],
|
|
60
|
+
stdin=subprocess.PIPE, pass_fds=(fd,),
|
|
61
|
+
start_new_session=sys.platform == 'darwin')
|
|
62
|
+
child.stdin.write(request)
|
|
63
|
+
child.stdin.close()
|
|
64
|
+
if sys.platform == 'darwin':
|
|
65
|
+
# NOTE_EXIT observes without waitpid/reaping. Our unreaped direct child
|
|
66
|
+
# pins the PGID until the final signal, including synchronous Git calls.
|
|
67
|
+
queue = select.kqueue()
|
|
68
|
+
event = select.kevent(child.pid, filter=select.KQ_FILTER_PROC,
|
|
69
|
+
flags=select.KQ_EV_ADD | select.KQ_EV_ONESHOT,
|
|
70
|
+
fflags=select.KQ_NOTE_EXIT)
|
|
71
|
+
queue.control([event], 1, None)
|
|
72
|
+
queue.close()
|
|
73
|
+
try:
|
|
74
|
+
os.killpg(child.pid, signal.SIGKILL)
|
|
75
|
+
except (ProcessLookupError, PermissionError):
|
|
76
|
+
# Darwin returns EPERM for an all-zombie group. This signal is
|
|
77
|
+
# best effort; inherited flock descriptions remain the cleanup
|
|
78
|
+
# authority even if a member cannot be signaled.
|
|
79
|
+
pass
|
|
80
|
+
code = child.wait()
|
|
81
|
+
settle(mirror)
|
|
82
|
+
# Node may have been SIGKILLed with detached Git grandchildren still writing.
|
|
83
|
+
# Keep flock until every descendant is reaped, including orphan grandchildren.
|
|
84
|
+
deadline = time.monotonic() + 5
|
|
85
|
+
warned = False
|
|
86
|
+
while sys.platform == 'linux':
|
|
87
|
+
try:
|
|
88
|
+
while os.waitpid(-1, os.WNOHANG)[0]:
|
|
89
|
+
pass
|
|
90
|
+
except ChildProcessError:
|
|
91
|
+
break
|
|
92
|
+
children = open(f'/proc/self/task/{os.getpid()}/children').read().split()
|
|
93
|
+
for pid in children:
|
|
94
|
+
os.kill(int(pid), signal.SIGKILL)
|
|
95
|
+
if time.monotonic() > deadline and not warned:
|
|
96
|
+
print('mirror fetch children still settling; kernel lock remains held', file=sys.stderr)
|
|
97
|
+
warned = True
|
|
98
|
+
time.sleep(.01)
|
|
99
|
+
os.close(fd)
|
|
100
|
+
return code if code >= 0 else 1
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def settle(mirror, nonblocking=False):
|
|
104
|
+
fd = os.open(mirror + '.fetch-writers', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
|
105
|
+
try:
|
|
106
|
+
fcntl.flock(fd, fcntl.LOCK_EX | (fcntl.LOCK_NB if nonblocking else 0))
|
|
107
|
+
except BlockingIOError:
|
|
108
|
+
raise RuntimeError('mirror fetch already in progress (writers still settling)')
|
|
109
|
+
finally:
|
|
110
|
+
os.close(fd)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def anchor():
|
|
114
|
+
"""One fetch group on either supported OS, anchored until its final group-wide SIGKILL.
|
|
115
|
+
|
|
116
|
+
Only Node retains the control pipe's write end; Git receives /dev/null.
|
|
117
|
+
The anchor survives loss of Node and its guardian and detects pipe EOF.
|
|
118
|
+
Git's stderr IS the writer lock's open description, not a PID receipt.
|
|
119
|
+
"""
|
|
120
|
+
mirror, timeout, inherited = sys.argv[2:5]
|
|
121
|
+
fd = os.open(mirror + '.fetch-writers', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
|
122
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
123
|
+
os.ftruncate(fd, 0)
|
|
124
|
+
child = None
|
|
125
|
+
try:
|
|
126
|
+
child = subprocess.Popen(sys.argv[5:], stdin=subprocess.DEVNULL,
|
|
127
|
+
stdout=subprocess.DEVNULL, stderr=fd,
|
|
128
|
+
pass_fds=(int(inherited), fd))
|
|
129
|
+
deadline = time.monotonic() + float(timeout) / 1000
|
|
130
|
+
timed_out = False
|
|
131
|
+
while child.poll() is None:
|
|
132
|
+
if select.select([0], [], [], .02)[0] and not os.read(0, 1):
|
|
133
|
+
return
|
|
134
|
+
if time.monotonic() >= deadline:
|
|
135
|
+
timed_out = True
|
|
136
|
+
break
|
|
137
|
+
# Output is a result, not settlement authority. The caller must acquire
|
|
138
|
+
# the independent writer barrier after this anchor has killed its group.
|
|
139
|
+
os.lseek(fd, max(0, os.lseek(fd, 0, os.SEEK_END) - 8192), os.SEEK_SET)
|
|
140
|
+
print(json.dumps({'code': child.returncode, 'timedOut': timed_out,
|
|
141
|
+
'stderr': os.read(fd, 8192).decode(errors='replace')}), flush=True)
|
|
142
|
+
finally:
|
|
143
|
+
# Our live PID pins the group identity. Do not reap/exit this anchor and
|
|
144
|
+
# later signal a recorded PGID, which could have been reused.
|
|
145
|
+
os.killpg(os.getpid(), signal.SIGKILL)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
try:
|
|
149
|
+
if sys.platform not in ('linux', 'darwin'):
|
|
150
|
+
raise RuntimeError('mirror fetch requires Linux or macOS')
|
|
151
|
+
if sys.argv[1] == '--check':
|
|
152
|
+
if sys.version_info < (3, 8):
|
|
153
|
+
raise RuntimeError('Python 3.8 or newer required')
|
|
154
|
+
sys.exit(0)
|
|
155
|
+
if sys.argv[1] == '--settle':
|
|
156
|
+
settle(sys.argv[2])
|
|
157
|
+
sys.exit(0)
|
|
158
|
+
if sys.argv[1] == '--anchor':
|
|
159
|
+
anchor()
|
|
160
|
+
else:
|
|
161
|
+
sys.exit(run())
|
|
162
|
+
except Exception as error:
|
|
163
|
+
print(str(error), file=sys.stderr)
|
|
164
|
+
sys.exit(1)
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// A fetch owns a private object store. Publish complete objects before refs so
|
|
2
|
+
// reference clones and live worktrees never depend on disposable attempt files.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
7
|
+
import { gitEnv } from './git-env.mjs';
|
|
8
|
+
|
|
9
|
+
const file = fileURLToPath(import.meta.url);
|
|
10
|
+
const guardianFile = fileURLToPath(new URL('./mirror-fetch-lock.py', import.meta.url));
|
|
11
|
+
let lockFd;
|
|
12
|
+
const inheritedLock = () => lockFd === undefined ? [] : Array.from({ length: lockFd - 2 }, (_, i) => i + 3 === lockFd ? lockFd : 'ignore');
|
|
13
|
+
const retention = ['-c', 'gc.auto=0', '-c', 'maintenance.auto=false', '-c', 'gc.autoDetach=false'];
|
|
14
|
+
const corrupt = /unresolved deltas|unpack-objects failed|index-pack failed|missing (?:blob|tree|commit) object|did not send all necessary objects|bad object|is corrupt/i;
|
|
15
|
+
|
|
16
|
+
export function fetchMirror(mirror, url, env, timeoutMs = 900000, revisions = null, { refetch = false } = {}) {
|
|
17
|
+
if(revisions!==null&&(!Array.isArray(revisions)||!revisions.length||revisions.some(sha=>typeof sha!=='string'||!/^[a-f0-9]{40}$/.test(sha)))) throw new Error('full pinned revisions required');
|
|
18
|
+
const result = spawnSync(process.execPath, [file, '--fetch'], {
|
|
19
|
+
input: JSON.stringify({ mirror, url, timeoutMs, revisions, refetch: refetch === true }), env: gitEnv(env), encoding: 'utf8', maxBuffer: 1024 * 1024,
|
|
20
|
+
});
|
|
21
|
+
// Repair notices must survive a later fetch failure as well as success.
|
|
22
|
+
for (const line of String(result.stderr || '').split('\n')) {
|
|
23
|
+
if (line.startsWith('mirror repair: ')) console.error(line);
|
|
24
|
+
}
|
|
25
|
+
if (result.error || result.status !== 0) {
|
|
26
|
+
const message = String(result.stderr || result.error?.message || 'fetch supervisor failed').replace(/https:\/\/[^/@\s]+@/g, 'https://<redacted>@');
|
|
27
|
+
throw new Error(`git failed: ${message.slice(0, 1000)}`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function git(args, input) {
|
|
32
|
+
const result = spawnSync('git', [...retention, ...args], { input, stdio: ['pipe', 'pipe', 'pipe', ...inheritedLock()], encoding: 'utf8', timeout: 30000, maxBuffer: 12 * 1024 * 1024 });
|
|
33
|
+
if (result.error || result.status !== 0) throw new Error(result.stderr || result.error?.message || 'git failed');
|
|
34
|
+
return result.stdout;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function fetch(args, timeoutMs, state) {
|
|
38
|
+
const mirror = path.dirname(args[1]).slice(0, -'.fetch-lock'.length);
|
|
39
|
+
const child = spawn('python3', [guardianFile, '--anchor', mirror, String(timeoutMs), String(lockFd), 'git', ...retention, ...args], {
|
|
40
|
+
detached: true, stdio: ['pipe', 'pipe', 'pipe', ...inheritedLock()],
|
|
41
|
+
});
|
|
42
|
+
// Keep this pipe open for exactly Node's lifetime. Git cannot inherit it.
|
|
43
|
+
child.stdin.on('error', () => {});
|
|
44
|
+
let output = '', errors = '';
|
|
45
|
+
child.stdout.on('data', data => { output += data; });
|
|
46
|
+
child.stderr.on('data', data => { errors = (errors + data).slice(-8192); });
|
|
47
|
+
await new Promise((resolve, reject) => { child.once('error', reject); child.once('close', resolve); });
|
|
48
|
+
const barrier = spawnSync('python3', [guardianFile, '--settle', mirror], { timeout: 5000, encoding: 'utf8' });
|
|
49
|
+
if (barrier.error || barrier.status !== 0) {
|
|
50
|
+
state.settled = false;
|
|
51
|
+
throw new Error('fetch writers still settling; attempt retained');
|
|
52
|
+
}
|
|
53
|
+
let result;
|
|
54
|
+
try { result = JSON.parse(output); } catch { throw new Error(errors || 'fetch anchor failed'); }
|
|
55
|
+
if (result.timedOut) throw new Error('mirror fetch timed out');
|
|
56
|
+
if (result.code !== 0) throw new Error(result.stderr || `fetch exited ${result.code}`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function publishObjects(source, target) {
|
|
60
|
+
for (const dir of fs.readdirSync(source)) {
|
|
61
|
+
if (dir !== 'pack' && !/^[a-f0-9]{2}$/.test(dir)) continue;
|
|
62
|
+
fs.mkdirSync(path.join(target, dir), { recursive: true });
|
|
63
|
+
for (const name of fs.readdirSync(path.join(source, dir))) {
|
|
64
|
+
if (dir === 'pack' && !/^pack-[a-f0-9]+\.(pack|idx|rev)$/.test(name)) continue;
|
|
65
|
+
if (dir !== 'pack' && !/^[a-f0-9]{38}$/.test(name)) continue;
|
|
66
|
+
try { fs.linkSync(path.join(source, dir, name), path.join(target, dir, name)); }
|
|
67
|
+
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Returns the listing of the refs that remain, in `for-each-ref` format.
|
|
73
|
+
function removeMissingRefs(mirror, refs) {
|
|
74
|
+
const entries = refs.split('\n').filter(Boolean).map(line => {
|
|
75
|
+
const match = /^([a-f0-9]{40}) (refs\/[^\t\n]+)\t([^\t\n]*)$/.exec(line);
|
|
76
|
+
if (!match) throw new Error('invalid mirror ref listing');
|
|
77
|
+
return { oid: match[1], ref: match[2], symbolic: Boolean(match[3]), line: match[1] + ' ' + match[2] };
|
|
78
|
+
});
|
|
79
|
+
if (!entries.length) return '';
|
|
80
|
+
const result = git(['-C', mirror, 'cat-file', '--batch-check=%(objectname) %(objecttype)'],
|
|
81
|
+
entries.map(entry => entry.oid).join('\n') + '\n').trimEnd().split('\n');
|
|
82
|
+
if (result.length !== entries.length) throw new Error('incomplete mirror object check');
|
|
83
|
+
const missing = new Set();
|
|
84
|
+
const healthy = [];
|
|
85
|
+
entries.forEach((entry, index) => {
|
|
86
|
+
if (result[index] === entry.oid + ' missing') { if (!entry.symbolic) missing.add(entry.ref); }
|
|
87
|
+
else if (new RegExp('^' + entry.oid + ' (commit|tree|blob|tag)$').test(result[index])) healthy.push(entry.line);
|
|
88
|
+
else throw new Error('unexpected mirror object check result');
|
|
89
|
+
});
|
|
90
|
+
if (missing.size) {
|
|
91
|
+
const commands = ['start'];
|
|
92
|
+
for (const entry of entries) if (missing.has(entry.ref)) commands.push(`delete ${entry.ref} ${entry.oid}`);
|
|
93
|
+
commands.push('prepare', 'commit', '');
|
|
94
|
+
git(['-C', mirror, 'update-ref', '--stdin'], commands.join('\n'));
|
|
95
|
+
console.error(`mirror repair: deleted ${missing.size} missing-object refs`);
|
|
96
|
+
for (const ref of [...missing].slice(0, 20)) console.error('mirror repair: deleted missing-object ref ' + JSON.stringify(ref));
|
|
97
|
+
if (missing.size > 20) console.error(`mirror repair: ... and ${missing.size - 20} more`);
|
|
98
|
+
}
|
|
99
|
+
return healthy.length ? healthy.join('\n') + '\n' : '';
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function prepare({ mirror, url, timeoutMs, revisions = null, refetch = false }) {
|
|
103
|
+
if(revisions!==null&&(!Array.isArray(revisions)||!revisions.length||revisions.some(sha=>typeof sha!=='string'||!/^[a-f0-9]{40}$/.test(sha)))) throw new Error('full pinned revisions required');
|
|
104
|
+
const deadline=performance.now()+timeoutMs;
|
|
105
|
+
const remaining=()=>{const ms=Math.floor(deadline-performance.now());if(ms<=0)throw new Error('mirror fetch timed out');return ms;};
|
|
106
|
+
const lock = mirror + '.fetch-lock';
|
|
107
|
+
fs.mkdirSync(lock, { mode: 0o700 });
|
|
108
|
+
const state = { settled: true };
|
|
109
|
+
try {
|
|
110
|
+
fs.writeFileSync(path.join(lock, 'owner.json'), JSON.stringify({ pid: process.pid, guardian: process.ppid, mirror }), { mode: 0o600 });
|
|
111
|
+
// A mirror directory that lost HEAD or config is not a repository to git, but its objects and refs are intact.
|
|
112
|
+
// `git init --bare` on an existing directory only adds what is missing, so it repairs the mirror in place.
|
|
113
|
+
if (!fs.existsSync(mirror) || !fs.existsSync(path.join(mirror, 'HEAD')) || !fs.existsSync(path.join(mirror, 'config'))) {
|
|
114
|
+
const repairing = fs.existsSync(mirror);
|
|
115
|
+
git(['init', '--bare', mirror]);
|
|
116
|
+
if (repairing) console.error('mirror repair: re-initialised a mirror without HEAD or config');
|
|
117
|
+
}
|
|
118
|
+
if (git(['-C', mirror, 'remote']).trim().split('\n').includes('origin')) git(['-C', mirror, 'remote', 'remove', 'origin']);
|
|
119
|
+
for (const [key, value] of [['gc.auto', '0'], ['maintenance.auto', 'false'], ['gc.autoDetach', 'false']]) git(['-C', mirror, 'config', '--local', key, value]);
|
|
120
|
+
const stage = path.join(lock, 'repo.git');
|
|
121
|
+
git(['init', '--bare', stage]);
|
|
122
|
+
// Carry bridge-owned settings (notably fetch.unpackLimit) into the attempt.
|
|
123
|
+
// Local retention settings also protect consumers between bridge invocations.
|
|
124
|
+
fs.copyFileSync(path.join(mirror, 'config'), path.join(stage, 'config'));
|
|
125
|
+
fs.writeFileSync(path.join(stage, 'objects/info/alternates'), path.join(mirror, 'objects') + '\n');
|
|
126
|
+
// A ref whose object is missing makes every fetch fail connectivity checks with "bad object".
|
|
127
|
+
// Delete only those refs, in the mirror itself and under the fetch lock: Git also advertises refs
|
|
128
|
+
// from the alternate object store, not only the stage's packed-refs. The fetch below restores
|
|
129
|
+
// whatever the caller needs.
|
|
130
|
+
const refs = removeMissingRefs(mirror, git(['-C', mirror, 'for-each-ref', '--format=%(objectname) %(refname)%09%(symref)']));
|
|
131
|
+
fs.writeFileSync(path.join(stage, 'packed-refs'), '# pack-refs with: sorted\n' + refs);
|
|
132
|
+
// A job names immutable commits, not every branch/tag/PR in the repository.
|
|
133
|
+
// Keep prior refs seeded above; only the requested pins may change here.
|
|
134
|
+
const selection=revisions===null?['--prune',url,'+refs/heads/*:refs/heads/*','+refs/tags/*:refs/tags/*','+refs/pull/*/head:refs/pull/*/head']:['--no-tags',url,...[...new Set(revisions)].map(sha=>`+${sha}:refs/dot-bridge/pins/${sha}`)];
|
|
135
|
+
// refetch: the caller proved the mirror lacks objects under a pin; ignore what it claims to have.
|
|
136
|
+
const args = ['-C', stage, 'fetch', '--no-auto-maintenance', ...(refetch === true ? ['--refetch'] : []), ...selection];
|
|
137
|
+
try { await fetch(args, remaining(), state); }
|
|
138
|
+
catch (error) {
|
|
139
|
+
if (!state.settled || refetch === true || !corrupt.test(error.message)) throw error;
|
|
140
|
+
await fetch([...args.slice(0, 3), '--refetch', ...args.slice(3)], remaining(), state);
|
|
141
|
+
}
|
|
142
|
+
publishObjects(path.join(stage, 'objects'), path.join(mirror, 'objects'));
|
|
143
|
+
const after = git(['-C', stage, 'for-each-ref', '--format=%(objectname) %(refname)']);
|
|
144
|
+
const old = new Map(refs.split('\n').filter(Boolean).map(line => { const [sha, ref] = line.split(' '); return [ref, sha]; }));
|
|
145
|
+
const commands = ['start'];
|
|
146
|
+
for (const line of after.split('\n').filter(Boolean)) {
|
|
147
|
+
const [sha, ref] = line.split(' ');
|
|
148
|
+
commands.push(`update ${ref} ${sha} ${old.get(ref) || '0'.repeat(40)}`); old.delete(ref);
|
|
149
|
+
}
|
|
150
|
+
for (const [ref, sha] of old) commands.push(`delete ${ref} ${sha}`);
|
|
151
|
+
commands.push('prepare', 'commit', '');
|
|
152
|
+
git(['-C', mirror, 'update-ref', '--stdin'], commands.join('\n'));
|
|
153
|
+
} finally {
|
|
154
|
+
if (state.settled) fs.rmSync(lock, { recursive: true, force: true });
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (process.argv[1] === file && process.argv[2] === '--fetch') {
|
|
159
|
+
const check = spawnSync('python3', [guardianFile, '--check'], { encoding: 'utf8' });
|
|
160
|
+
if (check.error || check.status !== 0) {
|
|
161
|
+
console.error('Mirror fetch requires Python 3.8+ on Linux or macOS. Install Python 3 and put python3 on the bridge service PATH, then retry. ' + (check.stderr || check.error?.message || ''));
|
|
162
|
+
process.exit(1);
|
|
163
|
+
}
|
|
164
|
+
const result = spawnSync('python3', [guardianFile, process.execPath, file], {
|
|
165
|
+
input: fs.readFileSync(0), stdio: ['pipe', 'inherit', 'inherit'],
|
|
166
|
+
});
|
|
167
|
+
if (result.error) console.error(result.error.message);
|
|
168
|
+
process.exitCode = result.status ?? 1;
|
|
169
|
+
}
|
|
170
|
+
if (process.argv[1] === file && process.argv[2] === '--owned-fetch') {
|
|
171
|
+
lockFd = Number(process.argv[3]);
|
|
172
|
+
try { await prepare(JSON.parse(fs.readFileSync(0, 'utf8'))); }
|
|
173
|
+
catch (error) { console.error(error.message); process.exitCode = 1; }
|
|
174
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
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 META_KEY='dot-bridge/idempotencyKey';
|
|
7
|
+
|
|
8
|
+
// Validate before argument auditing; metadata never enters argument summaries.
|
|
9
|
+
export function notifyKey(meta) {
|
|
10
|
+
if(meta===undefined||meta===null) return undefined;
|
|
11
|
+
if(typeof meta!=='object'||Array.isArray(meta)) throw new Error('invalid notification metadata');
|
|
12
|
+
if(!Object.hasOwn(meta,META_KEY)) return undefined;
|
|
13
|
+
const key=meta[META_KEY];
|
|
14
|
+
if(typeof key!=='string'||!key.trim()||key.length>256) throw new Error('invalid notification idempotency key');
|
|
15
|
+
return key;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Positive results only; outside J3, with no cross-process or crash exactly-once claim.
|
|
19
|
+
export class NotifyLedger {
|
|
20
|
+
constructor(file) {
|
|
21
|
+
fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});
|
|
22
|
+
if(!fs.existsSync(file)) { const fd=fs.openSync(file,'wx',0o600); fs.closeSync(fd); }
|
|
23
|
+
const stat=fs.lstatSync(file);
|
|
24
|
+
if(!stat.isFile()||(stat.mode&0o777)!==0o600) throw new Error('notification ledger must be a regular mode 0600 file');
|
|
25
|
+
this.db=new DatabaseSync(file);
|
|
26
|
+
this.inFlight=new Map();
|
|
27
|
+
try {
|
|
28
|
+
this.db.exec('PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS sent(key_sha256 TEXT PRIMARY KEY,result_json TEXT,state TEXT NOT NULL DEFAULT \'delivered\',sent_at INTEGER NOT NULL,reconcile_evidence TEXT) WITHOUT ROWID;');
|
|
29
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('sent') WHERE name='state'").get()) this.db.exec("ALTER TABLE sent ADD COLUMN state TEXT NOT NULL DEFAULT 'delivered'");
|
|
30
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('sent') WHERE name='reconcile_evidence'").get()) this.db.exec('ALTER TABLE sent ADD COLUMN reconcile_evidence TEXT');
|
|
31
|
+
if(this.db.prepare('PRAGMA integrity_check').get().integrity_check!=='ok') throw new Error('integrity check failed');
|
|
32
|
+
} catch(error) { this.db.close(); throw new Error('notification ledger unavailable',{cause:error}); }
|
|
33
|
+
}
|
|
34
|
+
pending() { return this.db.prepare("SELECT key_sha256,sent_at FROM sent WHERE state='pending' ORDER BY sent_at,key_sha256").all().map(row=>({key_sha256:row.key_sha256,reserved_at:row.sent_at})); }
|
|
35
|
+
reconcile({key_sha256,outcome,evidence}) {
|
|
36
|
+
if(typeof key_sha256!=='string'||!/^[a-f0-9]{64}$/.test(key_sha256)||!['sent','unsent'].includes(outcome)||typeof evidence!=='string'||!evidence.trim()||evidence.length>2000) throw new Error('invalid notification reconciliation');
|
|
37
|
+
if(this.inFlight.has(key_sha256)) throw new Error('notification still in flight');
|
|
38
|
+
const evidenceHash=createHash('sha256').update(evidence.trim()).digest('hex');
|
|
39
|
+
const result=outcome==='sent'
|
|
40
|
+
? this.db.prepare("UPDATE sent SET state='delivered',result_json=?,sent_at=?,reconcile_evidence=? WHERE key_sha256=? AND state='pending'").run(JSON.stringify({notified:true}),Date.now(),evidenceHash,key_sha256)
|
|
41
|
+
: this.db.prepare("UPDATE sent SET state='retryable',result_json='{}',reconcile_evidence=? WHERE key_sha256=? AND state='pending'").run(evidenceHash,key_sha256);
|
|
42
|
+
if(result.changes!==1) throw new Error('notification is not pending');
|
|
43
|
+
return {key_sha256,outcome,state:outcome==='sent'?'delivered':'retryable'};
|
|
44
|
+
}
|
|
45
|
+
async send(worker,text,key,publish) {
|
|
46
|
+
const hash=createHash('sha256').update(JSON.stringify([worker,key===undefined?'payload':'caller',key===undefined?text:key])).digest('hex');
|
|
47
|
+
const pending=this.inFlight.get(hash);
|
|
48
|
+
if(pending) return pending;
|
|
49
|
+
// Set the promise before running any cache or network work.
|
|
50
|
+
const promise=Promise.resolve().then(async()=>{
|
|
51
|
+
const row=this.db.prepare('SELECT result_json,state FROM sent WHERE key_sha256=?').get(hash);
|
|
52
|
+
if(row?.state==='pending') throw new Error('uncertain notification: reconcile receiver acceptance before retry');
|
|
53
|
+
if(row?.state==='delivered') {
|
|
54
|
+
const result=JSON.parse(row.result_json);
|
|
55
|
+
if(result?.notified!==true||Object.keys(result).length!==1) throw new Error('invalid notification ledger result');
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
58
|
+
if(row?.state==='retryable') {
|
|
59
|
+
const changed=this.db.prepare("UPDATE sent SET state='pending',result_json='{}',sent_at=?,reconcile_evidence=NULL WHERE key_sha256=? AND state='retryable'").run(Date.now(),hash);
|
|
60
|
+
if(changed.changes!==1) throw new Error('uncertain notification: another sender reserved this key');
|
|
61
|
+
} else {
|
|
62
|
+
const reservation=this.db.prepare("INSERT INTO sent(key_sha256,result_json,state,sent_at) VALUES(?,'{}','pending',?) ON CONFLICT(key_sha256) DO NOTHING").run(hash,Date.now());
|
|
63
|
+
if(reservation.changes!==1) throw new Error('uncertain notification: another sender reserved this key');
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
const published=await publish(hash);
|
|
67
|
+
if(published===false) throw Object.assign(new Error('notification was not accepted'),{notifyOutcome:'not_accepted'});
|
|
68
|
+
const result={notified:true};
|
|
69
|
+
// One synchronous autocommit; never a transaction held across publish.
|
|
70
|
+
this.db.prepare("UPDATE sent SET result_json=?,state='delivered',sent_at=?,reconcile_evidence=NULL WHERE key_sha256=? AND state='pending'").run(JSON.stringify(result),Date.now(),hash);
|
|
71
|
+
return result;
|
|
72
|
+
} catch(error) {
|
|
73
|
+
if(error?.notifyOutcome==='not_accepted') this.db.prepare("UPDATE sent SET state='retryable',reconcile_evidence=? WHERE key_sha256=? AND state='pending'").run(String(error.message).slice(0,2000),hash);
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
this.inFlight.set(hash,promise);
|
|
78
|
+
try { return await promise; }
|
|
79
|
+
finally { if(this.inFlight.get(hash)===promise) this.inFlight.delete(hash); }
|
|
80
|
+
}
|
|
81
|
+
close() { this.db.close(); }
|
|
82
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// Objective identity of an assignment: objective_key, revision, task_kind and the submitter (source). Live submitters send
|
|
2
|
+
// it with /submit; older rows get it only from a tuple that the request_id itself proves (see docs/usage.md, "Metrics").
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { legacyFixLoopName } from './legacy-names.mjs';
|
|
5
|
+
|
|
6
|
+
// Submitter identity stored next to (not inside) the payload. Every manifest is submitted by the drainer, so there is no
|
|
7
|
+
// separate producer source; 'unknown' is for a caller that declares it cannot say.
|
|
8
|
+
// The fix loop was first called by an older name: it is accepted as input and normalized to `fix-loop`, and it stays the
|
|
9
|
+
// stored form of `assignments.source` in databases created before the rename (their CHECK constraint lists it), so no
|
|
10
|
+
// stored row changes there. A database created after the rename stores and allows only `fix-loop`.
|
|
11
|
+
export const fixLoopSource='fix-loop';
|
|
12
|
+
export const objectiveSources=['drainer',fixLoopSource,'agent','unknown'];
|
|
13
|
+
// A database whose stored schema was created before the rename keeps the earlier spelling (its CHECK constraint lists it and
|
|
14
|
+
// SQLite cannot change a CHECK without rebuilding the table). A newer database stores the neutral spelling. `legacy` says which.
|
|
15
|
+
export const toStoredSource=(source,legacy=true)=>legacy&&source===fixLoopSource?legacyFixLoopName:source;
|
|
16
|
+
export const fromStoredSource=source=>source===legacyFixLoopName?fixLoopSource:source;
|
|
17
|
+
// The earlier spelling also prefixes stored objective keys and task kinds. Rows keep what they were written with; every
|
|
18
|
+
// comparison and report reads both spellings as one.
|
|
19
|
+
export const canonicalObjectiveKey=key=>typeof key==='string'&&key.startsWith(`${legacyFixLoopName}:`)?`${fixLoopSource}${key.slice(legacyFixLoopName.length)}`:key;
|
|
20
|
+
export const canonicalTaskKind=kind=>kind===legacyFixLoopName?fixLoopSource:kind;
|
|
21
|
+
// A "kind/priority" label (or a bare kind) as the metrics report it.
|
|
22
|
+
export const canonicalKindLabel=label=>typeof label==='string'&&(label===legacyFixLoopName||label.startsWith(`${legacyFixLoopName}/`))?`${fixLoopSource}${label.slice(legacyFixLoopName.length)}`:label;
|
|
23
|
+
// SQL for the same mapping over a kind expression.
|
|
24
|
+
export const canonicalKindSql=expr=>`CASE WHEN (${expr})='${legacyFixLoopName}' THEN '${fixLoopSource}' ELSE (${expr}) END`;
|
|
25
|
+
// The reverse mapping, for hashes that were persisted under the earlier spelling.
|
|
26
|
+
export const storedObjectiveKey=(key,legacy=true)=>legacy&&typeof key==='string'&&key.startsWith(`${fixLoopSource}:`)?`${legacyFixLoopName}${key.slice(fixLoopSource.length)}`:key;
|
|
27
|
+
export const storedTaskKind=(kind,legacy=true)=>legacy&&kind===fixLoopSource?legacyFixLoopName:kind;
|
|
28
|
+
export function canonicalMetaValue(field,value) {
|
|
29
|
+
if(value==null) return value;
|
|
30
|
+
return field==='source'?fromStoredSource(value):field==='objective_key'?canonicalObjectiveKey(value):field==='task_kind'?canonicalTaskKind(value):value;
|
|
31
|
+
}
|
|
32
|
+
export const metaFields=['objective_key','revision','task_kind','source'];
|
|
33
|
+
export function normalizeMeta(meta) {
|
|
34
|
+
const out=Object.fromEntries(metaFields.map(k=>[k,null]));
|
|
35
|
+
if(meta===undefined||meta===null) return out;
|
|
36
|
+
if(typeof meta!=='object'||Array.isArray(meta)||Object.keys(meta).some(k=>!metaFields.includes(k))) throw new Error('invalid meta');
|
|
37
|
+
for(const k of metaFields) {
|
|
38
|
+
const v=meta[k];
|
|
39
|
+
if(v===undefined||v===null) continue;
|
|
40
|
+
if(typeof v!=='string'||!v||Buffer.byteLength(v)>512) throw new Error(`invalid meta.${k}`);
|
|
41
|
+
out[k]=k==='source'?fromStoredSource(v):v;
|
|
42
|
+
}
|
|
43
|
+
if(out.source!==null&&!objectiveSources.includes(out.source)) throw new Error('invalid meta.source');
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
48
|
+
// The drainer's deterministic identity: the request_id commits to the whole tuple, so a matching hash proves it. A
|
|
49
|
+
// re-preparation (the producer prepares the objective again after the bridge cancelled attempt n-1 as expired) appends
|
|
50
|
+
// `-r<n>`, as fix-loop reopen attempts do; the first preparation keeps the bare id, so existing ids are unchanged.
|
|
51
|
+
export const maxPreparationAttempt = 3;
|
|
52
|
+
export const drainerRequestId = (repo, objectiveKey, revision, taskKind, policyVersion = 1, attempt = 0) => `dot_${hash(JSON.stringify([repo ?? '', objectiveKey, revision, taskKind, policyVersion]))}${attempt ? `-r${attempt}` : ''}`;
|
|
53
|
+
export const preparationAttemptOf = requestId => Number(/-r(\d+)$/.exec(requestId)?.[1] ?? 0);
|
|
54
|
+
// fix-loop: one request id per candidate and reopen attempt (`-r<n>`); the objective is the candidate, the revision the pinned head.
|
|
55
|
+
// The request id prefix is persisted in existing request ids and receipts, so it does not change.
|
|
56
|
+
export const fixLoopRequestId = (candidate, attempt = 0) => `dotfix-${candidate.id}-${hash(`${candidate.repo}:${candidate.id}`).slice(0, 8)}${attempt ? `-r${attempt}` : ''}`.slice(0, 128);
|
|
57
|
+
export const fixLoopObjective = candidate => `${fixLoopSource}:${candidate.repo}#${candidate.id}`;
|
|
58
|
+
export const fixLoopTaskKind = fixLoopSource;
|
|
59
|
+
// Producers of earlier releases send the old name in the objective key and task kind; both spellings verify.
|
|
60
|
+
const fixLoopObjectivePattern = new RegExp(`^(?:${fixLoopSource}|${legacyFixLoopName}):([^#]+)#(.+)$`);
|
|
61
|
+
const fixLoopTaskKinds = [fixLoopTaskKind, legacyFixLoopName];
|
|
62
|
+
|
|
63
|
+
const firstInput = payload => (Array.isArray(payload?.inputs) ? payload.inputs[0] : null) ?? null;
|
|
64
|
+
|
|
65
|
+
// Null when the tuple is proven for this row (request_id + stored payload), else the reason it is not.
|
|
66
|
+
export function verifyObjective(row, tuple) {
|
|
67
|
+
let meta;
|
|
68
|
+
try { meta = normalizeMeta(tuple); } catch (error) { return error.message; }
|
|
69
|
+
if (metaFields.some(k => meta[k] === null)) return 'incomplete tuple';
|
|
70
|
+
const payload = typeof row.payload === 'string' ? JSON.parse(row.payload) : row.payload, input = firstInput(payload);
|
|
71
|
+
if (meta.source === 'drainer') {
|
|
72
|
+
if (row.request_id !== drainerRequestId(input?.github_repo ?? '', meta.objective_key, meta.revision, meta.task_kind, 1, preparationAttemptOf(row.request_id))) return 'request_id does not match the drainer identity of this tuple';
|
|
73
|
+
if (input && meta.revision !== (input.head_sha ?? input.base_sha)) return 'revision differs from the pinned input';
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
if (meta.source === fixLoopSource) {
|
|
77
|
+
const m = fixLoopObjectivePattern.exec(meta.objective_key);
|
|
78
|
+
if (!m || !fixLoopTaskKinds.includes(meta.task_kind)) return 'not a fix-loop objective';
|
|
79
|
+
const candidate = { repo: m[1], id: m[2] }, attempt = Number(/-r(\d+)$/.exec(row.request_id)?.[1] ?? 0);
|
|
80
|
+
if (row.request_id !== fixLoopRequestId(candidate, 0) && row.request_id !== fixLoopRequestId(candidate, attempt)) return 'request_id does not match the fix-loop candidate';
|
|
81
|
+
if (input?.github_repo !== candidate.repo || input?.base_sha !== meta.revision) return 'revision or repo differs from the pinned input';
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
return `source ${meta.source} cannot be verified`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Lens names the producer has used for audit objectives, including retired ones; a guess counts only if the hash matches.
|
|
88
|
+
const auditLenses = ['correctness', 'errors', 'tests', 'concurrency', 'clarity'];
|
|
89
|
+
function guesses(payload) {
|
|
90
|
+
const input = firstInput(payload), repo = input?.github_repo;
|
|
91
|
+
if (!repo) return [];
|
|
92
|
+
const out = [];
|
|
93
|
+
if (input.head_sha && input.pr_number) out.push({ objective_key: `pr-review:${repo}#${input.pr_number}`, revision: input.head_sha, task_kind: 'review' });
|
|
94
|
+
const module = Array.isArray(payload.scope_paths) && typeof payload.scope_paths[0] === 'string' && payload.scope_paths[0].includes('/') ? payload.scope_paths[0].split('/')[0] : null;
|
|
95
|
+
if (module && input.base_sha && !input.head_sha) {
|
|
96
|
+
const part = /\(part (\d+) of \d+/.exec(payload.brief ?? '');
|
|
97
|
+
const indexes = part ? [Number(part[1]) - 1] : [];
|
|
98
|
+
for (const lens of auditLenses) for (const index of indexes) out.push({ objective_key: `audit:${repo}:${module}:${lens}:${index}`, revision: input.base_sha, task_kind: 'audit-review' });
|
|
99
|
+
for (const kind of ['audit-review', 'audit']) out.push({ objective_key: `audit:${repo}:${module}`, revision: input.base_sha, task_kind: kind });
|
|
100
|
+
}
|
|
101
|
+
return out.map(t => ({ ...t, source: 'drainer' }));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Host-side derivation for `dalan backfill-objectives`: receipts are the rows (their body is the submitted payload);
|
|
105
|
+
// manifests and the fix ledger supply exact tuples, and payload-shaped guesses cover consumed manifests. Only tuples
|
|
106
|
+
// that verifyObjective proves are returned; the server verifies again against its own stored payload.
|
|
107
|
+
export function deriveObjectives({ receipts = [], manifests = [], ledger = [] }) {
|
|
108
|
+
const fromManifest = new Map(), fromLedger = new Map();
|
|
109
|
+
for (const m of manifests) {
|
|
110
|
+
if (!m || typeof m !== 'object' || m.policy_version !== 1) continue;
|
|
111
|
+
const input = firstInput(m.assignment);
|
|
112
|
+
fromManifest.set(drainerRequestId(input?.github_repo ?? '', m.objective_key, m.revision, m.task_kind, 1, m.preparation_attempt ?? 0), { objective_key: m.objective_key, revision: m.revision, task_kind: m.task_kind, source: 'drainer' });
|
|
113
|
+
}
|
|
114
|
+
for (const e of ledger) if (e?.stage === 'assigned' && typeof e.request_id === 'string' && e.request_id.startsWith('dotfix-') && e.id && e.repo && e.base_sha)
|
|
115
|
+
fromLedger.set(e.request_id, { objective_key: fixLoopObjective(e), revision: e.base_sha, task_kind: fixLoopTaskKind, source: fixLoopSource });
|
|
116
|
+
const tuples = [], counts = { receipts: 0, verified: { manifest: 0, ledger: 0, payload: 0 }, unverified: 0 };
|
|
117
|
+
for (const r of receipts) {
|
|
118
|
+
let payload;
|
|
119
|
+
try { payload = JSON.parse(r.body); } catch { continue; }
|
|
120
|
+
if (!payload || payload.request_id !== r.request_id) continue;
|
|
121
|
+
counts.receipts++;
|
|
122
|
+
const row = { request_id: r.request_id, payload };
|
|
123
|
+
const tried = [['manifest', fromManifest.get(r.request_id)], ['ledger', fromLedger.get(r.request_id)], ...guesses(payload).map(t => ['payload', t])];
|
|
124
|
+
const hit = tried.find(([, t]) => t && verifyObjective(row, t) === null);
|
|
125
|
+
if (hit) { counts.verified[hit[0]]++; tuples.push({ request_id: r.request_id, ...hit[1] }); }
|
|
126
|
+
else counts.unverified++;
|
|
127
|
+
}
|
|
128
|
+
return { tuples, counts };
|
|
129
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {createHash,randomUUID} from 'node:crypto';
|
|
4
|
+
import {redactSinkText,splitFields} from './redaction.mjs';
|
|
5
|
+
|
|
6
|
+
export const OWNER_REPORT_ARTIFACT_LIMIT=8*1024*1024;
|
|
7
|
+
const clean=value=>redactSinkText(value);
|
|
8
|
+
|
|
9
|
+
const preparedReports=new WeakMap();
|
|
10
|
+
// Preparing a document performs redaction exactly once. Storage accepts only
|
|
11
|
+
// this process-local capability, not arbitrary bytes claiming to be prepared.
|
|
12
|
+
// New documents carry the neutral id; the original id is still accepted so documents written earlier stay valid.
|
|
13
|
+
export const ownerReportFormat='dalan-owner-report';
|
|
14
|
+
const ownerReportFormats=[ownerReportFormat,'dot-bridge-owner-report'];
|
|
15
|
+
export function prepareOwnerReportArtifact(doc) {
|
|
16
|
+
const invalid=()=>{throw new Error('invalid owner report artifact document');};
|
|
17
|
+
const closed=(value,keys)=>value&&Object.getPrototypeOf(value)===Object.prototype&&
|
|
18
|
+
Object.keys(value).length===keys.length&&keys.every(key=>Object.hasOwn(value,key));
|
|
19
|
+
if(!closed(doc,['format','version','summary','result','progress'])||!ownerReportFormats.includes(doc.format)||doc.version!==1||
|
|
20
|
+
typeof doc.summary!=='string'||typeof doc.result!=='string'||!Array.isArray(doc.progress))invalid();
|
|
21
|
+
for(const row of doc.progress) if(!closed(row,['sequence','at','text'])||!Number.isSafeInteger(row.sequence)||row.sequence<1||typeof row.at!=='string'||typeof row.text!=='string')invalid();
|
|
22
|
+
// A report whose raw text is already over the limit is refused before the split check, which reads all of it.
|
|
23
|
+
const rawTexts=[doc.summary,doc.result,...doc.progress.flatMap(row=>[row.at,row.text])];
|
|
24
|
+
if(rawTexts.reduce((n,text)=>n+Buffer.byteLength(text),0)>OWNER_REPORT_ARTIFACT_LIMIT)throw new Error('owner report artifact exceeds 8 MiB');
|
|
25
|
+
// One split check over every text the worker wrote: a credential split between summary, result and progress is
|
|
26
|
+
// masked. Timestamps come from the bridge and take no part.
|
|
27
|
+
const [summary,result,...texts]=splitFields([doc.summary,doc.result,...doc.progress.map(row=>row.text)]).map(clean);
|
|
28
|
+
const progress=doc.progress.map((row,i)=>({sequence:row.sequence,at:clean(row.at),text:texts[i]}));
|
|
29
|
+
const encoded=Buffer.from(JSON.stringify({format:doc.format,version:doc.version,summary,result,progress})+'\n');
|
|
30
|
+
if(encoded.length>OWNER_REPORT_ARTIFACT_LIMIT)throw new Error('owner report artifact exceeds 8 MiB');
|
|
31
|
+
const prepared=Object.freeze({size:encoded.length,sha256:createHash('sha256').update(encoded).digest('hex')});
|
|
32
|
+
preparedReports.set(prepared,encoded);
|
|
33
|
+
return prepared;
|
|
34
|
+
}
|
|
35
|
+
export function ownerReportArtifactBytes(prepared) {
|
|
36
|
+
const bytes=preparedReports.get(prepared);
|
|
37
|
+
if(!bytes)throw new Error('owner report artifact requires a prepared document');
|
|
38
|
+
return Buffer.from(bytes);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Called only from a trusted finish transaction. Workspace remains the owner of
|
|
42
|
+
// artifact storage, sealing, retention, and ordinary rollback cleanup.
|
|
43
|
+
export function captureOwnerReportArtifact(store,workspace,{requestId,claimId,outcome,summary,result,onRollback}) {
|
|
44
|
+
if(outcome!=='completed') return null;
|
|
45
|
+
if(!store.db.isTransaction||typeof onRollback!=='function') throw new Error('owner report artifact requires finish transaction');
|
|
46
|
+
const progress=store.db.prepare('SELECT id,note,created_at FROM progress WHERE request_id=? ORDER BY id').all(requestId)
|
|
47
|
+
.map(row=>({sequence:row.id,at:row.created_at,text:row.note}));
|
|
48
|
+
const document={format:ownerReportFormat,version:1,summary,result,progress};
|
|
49
|
+
const prepared=prepareOwnerReportArtifact(document);
|
|
50
|
+
const artifactId=`art_${randomUUID()}`;
|
|
51
|
+
const saved=workspace.saveArtifactInTransaction(requestId,claimId,'owner-report',prepared,artifactId,onRollback);
|
|
52
|
+
const row=store.db.prepare('SELECT path,size,sha256 FROM artifacts WHERE id=? AND request_id=? AND kind=\'owner-report\' AND sealed=1').get(artifactId,requestId);
|
|
53
|
+
if(!row||row.size!==prepared.size||row.sha256!==prepared.sha256) throw new Error('owner report artifact integrity failure');
|
|
54
|
+
const fd=fs.openSync(row.path,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
|
|
55
|
+
try {
|
|
56
|
+
const stat=fs.fstatSync(fd);
|
|
57
|
+
if(!stat.isFile()||stat.size!==row.size) throw new Error('owner report artifact integrity failure');
|
|
58
|
+
const actual=Buffer.alloc(row.size);let offset=0;
|
|
59
|
+
while(offset<actual.length){const count=fs.readSync(fd,actual,offset,actual.length-offset,offset);if(!count)throw new Error('owner report artifact integrity failure');offset+=count;}
|
|
60
|
+
if(createHash('sha256').update(actual).digest('hex')!==row.sha256) throw new Error('owner report artifact integrity failure');
|
|
61
|
+
fs.fsyncSync(fd);
|
|
62
|
+
} finally {fs.closeSync(fd);}
|
|
63
|
+
const dirfd=fs.openSync(path.dirname(row.path),fs.constants.O_RDONLY|fs.constants.O_DIRECTORY);
|
|
64
|
+
try {fs.fsyncSync(dirfd);} finally {fs.closeSync(dirfd);}
|
|
65
|
+
return {artifact_id:saved.artifact_id,kind:saved.kind,size:saved.size,sha256:saved.sha256};
|
|
66
|
+
}
|