pi-odd-worktree 1.1.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -7
- package/extensions/odd-worktree-tools.ts +490 -164
- package/lib/odd-prompt/odd-worktrees.with-codegraph.md +19 -0
- package/lib/odd-prompt/odd-worktrees.without-codegraph.md +15 -0
- package/lib/odd-worktrees-prompt.js +25 -28
- package/lib/warp-delete-confirm.js +1 -1
- package/lib/worktree-card.js +7 -7
- package/lib/worktree-close-herdr.js +1 -1
- package/lib/worktree-git.js +1 -190
- package/lib/worktree-hooks.js +2 -2
- package/lib/worktree-model-result.js +2 -2
- package/lib/worktree-session-guard.js +9 -1
- package/lib/worktree-warp-busy.js +564 -0
- package/package.json +1 -1
- package/tools/herdr-free-create.test.js +161 -0
- package/tools/odd-worktrees-prompt.test.js +36 -29
- package/tools/package-surface.test.js +7 -4
- package/tools/t5-session-identity.test.js +4 -4
- package/tools/warp-busy-guard.test.js +1123 -0
- package/tools/warp-delete-confirm.test.js +1 -1
- package/tools/worktree-close-herdr-async.test.js +2 -2
- package/tools/worktree-session-guard.test.js +1 -1
- package/tools/worktree-tools.test.js +35 -11
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// S4/S5/S9: a warp waits for THIS session's own background work — agent tasks
|
|
3
|
+
// AND background jobs — and the request is QUEUED while that work runs.
|
|
4
|
+
//
|
|
5
|
+
// WHAT IT READS. Two sources, both read through an injectable seam:
|
|
6
|
+
//
|
|
7
|
+
// 1. Agent tasks. Gentle Shell publishes one presence header per live Pi
|
|
8
|
+
// session, carrying that session's agent-task counters
|
|
9
|
+
// (`counts.{running,queued,waiting,finished}`) and a heartbeat. This module
|
|
10
|
+
// reads that store through the SAME bounded reader the checkout-deletion
|
|
11
|
+
// guard uses, hashes this session's id with the same sha256, and keeps only
|
|
12
|
+
// ITS freshest header. Nothing else is read from it: no transcript, no
|
|
13
|
+
// prompt, no activity payload.
|
|
14
|
+
// 2. Background jobs. Gentle Shell registers a `job_list` tool on the session,
|
|
15
|
+
// reachable through the host seam this package already uses for
|
|
16
|
+
// `session_worktree_register` (`ctx.tools` lists it, `ctx.executeTool` calls
|
|
17
|
+
// it). Its text is one line per job:
|
|
18
|
+
// `job-1 · running · Probe · 3s · /tmp/…/job-1.log`. A job is ACTIVE only
|
|
19
|
+
// when its status field says running or queued (`running`, `queued`, or a
|
|
20
|
+
// monitor's `monitor running`); `exited 0`, `failed 1` and `stopped` are all
|
|
21
|
+
// finished, and "not exited" is never read as activity.
|
|
22
|
+
//
|
|
23
|
+
// THE DECISION. One rule, shared by the tool front, the command front and the
|
|
24
|
+
// queue's poller: nothing may move while this session has a running or queued
|
|
25
|
+
// agent task OR an active job.
|
|
26
|
+
//
|
|
27
|
+
// THE QUEUE. One pending warp per session, held in this process (the tool and
|
|
28
|
+
// the command share it). A bounded poller re-reads both sources and
|
|
29
|
+
// re-dispatches the SAME validated handoff once the session reports neither
|
|
30
|
+
// workload; the caller clears the record on every terminal outcome (moved,
|
|
31
|
+
// refused, cancelled, expired, shutdown). A second warp is refused while one is
|
|
32
|
+
// pending: the pending request is never replaced. The pending lifetime is
|
|
33
|
+
// bounded (`ODD_WORKTREE_WARP_PENDING_MS`) and every timer is unref'd where the
|
|
34
|
+
// platform allows it, so a queue never keeps the process alive.
|
|
35
|
+
//
|
|
36
|
+
// FAILURE MODE. Best effort, like the close guard: an absent or unreadable
|
|
37
|
+
// presence store, a `job_list` that is missing, fails or answers in a shape this
|
|
38
|
+
// parser does not know, all answer `unknown` and block nothing. Such an answer
|
|
39
|
+
// is never reported as "no jobs" — the texts say the job state is unknown only
|
|
40
|
+
// when that actually happened, and never blame a missing tool that is present.
|
|
41
|
+
|
|
42
|
+
const { readGentlePresence, hashSessionId, PRESENCE_FRESH_MS } = require('./worktree-session-guard.js');
|
|
43
|
+
|
|
44
|
+
// The host tool that lists this session's background jobs, and the word that
|
|
45
|
+
// makes a job active. The status field is `running`/`queued`, or the job kind
|
|
46
|
+
// followed by it (`monitor running`), so the test is a positive status word and
|
|
47
|
+
// never "anything but exited".
|
|
48
|
+
const JOB_LIST_TOOL = 'job_list';
|
|
49
|
+
const ACTIVE_JOB_STATUS = /(^|\s)(running|queued)(\s|$)/i;
|
|
50
|
+
const NO_JOBS_LINE = /^no background jobs\b/i;
|
|
51
|
+
|
|
52
|
+
// How long the command front waits for both workloads to drain before it queues
|
|
53
|
+
// the request, and how often it re-reads. Overridable so a session can shorten or
|
|
54
|
+
// lengthen its own wait; the default keeps a warp from stalling a turn.
|
|
55
|
+
const DEFAULT_WAIT_MS = 60000;
|
|
56
|
+
const POLL_MS = 2000;
|
|
57
|
+
const MAX_WAIT_MS = 600000;
|
|
58
|
+
|
|
59
|
+
// How long a queued warp may wait for both workloads to drain before it expires
|
|
60
|
+
// with a notice, and how often its poller re-reads them.
|
|
61
|
+
const DEFAULT_PENDING_MS = 30 * 60 * 1000;
|
|
62
|
+
const MAX_PENDING_MS = 24 * 60 * 60 * 1000;
|
|
63
|
+
const DEFAULT_PENDING_POLL_MS = 2000;
|
|
64
|
+
const MAX_PENDING_POLL_MS = 60000;
|
|
65
|
+
|
|
66
|
+
const isCount = (value) => Number.isSafeInteger(value) && value >= 0;
|
|
67
|
+
|
|
68
|
+
function envBudget(env, name, fallback, max) {
|
|
69
|
+
const source = env && typeof env === 'object' ? env : {};
|
|
70
|
+
const raw = source[name];
|
|
71
|
+
if (raw === undefined || raw === null || raw === '') return fallback;
|
|
72
|
+
const parsed = Number.parseInt(String(raw), 10);
|
|
73
|
+
if (!Number.isSafeInteger(parsed) || parsed < 0) return fallback;
|
|
74
|
+
return Math.min(parsed, max);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function waitBudgetMs(env) {
|
|
78
|
+
return envBudget(env, 'ODD_WORKTREE_WARP_BUSY_WAIT_MS', DEFAULT_WAIT_MS, MAX_WAIT_MS);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function pendingBudgetMs(env) {
|
|
82
|
+
return envBudget(env, 'ODD_WORKTREE_WARP_PENDING_MS', DEFAULT_PENDING_MS, MAX_PENDING_MS);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function pendingPollMs(env) {
|
|
86
|
+
return envBudget(env, 'ODD_WORKTREE_WARP_PENDING_POLL_MS', DEFAULT_PENDING_POLL_MS, MAX_PENDING_POLL_MS);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function idleActivity(status) {
|
|
90
|
+
return { status, running: 0, queued: 0, waiting: 0, label: null, heartbeat: null };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// This session's own agent-task counters, or an idle/unavailable answer. Never
|
|
94
|
+
// rejects.
|
|
95
|
+
async function agentActivity(opts) {
|
|
96
|
+
const hash = hashSessionId(opts.sessionId);
|
|
97
|
+
if (hash === null) return idleActivity('unknown');
|
|
98
|
+
let read;
|
|
99
|
+
try {
|
|
100
|
+
read = await readGentlePresence({ env: opts.env, now: opts.now });
|
|
101
|
+
} catch {
|
|
102
|
+
return idleActivity('unavailable');
|
|
103
|
+
}
|
|
104
|
+
if (!read || read.status !== 'ok') return idleActivity(read && read.status === 'unavailable' ? 'unavailable' : 'unknown');
|
|
105
|
+
let freshest = null;
|
|
106
|
+
for (const entry of Array.isArray(read.entries) ? read.entries : []) {
|
|
107
|
+
if (!entry || entry.sessionHash !== hash || entry.recent !== true) continue;
|
|
108
|
+
if (!entry.counts || !isCount(entry.counts.running) || !isCount(entry.counts.queued) || !isCount(entry.counts.waiting)) continue;
|
|
109
|
+
if (freshest === null || entry.heartbeat > freshest.heartbeat) freshest = entry;
|
|
110
|
+
}
|
|
111
|
+
if (freshest === null) return idleActivity('ok');
|
|
112
|
+
return {
|
|
113
|
+
status: 'ok',
|
|
114
|
+
running: freshest.counts.running,
|
|
115
|
+
queued: freshest.counts.queued,
|
|
116
|
+
waiting: freshest.counts.waiting,
|
|
117
|
+
label: typeof freshest.label === 'string' ? freshest.label : null,
|
|
118
|
+
heartbeat: freshest.heartbeat,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// The one drain rule, applied to both workloads.
|
|
123
|
+
function combineActivity(agents, jobs) {
|
|
124
|
+
const active = isCount(jobs.active) ? jobs.active : 0;
|
|
125
|
+
return {
|
|
126
|
+
status: agents.status,
|
|
127
|
+
running: agents.running,
|
|
128
|
+
queued: agents.queued,
|
|
129
|
+
waiting: agents.waiting,
|
|
130
|
+
label: agents.label,
|
|
131
|
+
heartbeat: agents.heartbeat,
|
|
132
|
+
jobs: { status: jobs.status, active, count: isCount(jobs.count) ? jobs.count : 0 },
|
|
133
|
+
jobsUnknown: jobs.status !== 'ok',
|
|
134
|
+
busy: agents.running > 0 || agents.queued > 0 || active > 0,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// The text a `job_list` result carries, from either shape the host may use.
|
|
139
|
+
function toolResultText(outcome) {
|
|
140
|
+
if (!outcome || typeof outcome !== 'object') return null;
|
|
141
|
+
if (typeof outcome.text === 'string') return outcome.text;
|
|
142
|
+
const content = Array.isArray(outcome.content) ? outcome.content : null;
|
|
143
|
+
if (content === null) return null;
|
|
144
|
+
const parts = content
|
|
145
|
+
.filter((entry) => entry && entry.type === 'text' && typeof entry.text === 'string')
|
|
146
|
+
.map((entry) => entry.text);
|
|
147
|
+
return parts.length > 0 ? parts.join('\n') : null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// One `job_list` answer. Empty text and the host's own "nothing to list" line
|
|
151
|
+
// are a definitive empty list; a line that does not carry an id and a status is
|
|
152
|
+
// unparsable, which is unknown rather than "no jobs".
|
|
153
|
+
function parseJobList(text) {
|
|
154
|
+
const lines = String(text).split('\n').map((line) => line.trim()).filter((line) => line.length > 0);
|
|
155
|
+
let active = 0;
|
|
156
|
+
let count = 0;
|
|
157
|
+
let unparsable = false;
|
|
158
|
+
for (const line of lines) {
|
|
159
|
+
if (NO_JOBS_LINE.test(line)) continue;
|
|
160
|
+
const fields = line.split('\u00b7').map((field) => field.trim());
|
|
161
|
+
const status = fields.length >= 2 ? fields[1] : '';
|
|
162
|
+
if (fields[0].length === 0 || status.length === 0) {
|
|
163
|
+
unparsable = true;
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
count += 1;
|
|
167
|
+
if (ACTIVE_JOB_STATUS.test(status)) active += 1;
|
|
168
|
+
}
|
|
169
|
+
return unparsable ? { status: 'unparsable', active, count } : { status: 'ok', active, count };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// This session's background jobs through the host tool. Never rejects: a host
|
|
173
|
+
// without the tool, a failed call and an unknown shape all answer `unknown`.
|
|
174
|
+
async function sessionJobs(host) {
|
|
175
|
+
let available = false;
|
|
176
|
+
try {
|
|
177
|
+
available = !!host
|
|
178
|
+
&& typeof host.executeTool === 'function'
|
|
179
|
+
&& Array.isArray(host.tools)
|
|
180
|
+
&& host.tools.some((tool) => tool && tool.name === JOB_LIST_TOOL);
|
|
181
|
+
} catch {
|
|
182
|
+
available = false;
|
|
183
|
+
}
|
|
184
|
+
if (!available) return { status: 'unavailable', active: 0, count: 0 };
|
|
185
|
+
let outcome;
|
|
186
|
+
try {
|
|
187
|
+
outcome = await host.executeTool(JOB_LIST_TOOL, {});
|
|
188
|
+
} catch {
|
|
189
|
+
return { status: 'error', active: 0, count: 0 };
|
|
190
|
+
}
|
|
191
|
+
if (!outcome || typeof outcome !== 'object' || outcome.isError === true) return { status: 'error', active: 0, count: 0 };
|
|
192
|
+
const text = toolResultText(outcome);
|
|
193
|
+
if (text === null) return { status: 'unparsable', active: 0, count: 0 };
|
|
194
|
+
return parseJobList(text);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Both workloads, as one answer: `busy` is the single drain decision.
|
|
198
|
+
async function sessionActivity(options = {}) {
|
|
199
|
+
const opts = options && typeof options === 'object' ? options : {};
|
|
200
|
+
const agents = await agentActivity(opts);
|
|
201
|
+
return combineActivity(agents, await sessionJobs(opts.host));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// The workloads this session actually reports, as a phrase. `busy` is what makes
|
|
205
|
+
// a warp wait; `waiting`/`finished` never do.
|
|
206
|
+
function workloadText(activity) {
|
|
207
|
+
const running = activity && isCount(activity.running) ? activity.running : 0;
|
|
208
|
+
const queued = activity && isCount(activity.queued) ? activity.queued : 0;
|
|
209
|
+
const jobs = activity && activity.jobs && isCount(activity.jobs.active) ? activity.jobs.active : 0;
|
|
210
|
+
const parts = [];
|
|
211
|
+
if (running > 0) parts.push(`${running} running agent task(s)`);
|
|
212
|
+
if (queued > 0) parts.push(`${queued} queued agent task(s)`);
|
|
213
|
+
if (jobs > 0) parts.push(`${jobs} running background job${jobs === 1 ? '' : 's'}`);
|
|
214
|
+
return parts.length > 0 ? parts.join(' and ') : 'no';
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const JOB_STATE_REASONS = {
|
|
218
|
+
unavailable: `${JOB_LIST_TOOL} is not available on this host`,
|
|
219
|
+
error: `${JOB_LIST_TOOL} failed`,
|
|
220
|
+
unparsable: `${JOB_LIST_TOOL} answered in an unexpected shape`,
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
// Said only when the job state really is unknown: a missing tool, a failed call
|
|
224
|
+
// or an answer this parser does not know. Never thrown at a session whose jobs
|
|
225
|
+
// were readable.
|
|
226
|
+
function jobsUnknownText(activity) {
|
|
227
|
+
const jobs = activity && activity.jobs ? activity.jobs : null;
|
|
228
|
+
if (!jobs || jobs.status === 'ok') return '';
|
|
229
|
+
const reason = JOB_STATE_REASONS[jobs.status] || `${JOB_LIST_TOOL} gave no usable answer`;
|
|
230
|
+
return `the background-job state is unknown (${reason}), so confirm any bash_background or monitor job finished`;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// The first line of every queued answer: the handoff is QUEUED, waiting for both
|
|
234
|
+
// workloads. Never a claim that the session moved. The unknown-job caveat is not
|
|
235
|
+
// part of this line: a front adds it as its own row, only when it happened.
|
|
236
|
+
function queuedText(activity) {
|
|
237
|
+
return `handoff queued — waiting for ${workloadText(activity)} before the move`;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function expiredText(name, minutes, activity) {
|
|
241
|
+
const checkout = typeof name === 'string' && name.length > 0 ? name : 'that checkout';
|
|
242
|
+
const unknown = jobsUnknownText(activity);
|
|
243
|
+
const line = `worktree warp: the pending warp to ${checkout} expired after ${minutes} min with nothing moved; warp again when this session's agent tasks and background jobs finish`;
|
|
244
|
+
return unknown.length > 0 ? `${line} (${unknown})` : line;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Poll until this session has no running or queued agent task, or the budget
|
|
248
|
+
// runs out. `read` and `sleep` are injected so a test never waits for real.
|
|
249
|
+
async function waitForSessionActivity(options = {}) {
|
|
250
|
+
const opts = options && typeof options === 'object' ? options : {};
|
|
251
|
+
const read = typeof opts.read === 'function'
|
|
252
|
+
? opts.read
|
|
253
|
+
: () => sessionActivity({ sessionId: opts.sessionId, env: opts.env, host: opts.host });
|
|
254
|
+
const sleep = typeof opts.sleep === 'function' ? opts.sleep : (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
255
|
+
const budget = isCount(opts.waitMs) ? opts.waitMs : waitBudgetMs(opts.env);
|
|
256
|
+
const poll = isCount(opts.pollMs) && opts.pollMs > 0 ? opts.pollMs : POLL_MS;
|
|
257
|
+
let activity = await read();
|
|
258
|
+
let waited = 0;
|
|
259
|
+
while (activity && activity.busy === true && waited < budget) {
|
|
260
|
+
const step = Math.min(poll, budget - waited);
|
|
261
|
+
if (step <= 0) break;
|
|
262
|
+
await sleep(step);
|
|
263
|
+
waited += step;
|
|
264
|
+
activity = await read();
|
|
265
|
+
}
|
|
266
|
+
return { activity, waited, waitedOut: !!(activity && activity.busy === true) };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// ---------------------------------------------------------------------------
|
|
270
|
+
// The queued warp: one pending request per session.
|
|
271
|
+
// ---------------------------------------------------------------------------
|
|
272
|
+
|
|
273
|
+
// The queue is keyed by the session id, which both the tool and the command can
|
|
274
|
+
// read, and falls back to the checkout the session stands in when the host
|
|
275
|
+
// exposes no id. Null means the caller has nothing to key on.
|
|
276
|
+
function pendingKeyFor(source) {
|
|
277
|
+
const value = source && typeof source === 'object' ? source : {};
|
|
278
|
+
const sessionId = typeof value.sessionId === 'string' && value.sessionId.length > 0 ? value.sessionId : null;
|
|
279
|
+
if (sessionId !== null) return `session:${sessionId}`;
|
|
280
|
+
const root = typeof value.root === 'string' && value.root.length > 0 ? value.root : null;
|
|
281
|
+
return root !== null ? `root:${root}` : null;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function handoffShape(value) {
|
|
285
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
286
|
+
const changes = value.changes && typeof value.changes === 'object' && !Array.isArray(value.changes)
|
|
287
|
+
? {
|
|
288
|
+
mode: typeof value.changes.mode === 'string' ? value.changes.mode : 'none',
|
|
289
|
+
paths: Array.isArray(value.changes.paths) ? value.changes.paths.map(String) : [],
|
|
290
|
+
}
|
|
291
|
+
: { mode: 'none', paths: [] };
|
|
292
|
+
return {
|
|
293
|
+
name: String(value.name || ''),
|
|
294
|
+
target: String(value.target || ''),
|
|
295
|
+
from: String(value.from || ''),
|
|
296
|
+
branch: String(value.branch || ''),
|
|
297
|
+
changes,
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// Whether two handoff requests are the SAME queued move. The command uses this
|
|
302
|
+
// to tell its own pending retry (the token it re-dispatched) from a second warp
|
|
303
|
+
// request, which is refused.
|
|
304
|
+
function sameWarpHandoff(left, right) {
|
|
305
|
+
const a = handoffShape(left);
|
|
306
|
+
const b = handoffShape(right);
|
|
307
|
+
if (a === null || b === null) return false;
|
|
308
|
+
return a.name === b.name
|
|
309
|
+
&& a.target === b.target
|
|
310
|
+
&& a.from === b.from
|
|
311
|
+
&& a.branch === b.branch
|
|
312
|
+
&& a.changes.mode === b.changes.mode
|
|
313
|
+
&& a.changes.paths.length === b.changes.paths.length
|
|
314
|
+
&& a.changes.paths.every((entry, index) => entry === b.changes.paths[index]);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const pendingWarps = new Map();
|
|
318
|
+
|
|
319
|
+
const DEFAULT_TIMERS = {
|
|
320
|
+
set: (fn, ms) => setTimeout(fn, ms),
|
|
321
|
+
clear: (timer) => clearTimeout(timer),
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
function pendingInfo(record) {
|
|
325
|
+
if (!record) return null;
|
|
326
|
+
return {
|
|
327
|
+
key: record.key,
|
|
328
|
+
name: record.name,
|
|
329
|
+
handoff: record.handoff,
|
|
330
|
+
queuedAt: record.queuedAt,
|
|
331
|
+
expiresAt: record.expiresAt,
|
|
332
|
+
dispatching: record.dispatching === true,
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// The pending warp for a key, or null. A read-only copy: callers may inspect it
|
|
337
|
+
// and must never mutate the queue through it.
|
|
338
|
+
function pendingWarpFor(key) {
|
|
339
|
+
return pendingInfo(pendingWarps.get(key) || null);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function pendingWarpKeys() {
|
|
343
|
+
return [...pendingWarps.keys()];
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// The refusal a SECOND warp gets while one is already pending. It names the
|
|
347
|
+
// checkout that is queued, never the rejected request, and says what to do.
|
|
348
|
+
function pendingWarpRefusalText(pending, requestedName) {
|
|
349
|
+
const queuedName = pending && typeof pending.name === 'string' && pending.name.length > 0 ? pending.name : null;
|
|
350
|
+
const name = queuedName
|
|
351
|
+
|| (typeof requestedName === 'string' && requestedName.trim().length > 0 ? requestedName.trim() : 'that checkout');
|
|
352
|
+
return `a warp to ${name} is already pending for this session — it runs when the pending agent tasks and background jobs finish; wait for it or let it expire`;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function clearRecordTimer(record) {
|
|
356
|
+
if (record.timer === null) return;
|
|
357
|
+
try {
|
|
358
|
+
record.deps.timers.clear(record.timer);
|
|
359
|
+
} catch {
|
|
360
|
+
// A dead timer never fails the queue.
|
|
361
|
+
}
|
|
362
|
+
record.timer = null;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function arm(record, delayMs) {
|
|
366
|
+
if (pendingWarps.get(record.key) !== record) return;
|
|
367
|
+
clearRecordTimer(record);
|
|
368
|
+
const remaining = record.expiresAt - record.deps.now();
|
|
369
|
+
const delay = Math.max(0, Math.min(delayMs, remaining));
|
|
370
|
+
let timer = null;
|
|
371
|
+
try {
|
|
372
|
+
timer = record.deps.timers.set(() => {
|
|
373
|
+
record.timer = null;
|
|
374
|
+
// The timer must never throw into the host: a rejected tick is swallowed
|
|
375
|
+
// here, and the next poll or the expiry settles the record.
|
|
376
|
+
void tick(record).catch(() => {});
|
|
377
|
+
}, delay);
|
|
378
|
+
} catch {
|
|
379
|
+
timer = null;
|
|
380
|
+
}
|
|
381
|
+
// A queued warp is background work: its timer must never keep the session
|
|
382
|
+
// alive on its own.
|
|
383
|
+
if (timer && typeof timer.unref === 'function') {
|
|
384
|
+
try {
|
|
385
|
+
timer.unref();
|
|
386
|
+
} catch {
|
|
387
|
+
// unref is a nicety, not a requirement.
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
record.timer = timer;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function settle(record) {
|
|
394
|
+
clearRecordTimer(record);
|
|
395
|
+
if (pendingWarps.get(record.key) === record) pendingWarps.delete(record.key);
|
|
396
|
+
return pendingInfo(record);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function expire(record) {
|
|
400
|
+
const minutes = Math.max(1, Math.round((record.expiresAt - record.queuedAt) / 60000));
|
|
401
|
+
const name = record.name;
|
|
402
|
+
settle(record);
|
|
403
|
+
try {
|
|
404
|
+
if (typeof record.deps.notify === 'function') record.deps.notify(expiredText(name, minutes, record.lastActivity), 'error');
|
|
405
|
+
} catch {
|
|
406
|
+
// Nothing a dead UI can do may escape the timer.
|
|
407
|
+
}
|
|
408
|
+
return { status: 'expired' };
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// One poll step: expire, keep waiting while the counters are busy, or dispatch
|
|
412
|
+
// the SAME validated handoff once they drain. Awaitable so tests drive it
|
|
413
|
+
// deterministically; the timer above calls it fire-and-forget. Never rejects.
|
|
414
|
+
async function tick(record) {
|
|
415
|
+
if (pendingWarps.get(record.key) !== record) return { status: 'none' };
|
|
416
|
+
const now = record.deps.now();
|
|
417
|
+
if (now >= record.expiresAt) return expire(record);
|
|
418
|
+
if (record.dispatching === true) {
|
|
419
|
+
// Already re-dispatched; wait for that command to settle or the queue to
|
|
420
|
+
// expire, so one request is never dispatched twice.
|
|
421
|
+
arm(record, record.expiresAt - now);
|
|
422
|
+
return { status: 'waiting' };
|
|
423
|
+
}
|
|
424
|
+
let activity = null;
|
|
425
|
+
try {
|
|
426
|
+
activity = await record.deps.read();
|
|
427
|
+
} catch {
|
|
428
|
+
activity = null;
|
|
429
|
+
}
|
|
430
|
+
if (pendingWarps.get(record.key) !== record) return { status: 'none' };
|
|
431
|
+
// The last answer is what the expiry notice can honestly say: an unknown job
|
|
432
|
+
// state is reported only when it was actually seen.
|
|
433
|
+
record.lastActivity = activity;
|
|
434
|
+
if (activity && activity.busy === true) {
|
|
435
|
+
arm(record, record.deps.poll);
|
|
436
|
+
return { status: 'waiting' };
|
|
437
|
+
}
|
|
438
|
+
record.dispatching = true;
|
|
439
|
+
let refused = false;
|
|
440
|
+
try {
|
|
441
|
+
const dispatched = await record.deps.dispatch(record.handoff, record.token);
|
|
442
|
+
if (dispatched && dispatched.ok === false) refused = true;
|
|
443
|
+
} catch {
|
|
444
|
+
refused = true;
|
|
445
|
+
}
|
|
446
|
+
if (refused) {
|
|
447
|
+
// The host refused the re-dispatch: stay queued and try on the next poll
|
|
448
|
+
// instead of throwing out of a timer.
|
|
449
|
+
record.dispatching = false;
|
|
450
|
+
arm(record, record.deps.poll);
|
|
451
|
+
return { status: 'waiting' };
|
|
452
|
+
}
|
|
453
|
+
arm(record, record.expiresAt - record.deps.now());
|
|
454
|
+
return { status: 'dispatched' };
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// The poll step for a key, for the timer seam and for tests. Resolves; never
|
|
458
|
+
// rejects.
|
|
459
|
+
async function pendingWarpTick(key) {
|
|
460
|
+
const record = pendingWarps.get(key);
|
|
461
|
+
if (!record) return { status: 'none' };
|
|
462
|
+
return tick(record);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// Hold one validated handoff as this session's pending warp and start polling.
|
|
466
|
+
// A second request for the same key is refused (`reason: 'pending'`) and leaves
|
|
467
|
+
// the existing one untouched. Never throws.
|
|
468
|
+
function queuePendingWarp(options = {}) {
|
|
469
|
+
const opts = options && typeof options === 'object' ? options : {};
|
|
470
|
+
const key = typeof opts.key === 'string' && opts.key.length > 0 ? opts.key : null;
|
|
471
|
+
const handoff = handoffShape(opts.handoff);
|
|
472
|
+
const token = typeof opts.token === 'string' && opts.token.length > 0 ? opts.token : null;
|
|
473
|
+
if (key === null || handoff === null || token === null) return { ok: false, reason: 'invalid' };
|
|
474
|
+
const existing = pendingWarps.get(key);
|
|
475
|
+
if (existing) return { ok: false, reason: 'pending', pending: pendingInfo(existing) };
|
|
476
|
+
const env = opts.env && typeof opts.env === 'object' ? opts.env : process.env;
|
|
477
|
+
const now = typeof opts.now === 'function' ? opts.now : () => Date.now();
|
|
478
|
+
const queuedAt = now();
|
|
479
|
+
const record = {
|
|
480
|
+
key,
|
|
481
|
+
name: typeof opts.name === 'string' && opts.name.length > 0 ? opts.name : handoff.name,
|
|
482
|
+
handoff,
|
|
483
|
+
token,
|
|
484
|
+
queuedAt,
|
|
485
|
+
expiresAt: queuedAt + pendingBudgetMs(env),
|
|
486
|
+
dispatching: false,
|
|
487
|
+
timer: null,
|
|
488
|
+
lastActivity: null,
|
|
489
|
+
deps: {
|
|
490
|
+
read: typeof opts.read === 'function'
|
|
491
|
+
? opts.read
|
|
492
|
+
: () => sessionActivity({ env, host: opts.host }),
|
|
493
|
+
dispatch: typeof opts.dispatch === 'function' ? opts.dispatch : null,
|
|
494
|
+
notify: typeof opts.notify === 'function' ? opts.notify : null,
|
|
495
|
+
env,
|
|
496
|
+
now,
|
|
497
|
+
poll: Math.max(1, pendingPollMs(env)),
|
|
498
|
+
timers: opts.timers && typeof opts.timers === 'object' ? opts.timers : DEFAULT_TIMERS,
|
|
499
|
+
},
|
|
500
|
+
};
|
|
501
|
+
pendingWarps.set(key, record);
|
|
502
|
+
arm(record, record.deps.poll);
|
|
503
|
+
return { ok: true, pending: pendingInfo(record) };
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// The request was already dispatched (the tool front hands its handoff to the
|
|
507
|
+
// command and only keeps the record so a second warp is refused): wait for that
|
|
508
|
+
// dispatch to settle or for the queue to expire instead of sending a copy.
|
|
509
|
+
function markPendingWarpDispatched(key) {
|
|
510
|
+
const record = pendingWarps.get(key);
|
|
511
|
+
if (!record) return false;
|
|
512
|
+
record.dispatching = true;
|
|
513
|
+
arm(record, record.expiresAt - record.deps.now());
|
|
514
|
+
return true;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// The dispatched retry found the session busy again: resume polling for the SAME
|
|
518
|
+
// request instead of dispatching a second one.
|
|
519
|
+
function resumePendingWarp(key) {
|
|
520
|
+
const record = pendingWarps.get(key);
|
|
521
|
+
if (!record) return false;
|
|
522
|
+
record.dispatching = false;
|
|
523
|
+
arm(record, record.deps.poll);
|
|
524
|
+
return true;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// Every terminal outcome (moved, refused, cancelled, session gone) clears the
|
|
528
|
+
// record so a later warp is accepted again. Returns the cleared record, or null.
|
|
529
|
+
function settlePendingWarp(key) {
|
|
530
|
+
const record = pendingWarps.get(key);
|
|
531
|
+
return record ? settle(record) : null;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
module.exports = {
|
|
535
|
+
ACTIVE_JOB_STATUS,
|
|
536
|
+
DEFAULT_PENDING_MS,
|
|
537
|
+
DEFAULT_PENDING_POLL_MS,
|
|
538
|
+
DEFAULT_WAIT_MS,
|
|
539
|
+
JOB_LIST_TOOL,
|
|
540
|
+
MAX_PENDING_MS,
|
|
541
|
+
MAX_PENDING_POLL_MS,
|
|
542
|
+
MAX_WAIT_MS,
|
|
543
|
+
expiredText,
|
|
544
|
+
jobsUnknownText,
|
|
545
|
+
markPendingWarpDispatched,
|
|
546
|
+
parseJobList,
|
|
547
|
+
pendingBudgetMs,
|
|
548
|
+
pendingKeyFor,
|
|
549
|
+
pendingPollMs,
|
|
550
|
+
pendingWarpFor,
|
|
551
|
+
pendingWarpKeys,
|
|
552
|
+
pendingWarpRefusalText,
|
|
553
|
+
pendingWarpTick,
|
|
554
|
+
queuePendingWarp,
|
|
555
|
+
queuedText,
|
|
556
|
+
resumePendingWarp,
|
|
557
|
+
sameWarpHandoff,
|
|
558
|
+
sessionActivity,
|
|
559
|
+
sessionJobs,
|
|
560
|
+
settlePendingWarp,
|
|
561
|
+
waitBudgetMs,
|
|
562
|
+
waitForSessionActivity,
|
|
563
|
+
workloadText,
|
|
564
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-odd-worktree",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Pi package for odd-worktree: the Agent Worktree tools (create, list, close, warp), the /warp worktree panel, the /odd-list ODD viewer, and the /issues GitHub issue reader. Works in Pi alone; Herdr is optional.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|