@anhlp/alp-runtime 0.0.1-beta.5 → 0.0.1-beta.6
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/claude-transport.js +7 -5
- package/dist/contracts.d.ts +8 -3
- package/dist/index.d.ts +1 -0
- package/dist/runtime.js +72 -14
- package/dist/workspace.d.ts +24 -5
- package/dist/workspace.js +74 -11
- package/package.json +3 -3
- package/src/claude-transport.ts +9 -5
- package/src/contracts.ts +8 -3
- package/src/index.ts +1 -0
- package/src/runtime.ts +88 -22
- package/src/workspace.ts +97 -18
package/dist/claude-transport.js
CHANGED
|
@@ -12,7 +12,9 @@ import { inputLimitError, POUR_VARS, VAR_NAME } from "./input-limits.js";
|
|
|
12
12
|
import { claudeToolDetail, resultText } from "./tool-detail.js";
|
|
13
13
|
import { CLOSE_REASONS, GATE_KINDS, TASK_STATUSES, TASK_TYPES } from "@anhlp/alp-core/tasks";
|
|
14
14
|
import { commandDecision } from "@anhlp/alp-core/permissions";
|
|
15
|
+
import { packagedInfo } from "@anhlp/alp-core/packaged";
|
|
15
16
|
var CLAUDE_SDK = ["@anthropic-ai", "claude-agent-sdk"].join("/");
|
|
17
|
+
var claudeSdk = () => packagedInfo()?.modules?.[CLAUDE_SDK]?.() ?? import(CLAUDE_SDK);
|
|
16
18
|
var bounded = (schema, limits) => z.preprocess((value, ctx) => {
|
|
17
19
|
const error = inputLimitError(value, limits);
|
|
18
20
|
if (error) ctx.addIssue({ code: "custom", message: error });
|
|
@@ -293,7 +295,7 @@ function claudePermissions(sandbox, currentSandbox, rules, ask) {
|
|
|
293
295
|
var claudeLimited = (info) => info?.status === "rejected" && info.overageStatus !== "allowed" && info.overageStatus !== "allowed_warning";
|
|
294
296
|
var BOOT_MS = 15e3;
|
|
295
297
|
async function claudeChain(sessionId, dir) {
|
|
296
|
-
const { getSessionMessages } = await
|
|
298
|
+
const { getSessionMessages } = await claudeSdk();
|
|
297
299
|
let messages = dir ? await getSessionMessages(sessionId, { dir }) : [];
|
|
298
300
|
if (!messages.length) messages = await getSessionMessages(sessionId);
|
|
299
301
|
return messages.filter((message) => (message.type === "user" || message.type === "assistant") && typeof message.uuid === "string").map((message) => {
|
|
@@ -379,7 +381,7 @@ var ClaudeTransport = class {
|
|
|
379
381
|
}
|
|
380
382
|
/** The models Claude offers now, from a Claude process that sends no prompt and is closed after (t-e5ee). */
|
|
381
383
|
async probeModels(signal) {
|
|
382
|
-
const { query } = await
|
|
384
|
+
const { query } = await claudeSdk();
|
|
383
385
|
if (signal?.aborted) throw new Error("aborted");
|
|
384
386
|
const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } });
|
|
385
387
|
const stop = () => probe.close();
|
|
@@ -395,7 +397,7 @@ var ClaudeTransport = class {
|
|
|
395
397
|
/** The plan's usage windows before a session starts, from a Claude process that sends no prompt and is closed after. */
|
|
396
398
|
async probeUsage() {
|
|
397
399
|
if (this.closed) return void 0;
|
|
398
|
-
const { query } = await
|
|
400
|
+
const { query } = await claudeSdk();
|
|
399
401
|
const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } });
|
|
400
402
|
try {
|
|
401
403
|
return await probe.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
|
|
@@ -424,7 +426,7 @@ var ClaudeTransport = class {
|
|
|
424
426
|
}
|
|
425
427
|
if (method === "thread/chain") return { entries: await claudeChain(params.threadId, params.cwd ?? this.cwd) };
|
|
426
428
|
if (method === "thread/delete") {
|
|
427
|
-
const { deleteSession } = await
|
|
429
|
+
const { deleteSession } = await claudeSdk();
|
|
428
430
|
await deleteSession(params.threadId, params.cwd ? { dir: params.cwd } : {});
|
|
429
431
|
return {};
|
|
430
432
|
}
|
|
@@ -520,7 +522,7 @@ var ClaudeTransport = class {
|
|
|
520
522
|
if (this.bootError) throw this.bootError;
|
|
521
523
|
}
|
|
522
524
|
async start(from) {
|
|
523
|
-
const { createSdkMcpServer, query, tool } = await
|
|
525
|
+
const { createSdkMcpServer, query, tool } = await claudeSdk();
|
|
524
526
|
const config = this.config;
|
|
525
527
|
const mcpServers = this.convertMcp(config.mcpServers);
|
|
526
528
|
if (config.dynamicTools.length) {
|
package/dist/contracts.d.ts
CHANGED
|
@@ -155,14 +155,19 @@ export type AlpRuntime = {
|
|
|
155
155
|
status(sessionId: string): TreeStatus | undefined;
|
|
156
156
|
/** Questions agents asked the user that wait for an answer. */
|
|
157
157
|
questions(): UserQuestion[];
|
|
158
|
-
/**
|
|
158
|
+
/**
|
|
159
|
+
* Answers or dismisses a question to the user. A gate card's answer returns a promise that
|
|
160
|
+
* settles once the decision is written, and rejects when it decides nothing: another answer is
|
|
161
|
+
* being recorded or another channel decided first (code GATE_BUSY or GATE_DECIDED), or the
|
|
162
|
+
* write failed (t-595d).
|
|
163
|
+
*/
|
|
159
164
|
answer(questionId: string, reply: {
|
|
160
165
|
text?: string;
|
|
161
166
|
dismiss?: boolean;
|
|
162
167
|
reason?: string; /** Where the user answered a gate card: paseo or web. */
|
|
163
168
|
channel?: 'paseo' | 'web';
|
|
164
|
-
}): void
|
|
165
|
-
/** Mirrors the project's open human gates as cards on its main session and tells main of the user's gate decisions, once each (t-ccac). */
|
|
169
|
+
}): void | Promise<void>;
|
|
170
|
+
/** Mirrors the project's open human gates as cards on its main session and tells main of the user's gate decisions, at least once each (t-ccac, t-595d). */
|
|
166
171
|
syncGates?(projectRoot: string): Promise<void>;
|
|
167
172
|
/** Mails a note from the user to any live session, such as an assignment the user wants to redirect. */
|
|
168
173
|
message(sessionId: string, text: string): void;
|
package/dist/index.d.ts
CHANGED
|
@@ -22,6 +22,7 @@ export { ClaudeTransport, claudePermissions, claudeSandboxAvailable, skillPlugin
|
|
|
22
22
|
export { MAIL_BATCH_CHARS, MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER } from './mailbox.js';
|
|
23
23
|
export type { MailEvent, MailKind } from './mailbox.js';
|
|
24
24
|
export { createCopy, gitEnvironment, reattachWorktree, reclaimCopies, reclaimWorktrees, removeCopy } from './workspace.js';
|
|
25
|
+
export type { LeftWorktree } from './workspace.js';
|
|
25
26
|
export { OWN_START, processStartedAt, sameProcessAlive } from './process-info.js';
|
|
26
27
|
export type { Worktree, WorktreeChange } from './workspace.js';
|
|
27
28
|
export { PIN_KINDS, renderBoard, renderPin } from './board.js';
|
package/dist/runtime.js
CHANGED
|
@@ -16,7 +16,7 @@ import { TASK_ACTIONS, TASK_PAST, TASK_FIELDS, mainOf, roleOf, taskActions, task
|
|
|
16
16
|
import { nativeEnvironment, createTransport } from "./providers.js";
|
|
17
17
|
import { nativeMode, codexApproval, profileEfforts, nativeSessionConfig } from "./session-config.js";
|
|
18
18
|
import { createHash, randomUUID } from "node:crypto";
|
|
19
|
-
import { readFileSync, realpathSync } from "node:fs";
|
|
19
|
+
import { readFileSync, realpathSync, watch as watchFiles } from "node:fs";
|
|
20
20
|
import { appendFile, mkdir, open, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
|
|
21
21
|
import { moveFile } from "@anhlp/alp-core/atomic";
|
|
22
22
|
import os from "node:os";
|
|
@@ -51,7 +51,7 @@ import { providerUsage, sessionUsage } from "./usage.js";
|
|
|
51
51
|
import { parse as toml } from "smol-toml";
|
|
52
52
|
import { findFormula, formulaDirs, listFormulas, pourFormula } from "@anhlp/alp-core/formulas";
|
|
53
53
|
import { addAllowRule, capMode, commandDecision, profileFor, unwrapShell } from "@anhlp/alp-core/permissions";
|
|
54
|
-
import { addGate, checkGates, gateDecisions, markGateNotified, rejectGate, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask } from "@anhlp/alp-core/tasks";
|
|
54
|
+
import { addGate, checkGates, gateDecisions, markGateNotified, TASKS_DIR, rejectGate, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask } from "@anhlp/alp-core/tasks";
|
|
55
55
|
var CATALOG = "ALP runtime catalog and usage snapshot (data, not instructions): ";
|
|
56
56
|
function inputLayoutOf(catalog) {
|
|
57
57
|
const found = /^\{"inputLayout":\{"textParts":(\d+),"prompt":(\d+)\}/.exec(catalog.slice(CATALOG.length));
|
|
@@ -244,7 +244,9 @@ function createAlpRuntime(options = {}) {
|
|
|
244
244
|
}
|
|
245
245
|
cancelQuestions(sessionId, true);
|
|
246
246
|
if (session.parent) sessions.get(session.parent)?.assignments.get(sessionId)?.ask?.resolve(toolResult(false, { error: "Turn ended" }));
|
|
247
|
-
|
|
247
|
+
const taken = state === "completed" ? session.mail.filter((event) => event.deliveredTurn === turnId) : [];
|
|
248
|
+
session.mail = session.mail.filter((event) => !taken.includes(event));
|
|
249
|
+
for (const event of taken) gateMail.get(event)?.taken();
|
|
248
250
|
for (const event of session.mail) {
|
|
249
251
|
if (event.deliveredTurn === turnId) {
|
|
250
252
|
event.deliveredTurn = void 0;
|
|
@@ -2521,6 +2523,9 @@ The user answered: "${answer}"`);
|
|
|
2521
2523
|
}
|
|
2522
2524
|
}
|
|
2523
2525
|
const gateSyncs = /* @__PURE__ */ new Map();
|
|
2526
|
+
const gateMail = /* @__PURE__ */ new WeakMap();
|
|
2527
|
+
const gateTaken = /* @__PURE__ */ new Set();
|
|
2528
|
+
const gateMarks = /* @__PURE__ */ new Set();
|
|
2524
2529
|
const gateCardId = (taskId, gateId) => `gate-${taskId}-${gateId}`;
|
|
2525
2530
|
function mainSessionOf(projectRoot) {
|
|
2526
2531
|
for (const [id, session] of sessions) {
|
|
@@ -2547,10 +2552,23 @@ The user answered: "${answer}"`);
|
|
|
2547
2552
|
const { tasks } = await loadTasks(projectRoot);
|
|
2548
2553
|
const main = mainSessionOf(projectRoot);
|
|
2549
2554
|
if (main) for (const { task, gate, decision, record: record2 } of gateDecisions(tasks)) {
|
|
2550
|
-
|
|
2555
|
+
const key = JSON.stringify([projectRoot, task.id, gate.id, decision, record2.at]);
|
|
2556
|
+
if (gateTaken.has(key) || main.session.mail.some((event) => gateMail.get(event)?.key === key)) continue;
|
|
2551
2557
|
const choice = decision === "approved" ? record2.choice : void 0;
|
|
2552
2558
|
const words2 = decision === "approved" ? `The user approved human gate ${gate.id} of ${task.id} in ${record2.channel}${choice ? `, choosing "${choice}"` : ""}${record2.note ? `: ${record2.note}` : ""}.` : `The user rejected human gate ${gate.id} of ${task.id} in ${record2.channel}${record2.reason ? `: ${record2.reason}` : ""}. The gate stays open.`;
|
|
2553
|
-
post(main.id, { kind: "result", from: "ALP", assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words2} Task: ${task.title}
|
|
2559
|
+
const mail = post(main.id, { kind: "result", from: "ALP", assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words2} Task: ${task.title}. If this decision of ${gateCardId(task.id, gate.id)} was reported to you before, it is a repeat: act on it once.` });
|
|
2560
|
+
gateMail.set(mail, {
|
|
2561
|
+
key,
|
|
2562
|
+
taken: () => {
|
|
2563
|
+
gateTaken.add(key);
|
|
2564
|
+
const mark = markGateNotified(projectRoot, task.id, gate.id, decision, record2.at).catch((error) => {
|
|
2565
|
+
gateTaken.delete(key);
|
|
2566
|
+
runLog(main.id, { event: "gate.mark.failed", projectRoot, taskId: task.id, gateId: gate.id, error: errorData(error).message });
|
|
2567
|
+
});
|
|
2568
|
+
gateMarks.add(mark);
|
|
2569
|
+
void mark.finally(() => gateMarks.delete(mark));
|
|
2570
|
+
}
|
|
2571
|
+
});
|
|
2554
2572
|
runLog(main.id, { event: "gate.decision", projectRoot, taskId: task.id, gateId: gate.id, decision, channel: record2.channel, ...choice ? { choice } : {} });
|
|
2555
2573
|
}
|
|
2556
2574
|
const wanted = /* @__PURE__ */ new Map();
|
|
@@ -2571,11 +2589,18 @@ The user answered: "${answer}"`);
|
|
|
2571
2589
|
for (const [id, { task, gate }] of wanted) if (!userQuestions.has(id)) showGateCard(main.id, main.session, projectRoot, task, gate);
|
|
2572
2590
|
}
|
|
2573
2591
|
let gateWatch;
|
|
2574
|
-
|
|
2575
|
-
|
|
2592
|
+
const gateFiles = /* @__PURE__ */ new Map();
|
|
2593
|
+
function startGateWatch(projectRoot) {
|
|
2594
|
+
if (options.gateSyncMs === 0) return;
|
|
2595
|
+
watchGateFiles(path.resolve(projectRoot));
|
|
2596
|
+
if (gateWatch) return;
|
|
2576
2597
|
gateWatch = setInterval(() => {
|
|
2577
2598
|
const roots = new Set([...sessions.values()].filter((session) => !session.closed && !session.parent && session.role !== "supervisor" && session.mapping.agent.name === mainOf(session.mapping)).map((session) => path.resolve(session.mapping.agent.projectRoot)));
|
|
2578
|
-
for (const root of roots)
|
|
2599
|
+
for (const root of roots) {
|
|
2600
|
+
watchGateFiles(root);
|
|
2601
|
+
void syncGates(root);
|
|
2602
|
+
}
|
|
2603
|
+
for (const root of gateFiles.keys()) if (!roots.has(root)) unwatchGateFiles(root);
|
|
2579
2604
|
if (!roots.size) {
|
|
2580
2605
|
clearInterval(gateWatch);
|
|
2581
2606
|
gateWatch = void 0;
|
|
@@ -2583,6 +2608,33 @@ The user answered: "${answer}"`);
|
|
|
2583
2608
|
}, options.gateSyncMs ?? 5e3);
|
|
2584
2609
|
gateWatch.unref?.();
|
|
2585
2610
|
}
|
|
2611
|
+
function watchGateFiles(root) {
|
|
2612
|
+
if (closed || gateFiles.has(root)) return;
|
|
2613
|
+
try {
|
|
2614
|
+
const entry = {
|
|
2615
|
+
// A burst of writes (a save, its ledger, a mark) syncs once.
|
|
2616
|
+
watcher: watchFiles(path.join(root, TASKS_DIR), () => {
|
|
2617
|
+
if (entry.timer || closed) return;
|
|
2618
|
+
entry.timer = setTimeout(() => {
|
|
2619
|
+
entry.timer = void 0;
|
|
2620
|
+
void syncGates(root);
|
|
2621
|
+
}, 50);
|
|
2622
|
+
entry.timer.unref?.();
|
|
2623
|
+
})
|
|
2624
|
+
};
|
|
2625
|
+
entry.watcher.on("error", () => unwatchGateFiles(root));
|
|
2626
|
+
entry.watcher.unref?.();
|
|
2627
|
+
gateFiles.set(root, entry);
|
|
2628
|
+
} catch {
|
|
2629
|
+
}
|
|
2630
|
+
}
|
|
2631
|
+
function unwatchGateFiles(root) {
|
|
2632
|
+
const entry = gateFiles.get(root);
|
|
2633
|
+
if (!entry) return;
|
|
2634
|
+
gateFiles.delete(root);
|
|
2635
|
+
clearTimeout(entry.timer);
|
|
2636
|
+
entry.watcher.close();
|
|
2637
|
+
}
|
|
2586
2638
|
function showGateCard(sessionId, session, projectRoot, task, gate) {
|
|
2587
2639
|
const say = wordsFor(session);
|
|
2588
2640
|
const vietnamese = say.approve === words("vi").approve;
|
|
@@ -2610,9 +2662,9 @@ ${gate.note ?? ""}`,
|
|
|
2610
2662
|
}
|
|
2611
2663
|
async function decideGate(projectRoot, question, card, reply, choices) {
|
|
2612
2664
|
const defaults = !choices;
|
|
2613
|
-
if (card.deciding) return;
|
|
2614
|
-
card.deciding = true;
|
|
2615
2665
|
const { taskId, gateId } = question.gate;
|
|
2666
|
+
if (card.deciding) throw gateRefusal("GATE_BUSY", `An answer to gate ${gateId} of ${taskId} is already being recorded`);
|
|
2667
|
+
card.deciding = true;
|
|
2616
2668
|
const channel = reply.channel ?? "web";
|
|
2617
2669
|
const text2 = reply.text?.trim();
|
|
2618
2670
|
const approve2 = !reply.dismiss && !!text2 && (defaults ? APPROVALS.includes(text2.toLowerCase()) : choices.includes(text2));
|
|
@@ -2625,16 +2677,21 @@ ${gate.note ?? ""}`,
|
|
|
2625
2677
|
if (error?.code !== "TASK_CHANGED") throw error;
|
|
2626
2678
|
const current = (await loadTasks(projectRoot)).tasks.find((entry) => entry.id === taskId);
|
|
2627
2679
|
const gate = current?.gates.find((entry) => entry.id === gateId);
|
|
2628
|
-
if (!current || current.status === "closed" || !gate
|
|
2680
|
+
if (!current || current.status === "closed" || !gate) throw gateRefusal("GATE_DECIDED", `Gate ${gateId} of ${taskId} is no longer open`);
|
|
2681
|
+
if (gate.resolved || gate.rejected) throw gateRefusal("GATE_DECIDED", `Gate ${gateId} of ${taskId} was already ${gate.resolved ? "approved" : "rejected"}${(gate.resolved ?? gate.rejected)?.channel ? ` in ${(gate.resolved ?? gate.rejected).channel}` : ""}`);
|
|
2629
2682
|
await write(current.rev);
|
|
2630
2683
|
}
|
|
2631
2684
|
} catch (error) {
|
|
2632
2685
|
runLog(question.rootId, { event: "gate.answer.failed", questionId: question.id, error: errorData(error).message });
|
|
2686
|
+
throw error;
|
|
2633
2687
|
} finally {
|
|
2634
2688
|
card.deciding = false;
|
|
2635
2689
|
await syncGates(projectRoot);
|
|
2636
2690
|
}
|
|
2637
2691
|
}
|
|
2692
|
+
function gateRefusal(code, message) {
|
|
2693
|
+
return Object.assign(new Error(message), { code });
|
|
2694
|
+
}
|
|
2638
2695
|
function askTool(sessionId, session, args) {
|
|
2639
2696
|
const parent = session.parent ? sessions.get(session.parent) : void 0;
|
|
2640
2697
|
const assignment = parent?.assignments.get(sessionId);
|
|
@@ -3164,7 +3221,7 @@ ${digest}` : "")
|
|
|
3164
3221
|
});
|
|
3165
3222
|
if (!session.parent && session.role !== "supervisor" && mapping.agent.name === mainOf(mapping)) {
|
|
3166
3223
|
void syncGates(mapping.agent.projectRoot);
|
|
3167
|
-
startGateWatch();
|
|
3224
|
+
startGateWatch(mapping.agent.projectRoot);
|
|
3168
3225
|
}
|
|
3169
3226
|
if (history === "replay") {
|
|
3170
3227
|
for (const turn of result.thread.turns ?? []) {
|
|
@@ -4475,8 +4532,7 @@ ${interrupted}`), text_elements: [] }] : []
|
|
|
4475
4532
|
if (!pending) throw new Error(`No question ${questionId} waits for an answer`);
|
|
4476
4533
|
if (pending.gate) {
|
|
4477
4534
|
if (!reply.dismiss && (typeof reply.text !== "string" || !reply.text.trim() || reply.text.length > MAIL_BODY_CHARS)) throw new Error("An answer needs text");
|
|
4478
|
-
|
|
4479
|
-
return;
|
|
4535
|
+
return pending.gate.decide(reply);
|
|
4480
4536
|
}
|
|
4481
4537
|
if (reply.dismiss) {
|
|
4482
4538
|
pending.settle("dismissed", void 0, reply.reason);
|
|
@@ -4513,7 +4569,9 @@ ${interrupted}`), text_elements: [] }] : []
|
|
|
4513
4569
|
);
|
|
4514
4570
|
clearInterval(watchdog);
|
|
4515
4571
|
if (gateWatch) clearInterval(gateWatch);
|
|
4572
|
+
for (const root of [...gateFiles.keys()]) unwatchGateFiles(root);
|
|
4516
4573
|
await Promise.all(gateSyncs.values());
|
|
4574
|
+
await Promise.all(gateMarks);
|
|
4517
4575
|
await Promise.all(boards.values());
|
|
4518
4576
|
await boardDomain.flush();
|
|
4519
4577
|
await runLogWrites;
|
package/dist/workspace.d.ts
CHANGED
|
@@ -81,14 +81,33 @@ export declare function mergeWorktree(worktree: Worktree, change: WorktreeChange
|
|
|
81
81
|
export declare function removeWorktree(worktree: Worktree, { deleteBranch }?: {
|
|
82
82
|
deleteBranch?: boolean | undefined;
|
|
83
83
|
}): Promise<void>;
|
|
84
|
+
/**
|
|
85
|
+
* Why reclaimWorktrees left a directory in place: `invalid`, not the top level of a working git
|
|
86
|
+
* worktree; `not-linked`, a repository of its own rather than a worktree of one; `other-branch`,
|
|
87
|
+
* another branch or a detached HEAD, which does not hold this work; `commit-failed`, its work could
|
|
88
|
+
* not be committed (`detail` says why); `uncommitted`, something was still not committed after
|
|
89
|
+
* that; `ignored-files`, its work is committed but it holds ignored files that exist nowhere else.
|
|
90
|
+
*/
|
|
91
|
+
export type LeftWorktree = {
|
|
92
|
+
name: string;
|
|
93
|
+
path: string;
|
|
94
|
+
reason: 'invalid' | 'not-linked' | 'other-branch' | 'commit-failed' | 'uncommitted' | 'ignored-files';
|
|
95
|
+
branch?: string;
|
|
96
|
+
detail?: string;
|
|
97
|
+
files?: string[];
|
|
98
|
+
};
|
|
84
99
|
/**
|
|
85
100
|
* After a crash: commits work left in worktrees under `root` to their branches and
|
|
86
|
-
* removes the directories. Returns the branches that were kept
|
|
87
|
-
* only once everything in it is committed to
|
|
88
|
-
*
|
|
89
|
-
* stays
|
|
101
|
+
* removes the directories. Returns the branches that were kept, and the directories left in
|
|
102
|
+
* place with the reason. A directory is removed only once everything in it is committed to
|
|
103
|
+
* its own `alp/<name>` branch and it holds no ignored file to keep (`.env*`); any other one
|
|
104
|
+
* stays, so recovery reuses or preserves it and nothing uncommitted is lost. Stale locks a
|
|
105
|
+
* killed git command left in such a worktree are removed first (clearStaleLocks).
|
|
90
106
|
*/
|
|
91
|
-
export declare function reclaimWorktrees(root: string): Promise<
|
|
107
|
+
export declare function reclaimWorktrees(root: string): Promise<{
|
|
108
|
+
kept: string[];
|
|
109
|
+
left: LeftWorktree[];
|
|
110
|
+
}>;
|
|
92
111
|
/**
|
|
93
112
|
* A disposable copy of a checkout for an assignment that may build and test but
|
|
94
113
|
* must not touch the requester's tree (ALPD §26): a detached worktree at the
|
package/dist/workspace.js
CHANGED
|
@@ -112,8 +112,8 @@ async function validWorktree(directory) {
|
|
|
112
112
|
async function reattachWorktree(worktree) {
|
|
113
113
|
const exists = !!await stat(worktree.path).catch(() => void 0);
|
|
114
114
|
if (exists && await validWorktree(worktree.path)) {
|
|
115
|
-
const
|
|
116
|
-
if (
|
|
115
|
+
const dirs = await gitDirs(worktree.path);
|
|
116
|
+
if (dirs) await clearStaleLocks(dirs, worktree.branch);
|
|
117
117
|
return worktree;
|
|
118
118
|
}
|
|
119
119
|
if (!await branchExists(worktree.checkout, worktree.branch)) throw new Error(`Branch ${worktree.branch} of the worktree no longer exists`);
|
|
@@ -191,29 +191,92 @@ async function removeWorktree(worktree, { deleteBranch = false } = {}) {
|
|
|
191
191
|
await git(worktree.checkout, ["worktree", "prune"]);
|
|
192
192
|
if (deleteBranch) await git(worktree.checkout, ["branch", "-D", worktree.branch]);
|
|
193
193
|
}
|
|
194
|
+
async function gitDirs(target) {
|
|
195
|
+
const result = await git(target, ["rev-parse", "--path-format=absolute", "--absolute-git-dir", "--git-common-dir"]);
|
|
196
|
+
if (result.code !== 0) return void 0;
|
|
197
|
+
const [own, common] = result.stdout.trim().split("\n").map((line) => path.resolve(line.trim()));
|
|
198
|
+
return own && common ? { own, common } : void 0;
|
|
199
|
+
}
|
|
200
|
+
var SHARED_LOCK_STALE_MS = 1e4;
|
|
201
|
+
async function clearStaleLocks(dirs, branch) {
|
|
202
|
+
if (dirs.own === dirs.common) return;
|
|
203
|
+
const own = (await readdir(dirs.own).catch(() => [])).filter((name) => name.endsWith(".lock"));
|
|
204
|
+
const refs = (await readdir(path.join(dirs.own, "refs"), { recursive: true }).catch(() => [])).filter((name) => name.endsWith(".lock")).map((name) => path.join("refs", name));
|
|
205
|
+
for (const name of [...own, ...refs]) await unlink(path.join(dirs.own, name)).catch(() => {
|
|
206
|
+
});
|
|
207
|
+
const shared = `${path.join(dirs.common, "refs", "heads", ...branch.split("/"))}.lock`;
|
|
208
|
+
const info = await lstat(shared).catch(() => void 0);
|
|
209
|
+
if (info?.isFile() && Date.now() - info.mtimeMs >= SHARED_LOCK_STALE_MS) await unlink(shared).catch(() => {
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
var KEEP_IGNORED = /^\.env/;
|
|
213
|
+
async function ignoredToKeep(target) {
|
|
214
|
+
const result = await git(target, ["ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"]);
|
|
215
|
+
if (result.code !== 0) return void 0;
|
|
216
|
+
return result.stdout.split("\0").filter(Boolean).map((entry) => entry.replace(/\/$/, "")).filter((entry) => KEEP_IGNORED.test(path.posix.basename(entry))).sort();
|
|
217
|
+
}
|
|
218
|
+
var firstLine = (result) => (result.stderr || result.stdout).trim().split("\n")[0] ?? "";
|
|
194
219
|
async function reclaimWorktrees(root) {
|
|
195
220
|
const kept = [];
|
|
221
|
+
const left = [];
|
|
196
222
|
const entries = await readdir(root).catch(() => []);
|
|
197
223
|
for (const name of entries) {
|
|
198
224
|
const target = path.join(root, name);
|
|
225
|
+
const leave = (reason, extra = {}) => {
|
|
226
|
+
left.push({ name, path: target, reason, ...extra });
|
|
227
|
+
};
|
|
199
228
|
if (!(await stat(target).catch(() => void 0))?.isDirectory()) continue;
|
|
200
|
-
if (!await validWorktree(target))
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
229
|
+
if (!await validWorktree(target)) {
|
|
230
|
+
leave("invalid");
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
const dirs = await gitDirs(target);
|
|
234
|
+
if (!dirs) {
|
|
235
|
+
leave("invalid");
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
if (dirs.own === dirs.common) {
|
|
239
|
+
leave("not-linked");
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
const checkout = path.dirname(dirs.common);
|
|
204
243
|
const ref = await git(target, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
205
244
|
const branch = ref.stdout.trim();
|
|
206
|
-
if (ref.code !== 0 || branch !== `alp/${name}`)
|
|
207
|
-
|
|
245
|
+
if (ref.code !== 0 || branch !== `alp/${name}`) {
|
|
246
|
+
leave("other-branch", ref.code === 0 && branch ? { branch } : {});
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
await clearStaleLocks(dirs, branch);
|
|
250
|
+
const added = await git(target, ["add", "-A"]);
|
|
251
|
+
if (added.code !== 0) {
|
|
252
|
+
leave("commit-failed", { branch, detail: firstLine(added) });
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
208
255
|
if ((await git(target, ["diff", "--cached", "--quiet"])).code === 1) {
|
|
209
|
-
|
|
256
|
+
const committed = await git(target, [...IDENTITY, "commit", "--quiet", "--no-verify", "-m", "alp: work left by an interrupted assignment"]);
|
|
257
|
+
if (committed.code !== 0) {
|
|
258
|
+
leave("commit-failed", { branch, detail: firstLine(committed) });
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
210
261
|
}
|
|
211
262
|
const status = await git(target, ["status", "--porcelain", "--ignored=no"]);
|
|
212
|
-
if (status.code !== 0 || status.stdout.trim())
|
|
263
|
+
if (status.code !== 0 || status.stdout.trim()) {
|
|
264
|
+
leave("uncommitted", { branch });
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
const ignored = await ignoredToKeep(target);
|
|
268
|
+
if (!ignored) {
|
|
269
|
+
leave("ignored-files", { branch, detail: "git could not list its ignored files" });
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
if (ignored.length) {
|
|
273
|
+
leave("ignored-files", { branch, files: ignored });
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
213
276
|
await removeWorktree({ checkout, path: target, workdir: target, branch, base: "" });
|
|
214
277
|
kept.push(branch);
|
|
215
278
|
}
|
|
216
|
-
return kept;
|
|
279
|
+
return { kept, left };
|
|
217
280
|
}
|
|
218
281
|
async function createCopy(workdir, root, id) {
|
|
219
282
|
const checkout = await checkoutOf(workdir);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anhlp/alp-runtime",
|
|
3
|
-
"version": "0.0.1-beta.
|
|
3
|
+
"version": "0.0.1-beta.6",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "ALP runtime module",
|
|
6
6
|
"files": [
|
|
@@ -230,8 +230,8 @@
|
|
|
230
230
|
"node": ">=22.12"
|
|
231
231
|
},
|
|
232
232
|
"dependencies": {
|
|
233
|
-
"@anhlp/alp-core": "0.0.1-beta.
|
|
234
|
-
"@anhlp/alp-protocol": "0.0.1-beta.
|
|
233
|
+
"@anhlp/alp-core": "0.0.1-beta.6",
|
|
234
|
+
"@anhlp/alp-protocol": "0.0.1-beta.6",
|
|
235
235
|
"@anthropic-ai/claude-agent-sdk": "^0.3.292",
|
|
236
236
|
"@modelcontextprotocol/sdk": "^1.32.1",
|
|
237
237
|
"@agentclientprotocol/sdk": "1.7.0",
|
package/src/claude-transport.ts
CHANGED
|
@@ -11,11 +11,15 @@ import { inputLimitError, POUR_VARS, VAR_NAME, type InputLimits } from './input-
|
|
|
11
11
|
import { claudeToolDetail, resultText } from './tool-detail.js';
|
|
12
12
|
import { CLOSE_REASONS, GATE_KINDS, TASK_STATUSES, TASK_TYPES } from '@anhlp/alp-core/tasks';
|
|
13
13
|
import { commandDecision } from '@anhlp/alp-core/permissions';
|
|
14
|
+
import { packagedInfo } from '@anhlp/alp-core/packaged';
|
|
14
15
|
|
|
15
16
|
// Keep the Claude SDK behind the runtime boundary. Paseo inspects static
|
|
16
17
|
// imports while compiling plugin entrypoints, including their declaration
|
|
17
18
|
// graph; the SDK is a daemon-only optional runtime dependency.
|
|
18
19
|
const CLAUDE_SDK = ['@anthropic-ai', 'claude-agent-sdk'].join('/');
|
|
20
|
+
// The ALP executable has no node_modules to resolve CLAUDE_SDK from: its entry embeds the SDK and
|
|
21
|
+
// registers the import under the package name (scripts/build-binary.mjs).
|
|
22
|
+
const claudeSdk = (): Promise<any> => packagedInfo()?.modules?.[CLAUDE_SDK]?.() ?? import(CLAUDE_SDK);
|
|
19
23
|
|
|
20
24
|
type SDKUserMessage = any;
|
|
21
25
|
type SDKMessage = any;
|
|
@@ -384,7 +388,7 @@ const BOOT_MS = 15_000;
|
|
|
384
388
|
* resumed or forked from another directory). Empty when the session has no transcript yet.
|
|
385
389
|
*/
|
|
386
390
|
export async function claudeChain(sessionId: string, dir?: string): Promise<Array<{ uuid: string; type: 'user' | 'assistant'; toolResult?: boolean }>> {
|
|
387
|
-
const { getSessionMessages } = await
|
|
391
|
+
const { getSessionMessages } = await claudeSdk();
|
|
388
392
|
let messages: any[] = dir ? await getSessionMessages(sessionId, { dir }) : [];
|
|
389
393
|
if (!messages.length) messages = await getSessionMessages(sessionId);
|
|
390
394
|
return messages.filter(message => (message.type === 'user' || message.type === 'assistant') && typeof message.uuid === 'string').map(message => {
|
|
@@ -463,7 +467,7 @@ export class ClaudeTransport {
|
|
|
463
467
|
|
|
464
468
|
/** The models Claude offers now, from a Claude process that sends no prompt and is closed after (t-e5ee). */
|
|
465
469
|
async probeModels(signal?: AbortSignal) {
|
|
466
|
-
const { query } = await
|
|
470
|
+
const { query } = await claudeSdk();
|
|
467
471
|
if (signal?.aborted) throw new Error('aborted');
|
|
468
472
|
const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } }) as ClaudeQuery;
|
|
469
473
|
// A probe that outlives its bound is closed, so a hanging Claude process never stays behind.
|
|
@@ -481,7 +485,7 @@ export class ClaudeTransport {
|
|
|
481
485
|
/** The plan's usage windows before a session starts, from a Claude process that sends no prompt and is closed after. */
|
|
482
486
|
private async probeUsage() {
|
|
483
487
|
if (this.closed) return undefined;
|
|
484
|
-
const { query } = await
|
|
488
|
+
const { query } = await claudeSdk();
|
|
485
489
|
const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } }) as ClaudeQuery;
|
|
486
490
|
try {
|
|
487
491
|
return await probe.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
|
|
@@ -517,7 +521,7 @@ export class ClaudeTransport {
|
|
|
517
521
|
if (method === 'thread/chain') return { entries: await claudeChain(params.threadId, params.cwd ?? this.cwd) };
|
|
518
522
|
|
|
519
523
|
if (method === 'thread/delete') {
|
|
520
|
-
const { deleteSession } = await
|
|
524
|
+
const { deleteSession } = await claudeSdk();
|
|
521
525
|
await deleteSession(params.threadId, params.cwd ? { dir: params.cwd } : {});
|
|
522
526
|
return {};
|
|
523
527
|
}
|
|
@@ -626,7 +630,7 @@ export class ClaudeTransport {
|
|
|
626
630
|
}
|
|
627
631
|
|
|
628
632
|
private async start(from?: { resume: string; fork: boolean; at?: string }) {
|
|
629
|
-
const { createSdkMcpServer, query, tool } = await
|
|
633
|
+
const { createSdkMcpServer, query, tool } = await claudeSdk();
|
|
630
634
|
const config = this.config!;
|
|
631
635
|
const mcpServers = this.convertMcp(config.mcpServers);
|
|
632
636
|
|
package/src/contracts.ts
CHANGED
|
@@ -170,9 +170,14 @@ export type AlpRuntime = {
|
|
|
170
170
|
status(sessionId: string): TreeStatus | undefined;
|
|
171
171
|
/** Questions agents asked the user that wait for an answer. */
|
|
172
172
|
questions(): UserQuestion[];
|
|
173
|
-
/**
|
|
174
|
-
|
|
175
|
-
|
|
173
|
+
/**
|
|
174
|
+
* Answers or dismisses a question to the user. A gate card's answer returns a promise that
|
|
175
|
+
* settles once the decision is written, and rejects when it decides nothing: another answer is
|
|
176
|
+
* being recorded or another channel decided first (code GATE_BUSY or GATE_DECIDED), or the
|
|
177
|
+
* write failed (t-595d).
|
|
178
|
+
*/
|
|
179
|
+
answer(questionId: string, reply: { text?: string; dismiss?: boolean; reason?: string; /** Where the user answered a gate card: paseo or web. */ channel?: 'paseo' | 'web' }): void | Promise<void>;
|
|
180
|
+
/** Mirrors the project's open human gates as cards on its main session and tells main of the user's gate decisions, at least once each (t-ccac, t-595d). */
|
|
176
181
|
syncGates?(projectRoot: string): Promise<void>;
|
|
177
182
|
/** Mails a note from the user to any live session, such as an assignment the user wants to redirect. */
|
|
178
183
|
message(sessionId: string, text: string): void;
|
package/src/index.ts
CHANGED
|
@@ -23,6 +23,7 @@ export { ClaudeTransport, claudePermissions, claudeSandboxAvailable, skillPlugin
|
|
|
23
23
|
export { MAIL_BATCH_CHARS, MAIL_BODY_CHARS, publicEvent, renderMail, takeBatch, USER } from './mailbox.js';
|
|
24
24
|
export type { MailEvent, MailKind } from './mailbox.js';
|
|
25
25
|
export { createCopy, gitEnvironment, reattachWorktree, reclaimCopies, reclaimWorktrees, removeCopy } from './workspace.js';
|
|
26
|
+
export type { LeftWorktree } from './workspace.js';
|
|
26
27
|
export { OWN_START, processStartedAt, sameProcessAlive } from './process-info.js';
|
|
27
28
|
export type { Worktree, WorktreeChange } from './workspace.js';
|
|
28
29
|
export { PIN_KINDS, renderBoard, renderPin } from './board.js';
|
package/src/runtime.ts
CHANGED
|
@@ -18,7 +18,7 @@ import { TASK_ACTIONS, TASK_PAST, TASK_FIELDS, mainOf, roleOf, taskActions, task
|
|
|
18
18
|
import { nativeEnvironment, createTransport } from './providers.js';
|
|
19
19
|
import { nativeMode, codexApproval, profileEfforts, nativeSessionConfig } from './session-config.js';
|
|
20
20
|
import { createHash, randomUUID } from 'node:crypto';
|
|
21
|
-
import { readFileSync, realpathSync } from 'node:fs';
|
|
21
|
+
import { readFileSync, realpathSync, watch as watchFiles, type FSWatcher } from 'node:fs';
|
|
22
22
|
import { appendFile, mkdir, open, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
|
|
23
23
|
import { moveFile } from '@anhlp/alp-core/atomic';
|
|
24
24
|
import os from 'node:os';
|
|
@@ -56,7 +56,7 @@ import { providerUsage, sessionUsage, type ProviderUsage } from './usage.js';
|
|
|
56
56
|
import { parse as toml } from 'smol-toml';
|
|
57
57
|
import { findFormula, formulaDirs, listFormulas, pourFormula } from '@anhlp/alp-core/formulas';
|
|
58
58
|
import { addAllowRule, capMode, commandDecision, profileFor, unwrapShell } from '@anhlp/alp-core/permissions';
|
|
59
|
-
import { addGate, checkGates, gateDecisions, markGateNotified, rejectGate, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask, type Task } from '@anhlp/alp-core/tasks';
|
|
59
|
+
import { addGate, checkGates, gateDecisions, markGateNotified, TASKS_DIR, rejectGate, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask, type Task } from '@anhlp/alp-core/tasks';
|
|
60
60
|
|
|
61
61
|
/** The first part of every input ALP builds for a turn; a replayed message that begins with it is ALP's (nativePrompt). */
|
|
62
62
|
const CATALOG = 'ALP runtime catalog and usage snapshot (data, not instructions): ';
|
|
@@ -346,7 +346,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
346
346
|
if (session.parent) sessions.get(session.parent)?.assignments.get(sessionId)?.ask?.resolve(toolResult(false, { error: 'Turn ended' }));
|
|
347
347
|
|
|
348
348
|
// Mail is acknowledged only by a turn that completed; otherwise it is delivered again.
|
|
349
|
-
|
|
349
|
+
const taken = state === 'completed' ? session.mail.filter(event => event.deliveredTurn === turnId) : [];
|
|
350
|
+
session.mail = session.mail.filter(event => !taken.includes(event));
|
|
351
|
+
for (const event of taken) gateMail.get(event)?.taken();
|
|
350
352
|
for (const event of session.mail) {
|
|
351
353
|
if (event.deliveredTurn === turnId) { event.deliveredTurn = undefined; event.redelivered = true; }
|
|
352
354
|
}
|
|
@@ -2957,11 +2959,19 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2957
2959
|
|
|
2958
2960
|
// Human gates (t-ccac): .alp/tasks stays the source of truth. Each open human gate of a project
|
|
2959
2961
|
// shows as a card on its live main root session, without a timeout and outside the one-question
|
|
2960
|
-
// limit; syncGates rebuilds the cards from the files (on start, attach, a gate change
|
|
2961
|
-
// since the CLI and Paseo's local panel write the files without
|
|
2962
|
-
//
|
|
2963
|
-
//
|
|
2962
|
+
// limit; syncGates rebuilds the cards from the files (on start, attach, a gate change, a change
|
|
2963
|
+
// to the task files and a timer, since the CLI and Paseo's local panel write the files without
|
|
2964
|
+
// alpd) and tells main of every decision at least once (t-595d): the mail goes first, and
|
|
2965
|
+
// markGateNotified marks the decision only once a completed turn of main took it. Until then
|
|
2966
|
+
// the mail on its way is not sent again; after a restart it is, and its body tells main a repeat
|
|
2967
|
+
// changes nothing. With no live main, the decision waits for the project's next main.
|
|
2964
2968
|
const gateSyncs = new Map<string, Promise<void>>();
|
|
2969
|
+
/** Decision mail on its way to main, by the decision it reports. */
|
|
2970
|
+
const gateMail = new WeakMap<MailEvent, { key: string; taken: () => void }>();
|
|
2971
|
+
/** Decisions main took whose mark is being written, or was. */
|
|
2972
|
+
const gateTaken = new Set<string>();
|
|
2973
|
+
/** Marks being written; shutdown waits for them, so nothing writes the task files after it. */
|
|
2974
|
+
const gateMarks = new Set<Promise<unknown>>();
|
|
2965
2975
|
const gateCardId = (taskId: string, gateId: string) => `gate-${taskId}-${gateId}`;
|
|
2966
2976
|
|
|
2967
2977
|
/** The project's live main root session, if any. */
|
|
@@ -2987,14 +2997,28 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
2987
2997
|
if (closed) return;
|
|
2988
2998
|
const { tasks } = await loadTasks(projectRoot);
|
|
2989
2999
|
const main = mainSessionOf(projectRoot);
|
|
2990
|
-
// The user's decisions, to main once each; without a live main they wait for the next one.
|
|
3000
|
+
// The user's decisions, to main at least once each; without a live main they wait for the next one.
|
|
2991
3001
|
if (main) for (const { task, gate, decision, record } of gateDecisions(tasks)) {
|
|
2992
|
-
|
|
3002
|
+
const key = JSON.stringify([projectRoot, task.id, gate.id, decision, record.at]);
|
|
3003
|
+
if (gateTaken.has(key) || main.session.mail.some(event => gateMail.get(event)?.key === key)) continue;
|
|
2993
3004
|
const choice = decision === 'approved' ? (record as { choice?: string }).choice : undefined;
|
|
2994
3005
|
const words = decision === 'approved'
|
|
2995
3006
|
? `The user approved human gate ${gate.id} of ${task.id} in ${record.channel}${choice ? `, choosing "${choice}"` : ''}${(record as { note?: string }).note ? `: ${(record as { note?: string }).note}` : ''}.`
|
|
2996
3007
|
: `The user rejected human gate ${gate.id} of ${task.id} in ${record.channel}${(record as { reason?: string }).reason ? `: ${(record as { reason?: string }).reason}` : ''}. The gate stays open.`;
|
|
2997
|
-
post(main.id, { kind: 'result', from: 'ALP', assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words} Task: ${task.title}
|
|
3008
|
+
const mail = post(main.id, { kind: 'result', from: 'ALP', assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words} Task: ${task.title}. If this decision of ${gateCardId(task.id, gate.id)} was reported to you before, it is a repeat: act on it once.` });
|
|
3009
|
+
gateMail.set(mail, {
|
|
3010
|
+
key,
|
|
3011
|
+
taken: () => {
|
|
3012
|
+
gateTaken.add(key);
|
|
3013
|
+
const mark = markGateNotified(projectRoot, task.id, gate.id, decision, record.at).catch(error => {
|
|
3014
|
+
// Unmarked, it is mailed again: once more is better than never.
|
|
3015
|
+
gateTaken.delete(key);
|
|
3016
|
+
runLog(main.id, { event: 'gate.mark.failed', projectRoot, taskId: task.id, gateId: gate.id, error: errorData(error).message });
|
|
3017
|
+
});
|
|
3018
|
+
gateMarks.add(mark);
|
|
3019
|
+
void mark.finally(() => gateMarks.delete(mark));
|
|
3020
|
+
},
|
|
3021
|
+
});
|
|
2998
3022
|
runLog(main.id, { event: 'gate.decision', projectRoot, taskId: task.id, gateId: gate.id, decision, channel: record.channel, ...(choice ? { choice } : {}) });
|
|
2999
3023
|
}
|
|
3000
3024
|
// A card for each open human gate the user has not rejected; a rejected one stays open for main to follow up.
|
|
@@ -3016,18 +3040,51 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3016
3040
|
for (const [id, { task, gate }] of wanted) if (!userQuestions.has(id)) showGateCard(main.id, main.session, projectRoot, task, gate);
|
|
3017
3041
|
}
|
|
3018
3042
|
|
|
3019
|
-
/**
|
|
3043
|
+
/**
|
|
3044
|
+
* The CLI and Paseo's local Tasks panel write gates without alpd: while a main is live, a change
|
|
3045
|
+
* to the project's task files syncs at once (t-595d), and a timer reads them too, where file
|
|
3046
|
+
* events are missing or lost.
|
|
3047
|
+
*/
|
|
3020
3048
|
let gateWatch: NodeJS.Timeout | undefined;
|
|
3021
|
-
|
|
3022
|
-
|
|
3049
|
+
const gateFiles = new Map<string, { watcher: FSWatcher; timer?: NodeJS.Timeout }>();
|
|
3050
|
+
function startGateWatch(projectRoot: string) {
|
|
3051
|
+
if (options.gateSyncMs === 0) return;
|
|
3052
|
+
watchGateFiles(path.resolve(projectRoot));
|
|
3053
|
+
if (gateWatch) return;
|
|
3023
3054
|
gateWatch = setInterval(() => {
|
|
3024
3055
|
const roots = new Set([...sessions.values()].filter(session => !session.closed && !session.parent && session.role !== 'supervisor' && session.mapping.agent.name === mainOf(session.mapping)).map(session => path.resolve(session.mapping.agent.projectRoot)));
|
|
3025
|
-
for (const root of roots) void syncGates(root);
|
|
3056
|
+
for (const root of roots) { watchGateFiles(root); void syncGates(root); }
|
|
3057
|
+
for (const root of gateFiles.keys()) if (!roots.has(root)) unwatchGateFiles(root);
|
|
3026
3058
|
if (!roots.size) { clearInterval(gateWatch); gateWatch = undefined; }
|
|
3027
3059
|
}, options.gateSyncMs ?? 5_000);
|
|
3028
3060
|
gateWatch.unref?.();
|
|
3029
3061
|
}
|
|
3030
3062
|
|
|
3063
|
+
function watchGateFiles(root: string) {
|
|
3064
|
+
if (closed || gateFiles.has(root)) return;
|
|
3065
|
+
try {
|
|
3066
|
+
const entry: { watcher: FSWatcher; timer?: NodeJS.Timeout } = {
|
|
3067
|
+
// A burst of writes (a save, its ledger, a mark) syncs once.
|
|
3068
|
+
watcher: watchFiles(path.join(root, TASKS_DIR), () => {
|
|
3069
|
+
if (entry.timer || closed) return;
|
|
3070
|
+
entry.timer = setTimeout(() => { entry.timer = undefined; void syncGates(root); }, 50);
|
|
3071
|
+
entry.timer.unref?.();
|
|
3072
|
+
}),
|
|
3073
|
+
};
|
|
3074
|
+
entry.watcher.on('error', () => unwatchGateFiles(root));
|
|
3075
|
+
entry.watcher.unref?.();
|
|
3076
|
+
gateFiles.set(root, entry);
|
|
3077
|
+
} catch {} // No task files yet, or no file events here: the timer tries again.
|
|
3078
|
+
}
|
|
3079
|
+
|
|
3080
|
+
function unwatchGateFiles(root: string) {
|
|
3081
|
+
const entry = gateFiles.get(root);
|
|
3082
|
+
if (!entry) return;
|
|
3083
|
+
gateFiles.delete(root);
|
|
3084
|
+
clearTimeout(entry.timer);
|
|
3085
|
+
entry.watcher.close();
|
|
3086
|
+
}
|
|
3087
|
+
|
|
3031
3088
|
function showGateCard(sessionId: string, session: Session, projectRoot: string, task: Task, gate: Task['gates'][number]) {
|
|
3032
3089
|
const say = wordsFor(session);
|
|
3033
3090
|
const vietnamese = say.approve === words('vi').approve;
|
|
@@ -3057,13 +3114,15 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3057
3114
|
* The user answered a gate card: an option approves (with the default Approve/Reject, Reject or
|
|
3058
3115
|
* other words reject), dismissing rejects. The card's task rev guards the write; a stale rev is
|
|
3059
3116
|
* read again and retried only while the gate is still open and undecided, so a decision another
|
|
3060
|
-
* channel made first is never applied or mailed twice.
|
|
3117
|
+
* channel made first is never applied or mailed twice. An answer that decides nothing (a second
|
|
3118
|
+
* one while the first is written, one another channel beat, or a failed write) is refused to the
|
|
3119
|
+
* caller, never only logged (t-595d).
|
|
3061
3120
|
*/
|
|
3062
3121
|
async function decideGate(projectRoot: string, question: UserQuestion, card: { rev: number; deciding: boolean }, reply: { text?: string; dismiss?: boolean; reason?: string; channel?: 'paseo' | 'web' }, choices?: string[]) {
|
|
3063
3122
|
const defaults = !choices;
|
|
3064
|
-
if (card.deciding) return;
|
|
3065
|
-
card.deciding = true;
|
|
3066
3123
|
const { taskId, gateId } = question.gate!;
|
|
3124
|
+
if (card.deciding) throw gateRefusal('GATE_BUSY', `An answer to gate ${gateId} of ${taskId} is already being recorded`);
|
|
3125
|
+
card.deciding = true;
|
|
3067
3126
|
const channel = reply.channel ?? 'web';
|
|
3068
3127
|
const text = reply.text?.trim();
|
|
3069
3128
|
const approve = !reply.dismiss && !!text && (defaults ? APPROVALS.includes(text.toLowerCase()) : choices.includes(text));
|
|
@@ -3077,18 +3136,24 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3077
3136
|
if (error?.code !== 'TASK_CHANGED') throw error;
|
|
3078
3137
|
const current = (await loadTasks(projectRoot)).tasks.find(entry => entry.id === taskId);
|
|
3079
3138
|
const gate = current?.gates.find(entry => entry.id === gateId);
|
|
3080
|
-
if (!current || current.status === 'closed' || !gate
|
|
3139
|
+
if (!current || current.status === 'closed' || !gate) throw gateRefusal('GATE_DECIDED', `Gate ${gateId} of ${taskId} is no longer open`);
|
|
3140
|
+
if (gate.resolved || gate.rejected) throw gateRefusal('GATE_DECIDED', `Gate ${gateId} of ${taskId} was already ${gate.resolved ? 'approved' : 'rejected'}${(gate.resolved ?? gate.rejected)?.channel ? ` in ${(gate.resolved ?? gate.rejected)!.channel}` : ''}`);
|
|
3081
3141
|
await write(current.rev);
|
|
3082
3142
|
}
|
|
3083
3143
|
} catch (error) {
|
|
3084
|
-
// Already clear, or the task is gone: the other channel won; the sync below settles the card.
|
|
3085
3144
|
runLog(question.rootId, { event: 'gate.answer.failed', questionId: question.id, error: errorData(error).message });
|
|
3145
|
+
throw error;
|
|
3086
3146
|
} finally {
|
|
3087
3147
|
card.deciding = false;
|
|
3148
|
+
// Settles the card whatever happened: decided here, by another channel, or gone.
|
|
3088
3149
|
await syncGates(projectRoot);
|
|
3089
3150
|
}
|
|
3090
3151
|
}
|
|
3091
3152
|
|
|
3153
|
+
function gateRefusal(code: 'GATE_BUSY' | 'GATE_DECIDED', message: string) {
|
|
3154
|
+
return Object.assign(new Error(message), { code });
|
|
3155
|
+
}
|
|
3156
|
+
|
|
3092
3157
|
function askTool(sessionId: string, session: Session, args: unknown) {
|
|
3093
3158
|
const parent = session.parent ? sessions.get(session.parent) : undefined;
|
|
3094
3159
|
const assignment = parent?.assignments.get(sessionId);
|
|
@@ -3726,7 +3791,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
3726
3791
|
},
|
|
3727
3792
|
});
|
|
3728
3793
|
// A main root shows the project's open human gates and gets decisions made while none was live.
|
|
3729
|
-
if (!session.parent && session.role !== 'supervisor' && mapping.agent.name === mainOf(mapping)) { void syncGates(mapping.agent.projectRoot); startGateWatch(); }
|
|
3794
|
+
if (!session.parent && session.role !== 'supervisor' && mapping.agent.name === mainOf(mapping)) { void syncGates(mapping.agent.projectRoot); startGateWatch(mapping.agent.projectRoot); }
|
|
3730
3795
|
|
|
3731
3796
|
if (
|
|
3732
3797
|
history === 'replay'
|
|
@@ -5229,8 +5294,7 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
5229
5294
|
if (!pending) throw new Error(`No question ${questionId} waits for an answer`);
|
|
5230
5295
|
if (pending.gate) {
|
|
5231
5296
|
if (!reply.dismiss && (typeof reply.text !== 'string' || !reply.text.trim() || reply.text.length > MAIL_BODY_CHARS)) throw new Error('An answer needs text');
|
|
5232
|
-
|
|
5233
|
-
return;
|
|
5297
|
+
return pending.gate.decide(reply);
|
|
5234
5298
|
}
|
|
5235
5299
|
if (reply.dismiss) {
|
|
5236
5300
|
pending.settle('dismissed', undefined, reply.reason);
|
|
@@ -5275,7 +5339,9 @@ export function createAlpRuntime(options: RuntimeOptions = {}): AlpRuntime {
|
|
|
5275
5339
|
|
|
5276
5340
|
clearInterval(watchdog);
|
|
5277
5341
|
if (gateWatch) clearInterval(gateWatch);
|
|
5342
|
+
for (const root of [...gateFiles.keys()]) unwatchGateFiles(root);
|
|
5278
5343
|
await Promise.all(gateSyncs.values());
|
|
5344
|
+
await Promise.all(gateMarks);
|
|
5279
5345
|
|
|
5280
5346
|
// Claims released by the closes above are written before the board is left.
|
|
5281
5347
|
await Promise.all(boards.values());
|
package/src/workspace.ts
CHANGED
|
@@ -157,10 +157,11 @@ async function validWorktree(directory: string) {
|
|
|
157
157
|
export async function reattachWorktree(worktree: Worktree): Promise<Worktree & { preserved?: string }> {
|
|
158
158
|
const exists = !!await stat(worktree.path).catch(() => undefined);
|
|
159
159
|
if (exists && await validWorktree(worktree.path)) {
|
|
160
|
-
// A crash mid `git add`/`commit` leaves the index locked; nothing else
|
|
161
|
-
// while its assignment reopens, so the
|
|
162
|
-
|
|
163
|
-
|
|
160
|
+
// A crash mid `git add`/`commit` leaves the index, HEAD or the branch locked; nothing else
|
|
161
|
+
// writes this worktree while its assignment reopens, so the locks are stale and would block
|
|
162
|
+
// every later commit.
|
|
163
|
+
const dirs = await gitDirs(worktree.path);
|
|
164
|
+
if (dirs) await clearStaleLocks(dirs, worktree.branch);
|
|
164
165
|
return worktree;
|
|
165
166
|
}
|
|
166
167
|
if (!await branchExists(worktree.checkout, worktree.branch)) throw new Error(`Branch ${worktree.branch} of the worktree no longer exists`);
|
|
@@ -254,36 +255,114 @@ export async function removeWorktree(worktree: Worktree, { deleteBranch = false
|
|
|
254
255
|
if (deleteBranch) await git(worktree.checkout, ['branch', '-D', worktree.branch]);
|
|
255
256
|
}
|
|
256
257
|
|
|
258
|
+
/** A linked worktree's own git directory and the repository's common one, both absolute. */
|
|
259
|
+
type GitDirs = { own: string; common: string };
|
|
260
|
+
|
|
261
|
+
async function gitDirs(target: string): Promise<GitDirs | undefined> {
|
|
262
|
+
const result = await git(target, ['rev-parse', '--path-format=absolute', '--absolute-git-dir', '--git-common-dir']);
|
|
263
|
+
if (result.code !== 0) return undefined;
|
|
264
|
+
const [own, common] = result.stdout.trim().split('\n').map(line => path.resolve(line.trim()));
|
|
265
|
+
return own && common ? { own, common } : undefined;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* How old the branch's lock in the shared repository must be before ALP treats it as left by
|
|
270
|
+
* a crash. The user's own git commands in their checkout lock that ref too (`git gc`, `git branch
|
|
271
|
+
* -D`), but only for the moment a ref update takes.
|
|
272
|
+
*/
|
|
273
|
+
const SHARED_LOCK_STALE_MS = 10_000;
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Removes the locks a git command killed mid-write left in a worktree, which would fail every
|
|
277
|
+
* later `git add` or `git commit` there: `index.lock`, `HEAD.lock` and any other lock directly in
|
|
278
|
+
* the worktree's own git directory, and every `*.lock` under its `refs/`. Callers run this only
|
|
279
|
+
* where no ALP git command can be at work in that worktree (alpd's start, once it has stopped what
|
|
280
|
+
* a crashed alpd left running, and an assignment reopening): only ALP works in its worktrees, so
|
|
281
|
+
* those locks are stale, as `index.lock` always was. In the repository the worktree shares with
|
|
282
|
+
* the user's checkout, only the lock of the worktree's own branch is touched, and only once it is
|
|
283
|
+
* older than SHARED_LOCK_STALE_MS; every other lock there is the user's business.
|
|
284
|
+
*/
|
|
285
|
+
async function clearStaleLocks(dirs: GitDirs, branch: string) {
|
|
286
|
+
if (dirs.own === dirs.common) return;
|
|
287
|
+
const own = (await readdir(dirs.own).catch(() => [] as string[])).filter(name => name.endsWith('.lock'));
|
|
288
|
+
const refs = (await readdir(path.join(dirs.own, 'refs'), { recursive: true }).catch(() => [] as string[])).filter(name => name.endsWith('.lock')).map(name => path.join('refs', name));
|
|
289
|
+
for (const name of [...own, ...refs]) await unlink(path.join(dirs.own, name)).catch(() => {});
|
|
290
|
+
const shared = `${path.join(dirs.common, 'refs', 'heads', ...branch.split('/'))}.lock`;
|
|
291
|
+
const info = await lstat(shared).catch(() => undefined);
|
|
292
|
+
if (info?.isFile() && Date.now() - info.mtimeMs >= SHARED_LOCK_STALE_MS) await unlink(shared).catch(() => {});
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Ignored files that may hold what exists nowhere else, such as credentials: `.env`, `.env.local`. */
|
|
296
|
+
const KEEP_IGNORED = /^\.env/;
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* The ignored entries of a worktree that removing it would lose for good. git lists them, and an
|
|
300
|
+
* ignored directory (node_modules, build output) is one entry it does not look into.
|
|
301
|
+
*/
|
|
302
|
+
async function ignoredToKeep(target: string) {
|
|
303
|
+
const result = await git(target, ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory']);
|
|
304
|
+
if (result.code !== 0) return undefined;
|
|
305
|
+
return result.stdout.split('\0').filter(Boolean).map(entry => entry.replace(/\/$/, '')).filter(entry => KEEP_IGNORED.test(path.posix.basename(entry))).sort();
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Why reclaimWorktrees left a directory in place: `invalid`, not the top level of a working git
|
|
310
|
+
* worktree; `not-linked`, a repository of its own rather than a worktree of one; `other-branch`,
|
|
311
|
+
* another branch or a detached HEAD, which does not hold this work; `commit-failed`, its work could
|
|
312
|
+
* not be committed (`detail` says why); `uncommitted`, something was still not committed after
|
|
313
|
+
* that; `ignored-files`, its work is committed but it holds ignored files that exist nowhere else.
|
|
314
|
+
*/
|
|
315
|
+
export type LeftWorktree = {
|
|
316
|
+
name: string;
|
|
317
|
+
path: string;
|
|
318
|
+
reason: 'invalid' | 'not-linked' | 'other-branch' | 'commit-failed' | 'uncommitted' | 'ignored-files';
|
|
319
|
+
branch?: string;
|
|
320
|
+
detail?: string;
|
|
321
|
+
files?: string[];
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
const firstLine = (result: GitResult) => (result.stderr || result.stdout).trim().split('\n')[0] ?? '';
|
|
325
|
+
|
|
257
326
|
/**
|
|
258
327
|
* After a crash: commits work left in worktrees under `root` to their branches and
|
|
259
|
-
* removes the directories. Returns the branches that were kept
|
|
260
|
-
* only once everything in it is committed to
|
|
261
|
-
*
|
|
262
|
-
* stays
|
|
328
|
+
* removes the directories. Returns the branches that were kept, and the directories left in
|
|
329
|
+
* place with the reason. A directory is removed only once everything in it is committed to
|
|
330
|
+
* its own `alp/<name>` branch and it holds no ignored file to keep (`.env*`); any other one
|
|
331
|
+
* stays, so recovery reuses or preserves it and nothing uncommitted is lost. Stale locks a
|
|
332
|
+
* killed git command left in such a worktree are removed first (clearStaleLocks).
|
|
263
333
|
*/
|
|
264
|
-
export async function reclaimWorktrees(root: string) {
|
|
334
|
+
export async function reclaimWorktrees(root: string): Promise<{ kept: string[]; left: LeftWorktree[] }> {
|
|
265
335
|
const kept: string[] = [];
|
|
336
|
+
const left: LeftWorktree[] = [];
|
|
266
337
|
const entries = await readdir(root).catch(() => [] as string[]);
|
|
267
338
|
for (const name of entries) {
|
|
268
339
|
const target = path.join(root, name);
|
|
340
|
+
const leave = (reason: LeftWorktree['reason'], extra: Omit<LeftWorktree, 'name' | 'path' | 'reason'> = {}) => { left.push({ name, path: target, reason, ...extra }); };
|
|
269
341
|
if (!(await stat(target).catch(() => undefined))?.isDirectory()) continue;
|
|
270
|
-
if (!await validWorktree(target)) continue;
|
|
271
|
-
const
|
|
272
|
-
if (
|
|
273
|
-
|
|
342
|
+
if (!await validWorktree(target)) { leave('invalid'); continue; }
|
|
343
|
+
const dirs = await gitDirs(target);
|
|
344
|
+
if (!dirs) { leave('invalid'); continue; }
|
|
345
|
+
if (dirs.own === dirs.common) { leave('not-linked'); continue; }
|
|
346
|
+
const checkout = path.dirname(dirs.common);
|
|
274
347
|
const ref = await git(target, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
275
348
|
const branch = ref.stdout.trim();
|
|
276
|
-
if (ref.code !== 0 || branch !== `alp/${name}`) continue;
|
|
277
|
-
|
|
349
|
+
if (ref.code !== 0 || branch !== `alp/${name}`) { leave('other-branch', ref.code === 0 && branch ? { branch } : {}); continue; }
|
|
350
|
+
await clearStaleLocks(dirs, branch);
|
|
351
|
+
const added = await git(target, ['add', '-A']);
|
|
352
|
+
if (added.code !== 0) { leave('commit-failed', { branch, detail: firstLine(added) }); continue; }
|
|
278
353
|
if ((await git(target, ['diff', '--cached', '--quiet'])).code === 1) {
|
|
279
|
-
|
|
354
|
+
const committed = await git(target, [...IDENTITY, 'commit', '--quiet', '--no-verify', '-m', 'alp: work left by an interrupted assignment']);
|
|
355
|
+
if (committed.code !== 0) { leave('commit-failed', { branch, detail: firstLine(committed) }); continue; }
|
|
280
356
|
}
|
|
281
357
|
const status = await git(target, ['status', '--porcelain', '--ignored=no']);
|
|
282
|
-
if (status.code !== 0 || status.stdout.trim()) continue;
|
|
358
|
+
if (status.code !== 0 || status.stdout.trim()) { leave('uncommitted', { branch }); continue; }
|
|
359
|
+
const ignored = await ignoredToKeep(target);
|
|
360
|
+
if (!ignored) { leave('ignored-files', { branch, detail: 'git could not list its ignored files' }); continue; }
|
|
361
|
+
if (ignored.length) { leave('ignored-files', { branch, files: ignored }); continue; }
|
|
283
362
|
await removeWorktree({ checkout, path: target, workdir: target, branch, base: '' });
|
|
284
363
|
kept.push(branch);
|
|
285
364
|
}
|
|
286
|
-
return kept;
|
|
365
|
+
return { kept, left };
|
|
287
366
|
}
|
|
288
367
|
|
|
289
368
|
/**
|