@evomap/evolver-cli 2.0.35 → 2.0.37
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/dist/antiGeneRollout.d.ts +2 -0
- package/dist/antiGeneRollout.js +21 -3
- package/dist/assetTrust.js +9 -0
- package/dist/atpAutoDeliver.d.ts +10 -0
- package/dist/atpAutoDeliver.js +28 -1
- package/dist/autoRecall.js +8 -4
- package/dist/autoexec.d.ts +15 -0
- package/dist/autoexec.js +139 -7
- package/dist/autoexecConfig.d.ts +1 -1
- package/dist/autoexecConfig.js +1 -1
- package/dist/cursorRewrite.d.ts +6 -0
- package/dist/cursorRewrite.js +64 -6
- package/dist/cycleConsumer.js +1 -0
- package/dist/index.js +11 -3
- package/dist/promptRecallHook.js +11 -4
- package/dist/recall.d.ts +2 -0
- package/dist/recall.js +19 -1
- package/dist/referenceAccess.d.ts +3 -0
- package/dist/referenceAccess.js +232 -0
- package/dist/reviewFilter.d.ts +1 -1
- package/dist/reviewFilter.js +12 -1
- package/dist/sourceQualification.d.ts +2 -0
- package/dist/sourceQualification.js +120 -0
- package/dist/taskCommitments.d.ts +135 -0
- package/dist/taskCommitments.js +492 -0
- package/dist/taskReceiver.d.ts +151 -0
- package/dist/taskReceiver.js +459 -0
- package/dist/thesis.d.ts +3 -0
- package/dist/thesis.js +122 -100
- package/dist/workflowRuntime.js +13 -2
- package/package.json +7 -7
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { AtpHubClient } from '@evomap/evolver-adapter-public';
|
|
2
|
+
/**
|
|
3
|
+
* A claim is a promise, and this file is where the promises live: the execute-queue entry a
|
|
4
|
+
* claimed task becomes, the ledger of what is still owed, and the wiring that keeps or
|
|
5
|
+
* re-files each debt. Choosing which task to take is the receiver's job, not this one's.
|
|
6
|
+
*/
|
|
7
|
+
/** The execute-queue record a claimed Hub task becomes. */
|
|
8
|
+
export interface QueueTask {
|
|
9
|
+
id: string;
|
|
10
|
+
hubTaskId: string;
|
|
11
|
+
/** Which filing of this queue id this is. Tells a late result from the current one. */
|
|
12
|
+
generation: string;
|
|
13
|
+
repo: string;
|
|
14
|
+
target: string;
|
|
15
|
+
expectedEffect: string;
|
|
16
|
+
signals: string[];
|
|
17
|
+
commitmentDeadline?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface QueueRetryResult {
|
|
20
|
+
retried: number;
|
|
21
|
+
queued: number;
|
|
22
|
+
pending: number;
|
|
23
|
+
/** Claims let go of: the commitment ran out, or the queue name never came free. */
|
|
24
|
+
dropped: number;
|
|
25
|
+
}
|
|
26
|
+
export interface CompletionRetryResult {
|
|
27
|
+
retried: number;
|
|
28
|
+
completed: number;
|
|
29
|
+
abandoned: number;
|
|
30
|
+
pending: number;
|
|
31
|
+
/** Outcomes the ledger would not take. The next run will see a stale picture. */
|
|
32
|
+
unrecorded: number;
|
|
33
|
+
/** Deliveries given up on. They are gone from the ledger, so they must be said out loud. */
|
|
34
|
+
abandonedTasks: Array<{
|
|
35
|
+
taskId: string;
|
|
36
|
+
resultAssetId: string;
|
|
37
|
+
lastError: string;
|
|
38
|
+
}>;
|
|
39
|
+
}
|
|
40
|
+
export interface CompletedTask {
|
|
41
|
+
/** The Hub was told, but the ledger would not take the update. The next run sees stale state. */
|
|
42
|
+
unrecorded?: boolean;
|
|
43
|
+
taskId: string;
|
|
44
|
+
completed: boolean;
|
|
45
|
+
error?: string;
|
|
46
|
+
/** The report could not be delivered and is now owed to the Hub on a later beat. */
|
|
47
|
+
pending?: boolean;
|
|
48
|
+
}
|
|
49
|
+
export interface PendingCompletion {
|
|
50
|
+
/** Which filing this debt belongs to. A late report from an earlier one is not it. */
|
|
51
|
+
generation?: string;
|
|
52
|
+
taskId: string;
|
|
53
|
+
resultAssetId: string;
|
|
54
|
+
attempts: number;
|
|
55
|
+
nextAttemptMs: number;
|
|
56
|
+
lastError?: string;
|
|
57
|
+
}
|
|
58
|
+
export interface PendingClaim {
|
|
59
|
+
taskId: string;
|
|
60
|
+
queueTask: QueueTask;
|
|
61
|
+
attempts: number;
|
|
62
|
+
lastError?: string;
|
|
63
|
+
}
|
|
64
|
+
/** A claim this node holds, keyed by the execute-queue id it was filed under. */
|
|
65
|
+
export interface OwnedClaim {
|
|
66
|
+
queueTaskId: string;
|
|
67
|
+
hubTaskId: string;
|
|
68
|
+
generation: string;
|
|
69
|
+
commitmentDeadline?: string;
|
|
70
|
+
}
|
|
71
|
+
export interface PendingCompletionLedger {
|
|
72
|
+
version: 1;
|
|
73
|
+
pending: Record<string, PendingCompletion>;
|
|
74
|
+
/** Claims the Hub granted that never reached the execute queue. */
|
|
75
|
+
unqueued?: Record<string, PendingClaim>;
|
|
76
|
+
/**
|
|
77
|
+
* Queue ids this receiver really claimed from the Hub. The `hub-` prefix is only a
|
|
78
|
+
* naming convention — a local task is free to use it — so the register, not the id,
|
|
79
|
+
* is what says a queue entry is remote work under a commitment.
|
|
80
|
+
*/
|
|
81
|
+
owned?: Record<string, OwnedClaim>;
|
|
82
|
+
}
|
|
83
|
+
export declare const COMPLETION_LEDGER_FILENAME = "task-complete-pending.json";
|
|
84
|
+
export declare function completionLedgerPath(env?: NodeJS.ProcessEnv): string;
|
|
85
|
+
export declare function readCompletionLedger(path: string): PendingCompletionLedger;
|
|
86
|
+
export declare function rememberUnqueued(path: string, queueTask: QueueTask, error: string): void;
|
|
87
|
+
/** Queue ids the receiver writes carry this prefix, so the loop can tell hub work apart. */
|
|
88
|
+
export declare const HUB_QUEUE_PREFIX = "hub-";
|
|
89
|
+
/** A task id becomes a filename, so it may only be what a filename may safely be. */
|
|
90
|
+
/** The queue entry already under this id, or null when there is none we can read. */
|
|
91
|
+
export declare function defaultReadQueueTask(dir: string, id: string): QueueTask | null;
|
|
92
|
+
export declare function defaultWriteQueueTask(dir: string, task: QueueTask): void;
|
|
93
|
+
export declare function defaultRemoveQueueTask(dir: string, id: string): void;
|
|
94
|
+
type FileOutcome = 'written' | 'name_taken' | 'unrecorded';
|
|
95
|
+
/**
|
|
96
|
+
* File a claimed task under its queue id. An `EEXIST` is only "an earlier beat already did
|
|
97
|
+
* this" when the register says that queue id is ours; otherwise the name belongs to a local
|
|
98
|
+
* task, and treating the collision as success would hand its capsule to the Hub.
|
|
99
|
+
*/
|
|
100
|
+
export declare function fileClaim(deps: CommitmentDeps, queueDir: string, claim: QueueTask): FileOutcome;
|
|
101
|
+
/**
|
|
102
|
+
* Wire a receive pass into the resident loop. It stays off without a node
|
|
103
|
+
* identity or an allowlisted repo: claiming a task this daemon cannot execute
|
|
104
|
+
* is a promise to the Hub we would break.
|
|
105
|
+
*/
|
|
106
|
+
/** What a receiver can do about promises already made, on or off. */
|
|
107
|
+
export interface CommitmentWiring {
|
|
108
|
+
/**
|
|
109
|
+
* Report a finished task back to the Hub. A claim is a promise; the Hub only
|
|
110
|
+
* learns it was kept when the produced asset comes back.
|
|
111
|
+
*/
|
|
112
|
+
complete: (taskId: string, resultAssetId: string, generation?: string) => Promise<CompletedTask>;
|
|
113
|
+
/** Re-send reports the Hub never acknowledged. Due entries only, oldest backoff first. */
|
|
114
|
+
retryCompletions: () => Promise<CompletionRetryResult>;
|
|
115
|
+
/** Re-file claims that never reached the execute queue. The claim is already spent. */
|
|
116
|
+
retryQueueWrites: () => Promise<QueueRetryResult>;
|
|
117
|
+
/**
|
|
118
|
+
* The Hub claim behind an execute-queue id, or null when that id is not remote work.
|
|
119
|
+
* A local task is free to be named `hub-anything`; only a registered claim is ours.
|
|
120
|
+
*/
|
|
121
|
+
claimFor: (queueTaskId: string) => OwnedClaim | null;
|
|
122
|
+
}
|
|
123
|
+
export interface CommitmentDeps {
|
|
124
|
+
read?: (dir: string, id: string) => QueueTask | null;
|
|
125
|
+
ledgerPath: string;
|
|
126
|
+
now: () => number;
|
|
127
|
+
queueDir?: string;
|
|
128
|
+
write: (dir: string, task: QueueTask) => void;
|
|
129
|
+
remove?: (dir: string, id: string) => void;
|
|
130
|
+
}
|
|
131
|
+
export declare function unsentCommitments(ledgerPath: string, now: () => number): CommitmentWiring;
|
|
132
|
+
export declare function liveCommitments(client: AtpHubClient, deps: CommitmentDeps): CommitmentWiring;
|
|
133
|
+
/** The Hub task id behind an execute-queue id, or null when the task is local. */
|
|
134
|
+
export declare function hubTaskIdOf(queueTaskId: string): string | null;
|
|
135
|
+
export {};
|
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { util } from '@evomap/evolver-core';
|
|
5
|
+
import { AtpHubClient } from '@evomap/evolver-adapter-public';
|
|
6
|
+
import { resolveAtpHome } from './atp.js';
|
|
7
|
+
export const COMPLETION_LEDGER_FILENAME = 'task-complete-pending.json';
|
|
8
|
+
const COMPLETION_RETRY_BASE_MS = 60_000;
|
|
9
|
+
const COMPLETION_RETRY_CAP_MS = 60 * 60_000;
|
|
10
|
+
const COMPLETION_MAX_ATTEMPTS = 8;
|
|
11
|
+
const COMPLETION_RETRIES_PER_TICK = 5;
|
|
12
|
+
/** A queue name that never comes free is a name we are not getting; stop owing it. */
|
|
13
|
+
const UNQUEUED_MAX_ATTEMPTS = 8;
|
|
14
|
+
export function completionLedgerPath(env = process.env) {
|
|
15
|
+
return join(resolveAtpHome(env), 'evolution', COMPLETION_LEDGER_FILENAME);
|
|
16
|
+
}
|
|
17
|
+
export function readCompletionLedger(path) {
|
|
18
|
+
try {
|
|
19
|
+
if (!existsSync(path))
|
|
20
|
+
return { version: 1, pending: {}, unqueued: {}, owned: {} };
|
|
21
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
22
|
+
return {
|
|
23
|
+
version: 1,
|
|
24
|
+
pending: parsed?.pending && typeof parsed.pending === 'object' ? parsed.pending : {},
|
|
25
|
+
unqueued: parsed?.unqueued && typeof parsed.unqueued === 'object' ? parsed.unqueued : {},
|
|
26
|
+
owned: parsed?.owned && typeof parsed.owned === 'object' ? parsed.owned : {},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return { version: 1, pending: {}, unqueued: {}, owned: {} };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Hold the ledger for one read-modify-write. Without it two writers read the same version,
|
|
35
|
+
* both replace the file, both are told they succeeded, and one update is simply gone — a
|
|
36
|
+
* unique temp name per write stops them corrupting each other's bytes, not their meaning.
|
|
37
|
+
*
|
|
38
|
+
* The lock is `util.acquireLock`, the one the daemon already uses for its single-instance
|
|
39
|
+
* guard: it reclaims by checking whether the owning pid is alive rather than by guessing
|
|
40
|
+
* from an mtime, and it has been carrying that weight in this codebase for far longer than
|
|
41
|
+
* anything written here would have.
|
|
42
|
+
*/
|
|
43
|
+
function withLedgerLock(path, held, unavailable) {
|
|
44
|
+
const lock = `${path}.lock`;
|
|
45
|
+
try {
|
|
46
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
47
|
+
util.acquireLock(lock, { maxTries: 60, waitMs: 25 });
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return unavailable;
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
return held();
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
util.releaseLock(lock);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Read the ledger, change it, and put it back as one step — the only way any of this file
|
|
61
|
+
* mutates it. Returning null from `change` means "nothing to do" and leaves it untouched.
|
|
62
|
+
*/
|
|
63
|
+
function updateCompletionLedger(path, change) {
|
|
64
|
+
return withLedgerLock(path, () => {
|
|
65
|
+
const next = change(readCompletionLedger(path));
|
|
66
|
+
return next === null ? true : replaceCompletionLedger(path, next);
|
|
67
|
+
}, false);
|
|
68
|
+
}
|
|
69
|
+
/** False when the ledger could not be persisted — the caller decides what that costs. */
|
|
70
|
+
function replaceCompletionLedger(path, ledger) {
|
|
71
|
+
// Unique per write, not per process: a worker thread shares the pid with its parent.
|
|
72
|
+
const temporary = `${path}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
|
|
73
|
+
try {
|
|
74
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
75
|
+
writeFileSync(temporary, `${JSON.stringify(ledger, null, 2)}\n`, 'utf8');
|
|
76
|
+
renameSync(temporary, path);
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
// A failed rename leaves the temp file behind, and every attempt now picks a new name,
|
|
81
|
+
// so sweeping it up here is what keeps a retry loop from filling the directory.
|
|
82
|
+
rmSync(temporary, { force: true });
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export function rememberUnqueued(path, queueTask, error) {
|
|
87
|
+
updateCompletionLedger(path, (ledger) => ({
|
|
88
|
+
...ledger,
|
|
89
|
+
unqueued: { ...(ledger.unqueued ?? {}), [queueTask.id]: { taskId: queueTask.id, queueTask, attempts: (ledger.unqueued?.[queueTask.id]?.attempts ?? 0) + 1, lastError: error } },
|
|
90
|
+
}));
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Release a claim — but only the filing named, when one is. A retry round that decided in
|
|
94
|
+
* favour of dropping an old claim shares its queue id with whatever was registered since,
|
|
95
|
+
* and deleting by id alone takes that newer filing's ownership with it.
|
|
96
|
+
*/
|
|
97
|
+
function forgetOwned(path, queueTaskId, generation) {
|
|
98
|
+
updateCompletionLedger(path, (ledger) => {
|
|
99
|
+
const held = ledger.owned?.[queueTaskId];
|
|
100
|
+
if (!held)
|
|
101
|
+
return null;
|
|
102
|
+
if (generation !== undefined && held.generation !== generation)
|
|
103
|
+
return null;
|
|
104
|
+
const owned = { ...ledger.owned };
|
|
105
|
+
delete owned[queueTaskId];
|
|
106
|
+
return { ...ledger, owned };
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
/** The same claim, not merely the same task id: filing and attempt both have to agree. */
|
|
110
|
+
function sameClaim(current, other) {
|
|
111
|
+
if (!current || !other)
|
|
112
|
+
return false;
|
|
113
|
+
return current.queueTask.generation === other.queueTask.generation && current.attempts === other.attempts;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The same debt, not merely the same task. Asset, attempt and filing all have to agree:
|
|
117
|
+
* two filings can produce the same asset on the same attempt and still be different work.
|
|
118
|
+
*/
|
|
119
|
+
function sameDebt(current, other) {
|
|
120
|
+
if (!current || !other)
|
|
121
|
+
return false;
|
|
122
|
+
return current.resultAssetId === other.resultAssetId
|
|
123
|
+
&& current.attempts === other.attempts
|
|
124
|
+
&& current.generation === other.generation;
|
|
125
|
+
}
|
|
126
|
+
/** A deadline the clock has passed. An absent one is not expired — it is unknown. */
|
|
127
|
+
function lapsed(deadline, nowMs) {
|
|
128
|
+
if (!deadline)
|
|
129
|
+
return false;
|
|
130
|
+
const parsed = Date.parse(deadline);
|
|
131
|
+
return Number.isFinite(parsed) && parsed <= nowMs;
|
|
132
|
+
}
|
|
133
|
+
/** A commitment the Hub has stopped holding for us; it is free to re-dispatch the task. */
|
|
134
|
+
function commitmentExpired(claim, nowMs) {
|
|
135
|
+
return lapsed(claim?.commitmentDeadline, nowMs);
|
|
136
|
+
}
|
|
137
|
+
function retryDelayMs(attempts) {
|
|
138
|
+
return Math.min(COMPLETION_RETRY_BASE_MS * 2 ** Math.max(0, attempts - 1), COMPLETION_RETRY_CAP_MS);
|
|
139
|
+
}
|
|
140
|
+
/** Queue ids the receiver writes carry this prefix, so the loop can tell hub work apart. */
|
|
141
|
+
export const HUB_QUEUE_PREFIX = 'hub-';
|
|
142
|
+
/** A task id becomes a filename, so it may only be what a filename may safely be. */
|
|
143
|
+
/** The queue entry already under this id, or null when there is none we can read. */
|
|
144
|
+
export function defaultReadQueueTask(dir, id) {
|
|
145
|
+
try {
|
|
146
|
+
const parsed = JSON.parse(readFileSync(join(dir, `${id}.json`), 'utf8'));
|
|
147
|
+
return typeof parsed?.hubTaskId === 'string' ? parsed : null;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
export function defaultWriteQueueTask(dir, task) {
|
|
154
|
+
writeFileSync(join(dir, `${task.id}.json`), `${JSON.stringify(task, null, 2)}\n`, { encoding: 'utf8', flag: 'wx' });
|
|
155
|
+
}
|
|
156
|
+
export function defaultRemoveQueueTask(dir, id) {
|
|
157
|
+
rmSync(join(dir, `${id}.json`), { force: true });
|
|
158
|
+
}
|
|
159
|
+
function alreadyQueued(error) {
|
|
160
|
+
return error?.code === 'EEXIST';
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* File a claimed task under its queue id. An `EEXIST` is only "an earlier beat already did
|
|
164
|
+
* this" when the register says that queue id is ours; otherwise the name belongs to a local
|
|
165
|
+
* task, and treating the collision as success would hand its capsule to the Hub.
|
|
166
|
+
*/
|
|
167
|
+
export function fileClaim(deps, queueDir, claim) {
|
|
168
|
+
// One write-ahead record before the queue file: the claim is already spent at the Hub,
|
|
169
|
+
// so a crash here must leave behind both who owns the task (`owned`, or it can never be
|
|
170
|
+
// delivered) and that it still needs queueing (`unqueued`, or nothing will retry it).
|
|
171
|
+
const recorded = updateCompletionLedger(deps.ledgerPath, (ledger) => ({
|
|
172
|
+
...ledger,
|
|
173
|
+
owned: { ...(ledger.owned ?? {}), [claim.id]: { queueTaskId: claim.id, hubTaskId: claim.hubTaskId, generation: claim.generation, ...(claim.commitmentDeadline ? { commitmentDeadline: claim.commitmentDeadline } : {}) } },
|
|
174
|
+
unqueued: { ...(ledger.unqueued ?? {}), [claim.id]: { taskId: claim.id, queueTask: claim, attempts: ledger.unqueued?.[claim.id]?.attempts ?? 0, lastError: 'not queued yet' } },
|
|
175
|
+
}));
|
|
176
|
+
if (!recorded)
|
|
177
|
+
return 'unrecorded';
|
|
178
|
+
try {
|
|
179
|
+
deps.write(queueDir, claim);
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
if (!alreadyQueued(error))
|
|
183
|
+
throw error;
|
|
184
|
+
// The name is taken. Only the file on disk can say by what — a register entry from a
|
|
185
|
+
// previous filing proves nothing about what is sitting there now, and believing it is
|
|
186
|
+
// how a local task's capsule gets reported as this claim's result.
|
|
187
|
+
const existing = (deps.read ?? defaultReadQueueTask)(queueDir, claim.id);
|
|
188
|
+
if (existing?.hubTaskId !== claim.hubTaskId) {
|
|
189
|
+
// Not this claim's queue entry, so not its registration either: leaving it would make
|
|
190
|
+
// `claimFor` answer for a task we never filed. Only this filing's registration goes —
|
|
191
|
+
// the one written moments ago, above. The claim stays owed in `unqueued`.
|
|
192
|
+
forgetOwned(deps.ledgerPath, claim.id, claim.generation);
|
|
193
|
+
return 'name_taken';
|
|
194
|
+
}
|
|
195
|
+
if (existing.generation !== claim.generation) {
|
|
196
|
+
// Same task, earlier filing. The Hub only let us claim it again because that filing
|
|
197
|
+
// is over, so its queue entry is stale work: replace it. Taking its generation
|
|
198
|
+
// instead would let that run's late result walk through the gate as this claim's.
|
|
199
|
+
// Drop then create exclusively, so a file that changed between the read and the
|
|
200
|
+
// write collides again instead of being silently overwritten.
|
|
201
|
+
(deps.remove ?? defaultRemoveQueueTask)(queueDir, claim.id);
|
|
202
|
+
deps.write(queueDir, claim);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
clearUnqueued(deps.ledgerPath, claim.id);
|
|
206
|
+
return 'written';
|
|
207
|
+
}
|
|
208
|
+
function clearUnqueued(path, queueTaskId) {
|
|
209
|
+
updateCompletionLedger(path, (ledger) => {
|
|
210
|
+
if (!ledger.unqueued?.[queueTaskId])
|
|
211
|
+
return null;
|
|
212
|
+
const unqueued = { ...ledger.unqueued };
|
|
213
|
+
delete unqueued[queueTaskId];
|
|
214
|
+
return { ...ledger, unqueued };
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Write the debt down, unless it is no longer owed. A report that failed while an
|
|
219
|
+
* overlapping one succeeded must not come back as a pending debt: the Hub already has the
|
|
220
|
+
* result, and re-sending it is how a settled task starts failing as `not_claimed`.
|
|
221
|
+
* Returns false when nothing was recorded, so no caller promises a retry that will not come.
|
|
222
|
+
*/
|
|
223
|
+
function oweCompletion(ledgerPath, taskId, resultAssetId, error, nowMs, settled, generation) {
|
|
224
|
+
if (settled?.())
|
|
225
|
+
return false;
|
|
226
|
+
return updateCompletionLedger(ledgerPath, (ledger) => {
|
|
227
|
+
// A debt belongs to one filing. A later filing's first failure is its first attempt,
|
|
228
|
+
// not the continuation of a budget the previous one spent.
|
|
229
|
+
const prior = ledger.pending[taskId];
|
|
230
|
+
const continues = prior !== undefined && (prior.generation ?? generation) === generation;
|
|
231
|
+
const attempts = (continues ? prior.attempts : 0) + 1;
|
|
232
|
+
return { ...ledger, pending: { ...ledger.pending, [taskId]: { taskId, resultAssetId, attempts, nextAttemptMs: nowMs + retryDelayMs(attempts), lastError: error, ...(generation ? { generation } : {}) } } };
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* What a wiring with no Hub client can still do: write the debt down. A task claimed before
|
|
237
|
+
* a restart finishes in a process that may have no identity left, and dropping the report
|
|
238
|
+
* there is the one outcome the Hub cannot recover from — it waits out the whole commitment.
|
|
239
|
+
*/
|
|
240
|
+
/** A thrown transport error is the same event as a refusal, and must not escape the loop. */
|
|
241
|
+
async function hubComplete(client, taskId, assetId) {
|
|
242
|
+
try {
|
|
243
|
+
const result = await client.completeTask(taskId, assetId);
|
|
244
|
+
return result.ok ? { ok: true } : { ok: false, error: result.error ?? `hub ${result.status ?? 0}` };
|
|
245
|
+
}
|
|
246
|
+
catch (error) {
|
|
247
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const NO_RETRIES = async () => ({ retried: 0, completed: 0, abandoned: 0, pending: 0, unrecorded: 0, abandonedTasks: [] });
|
|
251
|
+
const NO_QUEUE_RETRIES = async () => ({ retried: 0, queued: 0, pending: 0, dropped: 0 });
|
|
252
|
+
export function unsentCommitments(ledgerPath, now) {
|
|
253
|
+
return {
|
|
254
|
+
claimFor: (queueTaskId) => readCompletionLedger(ledgerPath).owned?.[queueTaskId] ?? null,
|
|
255
|
+
complete: async (taskId, resultAssetId, generation) => {
|
|
256
|
+
// The same gate as the live wiring: a debt is only worth recording for a claim this
|
|
257
|
+
// node actually holds, under the filing that holds it.
|
|
258
|
+
const owned = readCompletionLedger(ledgerPath).owned?.[`${HUB_QUEUE_PREFIX}${taskId}`];
|
|
259
|
+
if (!owned)
|
|
260
|
+
return { taskId, completed: false, error: 'not_claimed' };
|
|
261
|
+
if (owned.generation !== generation)
|
|
262
|
+
return { taskId, completed: false, error: 'stale_generation' };
|
|
263
|
+
// Nothing can send this now, so writing it down is the whole job — and claiming a
|
|
264
|
+
// retry the ledger never recorded would promise a delivery no later run can make.
|
|
265
|
+
const recorded = oweCompletion(ledgerPath, taskId, resultAssetId, 'task_receiver_disabled', now(), undefined, generation);
|
|
266
|
+
return { taskId, completed: false, error: 'task_receiver_disabled', ...(recorded ? { pending: true } : { unrecorded: true }) };
|
|
267
|
+
},
|
|
268
|
+
retryCompletions: NO_RETRIES,
|
|
269
|
+
retryQueueWrites: NO_QUEUE_RETRIES,
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
export function liveCommitments(client, deps) {
|
|
273
|
+
const { ledgerPath, now, queueDir } = deps;
|
|
274
|
+
// Clearing a debt is itself a ledger write, and a write that did not land leaves the
|
|
275
|
+
// record disagreeing with what the caller was told. `unrecorded` says so out loud.
|
|
276
|
+
// Clearing a debt is itself a ledger write, and a write that did not land leaves the
|
|
277
|
+
// record disagreeing with what the caller was told. `unrecorded` says so out loud.
|
|
278
|
+
// The claim only goes with it when it is the claim this debt was made under: a later
|
|
279
|
+
// filing shares the task id and is still held.
|
|
280
|
+
const settle = (taskId, outcome, generation) => {
|
|
281
|
+
const persisted = updateCompletionLedger(ledgerPath, (ledger) => {
|
|
282
|
+
const queueTaskId = `${HUB_QUEUE_PREFIX}${taskId}`;
|
|
283
|
+
const owned = { ...(ledger.owned ?? {}) };
|
|
284
|
+
// The claim goes only when this debt can prove the claim is its own. A debt written
|
|
285
|
+
// before the field existed cannot prove it, and an unknown generation must not read
|
|
286
|
+
// as a wildcard: releasing a claim that a later filing now holds is worse than
|
|
287
|
+
// leaving a dead register entry for the next filing to overwrite.
|
|
288
|
+
if (generation !== undefined && owned[queueTaskId]?.generation === generation)
|
|
289
|
+
delete owned[queueTaskId];
|
|
290
|
+
const pending = { ...ledger.pending };
|
|
291
|
+
// The debt itself is this task's either way: a legacy entry has no filing to belong
|
|
292
|
+
// to, and one naming a later filing is not the entry this settle was called for.
|
|
293
|
+
const debt = pending[taskId];
|
|
294
|
+
if (debt && (debt.generation === undefined || debt.generation === generation))
|
|
295
|
+
delete pending[taskId];
|
|
296
|
+
return { ...ledger, pending, owned };
|
|
297
|
+
});
|
|
298
|
+
return persisted ? outcome : { ...outcome, unrecorded: true };
|
|
299
|
+
};
|
|
300
|
+
// A debt is only this attempt's to settle while the ledger still holds the entry the
|
|
301
|
+
// attempt was made against. A late response must never clear a newer one for another asset.
|
|
302
|
+
const stillOurs = (entry) => {
|
|
303
|
+
const current = readCompletionLedger(ledgerPath).pending[entry.taskId];
|
|
304
|
+
return sameDebt(current, entry);
|
|
305
|
+
};
|
|
306
|
+
// A task the register has let go of has been settled — by this pass or an overlapping
|
|
307
|
+
// one — and its debt is paid. `held` is read before the Hub call, so a claim that was
|
|
308
|
+
// never registered (an old ledger) does not read as "settled" here.
|
|
309
|
+
// Settled, or moved on: either way this filing no longer holds the claim, and a debt
|
|
310
|
+
// recorded for it now would block the filing that does from recording its own.
|
|
311
|
+
const settledSince = (taskId, held, generation) => () => {
|
|
312
|
+
if (!held)
|
|
313
|
+
return false;
|
|
314
|
+
const owned = readCompletionLedger(ledgerPath).owned?.[`${HUB_QUEUE_PREFIX}${taskId}`];
|
|
315
|
+
return owned === undefined || owned.generation !== generation;
|
|
316
|
+
};
|
|
317
|
+
// Two reports for the same task can fail out of order. `before` is what the ledger held
|
|
318
|
+
// when this attempt started; anything else on record now is a later word than this one.
|
|
319
|
+
const supersededSince = (taskId, before) => () => {
|
|
320
|
+
const current = readCompletionLedger(ledgerPath).pending[taskId];
|
|
321
|
+
if (!current)
|
|
322
|
+
return false;
|
|
323
|
+
return !sameDebt(current, before);
|
|
324
|
+
};
|
|
325
|
+
const owe = (taskId, resultAssetId, error, settled, generation) => {
|
|
326
|
+
const recorded = oweCompletion(ledgerPath, taskId, resultAssetId, error, now(), settled, generation);
|
|
327
|
+
// Only a recorded debt is a promised retry; an unwritable ledger has to say so.
|
|
328
|
+
return { taskId, completed: false, error, ...(recorded ? { pending: true } : { unrecorded: true }) };
|
|
329
|
+
};
|
|
330
|
+
const report = async (taskId, resultAssetId, generation) => {
|
|
331
|
+
const opening = readCompletionLedger(ledgerPath);
|
|
332
|
+
const owned = opening.owned?.[`${HUB_QUEUE_PREFIX}${taskId}`];
|
|
333
|
+
const wasHeld = Boolean(owned);
|
|
334
|
+
const before = opening.pending[taskId];
|
|
335
|
+
// Only a claim this node registered may be completed, and only by the filing that
|
|
336
|
+
// holds it. No record, or a record from a later filing, and the result is not ours to
|
|
337
|
+
// hand over — the Hub cannot take a completion back once it has one.
|
|
338
|
+
if (!owned)
|
|
339
|
+
return { taskId, completed: false, error: 'not_claimed' };
|
|
340
|
+
if (owned.generation !== generation)
|
|
341
|
+
return { taskId, completed: false, error: 'stale_generation' };
|
|
342
|
+
// The Hub holds a task for its claimant only until the commitment runs out. Past that
|
|
343
|
+
// it may have re-dispatched the work, and a late report would overwrite whoever now
|
|
344
|
+
// owns it — so stop, and name the orphaned asset loudly enough to be recoverable.
|
|
345
|
+
if (commitmentExpired(owned, now())) {
|
|
346
|
+
// This filing's commitment is over, so this filing's claim goes with it — scoped, so
|
|
347
|
+
// a re-claim that happened in the meantime keeps the claim it made.
|
|
348
|
+
return settle(taskId, { taskId, completed: false, error: 'commitment_expired' }, generation);
|
|
349
|
+
}
|
|
350
|
+
const result = await hubComplete(client, taskId, resultAssetId);
|
|
351
|
+
const stale = settledSince(taskId, wasHeld, generation);
|
|
352
|
+
const superseded = supersededSince(taskId, before);
|
|
353
|
+
// The Hub has this asset. Whatever this filing owed is paid, including a debt another
|
|
354
|
+
// attempt of the SAME filing recorded while we waited — leaving it would re-send a
|
|
355
|
+
// completed task. A later filing's debt is another claim's and stays.
|
|
356
|
+
if (result.ok)
|
|
357
|
+
return settle(taskId, { taskId, completed: true }, generation);
|
|
358
|
+
// The work is done and the Hub does not know it. Owe the report and retry it on
|
|
359
|
+
// later beats — otherwise a transient 429 silently costs us the whole delivery.
|
|
360
|
+
return owe(taskId, resultAssetId, result.error, () => stale() || superseded(), generation);
|
|
361
|
+
};
|
|
362
|
+
return {
|
|
363
|
+
claimFor: (queueTaskId) => readCompletionLedger(ledgerPath).owned?.[queueTaskId] ?? null,
|
|
364
|
+
complete: report,
|
|
365
|
+
retryQueueWrites: async () => {
|
|
366
|
+
const ledger = readCompletionLedger(ledgerPath);
|
|
367
|
+
const owed = Object.values(ledger.unqueued ?? {});
|
|
368
|
+
const out = { retried: 0, queued: 0, pending: owed.length, dropped: 0 };
|
|
369
|
+
if (owed.length === 0 || !queueDir)
|
|
370
|
+
return out;
|
|
371
|
+
// What this pass decided, key by key. Replacing the whole `unqueued` map with a
|
|
372
|
+
// snapshot taken before the work would delete any claim another writer filed while
|
|
373
|
+
// this pass ran — the lock protects the write, not a stale picture carried into it.
|
|
374
|
+
const settled = new Set();
|
|
375
|
+
const requeued = new Map();
|
|
376
|
+
const seen = new Map(owed.map((entry) => [entry.taskId, entry]));
|
|
377
|
+
for (const entry of owed) {
|
|
378
|
+
// A claim whose commitment ran out is not work any more, and neither is one whose
|
|
379
|
+
// queue name is permanently taken: both would otherwise sit here being retried for
|
|
380
|
+
// the life of the process.
|
|
381
|
+
if (lapsed(entry.queueTask.commitmentDeadline, now()) || entry.attempts >= UNQUEUED_MAX_ATTEMPTS) {
|
|
382
|
+
settled.add(entry.taskId);
|
|
383
|
+
forgetOwned(ledgerPath, entry.taskId, entry.queueTask.generation);
|
|
384
|
+
out.dropped += 1;
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
out.retried += 1;
|
|
388
|
+
try {
|
|
389
|
+
const filed = fileClaim(deps, queueDir, entry.queueTask);
|
|
390
|
+
if (filed === 'name_taken' || filed === 'unrecorded') {
|
|
391
|
+
requeued.set(entry.taskId, { ...entry, attempts: entry.attempts + 1, lastError: filed === 'name_taken' ? 'queue id taken by another task' : 'ownership could not be recorded' });
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
settled.add(entry.taskId);
|
|
395
|
+
out.queued += 1;
|
|
396
|
+
}
|
|
397
|
+
catch (error) {
|
|
398
|
+
requeued.set(entry.taskId, { ...entry, attempts: entry.attempts + 1, lastError: error instanceof Error ? error.message : String(error) });
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
updateCompletionLedger(ledgerPath, (ledger) => {
|
|
402
|
+
const unqueued = { ...(ledger.unqueued ?? {}) };
|
|
403
|
+
// Each key is written back only while it still holds the claim this pass answered
|
|
404
|
+
// for. A filing recorded by another writer meanwhile shares the task id and is not
|
|
405
|
+
// this pass's to delete or to overwrite with an older generation and attempt count.
|
|
406
|
+
for (const taskId of settled) {
|
|
407
|
+
if (sameClaim(unqueued[taskId], seen.get(taskId)))
|
|
408
|
+
delete unqueued[taskId];
|
|
409
|
+
}
|
|
410
|
+
for (const [taskId, entry] of requeued) {
|
|
411
|
+
if (sameClaim(unqueued[taskId], seen.get(taskId)))
|
|
412
|
+
unqueued[taskId] = entry;
|
|
413
|
+
}
|
|
414
|
+
return { ...ledger, unqueued };
|
|
415
|
+
});
|
|
416
|
+
out.pending = Object.keys(readCompletionLedger(ledgerPath).unqueued ?? {}).length;
|
|
417
|
+
return out;
|
|
418
|
+
},
|
|
419
|
+
retryCompletions: async () => {
|
|
420
|
+
const ledger = readCompletionLedger(ledgerPath);
|
|
421
|
+
// Oldest due first, not insertion order: a fixed slice of an unsorted map lets the
|
|
422
|
+
// same five debts hold every slot forever while the ones behind them expire unsent.
|
|
423
|
+
const due = Object.values(ledger.pending)
|
|
424
|
+
.filter((entry) => entry.nextAttemptMs <= now())
|
|
425
|
+
.sort((left, right) => left.nextAttemptMs - right.nextAttemptMs)
|
|
426
|
+
.slice(0, COMPLETION_RETRIES_PER_TICK);
|
|
427
|
+
const out = { retried: 0, completed: 0, abandoned: 0, pending: Object.keys(ledger.pending).length, unrecorded: 0, abandonedTasks: [] };
|
|
428
|
+
for (const entry of due) {
|
|
429
|
+
out.retried += 1;
|
|
430
|
+
const owned = readCompletionLedger(ledgerPath).owned?.[`${HUB_QUEUE_PREFIX}${entry.taskId}`];
|
|
431
|
+
if (commitmentExpired(owned, now())) {
|
|
432
|
+
if (!stillOurs(entry))
|
|
433
|
+
continue;
|
|
434
|
+
// A debt the ledger still holds has not been let go of, whatever this tick says.
|
|
435
|
+
if (settle(entry.taskId, { taskId: entry.taskId, completed: false }, entry.generation).unrecorded) {
|
|
436
|
+
out.unrecorded += 1;
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
out.abandoned += 1;
|
|
440
|
+
out.abandonedTasks.push({ taskId: entry.taskId, resultAssetId: entry.resultAssetId, lastError: 'commitment_expired' });
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
// The same gate the first report passed: a debt with no claim behind it, or one
|
|
444
|
+
// whose claim moved on to a later filing, is not ours to send. Drop it, and leave
|
|
445
|
+
// any claim that is not this debt's alone — it is still held.
|
|
446
|
+
if (!owned || owned.generation !== entry.generation) {
|
|
447
|
+
if (stillOurs(entry))
|
|
448
|
+
settle(entry.taskId, { taskId: entry.taskId, completed: false }, entry.generation);
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
const result = await hubComplete(client, entry.taskId, entry.resultAssetId);
|
|
452
|
+
if (result.ok) {
|
|
453
|
+
// The Hub has the result; the record must go even if a newer debt replaced it.
|
|
454
|
+
if (settle(entry.taskId, { taskId: entry.taskId, completed: true }, entry.generation).unrecorded)
|
|
455
|
+
out.unrecorded += 1;
|
|
456
|
+
out.completed += 1;
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
// Both outcomes below rewrite the ledger, so both need the same proof that this
|
|
460
|
+
// attempt's debt is still the one on record — giving up is a deletion, and a stale
|
|
461
|
+
// response must not delete a newer debt any more than it may overwrite one.
|
|
462
|
+
if (!stillOurs(entry))
|
|
463
|
+
continue;
|
|
464
|
+
const attempts = entry.attempts + 1;
|
|
465
|
+
if (attempts >= COMPLETION_MAX_ATTEMPTS) {
|
|
466
|
+
if (settle(entry.taskId, { taskId: entry.taskId, completed: false }, entry.generation).unrecorded) {
|
|
467
|
+
out.unrecorded += 1;
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
out.abandoned += 1;
|
|
471
|
+
out.abandonedTasks.push({ taskId: entry.taskId, resultAssetId: entry.resultAssetId, lastError: result.error });
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
const written = updateCompletionLedger(ledgerPath, (ledger) => {
|
|
475
|
+
// Re-checked under the lock, not merely before it: the debt may have been
|
|
476
|
+
// settled or replaced between the check above and this write.
|
|
477
|
+
if (!sameDebt(ledger.pending[entry.taskId], entry))
|
|
478
|
+
return null;
|
|
479
|
+
return { ...ledger, pending: { ...ledger.pending, [entry.taskId]: { ...entry, attempts, nextAttemptMs: now() + retryDelayMs(attempts), lastError: result.error } } };
|
|
480
|
+
});
|
|
481
|
+
if (!written)
|
|
482
|
+
out.unrecorded += 1;
|
|
483
|
+
}
|
|
484
|
+
out.pending = Object.keys(readCompletionLedger(ledgerPath).pending).length;
|
|
485
|
+
return out;
|
|
486
|
+
},
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
/** The Hub task id behind an execute-queue id, or null when the task is local. */
|
|
490
|
+
export function hubTaskIdOf(queueTaskId) {
|
|
491
|
+
return queueTaskId.startsWith(HUB_QUEUE_PREFIX) ? queueTaskId.slice(HUB_QUEUE_PREFIX.length) : null;
|
|
492
|
+
}
|