tr-plugin-meta-harness 0.3.0 → 0.5.27
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/DESIGN.md +86 -0
- package/README.md +257 -11
- package/capability/BRICK.md +1 -1
- package/capability/index.mjs +154 -13
- package/cli.mjs +426 -41
- package/package.json +15 -3
- package/plugin.json +1457 -119
- package/skills/meta-harness/SKILL.md +63 -25
- package/src/adoption.mjs +102 -0
- package/src/agent-user.mjs +194 -0
- package/src/alerts.mjs +220 -14
- package/src/cascade.mjs +185 -0
- package/src/chat.mjs +80 -0
- package/src/codex-models.mjs +54 -0
- package/src/compat-harness.mjs +117 -0
- package/src/control.mjs +145 -0
- package/src/coordinator.mjs +267 -358
- package/src/dispatch-request.mjs +76 -0
- package/src/dispatch.mjs +119 -0
- package/src/documentation-authority.mjs +57 -0
- package/src/documentation.mjs +120 -32
- package/src/executor.mjs +101 -22
- package/src/gate-adapters/agy.mjs +155 -0
- package/src/gate-adapters/claude.mjs +303 -0
- package/src/gate-adapters/cline.mjs +111 -0
- package/src/gate-adapters/codex.mjs +164 -0
- package/src/gate-adapters/cursor.mjs +164 -0
- package/src/gate-adapters/devin.mjs +116 -0
- package/src/gate-adapters/dsh.mjs +284 -0
- package/src/gate-adapters/grok.mjs +112 -0
- package/src/gate-adapters/hermes.mjs +217 -0
- package/src/gate-adapters/hook-files.mjs +156 -0
- package/src/gate-adapters/index.mjs +131 -0
- package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
- package/src/gate-adapters/openclaw-plugin/index.js +25 -0
- package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
- package/src/gate-adapters/openclaw-plugin/package.json +15 -0
- package/src/gate-adapters/openclaw.mjs +288 -0
- package/src/gate-adapters/pi.mjs +146 -0
- package/src/gate.mjs +18 -0
- package/src/harness-updates.mjs +170 -0
- package/src/included-usage.mjs +344 -0
- package/src/jobs.mjs +135 -0
- package/src/json-reply.mjs +22 -0
- package/src/learner.mjs +97 -67
- package/src/maintenance.mjs +18 -0
- package/src/mcp-server.mjs +228 -0
- package/src/model-catalog.mjs +195 -0
- package/src/model-selection.mjs +67 -0
- package/src/paths.mjs +23 -0
- package/src/pool.mjs +69 -0
- package/src/process-manager.mjs +246 -0
- package/src/process-worker.mjs +18 -0
- package/src/reasoning.mjs +231 -0
- package/src/remote-operation.mjs +76 -0
- package/src/review.mjs +241 -0
- package/src/reviews.mjs +25 -0
- package/src/router-benchmark-corpus.mjs +16 -0
- package/src/router-benchmark.mjs +208 -0
- package/src/router.mjs +265 -346
- package/src/runtime.mjs +30 -8
- package/src/session/claude.mjs +358 -0
- package/src/session/codex.mjs +501 -0
- package/src/session/result.mjs +90 -0
- package/src/session/resume.mjs +393 -0
- package/src/session/run.mjs +258 -0
- package/src/session-jobs.mjs +77 -0
- package/src/setup.mjs +6 -3
- package/src/ssss-store.mjs +20 -0
- package/src/telemetry.mjs +267 -0
- package/src/termination.mjs +28 -0
- package/src/threads.mjs +150 -0
- package/src/usage-queue.mjs +137 -0
- package/src/verify-ssss.mjs +102 -0
- package/src/worker.mjs +955 -84
- package/src/worktree.mjs +244 -0
- package/ui/chunks/adapter-docs-freshness.md +16 -0
- package/ui/chunks/chat-handoff.md +26 -0
- package/ui/chunks/fleet-maintenance.md +21 -0
- package/ui/chunks/harness-inventory.md +21 -0
- package/ui/chunks/included-access.md +18 -0
- package/ui/chunks/included-usage-verification.md +15 -0
- package/ui/chunks/independent-review.md +17 -0
- package/ui/chunks/managed-execution.md +20 -0
- package/ui/chunks/official-documentation.md +18 -0
- package/ui/chunks/quota-recovery.md +21 -0
- package/ui/chunks/review-routing-decision.md +16 -0
- package/ui/chunks/route-work.md +18 -0
- package/ui/chunks/routing-evidence.md +18 -0
- package/ui/chunks/run-ledger.md +18 -0
- package/ui/chunks/session-controls.md +16 -0
- package/ui/home.js +198 -0
- package/ui/DESIGN.md +0 -32
- package/ui/card.js +0 -845
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Stop agents first. Let the operation save its work and return before the process exits. */
|
|
2
|
+
import { cancelExecution, cancellationResult } from './worker.mjs';
|
|
3
|
+
import { removeActiveWorktrees } from './worktree.mjs';
|
|
4
|
+
import { failOpenThreads } from './coordinator.mjs';
|
|
5
|
+
|
|
6
|
+
const SIGNALS = { SIGTERM: 143, SIGINT: 130, SIGHUP: 129 };
|
|
7
|
+
let installed = false;
|
|
8
|
+
|
|
9
|
+
export function stopOnTermination({ graceMs = 500 } = {}) {
|
|
10
|
+
if (installed) return;
|
|
11
|
+
installed = true;
|
|
12
|
+
for (const [signal, code] of Object.entries(SIGNALS)) process.on(signal, () => {
|
|
13
|
+
if (cancellationResult()) return;
|
|
14
|
+
cancelExecution(signal, graceMs);
|
|
15
|
+
process.exitCode = code;
|
|
16
|
+
});
|
|
17
|
+
// Also cover callers that use the lifecycle helper without the CLI wrapper.
|
|
18
|
+
process.once('beforeExit', () => { if (cancellationResult()) finishCancellation(); });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function finishCancellation(result) {
|
|
22
|
+
const cancelled = cancellationResult();
|
|
23
|
+
if (!cancelled) return result;
|
|
24
|
+
const saved = removeActiveWorktrees({ preserveChanges: true });
|
|
25
|
+
failOpenThreads('The run was cancelled.');
|
|
26
|
+
process.exitCode = cancelled.exitCode;
|
|
27
|
+
return { ...result, ...cancelled, ...(saved.length ? { saved } : {}) };
|
|
28
|
+
}
|
package/src/threads.mjs
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/** Thread state is canonical SSSS, mutated through the native kernel with optimistic concurrency. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import { threadsFile } from './paths.mjs';
|
|
5
|
+
import { PluginStateStore } from './ssss-store.mjs';
|
|
6
|
+
|
|
7
|
+
const STATUSES = new Set(['active', 'review_pending', 'approved', 'completed', 'failed']);
|
|
8
|
+
const identifier = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
|
|
9
|
+
const storeForThreads = () => new PluginStateStore(threadsFile(), 'meta-harness');
|
|
10
|
+
|
|
11
|
+
function validateThreads(value) {
|
|
12
|
+
if (!Array.isArray(value)) throw new Error('The thread store is corrupt: threads must be an array');
|
|
13
|
+
const ids = new Set();
|
|
14
|
+
for (const thread of value) {
|
|
15
|
+
if (!thread || typeof thread !== 'object' || !identifier.test(thread.id || '') || ids.has(thread.id)
|
|
16
|
+
|| typeof thread.title !== 'string' || !STATUSES.has(thread.status) || !Array.isArray(thread.turns)
|
|
17
|
+
|| thread.turns.some(turn => !turn || typeof turn !== 'object' || typeof turn.content !== 'string')) {
|
|
18
|
+
throw new Error('The thread store is corrupt: invalid thread identity, status or turns');
|
|
19
|
+
}
|
|
20
|
+
ids.add(thread.id);
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Existing JSON is read only for migration. The first mutation imports it through SSSS; it is never overwritten. */
|
|
26
|
+
function readState(store) {
|
|
27
|
+
let value;
|
|
28
|
+
try { value = store.read(null); }
|
|
29
|
+
catch (error) { throw new Error(`The canonical thread store is corrupt or unsafe: ${error.message}`); }
|
|
30
|
+
if (value === null) {
|
|
31
|
+
let content;
|
|
32
|
+
try { content = fs.readFileSync(threadsFile(), 'utf8'); }
|
|
33
|
+
catch (error) { if (error.code === 'ENOENT') return { threads: [] }; throw error; }
|
|
34
|
+
try { value = JSON.parse(content); }
|
|
35
|
+
catch { throw new Error(`The thread store ${threadsFile()} is corrupt. It was left in place.`); }
|
|
36
|
+
}
|
|
37
|
+
const state = Array.isArray(value) ? { threads: value } : value;
|
|
38
|
+
if (!state || typeof state !== 'object') throw new Error('The thread store is corrupt: missing thread state');
|
|
39
|
+
validateThreads(state.threads);
|
|
40
|
+
return state;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export const threadDocumentPath = () => storeForThreads().documentPath;
|
|
44
|
+
export function readThreads() { return readState(storeForThreads()).threads; }
|
|
45
|
+
|
|
46
|
+
/** Native SSSS owns the mutation guard and leases. CAS retries reload state; no age-based lock stealing. */
|
|
47
|
+
function mutate(work) {
|
|
48
|
+
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
49
|
+
const store = storeForThreads();
|
|
50
|
+
const state = readState(store);
|
|
51
|
+
const result = work(state.threads, state);
|
|
52
|
+
validateThreads(state.threads);
|
|
53
|
+
try {
|
|
54
|
+
store.write({ ...state, version: '2.0.0', updatedAt: new Date().toISOString(), threads: state.threads });
|
|
55
|
+
return structuredClone(result);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
if (!String(error.message).includes('version conflict') || attempt === 7) throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function writeThreads(threads) {
|
|
63
|
+
validateThreads(threads);
|
|
64
|
+
return mutate(current => { current.splice(0, current.length, ...structuredClone(threads)); return current; });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function listThreads(filter = {}) {
|
|
68
|
+
return readThreads().filter(thread => (!filter.platform || thread.platform === filter.platform)
|
|
69
|
+
&& (!filter.status || thread.status === filter.status) && (!filter.branch || thread.branch === filter.branch))
|
|
70
|
+
.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
|
|
71
|
+
}
|
|
72
|
+
export function getThread(id) { return readThreads().find(thread => thread.id === id) || null; }
|
|
73
|
+
|
|
74
|
+
export function createThread(data = {}) {
|
|
75
|
+
const id = data.id || `thread-${crypto.randomUUID()}`;
|
|
76
|
+
return mutate(threads => {
|
|
77
|
+
if (threads.some(thread => thread.id === id)) throw new Error(`Thread already exists: ${id}`);
|
|
78
|
+
const now = new Date().toISOString();
|
|
79
|
+
const thread = {
|
|
80
|
+
...data, id, title: String(data.title || 'Untitled Agent Thread').slice(0, 140),
|
|
81
|
+
task: String(data.task || data.title || '').trim(), platform: data.platform || 'universal', model: data.model || 'auto',
|
|
82
|
+
branch: data.branch || null, worktreePath: data.worktreePath || null, prNumber: data.prNumber || null, prUrl: data.prUrl || null,
|
|
83
|
+
status: data.status || 'active', createdAt: now, updatedAt: now,
|
|
84
|
+
turns: Array.isArray(data.turns) ? data.turns : [], review: data.review || null, summary: data.summary || null,
|
|
85
|
+
};
|
|
86
|
+
threads.unshift(thread);
|
|
87
|
+
return thread;
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function appendThreadTurn(id, turn = {}) {
|
|
92
|
+
return mutate(threads => {
|
|
93
|
+
const thread = threads.find(item => item.id === id);
|
|
94
|
+
if (!thread) throw new Error(`Thread not found: ${id}`);
|
|
95
|
+
const now = new Date().toISOString();
|
|
96
|
+
thread.turns.push({ role: turn.role || 'agent', agent: turn.agent || 'unknown', content: String(turn.content || '').slice(0, 50000), timestamp: now });
|
|
97
|
+
thread.updatedAt = now;
|
|
98
|
+
return thread;
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function updateThread(id, updates = {}) {
|
|
103
|
+
if (!updates || typeof updates !== 'object' || Array.isArray(updates)) throw new Error('Thread updates must be an object');
|
|
104
|
+
return mutate(threads => {
|
|
105
|
+
const index = threads.findIndex(thread => thread.id === id);
|
|
106
|
+
if (index < 0) throw new Error(`Thread not found: ${id}`);
|
|
107
|
+
threads[index] = { ...threads[index], ...updates, id, createdAt: threads[index].createdAt, updatedAt: new Date().toISOString() };
|
|
108
|
+
return threads[index];
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
export function closeThread(id, resolution = 'completed') { return updateThread(id, { status: resolution, closedAt: new Date().toISOString() }); }
|
|
112
|
+
export function deleteThread(id) {
|
|
113
|
+
return mutate(threads => {
|
|
114
|
+
const index = threads.findIndex(thread => thread.id === id);
|
|
115
|
+
if (index < 0) return false;
|
|
116
|
+
threads.splice(index, 1);
|
|
117
|
+
return true;
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Exact titles from test/threads.test.mjs and test/coordinator.test.mjs.
|
|
122
|
+
// Real multiply-job threads do not match, including failed end-to-end attempts.
|
|
123
|
+
const FIXTURE_TITLES = new Set([
|
|
124
|
+
'Implement Multi-Platform Threads', 'Canonical state', 'concurrent',
|
|
125
|
+
'Implement token bucket', 'task one', 'task two', 'task three', 'task four', 'failed verification',
|
|
126
|
+
]);
|
|
127
|
+
const CLEANUP_ID = 'a118-fixture-threads-v1';
|
|
128
|
+
|
|
129
|
+
/** Delete the known fixture titles once. The same SSSS operation records every removal. */
|
|
130
|
+
export function cleanupFixtureThreads({ dryRun = false } = {}) {
|
|
131
|
+
const plan = (threads, state) => {
|
|
132
|
+
const previous = state.cleanups?.find(row => row.id === CLEANUP_ID);
|
|
133
|
+
if (previous) return { ok: true, alreadyApplied: true, record: previous };
|
|
134
|
+
const removed = threads.filter(thread => FIXTURE_TITLES.has(thread.title))
|
|
135
|
+
.map(({ id, title, status }) => ({ id, title, status }));
|
|
136
|
+
const kept = threads.filter(thread => !FIXTURE_TITLES.has(thread.title)).map(thread => thread.id);
|
|
137
|
+
return { ok: true, record: { id: CLEANUP_ID, timestamp: new Date().toISOString(), sources: ['test/threads.test.mjs', 'test/coordinator.test.mjs'], removed, kept } };
|
|
138
|
+
};
|
|
139
|
+
const state = readState(storeForThreads());
|
|
140
|
+
const preview = plan(state.threads, state);
|
|
141
|
+
if (dryRun || preview.alreadyApplied) return { ...preview, dryRun };
|
|
142
|
+
return mutate((threads, current) => {
|
|
143
|
+
const result = plan(threads, current);
|
|
144
|
+
if (result.alreadyApplied) return result;
|
|
145
|
+
const ids = new Set(result.record.removed.map(row => row.id));
|
|
146
|
+
threads.splice(0, threads.length, ...threads.filter(thread => !ids.has(thread.id)));
|
|
147
|
+
current.cleanups = [...(current.cleanups || []), result.record];
|
|
148
|
+
return result;
|
|
149
|
+
});
|
|
150
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/** SSSS-backed queue for work deferred by included usage limits. */
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { configDir } from './paths.mjs';
|
|
5
|
+
import { destinationDispatchRequest } from './dispatch-request.mjs';
|
|
6
|
+
import { readIncludedPolicy } from './included-usage.mjs';
|
|
7
|
+
|
|
8
|
+
async function queueStore(file = 'usage-queue.json') {
|
|
9
|
+
const { PluginStateStore } = await import('./ssss-store.mjs');
|
|
10
|
+
return new PluginStateStore(path.join(configDir(), file), 'meta-harness');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function readRows(store) {
|
|
14
|
+
const jobs = store.read([]);
|
|
15
|
+
if (!Array.isArray(jobs) || jobs.some(job => !job?.id || typeof job.task !== 'string' || !path.isAbsolute(job.workspace || '') ||
|
|
16
|
+
!['waiting', 'running', 'completed', 'cancelled', 'failed'].includes(job.status))) {
|
|
17
|
+
throw new Error('Invalid included usage queue.');
|
|
18
|
+
}
|
|
19
|
+
return jobs;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function mutateQueue(change, file) {
|
|
23
|
+
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
24
|
+
const store = await queueStore(file);
|
|
25
|
+
const jobs = readRows(store);
|
|
26
|
+
const result = change(jobs);
|
|
27
|
+
try { store.write(jobs); return result; }
|
|
28
|
+
catch (error) { if (!error.message.includes('version conflict') || attempt === 7) throw error; }
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function publicJob({ replay, task, ...job }) {
|
|
33
|
+
return { ...job, task: task.slice(0, 160), canRetry: Boolean(replay) && !job.needsReview };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function queueIncludedJob(request, result, { role, replay, launchPrevented = false } = {}) {
|
|
37
|
+
const workspace = request.contextCwd || request.cwd;
|
|
38
|
+
const direct = !replay && role === 'Dispatch' && workspace === request.cwd;
|
|
39
|
+
if (direct) replay = { kind: 'dispatch', request: destinationDispatchRequest(request) };
|
|
40
|
+
const job = {
|
|
41
|
+
id: randomUUID(), status: 'waiting', agent: request.agent, workspace, role: role || 'Dispatch',
|
|
42
|
+
task: String(request.contextTask || request.prompt).slice(0, direct ? 160 : 65536),
|
|
43
|
+
reason: 'included-usage-exhausted',
|
|
44
|
+
resetsAt: Number.isFinite(Date.parse(result.resetsAt)) ? result.resetsAt : null,
|
|
45
|
+
queuedAt: new Date().toISOString(), attempts: 0,
|
|
46
|
+
needsReview: !replay || (!launchPrevented && request.permissions?.write === true),
|
|
47
|
+
replay: replay || null,
|
|
48
|
+
};
|
|
49
|
+
return mutateQueue(jobs => {
|
|
50
|
+
if (jobs.filter(item => ['waiting', 'running'].includes(item.status)).length >= 200) throw new Error('Included usage queue is full.');
|
|
51
|
+
const history = jobs.filter(item => !['waiting', 'running'].includes(item.status)).slice(0, -50);
|
|
52
|
+
for (const item of history) jobs.splice(jobs.indexOf(item), 1);
|
|
53
|
+
jobs.push(job);
|
|
54
|
+
if (Buffer.byteLength(JSON.stringify(jobs)) > 4 * 1024 * 1024) throw new Error('Included usage queue exceeds its storage bound.');
|
|
55
|
+
return publicJob(job);
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function listIncludedJobs() {
|
|
60
|
+
const jobs = readRows(await queueStore());
|
|
61
|
+
return jobs.map(publicJob);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Preserve legacy, non-replayable attempts before removing them from the waiting count. */
|
|
65
|
+
export async function archiveUnreplayableReasoning({ apply = false, now = Date.now() } = {}) {
|
|
66
|
+
const eligible = job => job.status === 'waiting' && job.role === 'Reasoning' && job.reason === 'included-usage-exhausted'
|
|
67
|
+
&& job.needsReview && !job.replay && job.attempts === 0 && Date.parse(job.resetsAt) <= now;
|
|
68
|
+
const candidates = readRows(await queueStore()).filter(eligible);
|
|
69
|
+
if (!apply || !candidates.length) return { ok: true, eligible: candidates.length, archived: 0 };
|
|
70
|
+
|
|
71
|
+
const ids = new Set(candidates.map(job => job.id));
|
|
72
|
+
const archivedAt = new Date(now).toISOString();
|
|
73
|
+
await mutateQueue(rows => {
|
|
74
|
+
const archived = new Set(rows.map(job => job.id));
|
|
75
|
+
rows.push(...candidates.filter(job => !archived.has(job.id)).map(job => ({ ...job, archivedAt })));
|
|
76
|
+
}, 'unreplayable-reasoning.json');
|
|
77
|
+
|
|
78
|
+
const archived = await mutateQueue(rows => {
|
|
79
|
+
let count = 0;
|
|
80
|
+
for (const job of rows) {
|
|
81
|
+
if (!ids.has(job.id) || !eligible(job)) continue;
|
|
82
|
+
Object.assign(job, { status: 'failed', needsReview: false, finishedAt: archivedAt,
|
|
83
|
+
lastError: 'Legacy internal reasoning has no replay request. The original record is archived.' });
|
|
84
|
+
count += 1;
|
|
85
|
+
}
|
|
86
|
+
return count;
|
|
87
|
+
});
|
|
88
|
+
return { ok: true, eligible: candidates.length, archived };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function updateJob(jobs, id, change) {
|
|
92
|
+
const index = jobs.findIndex(job => job.id === id);
|
|
93
|
+
if (index < 0) throw new Error('Included usage job was not found.');
|
|
94
|
+
return jobs[index] = change(jobs[index]);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function cancelIncludedJob(id) {
|
|
98
|
+
return mutateQueue(jobs => publicJob(updateJob(jobs, id, job => {
|
|
99
|
+
if (job.status !== 'waiting') throw new Error('Only a waiting job can be cancelled.');
|
|
100
|
+
return { ...job, status: 'cancelled', replay: null };
|
|
101
|
+
})));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Claim atomically before retry, so two callers cannot start the same job. */
|
|
105
|
+
export async function retryIncludedJob(id, { dispatch, route, now = Date.now() } = {}) {
|
|
106
|
+
if (!(await readIncludedPolicy()).enabled) throw new Error('Included usage policy must be enabled to retry.');
|
|
107
|
+
const claimed = await mutateQueue(jobs => updateJob(jobs, id, job => {
|
|
108
|
+
if (job.status !== 'waiting') throw new Error('Only a waiting job can be retried.');
|
|
109
|
+
if (job.needsReview || !job.replay) throw new Error('Review the prior attempt and resubmit this task from its original workspace.');
|
|
110
|
+
if (Date.parse(job.resetsAt) > now) throw new Error('The provider-reported reset time has not arrived.');
|
|
111
|
+
return { ...job, status: 'running', attempts: job.attempts + 1, startedAt: new Date(now).toISOString() };
|
|
112
|
+
}));
|
|
113
|
+
let result;
|
|
114
|
+
try {
|
|
115
|
+
if (claimed.replay.kind === 'dispatch') {
|
|
116
|
+
dispatch ??= (await import('./dispatch.mjs')).dispatchWithReceipt;
|
|
117
|
+
result = await dispatch(claimed.replay.request, { role: 'Dispatch', retryId: id });
|
|
118
|
+
} else if (claimed.replay.kind === 'route') {
|
|
119
|
+
route ??= (await import('./cascade.mjs')).executeRoutedTask;
|
|
120
|
+
result = await route(claimed.task, { ...claimed.replay.controls, cwd: claimed.workspace, gate: claimed.replay.gate, gateOptions: claimed.replay.gateOptions,
|
|
121
|
+
route: { selected: claimed.agent }, pool: [claimed.agent], retryId: id });
|
|
122
|
+
} else throw new Error('Unknown included usage job operation.');
|
|
123
|
+
} catch (error) {
|
|
124
|
+
result = { ok: false, failureKind: 'execution', error: error.message };
|
|
125
|
+
}
|
|
126
|
+
const held = ['quota', 'billing-policy', 'auth'].includes(result.failureKind);
|
|
127
|
+
const updated = await mutateQueue(jobs => updateJob(jobs, id, job => {
|
|
128
|
+
if (job.status !== 'running') throw new Error('Included usage job lost its claim.');
|
|
129
|
+
return { ...job, status: result.ok ? 'completed' : held ? 'waiting' : 'failed',
|
|
130
|
+
resetsAt: held && Number.isFinite(Date.parse(result.resetsAt)) ? result.resetsAt : null,
|
|
131
|
+
needsReview: job.needsReview || result.needsReview === true ||
|
|
132
|
+
(held && !result.launchPrevented && (job.replay.kind === 'route' || job.replay.request?.permissions?.write === true)),
|
|
133
|
+
lastError: result.ok ? null : result.error,
|
|
134
|
+
replay: held ? job.replay : null, finishedAt: new Date().toISOString() };
|
|
135
|
+
}));
|
|
136
|
+
return { ...result, job: publicJob(updated) };
|
|
137
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/** Verify the selected checkout's real native state operations without dispatching an agent. */
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { pathToFileURL } from 'node:url';
|
|
7
|
+
import { createCanonicalEvent, JsonlEventStore } from '@gregiteen/ssss-cli/events';
|
|
8
|
+
import { createKernel } from '@gregiteen/ssss-cli/kernel';
|
|
9
|
+
import { FileSystemVfs } from '@gregiteen/ssss-cli/vfs';
|
|
10
|
+
|
|
11
|
+
const owner = 'meta-harness';
|
|
12
|
+
|
|
13
|
+
function readTargetFile(target, file) {
|
|
14
|
+
const resolved = fs.realpathSync(path.join(target, file));
|
|
15
|
+
assert.ok(resolved.startsWith(`${target}${path.sep}`), `Target file leaves the checkout: ${file}`);
|
|
16
|
+
return resolved;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function verifyEvents(documentPath, primitive, expectedCount) {
|
|
20
|
+
const root = path.dirname(path.dirname(documentPath));
|
|
21
|
+
const subject = path.relative(root, documentPath);
|
|
22
|
+
const vfs = new FileSystemVfs(root);
|
|
23
|
+
const document = await vfs.read(subject);
|
|
24
|
+
assert.ok(document, `Missing native ${primitive} document`);
|
|
25
|
+
|
|
26
|
+
const eventStore = new JsonlEventStore(path.join(root, '.events'));
|
|
27
|
+
const events = [];
|
|
28
|
+
for await (const { event } of eventStore.replay({ workspaceId: owner })) {
|
|
29
|
+
if (event.subject === subject) events.push(event);
|
|
30
|
+
}
|
|
31
|
+
assert.equal(events.length, expectedCount, `Unexpected mutation count for ${primitive}`);
|
|
32
|
+
let previousHash = null;
|
|
33
|
+
for (const event of events) {
|
|
34
|
+
const canonical = createCanonicalEvent(event);
|
|
35
|
+
for (const [field, value] of Object.entries(canonical)) assert.deepEqual(event[field], value, `Invalid canonical event field ${field}`);
|
|
36
|
+
assert.equal(event.workspace_id, owner);
|
|
37
|
+
assert.equal(event.primitive_id, primitive);
|
|
38
|
+
assert.equal(event.principal.id, `plugin:${owner}`);
|
|
39
|
+
assert.equal(event.before_hash, previousHash);
|
|
40
|
+
assert.match(event.after_hash, /^sha256:[a-f0-9]{64}$/);
|
|
41
|
+
previousHash = event.after_hash;
|
|
42
|
+
}
|
|
43
|
+
assert.equal(previousHash, document.hash, `Final event hash does not describe the current ${primitive} document`);
|
|
44
|
+
return { primitive, events: events.length };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function verifyTarget(targetArgument) {
|
|
48
|
+
const target = fs.realpathSync(path.resolve(targetArgument));
|
|
49
|
+
const readJson = file => JSON.parse(fs.readFileSync(readTargetFile(target, file), 'utf8'));
|
|
50
|
+
assert.equal(readJson('package.json').name, 'tr-plugin-meta-harness', 'Select a Metaharness checkout');
|
|
51
|
+
assert.equal(readJson('plugin.json').id, owner, 'The target must own Metaharness state');
|
|
52
|
+
|
|
53
|
+
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'meta-harness-ssss-gate-'));
|
|
54
|
+
const previousBrain = process.env.TR_SECRETS_BRAIN;
|
|
55
|
+
process.env.TR_SECRETS_BRAIN = path.join(scratch, 'brain');
|
|
56
|
+
try {
|
|
57
|
+
const importTarget = file => import(pathToFileURL(readTargetFile(target, `src/${file}.mjs`)).href);
|
|
58
|
+
const [threads, learner, paths, storage] = await Promise.all([
|
|
59
|
+
importTarget('threads'), importTarget('learner'), importTarget('paths'), importTarget('ssss-store'),
|
|
60
|
+
]);
|
|
61
|
+
|
|
62
|
+
const thread = threads.createThread({ title: 'SSSS verification thread' });
|
|
63
|
+
threads.appendThreadTurn(thread.id, { role: 'verifier', content: 'Native storage gate' });
|
|
64
|
+
threads.closeThread(thread.id);
|
|
65
|
+
const threadStore = new storage.PluginStateStore(paths.threadsFile(), owner);
|
|
66
|
+
const savedThread = threadStore.read(null)?.threads?.find(row => row.id === thread.id);
|
|
67
|
+
assert.equal(savedThread?.status, 'completed');
|
|
68
|
+
assert.equal(savedThread?.turns?.[0]?.content, 'Native storage gate');
|
|
69
|
+
|
|
70
|
+
const first = await learner.recordRunReceipt({ harness: 'ssss-gate-fixture', success: true });
|
|
71
|
+
const second = await learner.recordRunReceipt({ harness: 'ssss-gate-fixture', success: false, failureKind: 'gate' });
|
|
72
|
+
const ledger = new storage.PluginStateStore(paths.receiptsFile(), owner);
|
|
73
|
+
assert.deepEqual(ledger.read([]).map(row => row.id), [first.id, second.id]);
|
|
74
|
+
|
|
75
|
+
assert.throws(() => threads.updateThread(thread.id, { status: 'invalid-status' }), /invalid thread/);
|
|
76
|
+
assert.throws(() => threadStore.append({ unexpected: true }), /not append-only/);
|
|
77
|
+
const records = [await verifyEvents(threadStore.documentPath, 'plugin-store:state', 3), await verifyEvents(ledger.documentPath, 'plugin-store:ledger', 2)];
|
|
78
|
+
|
|
79
|
+
// This corruption exists only in the disposable verification brain.
|
|
80
|
+
fs.writeFileSync(threadStore.documentPath, '---\ntype: plugin-store:state\n---\n{}\n');
|
|
81
|
+
assert.throws(() => threadStore.read(null), /Invalid SSSS plugin state/);
|
|
82
|
+
const invalidKernel = createKernel({ vfs: new FileSystemVfs(scratch), eventStore: new JsonlEventStore(path.join(scratch, 'invalid-events')) });
|
|
83
|
+
const invalid = await invalidKernel.execute({ type: 'operation', workspace_id: owner, path: 'missing-content.md', idempotency_key: 'missing-content' });
|
|
84
|
+
assert.equal(invalid.success, false);
|
|
85
|
+
assert.equal(invalid.error?.code, 'invalid_request');
|
|
86
|
+
|
|
87
|
+
return { ok: true, target, records, rejected: ['invalid-thread-status', 'append-to-state', 'malformed-document', 'missing-operation-content'] };
|
|
88
|
+
} finally {
|
|
89
|
+
if (previousBrain === undefined) delete process.env.TR_SECRETS_BRAIN;
|
|
90
|
+
else process.env.TR_SECRETS_BRAIN = previousBrain;
|
|
91
|
+
fs.rmSync(scratch, { recursive: true, force: true });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
try {
|
|
96
|
+
const [flag, target, ...rest] = process.argv.slice(2);
|
|
97
|
+
if (flag !== '--target' || !target || rest.length) throw new Error('Supply an explicit Metaharness checkout with --target <directory>');
|
|
98
|
+
process.stdout.write(`${JSON.stringify(await verifyTarget(target))}\n`);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
process.stdout.write(`${JSON.stringify({ ok: false, error: error.message })}\n`);
|
|
101
|
+
process.exitCode = 1;
|
|
102
|
+
}
|