@evomap/evolver-cli 2.0.36 → 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,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* taskReceiver — pulls tasks the Hub offers this node, scores them, claims the
|
|
3
|
+
* one worth doing, and shapes it for the execute queue.
|
|
4
|
+
*
|
|
5
|
+
* Ported from evolver v1 (`src/gep/taskReceiver.js`), which v2 dropped: the
|
|
6
|
+
* adapter kept `listMyTasks` but nothing could fetch, score, claim or complete,
|
|
7
|
+
* so a v2 node saw its tasks and could never take one.
|
|
8
|
+
*/
|
|
9
|
+
import { AtpHubClient } from '@evomap/evolver-adapter-public';
|
|
10
|
+
import { type CommitmentWiring, type OwnedClaim, type QueueTask } from './taskCommitments.js';
|
|
11
|
+
export { COMPLETION_LEDGER_FILENAME, HUB_QUEUE_PREFIX, completionLedgerPath, hubTaskIdOf, readCompletionLedger, type CompletedTask, type CompletionRetryResult, type OwnedClaim, type PendingClaim, type PendingCompletion, type PendingCompletionLedger, type QueueRetryResult, type QueueTask, } from './taskCommitments.js';
|
|
12
|
+
export declare const TASK_STRATEGIES: readonly ["greedy", "balanced", "conservative"];
|
|
13
|
+
export type TaskStrategy = (typeof TASK_STRATEGIES)[number];
|
|
14
|
+
export interface HubTask {
|
|
15
|
+
task_id: string;
|
|
16
|
+
title?: string;
|
|
17
|
+
body?: string;
|
|
18
|
+
description?: string;
|
|
19
|
+
status?: string;
|
|
20
|
+
claimed_by?: string | null;
|
|
21
|
+
signals?: string[] | string | null;
|
|
22
|
+
bounty_id?: string | null;
|
|
23
|
+
bounty_amount?: number;
|
|
24
|
+
complexity_score?: number | null;
|
|
25
|
+
historical_completion_rate?: number | null;
|
|
26
|
+
expires_at?: string | null;
|
|
27
|
+
/** The Hub's own view of how long it is holding the task for its claimant. */
|
|
28
|
+
commitment_deadline?: string | null;
|
|
29
|
+
result_asset_id?: string | null;
|
|
30
|
+
}
|
|
31
|
+
export interface MemoryEvent {
|
|
32
|
+
signals?: string[] | string | null;
|
|
33
|
+
status?: string;
|
|
34
|
+
}
|
|
35
|
+
/** The cycle log as this module needs to see it: a type and whatever payload came with it. */
|
|
36
|
+
export interface CycleLogEvent {
|
|
37
|
+
type: string;
|
|
38
|
+
payload?: unknown;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The node's own record of what it has finished, folded out of the cycle log: each terminal
|
|
42
|
+
* cycle joined to the signals that drove it. Without this, capability matching scores every
|
|
43
|
+
* task against an empty history and the strategy weights never touch a real decision.
|
|
44
|
+
*/
|
|
45
|
+
export declare function memoryEventsFromCycleLog(events: readonly CycleLogEvent[], window?: number): MemoryEvent[];
|
|
46
|
+
export interface TaskScore {
|
|
47
|
+
composite: number;
|
|
48
|
+
factors: {
|
|
49
|
+
roi: number;
|
|
50
|
+
capability: number;
|
|
51
|
+
completion: number;
|
|
52
|
+
bounty: number;
|
|
53
|
+
difficulty: number;
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
export declare function taskStrategy(env?: NodeJS.ProcessEnv): TaskStrategy;
|
|
57
|
+
export declare function minCapabilityMatch(env?: NodeJS.ProcessEnv): number;
|
|
58
|
+
export declare function parseSignals(signals: HubTask['signals']): string[];
|
|
59
|
+
/** How much this node's own history looks like the task, in [0, 1]. */
|
|
60
|
+
export declare function estimateCapabilityMatch(task: HubTask, memoryEvents?: readonly MemoryEvent[]): number;
|
|
61
|
+
export declare function localDifficultyEstimate(task: HubTask): number;
|
|
62
|
+
export declare function scoreTask(task: HubTask, capabilityMatch: number, strategy?: TaskStrategy): TaskScore;
|
|
63
|
+
export interface TaskSelection {
|
|
64
|
+
task: HubTask;
|
|
65
|
+
reason: 'resume' | 'scored';
|
|
66
|
+
score?: TaskScore;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Pick what to work on. A task this node already holds always wins — finishing
|
|
70
|
+
* a commitment beats starting a better one.
|
|
71
|
+
*/
|
|
72
|
+
export declare function selectBestTask(tasks: readonly HubTask[], nodeId: string, memoryEvents?: readonly MemoryEvent[], env?: NodeJS.ProcessEnv): TaskSelection | null;
|
|
73
|
+
/**
|
|
74
|
+
* Every task worth trying, best first. A ranked list rather than one winner: the
|
|
75
|
+
* top candidate can turn out to be unusable — a lapsed commitment, a window too
|
|
76
|
+
* short to promise — and one bad head must not hide the rest of the batch.
|
|
77
|
+
*/
|
|
78
|
+
export declare function rankTasks(tasks: readonly HubTask[], nodeId: string, memoryEvents?: readonly MemoryEvent[], env?: NodeJS.ProcessEnv): TaskSelection[];
|
|
79
|
+
/**
|
|
80
|
+
* What this node can honestly promise: harder tasks get longer, but never past
|
|
81
|
+
* the task's own expiry, and never a window too short to be worth claiming.
|
|
82
|
+
*/
|
|
83
|
+
export declare function estimateCommitmentDeadline(task: HubTask, now?: number): string | null;
|
|
84
|
+
export interface PrivacyParams {
|
|
85
|
+
toolId: string;
|
|
86
|
+
blobIds: string[];
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* A privacy task carries its parameters as a fenced block in the body. Ported
|
|
90
|
+
* from v1 `privacyClient.parsePrivacyParams`; the rest of that client (blob
|
|
91
|
+
* upload, sealed execution) has no v2 counterpart yet.
|
|
92
|
+
*/
|
|
93
|
+
export declare function detectPrivacyTask(task: Pick<HubTask, 'body' | 'description'>): PrivacyParams | null;
|
|
94
|
+
/** Signals an execute-queue task should carry so the loop knows what it is. */
|
|
95
|
+
export declare function taskToSignals(task: HubTask): string[];
|
|
96
|
+
/** Same signals, plus the two a sealed-tool task needs so the loop routes it. */
|
|
97
|
+
export declare function taskToSignalsWithPrivacy(task: HubTask): string[];
|
|
98
|
+
export interface ReceiveOptions {
|
|
99
|
+
nodeId: string;
|
|
100
|
+
repo: string;
|
|
101
|
+
/** The commitment behind a queue id, so a resume honours the promise that was made. */
|
|
102
|
+
claimFor?: (queueTaskId: string) => OwnedClaim | null;
|
|
103
|
+
memoryEvents?: readonly MemoryEvent[];
|
|
104
|
+
env?: NodeJS.ProcessEnv;
|
|
105
|
+
now?: () => number;
|
|
106
|
+
}
|
|
107
|
+
export interface ReceivedTask {
|
|
108
|
+
claimed: boolean;
|
|
109
|
+
reason: 'resume' | 'scored' | 'none' | 'claim_failed' | 'no_deadline' | 'fetch_failed' | 'queue_failed' | 'expired';
|
|
110
|
+
/** Tasks the Hub offered this pass — the signal that fetching works at all. */
|
|
111
|
+
seen: number;
|
|
112
|
+
/** Offered tasks dropped because their id could not be a safe filename. */
|
|
113
|
+
rejected?: number;
|
|
114
|
+
task?: HubTask;
|
|
115
|
+
score?: TaskScore;
|
|
116
|
+
commitmentDeadline?: string | null;
|
|
117
|
+
error?: string;
|
|
118
|
+
queueTask?: QueueTask;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* One receive pass: ask, choose, claim. Returns what the execute queue should
|
|
122
|
+
* run, or why nothing was taken.
|
|
123
|
+
*/
|
|
124
|
+
export declare function receiveTask(client: AtpHubClient, opts: ReceiveOptions): Promise<ReceivedTask>;
|
|
125
|
+
export interface TaskReceiverWiring extends CommitmentWiring {
|
|
126
|
+
enabled: boolean;
|
|
127
|
+
reason?: 'off' | 'no_node' | 'no_repo' | 'client_error';
|
|
128
|
+
tick: () => Promise<ReceivedTask>;
|
|
129
|
+
}
|
|
130
|
+
export declare function isSafeTaskId(taskId: unknown): taskId is string;
|
|
131
|
+
/**
|
|
132
|
+
* The Hub and the proxies in front of it serialize tasks either way, and the neighbouring
|
|
133
|
+
* `/a2a/task/my` reader already accepts both. Read one shape here so a camelCase response
|
|
134
|
+
* is not silently an empty task list.
|
|
135
|
+
*/
|
|
136
|
+
export declare function normalizeHubTask(raw: unknown): HubTask | null;
|
|
137
|
+
export interface TaskReceiverDeps {
|
|
138
|
+
client?: AtpHubClient;
|
|
139
|
+
repo?: string;
|
|
140
|
+
queueDir?: string;
|
|
141
|
+
/** Read per tick, not captured once: history the daemon writes as it runs must count. */
|
|
142
|
+
memoryEvents?: () => readonly MemoryEvent[];
|
|
143
|
+
/** Whether the loop is already running this queue id — a file it took is not a file lost. */
|
|
144
|
+
inFlight?: (queueTaskId: string) => boolean;
|
|
145
|
+
nodeId?: string;
|
|
146
|
+
now?: () => number;
|
|
147
|
+
completionLedgerPath?: string;
|
|
148
|
+
writeQueueTask?: (dir: string, task: QueueTask) => void;
|
|
149
|
+
}
|
|
150
|
+
export declare function isTaskReceiverEnabled(env?: NodeJS.ProcessEnv): boolean;
|
|
151
|
+
export declare function resolveTaskReceiver(env?: NodeJS.ProcessEnv, deps?: TaskReceiverDeps): TaskReceiverWiring;
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* taskReceiver — pulls tasks the Hub offers this node, scores them, claims the
|
|
3
|
+
* one worth doing, and shapes it for the execute queue.
|
|
4
|
+
*
|
|
5
|
+
* Ported from evolver v1 (`src/gep/taskReceiver.js`), which v2 dropped: the
|
|
6
|
+
* adapter kept `listMyTasks` but nothing could fetch, score, claim or complete,
|
|
7
|
+
* so a v2 node saw its tasks and could never take one.
|
|
8
|
+
*/
|
|
9
|
+
import { randomUUID } from 'node:crypto';
|
|
10
|
+
import { AtpHubClient } from '@evomap/evolver-adapter-public';
|
|
11
|
+
import { createAtpClientFromEnv, resolveAtpSenderId } from './atp.js';
|
|
12
|
+
import { completionLedgerPath, defaultReadQueueTask, defaultWriteQueueTask, fileClaim, liveCommitments, rememberUnqueued, unsentCommitments, HUB_QUEUE_PREFIX, } from './taskCommitments.js';
|
|
13
|
+
export { COMPLETION_LEDGER_FILENAME, HUB_QUEUE_PREFIX, completionLedgerPath, hubTaskIdOf, readCompletionLedger, } from './taskCommitments.js';
|
|
14
|
+
export const TASK_STRATEGIES = ['greedy', 'balanced', 'conservative'];
|
|
15
|
+
const STRATEGY_WEIGHTS = {
|
|
16
|
+
greedy: { roi: 0.1, capability: 0.05, completion: 0.05, bounty: 0.8 },
|
|
17
|
+
balanced: { roi: 0.35, capability: 0.3, completion: 0.2, bounty: 0.15 },
|
|
18
|
+
conservative: { roi: 0.25, capability: 0.45, completion: 0.25, bounty: 0.05 },
|
|
19
|
+
};
|
|
20
|
+
const MIN_COMMITMENT_MS = 5 * 60_000;
|
|
21
|
+
const MAX_COMMITMENT_MS = 24 * 60 * 60_000;
|
|
22
|
+
const DEADLINE_SAFETY_MS = 60_000;
|
|
23
|
+
const DIFFICULTY_DURATION = [
|
|
24
|
+
{ threshold: 0.3, durationMs: 15 * 60_000 },
|
|
25
|
+
{ threshold: 0.5, durationMs: 30 * 60_000 },
|
|
26
|
+
{ threshold: 0.7, durationMs: 60 * 60_000 },
|
|
27
|
+
{ threshold: 1.0, durationMs: 120 * 60_000 },
|
|
28
|
+
];
|
|
29
|
+
const ROI_REFERENCE = 200;
|
|
30
|
+
const BOUNTY_REFERENCE = 100;
|
|
31
|
+
const SIGNAL_SIMILARITY_FLOOR = 0.15;
|
|
32
|
+
const HISTORY_WINDOW = 200;
|
|
33
|
+
/**
|
|
34
|
+
* The node's own record of what it has finished, folded out of the cycle log: each terminal
|
|
35
|
+
* cycle joined to the signals that drove it. Without this, capability matching scores every
|
|
36
|
+
* task against an empty history and the strategy weights never touch a real decision.
|
|
37
|
+
*/
|
|
38
|
+
export function memoryEventsFromCycleLog(events, window = HISTORY_WINDOW) {
|
|
39
|
+
const statusByCycle = new Map();
|
|
40
|
+
const signalsByCycle = new Map();
|
|
41
|
+
for (const event of events) {
|
|
42
|
+
const payload = event.payload && typeof event.payload === 'object' ? event.payload : null;
|
|
43
|
+
const cycleId = typeof payload?.['cycleId'] === 'string' ? payload['cycleId'] : null;
|
|
44
|
+
if (!cycleId)
|
|
45
|
+
continue;
|
|
46
|
+
if (event.type === 'cycle.solidified')
|
|
47
|
+
statusByCycle.set(cycleId, 'success');
|
|
48
|
+
else if (event.type === 'cycle.failed')
|
|
49
|
+
statusByCycle.set(cycleId, 'failed');
|
|
50
|
+
else if (event.type === 'cycle.signals_collected') {
|
|
51
|
+
const base = payload?.['baseSignals'] ?? payload?.['signals'];
|
|
52
|
+
if (Array.isArray(base))
|
|
53
|
+
signalsByCycle.set(cycleId, base.filter((signal) => typeof signal === 'string'));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return [...statusByCycle.entries()]
|
|
57
|
+
.slice(-window)
|
|
58
|
+
.map(([cycleId, status]) => ({ status, signals: signalsByCycle.get(cycleId) ?? [] }));
|
|
59
|
+
}
|
|
60
|
+
export function taskStrategy(env = process.env) {
|
|
61
|
+
const raw = String(env.TASK_STRATEGY ?? 'balanced').toLowerCase().trim();
|
|
62
|
+
return TASK_STRATEGIES.includes(raw) ? raw : 'balanced';
|
|
63
|
+
}
|
|
64
|
+
export function minCapabilityMatch(env = process.env) {
|
|
65
|
+
const parsed = Number(env.TASK_MIN_CAPABILITY_MATCH);
|
|
66
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0.1;
|
|
67
|
+
}
|
|
68
|
+
export function parseSignals(signals) {
|
|
69
|
+
if (Array.isArray(signals))
|
|
70
|
+
return signals.map((s) => String(s).trim().toLowerCase()).filter(Boolean);
|
|
71
|
+
if (typeof signals === 'string')
|
|
72
|
+
return signals.split(/[,|]/).map((s) => s.trim().toLowerCase()).filter(Boolean);
|
|
73
|
+
return [];
|
|
74
|
+
}
|
|
75
|
+
function jaccard(left, right) {
|
|
76
|
+
if (left.length === 0 || right.length === 0)
|
|
77
|
+
return 0;
|
|
78
|
+
const a = new Set(left);
|
|
79
|
+
const b = new Set(right);
|
|
80
|
+
let shared = 0;
|
|
81
|
+
for (const value of a)
|
|
82
|
+
if (b.has(value))
|
|
83
|
+
shared += 1;
|
|
84
|
+
return shared / (a.size + b.size - shared);
|
|
85
|
+
}
|
|
86
|
+
/** How much this node's own history looks like the task, in [0, 1]. */
|
|
87
|
+
export function estimateCapabilityMatch(task, memoryEvents = []) {
|
|
88
|
+
const taskSignals = parseSignals(task.signals);
|
|
89
|
+
if (taskSignals.length === 0 || memoryEvents.length === 0)
|
|
90
|
+
return 0;
|
|
91
|
+
const seen = new Set();
|
|
92
|
+
const totals = new Map();
|
|
93
|
+
for (const event of memoryEvents) {
|
|
94
|
+
const signals = parseSignals(event.signals);
|
|
95
|
+
if (signals.length === 0)
|
|
96
|
+
continue;
|
|
97
|
+
for (const signal of signals)
|
|
98
|
+
seen.add(signal);
|
|
99
|
+
const key = signals.join('|');
|
|
100
|
+
const entry = totals.get(key) ?? { total: 0, success: 0 };
|
|
101
|
+
entry.total += 1;
|
|
102
|
+
if (event.status === 'success')
|
|
103
|
+
entry.success += 1;
|
|
104
|
+
totals.set(key, entry);
|
|
105
|
+
}
|
|
106
|
+
const overlap = jaccard(taskSignals, [...seen]);
|
|
107
|
+
let weighted = 0;
|
|
108
|
+
let weight = 0;
|
|
109
|
+
for (const [key, entry] of totals) {
|
|
110
|
+
const similarity = jaccard(taskSignals, key.split('|'));
|
|
111
|
+
if (similarity < SIGNAL_SIMILARITY_FLOOR)
|
|
112
|
+
continue;
|
|
113
|
+
// Laplace smoothing keeps a single lucky success from reading as certainty.
|
|
114
|
+
weighted += ((entry.success + 1) / (entry.total + 2)) * similarity;
|
|
115
|
+
weight += similarity;
|
|
116
|
+
}
|
|
117
|
+
const successScore = weight > 0 ? weighted / weight : 0.5;
|
|
118
|
+
return Math.min(1, overlap * 0.4 + successScore * 0.6);
|
|
119
|
+
}
|
|
120
|
+
export function localDifficultyEstimate(task) {
|
|
121
|
+
const signalFactor = Math.min(parseSignals(task.signals).length / 8, 1);
|
|
122
|
+
const words = String(task.title ?? '').split(/\s+/).filter(Boolean).length;
|
|
123
|
+
return Math.min(1, signalFactor * 0.6 + Math.min(words / 15, 1) * 0.4);
|
|
124
|
+
}
|
|
125
|
+
export function scoreTask(task, capabilityMatch, strategy = 'balanced') {
|
|
126
|
+
const weights = STRATEGY_WEIGHTS[strategy];
|
|
127
|
+
const difficulty = task.complexity_score ?? localDifficultyEstimate(task);
|
|
128
|
+
const bounty = task.bounty_amount ?? 0;
|
|
129
|
+
const completion = task.historical_completion_rate ?? 0.5;
|
|
130
|
+
const roi = Math.min(bounty / (difficulty + 0.1) / ROI_REFERENCE, 1);
|
|
131
|
+
const bountyNorm = Math.min(bounty / BOUNTY_REFERENCE, 1);
|
|
132
|
+
const composite = weights.roi * roi + weights.capability * capabilityMatch + weights.completion * completion + weights.bounty * bountyNorm;
|
|
133
|
+
return {
|
|
134
|
+
composite: round(composite, 3),
|
|
135
|
+
factors: { roi: round(roi, 2), capability: round(capabilityMatch, 2), completion: round(completion, 2), bounty: round(bountyNorm, 2), difficulty: round(difficulty, 2) },
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function round(value, digits) {
|
|
139
|
+
const factor = 10 ** digits;
|
|
140
|
+
return Math.round(value * factor) / factor;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Pick what to work on. A task this node already holds always wins — finishing
|
|
144
|
+
* a commitment beats starting a better one.
|
|
145
|
+
*/
|
|
146
|
+
export function selectBestTask(tasks, nodeId, memoryEvents = [], env = process.env) {
|
|
147
|
+
return rankTasks(tasks, nodeId, memoryEvents, env)[0] ?? null;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Every task worth trying, best first. A ranked list rather than one winner: the
|
|
151
|
+
* top candidate can turn out to be unusable — a lapsed commitment, a window too
|
|
152
|
+
* short to promise — and one bad head must not hide the rest of the batch.
|
|
153
|
+
*/
|
|
154
|
+
export function rankTasks(tasks, nodeId, memoryEvents = [], env = process.env) {
|
|
155
|
+
const mine = tasks
|
|
156
|
+
.filter((task) => task.status === 'claimed' && task.claimed_by === nodeId)
|
|
157
|
+
.map((task) => ({ task, reason: 'resume' }));
|
|
158
|
+
const open = tasks.filter((task) => task.status === 'open');
|
|
159
|
+
const strategy = taskStrategy(env);
|
|
160
|
+
if (strategy === 'greedy' && memoryEvents.length === 0) {
|
|
161
|
+
const byBounty = [...open].sort((left, right) => Number(Boolean(right.bounty_id)) - Number(Boolean(left.bounty_id)) || (right.bounty_amount ?? 0) - (left.bounty_amount ?? 0));
|
|
162
|
+
return [...mine, ...byBounty.map((task) => ({ task, reason: 'scored', score: scoreTask(task, 0, strategy) }))];
|
|
163
|
+
}
|
|
164
|
+
const floor = minCapabilityMatch(env);
|
|
165
|
+
const scored = open
|
|
166
|
+
.map((task) => ({ task, reason: 'scored', score: scoreTask(task, estimateCapabilityMatch(task, memoryEvents), strategy) }))
|
|
167
|
+
.filter((entry) => entry.score.factors.capability >= floor || memoryEvents.length === 0)
|
|
168
|
+
.sort((left, right) => right.score.composite - left.score.composite);
|
|
169
|
+
return [...mine, ...scored];
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* What this node can honestly promise: harder tasks get longer, but never past
|
|
173
|
+
* the task's own expiry, and never a window too short to be worth claiming.
|
|
174
|
+
*/
|
|
175
|
+
export function estimateCommitmentDeadline(task, now = Date.now()) {
|
|
176
|
+
const difficulty = task.complexity_score ?? localDifficultyEstimate(task);
|
|
177
|
+
const band = DIFFICULTY_DURATION.find((entry) => difficulty <= entry.threshold);
|
|
178
|
+
const durationMs = Math.max(MIN_COMMITMENT_MS, Math.min(MAX_COMMITMENT_MS, band?.durationMs ?? MAX_COMMITMENT_MS));
|
|
179
|
+
let deadline = now + durationMs;
|
|
180
|
+
if (task.expires_at) {
|
|
181
|
+
const expiresAt = Date.parse(task.expires_at);
|
|
182
|
+
if (Number.isFinite(expiresAt) && expiresAt < deadline) {
|
|
183
|
+
const adjusted = expiresAt - DEADLINE_SAFETY_MS;
|
|
184
|
+
if (adjusted - now < MIN_COMMITMENT_MS)
|
|
185
|
+
return null;
|
|
186
|
+
deadline = adjusted;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return new Date(deadline).toISOString();
|
|
190
|
+
}
|
|
191
|
+
const PRIVACY_OPEN = '[PRIVACY_PARAMS]';
|
|
192
|
+
const PRIVACY_CLOSE = '[/PRIVACY_PARAMS]';
|
|
193
|
+
/**
|
|
194
|
+
* A privacy task carries its parameters as a fenced block in the body. Ported
|
|
195
|
+
* from v1 `privacyClient.parsePrivacyParams`; the rest of that client (blob
|
|
196
|
+
* upload, sealed execution) has no v2 counterpart yet.
|
|
197
|
+
*/
|
|
198
|
+
export function detectPrivacyTask(task) {
|
|
199
|
+
const body = task.body ?? task.description ?? '';
|
|
200
|
+
if (typeof body !== 'string')
|
|
201
|
+
return null;
|
|
202
|
+
const start = body.indexOf(PRIVACY_OPEN);
|
|
203
|
+
const end = body.indexOf(PRIVACY_CLOSE);
|
|
204
|
+
if (start === -1 || end === -1 || end <= start)
|
|
205
|
+
return null;
|
|
206
|
+
const params = new Map();
|
|
207
|
+
for (const line of body.slice(start + PRIVACY_OPEN.length, end).split('\n')) {
|
|
208
|
+
const trimmed = line.trim();
|
|
209
|
+
const colon = trimmed.indexOf(':');
|
|
210
|
+
if (colon === -1)
|
|
211
|
+
continue;
|
|
212
|
+
params.set(trimmed.slice(0, colon).trim(), trimmed.slice(colon + 1).trim());
|
|
213
|
+
}
|
|
214
|
+
const toolId = params.get('tool_id');
|
|
215
|
+
if (!toolId)
|
|
216
|
+
return null;
|
|
217
|
+
return { toolId, blobIds: (params.get('blob_ids') ?? '').split(',').map((id) => id.trim()).filter(Boolean) };
|
|
218
|
+
}
|
|
219
|
+
/** Signals an execute-queue task should carry so the loop knows what it is. */
|
|
220
|
+
export function taskToSignals(task) {
|
|
221
|
+
const signals = parseSignals(task.signals);
|
|
222
|
+
const fromTitle = String(task.title ?? '').toLowerCase().split(/[^a-z0-9_]+/).filter((word) => word.length > 3).slice(0, 5);
|
|
223
|
+
return [...new Set([...signals, ...fromTitle])];
|
|
224
|
+
}
|
|
225
|
+
/** Same signals, plus the two a sealed-tool task needs so the loop routes it. */
|
|
226
|
+
export function taskToSignalsWithPrivacy(task) {
|
|
227
|
+
const signals = taskToSignals(task);
|
|
228
|
+
if (!detectPrivacyTask(task))
|
|
229
|
+
return signals;
|
|
230
|
+
return [...new Set([...signals, 'privacy_computing', 'sealed_tool'])];
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* One receive pass: ask, choose, claim. Returns what the execute queue should
|
|
234
|
+
* run, or why nothing was taken.
|
|
235
|
+
*/
|
|
236
|
+
export async function receiveTask(client, opts) {
|
|
237
|
+
const env = opts.env ?? process.env;
|
|
238
|
+
const now = opts.now ?? Date.now;
|
|
239
|
+
const fetched = await call(() => client.fetchTasks());
|
|
240
|
+
// A failed fetch is not an idle Hub. Saying "none" here hid a 401 behind silence.
|
|
241
|
+
if (!fetched.ok)
|
|
242
|
+
return { claimed: false, reason: 'fetch_failed', seen: 0, error: errorOf(fetched) };
|
|
243
|
+
// A task id lands in a queue filename: anything outside the safe charset (a `..`
|
|
244
|
+
// segment above all) would write outside the queue directory, so drop it here.
|
|
245
|
+
const offered = Array.isArray(fetched.data?.tasks) ? fetched.data.tasks : [];
|
|
246
|
+
const tasks = offered.map(normalizeHubTask).filter((task) => task !== null);
|
|
247
|
+
const seen = { seen: tasks.length, ...(offered.length > tasks.length ? { rejected: offered.length - tasks.length } : {}) };
|
|
248
|
+
let blocked = null;
|
|
249
|
+
for (const selection of rankTasks(tasks, opts.nodeId, opts.memoryEvents ?? [], env)) {
|
|
250
|
+
const taken = selection.reason === 'resume'
|
|
251
|
+
? resumeClaim(selection, opts, now())
|
|
252
|
+
: await takeClaim(client, selection, opts, now());
|
|
253
|
+
if (taken.claimed)
|
|
254
|
+
return { ...taken, ...seen };
|
|
255
|
+
// One unusable head must not hide the rest of the batch: remember why, keep looking.
|
|
256
|
+
blocked ??= taken;
|
|
257
|
+
}
|
|
258
|
+
return blocked ? { ...blocked, ...seen } : { claimed: false, reason: 'none', ...seen };
|
|
259
|
+
}
|
|
260
|
+
/** A task this node already holds: no second claim, but the promise must still stand. */
|
|
261
|
+
function resumeClaim(selection, opts, nowMs) {
|
|
262
|
+
const held = opts.claimFor?.(`${HUB_QUEUE_PREFIX}${selection.task.task_id}`);
|
|
263
|
+
const deadline = held?.commitmentDeadline ?? commitmentDeadlineOf(selection.task);
|
|
264
|
+
// No record of the promise, and the Hub did not restate it. Inventing a fresh window
|
|
265
|
+
// here would make a commitment that lapsed weeks ago look alive on every restart, so
|
|
266
|
+
// the claim is not resumed — the Hub releases it at its own deadline either way.
|
|
267
|
+
if (!deadline) {
|
|
268
|
+
return { claimed: false, reason: 'expired', seen: 0, task: selection.task, commitmentDeadline: null };
|
|
269
|
+
}
|
|
270
|
+
const parsed = Date.parse(deadline);
|
|
271
|
+
if (Number.isFinite(parsed) && parsed <= nowMs) {
|
|
272
|
+
return { claimed: false, reason: 'expired', seen: 0, task: selection.task, commitmentDeadline: deadline };
|
|
273
|
+
}
|
|
274
|
+
// Resuming is the same filing, not a new one: keep the generation the claim was filed
|
|
275
|
+
// under, or a result from the run already in flight would look stale on return.
|
|
276
|
+
return { claimed: true, reason: 'resume', seen: 0, task: selection.task, score: selection.score, queueTask: queueTaskFor(selection.task, opts.repo, deadline, held?.generation ?? newGeneration()) };
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* The Hub's own view of how long it is holding a task for its claimant. Not `expires_at`:
|
|
280
|
+
* the bounty outlives the commitment by days, and resuming on it is how a node keeps
|
|
281
|
+
* working on something that was re-dispatched hours ago.
|
|
282
|
+
*/
|
|
283
|
+
function commitmentDeadlineOf(task) {
|
|
284
|
+
const raw = task.commitment_deadline ?? null;
|
|
285
|
+
return typeof raw === 'string' && Number.isFinite(Date.parse(raw)) ? raw : null;
|
|
286
|
+
}
|
|
287
|
+
/** A task no one holds: promise a deadline this node can keep, then take it. */
|
|
288
|
+
async function takeClaim(client, selection, opts, nowMs) {
|
|
289
|
+
const commitmentDeadline = estimateCommitmentDeadline(selection.task, nowMs);
|
|
290
|
+
if (!commitmentDeadline) {
|
|
291
|
+
return { claimed: false, reason: 'no_deadline', seen: 0, task: selection.task, score: selection.score, commitmentDeadline: null };
|
|
292
|
+
}
|
|
293
|
+
const claim = await call(() => client.claimTask(selection.task.task_id, { commitmentDeadline }));
|
|
294
|
+
if (!claim.ok) {
|
|
295
|
+
return { claimed: false, reason: 'claim_failed', seen: 0, task: selection.task, score: selection.score, commitmentDeadline, error: errorOf(claim) };
|
|
296
|
+
}
|
|
297
|
+
return { claimed: true, reason: 'scored', seen: 0, task: selection.task, score: selection.score, commitmentDeadline, queueTask: queueTaskFor(selection.task, opts.repo, commitmentDeadline, newGeneration()) };
|
|
298
|
+
}
|
|
299
|
+
/** The execute-queue entry under this id, if the loop has not taken it yet. */
|
|
300
|
+
function queuedTask(queueDir, id) {
|
|
301
|
+
return defaultReadQueueTask(queueDir, id);
|
|
302
|
+
}
|
|
303
|
+
function newGeneration() {
|
|
304
|
+
return randomUUID().slice(0, 8);
|
|
305
|
+
}
|
|
306
|
+
function queueTaskFor(task, repo, commitmentDeadline, generation) {
|
|
307
|
+
return {
|
|
308
|
+
id: `${HUB_QUEUE_PREFIX}${task.task_id}`,
|
|
309
|
+
hubTaskId: task.task_id,
|
|
310
|
+
generation,
|
|
311
|
+
repo,
|
|
312
|
+
target: String(task.title ?? task.task_id).slice(0, 200),
|
|
313
|
+
expectedEffect: `complete hub task ${task.task_id}`,
|
|
314
|
+
signals: taskToSignalsWithPrivacy(task),
|
|
315
|
+
...(commitmentDeadline ? { commitmentDeadline } : {}),
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
/** A thrown transport error is the same event as `{ ok: false }` and must read as one. */
|
|
319
|
+
async function call(rpc) {
|
|
320
|
+
try {
|
|
321
|
+
return await rpc();
|
|
322
|
+
}
|
|
323
|
+
catch (error) {
|
|
324
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function errorOf(result) {
|
|
328
|
+
return result.error ?? `hub ${result.status ?? 0}`;
|
|
329
|
+
}
|
|
330
|
+
const SAFE_TASK_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
331
|
+
export function isSafeTaskId(taskId) {
|
|
332
|
+
return typeof taskId === 'string' && SAFE_TASK_ID.test(taskId);
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* The Hub and the proxies in front of it serialize tasks either way, and the neighbouring
|
|
336
|
+
* `/a2a/task/my` reader already accepts both. Read one shape here so a camelCase response
|
|
337
|
+
* is not silently an empty task list.
|
|
338
|
+
*/
|
|
339
|
+
export function normalizeHubTask(raw) {
|
|
340
|
+
if (!raw || typeof raw !== 'object')
|
|
341
|
+
return null;
|
|
342
|
+
const task = raw;
|
|
343
|
+
const pick = (...keys) => {
|
|
344
|
+
for (const key of keys)
|
|
345
|
+
if (task[key] !== undefined && task[key] !== null)
|
|
346
|
+
return task[key];
|
|
347
|
+
return undefined;
|
|
348
|
+
};
|
|
349
|
+
const taskId = pick('task_id', 'taskId');
|
|
350
|
+
if (!isSafeTaskId(taskId))
|
|
351
|
+
return null;
|
|
352
|
+
return {
|
|
353
|
+
...task,
|
|
354
|
+
task_id: taskId,
|
|
355
|
+
...(pick('claimed_by', 'claimedBy') === undefined ? {} : { claimed_by: pick('claimed_by', 'claimedBy') }),
|
|
356
|
+
...(pick('bounty_amount', 'bountyAmount') === undefined ? {} : { bounty_amount: pick('bounty_amount', 'bountyAmount') }),
|
|
357
|
+
...(pick('bounty_id', 'bountyId') === undefined ? {} : { bounty_id: pick('bounty_id', 'bountyId') }),
|
|
358
|
+
...(pick('expires_at', 'expiresAt') === undefined ? {} : { expires_at: pick('expires_at', 'expiresAt') }),
|
|
359
|
+
...(pick('commitment_deadline', 'commitmentDeadline') === undefined ? {} : { commitment_deadline: pick('commitment_deadline', 'commitmentDeadline') }),
|
|
360
|
+
...(pick('complexity_score', 'complexityScore') === undefined ? {} : { complexity_score: pick('complexity_score', 'complexityScore') }),
|
|
361
|
+
...(pick('historical_completion_rate', 'historicalCompletionRate') === undefined ? {} : { historical_completion_rate: pick('historical_completion_rate', 'historicalCompletionRate') }),
|
|
362
|
+
...(pick('result_asset_id', 'resultAssetId') === undefined ? {} : { result_asset_id: pick('result_asset_id', 'resultAssetId') }),
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
const IDLE = { claimed: false, reason: 'none', seen: 0 };
|
|
366
|
+
export function isTaskReceiverEnabled(env = process.env) {
|
|
367
|
+
return String(env['EVOLVER_TASK_RECEIVER'] ?? 'on').toLowerCase().trim() !== '0';
|
|
368
|
+
}
|
|
369
|
+
function hubClientOrNull(env, deps) {
|
|
370
|
+
try {
|
|
371
|
+
return deps.client ?? createAtpClientFromEnv(env);
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
return null;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
export function resolveTaskReceiver(env = process.env, deps = {}) {
|
|
378
|
+
const ledgerPath = deps.completionLedgerPath ?? completionLedgerPath(env);
|
|
379
|
+
const now = deps.now ?? (() => Date.now());
|
|
380
|
+
const write = deps.writeQueueTask ?? defaultWriteQueueTask;
|
|
381
|
+
// One identity, and it is the client's: filtering tasks as one node while claiming and
|
|
382
|
+
// completing them as another is how a node skips its own work and takes someone else's.
|
|
383
|
+
// With a client present its answer is final — an env or caller value is not bound to the
|
|
384
|
+
// credentials that will do the claiming, so it only stands in when there is no client.
|
|
385
|
+
const client = hubClientOrNull(env, deps);
|
|
386
|
+
const nodeId = client ? client.nodeId?.() : deps.nodeId ?? resolveAtpSenderId(env);
|
|
387
|
+
// A promise made in an earlier run outlives the switch, the identity and the process that
|
|
388
|
+
// made it, so the debt is carried on every wiring — receiving new work is what turns off.
|
|
389
|
+
const commitmentDeps = { ledgerPath, now, write, ...(deps.queueDir ? { queueDir: deps.queueDir } : {}) };
|
|
390
|
+
const commitments = client ? liveCommitments(client, commitmentDeps) : unsentCommitments(ledgerPath, now);
|
|
391
|
+
const off = (reason) => ({ enabled: false, reason, tick: async () => IDLE, ...commitments });
|
|
392
|
+
if (!isTaskReceiverEnabled(env))
|
|
393
|
+
return off('off');
|
|
394
|
+
if (!nodeId)
|
|
395
|
+
return off('no_node');
|
|
396
|
+
if (!client)
|
|
397
|
+
return off('client_error');
|
|
398
|
+
if (!deps.repo || !deps.queueDir)
|
|
399
|
+
return off('no_repo');
|
|
400
|
+
const repo = deps.repo;
|
|
401
|
+
const queueDir = deps.queueDir;
|
|
402
|
+
// Bound here so the pass below keeps the narrowing the guards above established.
|
|
403
|
+
const hub = client;
|
|
404
|
+
const node = nodeId;
|
|
405
|
+
// One pass at a time, whoever calls. Two overlapping passes both see a task as
|
|
406
|
+
// unclaimed, both claim it, and the Hub commitment ends up with two queue entries.
|
|
407
|
+
// autoexec happens to single-flight its tick; the guarantee belongs here, not there.
|
|
408
|
+
let inProgress = null;
|
|
409
|
+
return {
|
|
410
|
+
enabled: true,
|
|
411
|
+
...commitments,
|
|
412
|
+
tick: async () => {
|
|
413
|
+
if (inProgress)
|
|
414
|
+
return inProgress;
|
|
415
|
+
inProgress = receivePass();
|
|
416
|
+
try {
|
|
417
|
+
return await inProgress;
|
|
418
|
+
}
|
|
419
|
+
finally {
|
|
420
|
+
inProgress = null;
|
|
421
|
+
}
|
|
422
|
+
},
|
|
423
|
+
};
|
|
424
|
+
async function receivePass() {
|
|
425
|
+
const received = await receiveTask(hub, { nodeId: node, repo, claimFor: commitments.claimFor, memoryEvents: deps.memoryEvents?.() ?? [], env, now: deps.now });
|
|
426
|
+
if (!received.claimed || !received.queueTask)
|
|
427
|
+
return received;
|
|
428
|
+
// Resuming is not re-filing. A claim already registered under this generation is
|
|
429
|
+
// either sitting in the queue or being executed right now; writing it again would
|
|
430
|
+
// either be read as a stranger's queue entry or hand the executor a duplicate.
|
|
431
|
+
// "Still in the loop's hands" is the queue entry OR a run already under way: the
|
|
432
|
+
// executor moves the file out of the queue when it starts, and re-filing then would
|
|
433
|
+
// hand it the same task twice.
|
|
434
|
+
const held = commitments.claimFor(received.queueTask.id);
|
|
435
|
+
const queued = queuedTask(queueDir, received.queueTask.id)?.generation === held?.generation;
|
|
436
|
+
const inFlight = deps.inFlight?.(received.queueTask.id) ?? false;
|
|
437
|
+
if (received.reason === 'resume' && held !== null && (queued || inFlight))
|
|
438
|
+
return received;
|
|
439
|
+
// We hold a claim the moment the Hub grants it. Anything that keeps the loop from
|
|
440
|
+
// seeing the task leaves the Hub waiting on work that cannot start, so the failure
|
|
441
|
+
// is written down and retried on later beats rather than dropped with the claim.
|
|
442
|
+
try {
|
|
443
|
+
const filed = fileClaim(commitmentDeps, queueDir, received.queueTask);
|
|
444
|
+
if (filed === 'name_taken' || filed === 'unrecorded') {
|
|
445
|
+
const why = filed === 'name_taken'
|
|
446
|
+
? `queue id ${received.queueTask.id} is taken by another task`
|
|
447
|
+
: `ownership of ${received.queueTask.id} could not be recorded`;
|
|
448
|
+
rememberUnqueued(ledgerPath, received.queueTask, why);
|
|
449
|
+
return { ...received, claimed: false, reason: 'queue_failed', error: why };
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
catch (error) {
|
|
453
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
454
|
+
rememberUnqueued(ledgerPath, received.queueTask, reason);
|
|
455
|
+
return { ...received, claimed: false, reason: 'queue_failed', error: reason };
|
|
456
|
+
}
|
|
457
|
+
return received;
|
|
458
|
+
}
|
|
459
|
+
}
|
package/dist/thesis.d.ts
CHANGED
|
@@ -28,6 +28,9 @@ type CycleExecute = (mutation: never, decision: {
|
|
|
28
28
|
};
|
|
29
29
|
};
|
|
30
30
|
export interface ThesisCommandDeps {
|
|
31
|
+
env?: Readonly<NodeJS.ProcessEnv>;
|
|
32
|
+
provenance?: assetstore.ProvenanceStore;
|
|
33
|
+
review?: assetstore.ReviewLedger;
|
|
31
34
|
/** evolver-arm store (the learned-gene pool). Default: the live asset store. */
|
|
32
35
|
pool?: assetstore.AssetStoreProvider;
|
|
33
36
|
/** Inject a deterministic agent for tests / a dry simulation. Default: makeSafeExecute against `--repo` (live). */
|