@oyasmi/pipiclaw 0.8.10 → 0.8.11-beta.3
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 +3 -3
- package/dist/agent/channel-runner.d.ts +11 -0
- package/dist/agent/channel-runner.js +58 -27
- package/dist/agent/commands.js +2 -3
- package/dist/agent/effect-ledger.d.ts +1 -1
- package/dist/agent/effect-ledger.js +2 -2
- package/dist/agent/prompt/sections.js +3 -3
- package/dist/agent/runner-factory.d.ts +2 -0
- package/dist/agent/session-events.js +1 -1
- package/dist/main.js +6 -0
- package/dist/memory/commands.js +6 -1
- package/dist/memory/consolidation.d.ts +8 -1
- package/dist/memory/consolidation.js +34 -6
- package/dist/memory/extraction.d.ts +11 -3
- package/dist/memory/extraction.js +19 -6
- package/dist/memory/files.d.ts +2 -0
- package/dist/memory/files.js +14 -0
- package/dist/memory/maintenance-gates.d.ts +3 -0
- package/dist/memory/maintenance-gates.js +5 -2
- package/dist/memory/maintenance-jobs.js +19 -2
- package/dist/memory/maintenance-state.d.ts +29 -0
- package/dist/memory/maintenance-state.js +100 -8
- package/dist/memory/metadata.d.ts +9 -0
- package/dist/memory/metadata.js +5 -0
- package/dist/memory/probation.d.ts +21 -0
- package/dist/memory/probation.js +48 -0
- package/dist/memory/promotion.d.ts +26 -1
- package/dist/memory/promotion.js +34 -4
- package/dist/memory/recall.js +38 -19
- package/dist/memory/session-corpus.js +12 -11
- package/dist/memory/session-search.js +25 -6
- package/dist/memory/sidecar-worker.js +2 -0
- package/dist/memory/task-digest.d.ts +3 -2
- package/dist/memory/task-digest.js +22 -8
- package/dist/models/auth-cli.d.ts +25 -0
- package/dist/models/auth-cli.js +344 -0
- package/dist/models/login-ui.d.ts +35 -0
- package/dist/models/login-ui.js +145 -0
- package/dist/models/provider-login.d.ts +41 -0
- package/dist/models/provider-login.js +126 -0
- package/dist/models/utils.d.ts +6 -0
- package/dist/models/utils.js +10 -0
- package/dist/playbooks/memory-and-learning.md +7 -1
- package/dist/playbooks/outbound-media.md +7 -33
- package/dist/playbooks/runtime-orientation.md +2 -0
- package/dist/playbooks/task-closeout.md +22 -35
- package/dist/playbooks/task-delegation.md +13 -35
- package/dist/playbooks/task-driving.md +36 -56
- package/dist/playbooks/task-planning.md +26 -45
- package/dist/runtime/bootstrap.js +48 -14
- package/dist/runtime/delivery.js +8 -2
- package/dist/runtime/dingtalk.d.ts +6 -3
- package/dist/runtime/dingtalk.js +6 -39
- package/dist/runtime/events.js +4 -3
- package/dist/runtime/proxy.d.ts +36 -0
- package/dist/runtime/proxy.js +68 -0
- package/dist/runtime/store.d.ts +8 -2
- package/dist/runtime/store.js +12 -6
- package/dist/runtime/task-commands.d.ts +0 -2
- package/dist/runtime/task-commands.js +99 -112
- package/dist/runtime/task-driver.d.ts +5 -0
- package/dist/runtime/task-driver.js +155 -53
- package/dist/runtime/task-migration.d.ts +9 -0
- package/dist/runtime/task-migration.js +75 -2
- package/dist/security/command-guard.js +51 -17
- package/dist/security/path-guard.js +72 -14
- package/dist/shared/open-browser.d.ts +6 -0
- package/dist/shared/open-browser.js +22 -0
- package/dist/shared/recoverable-error.d.ts +1 -1
- package/dist/shared/recoverable-error.js +1 -1
- package/dist/subagents/tool.js +2 -0
- package/dist/tasks/control.d.ts +38 -67
- package/dist/tasks/control.js +90 -152
- package/dist/tasks/ledger.d.ts +104 -22
- package/dist/tasks/ledger.js +419 -56
- package/dist/tasks/store.d.ts +11 -10
- package/dist/tasks/store.js +58 -27
- package/dist/tasks/transitions.d.ts +8 -36
- package/dist/tasks/transitions.js +29 -54
- package/dist/tasks/verification.d.ts +2 -2
- package/dist/tools/index.d.ts +2 -0
- package/dist/tools/index.js +1 -0
- package/dist/tools/memory-manage.js +8 -1
- package/dist/tools/read.js +19 -5
- package/dist/tools/registry.d.ts +1 -0
- package/dist/tools/registry.js +1 -0
- package/dist/tools/task-manage/lifecycle.d.ts +1 -7
- package/dist/tools/task-manage/lifecycle.js +76 -77
- package/dist/tools/task-manage/schema.d.ts +10 -5
- package/dist/tools/task-manage/schema.js +35 -21
- package/dist/tools/task-manage/shared.d.ts +1 -1
- package/dist/tools/task-manage/shared.js +29 -30
- package/dist/tools/task-manage/types.d.ts +7 -1
- package/dist/tools/task-manage/verification.d.ts +4 -5
- package/dist/tools/task-manage/verification.js +43 -15
- package/dist/tools/task-manage.d.ts +1 -1
- package/dist/tools/task-manage.js +9 -9
- package/dist/tui/app.js +1 -2
- package/dist/tui/commands.d.ts +1 -1
- package/dist/tui/commands.js +1 -1
- package/dist/tui/turn-controller.d.ts +1 -1
- package/dist/usage/ledger.d.ts +1 -1
- package/dist/usage/ledger.js +47 -22
- package/dist/usage/render.d.ts +1 -1
- package/dist/usage/render.js +8 -6
- package/package.json +7 -6
|
@@ -3,11 +3,11 @@ import { join } from "node:path";
|
|
|
3
3
|
import * as log from "../log.js";
|
|
4
4
|
import { PLAYBOOKS_DIR } from "../paths.js";
|
|
5
5
|
import { parseLocalTime } from "../shared/local-time.js";
|
|
6
|
+
import { nextTaskWake } from "../shared/task-schedule.js";
|
|
6
7
|
import { errorMessage } from "../shared/text-utils.js";
|
|
7
8
|
import { taskBudgetViolation } from "../tasks/control.js";
|
|
8
|
-
import { normalizeTaskFields, readActiveTasks } from "../tasks/ledger.js";
|
|
9
|
-
import { claimTaskAttempt, escalateTask, openRecurringTaskCycle, releaseTaskAttemptClaim, updateStoredTask, } from "../tasks/store.js";
|
|
10
|
-
import { TERMINAL_TASK_STATUSES } from "../tasks/transitions.js";
|
|
9
|
+
import { normalizeTaskFields, readActiveTasks, recurringTaskMissedOccurrence, } from "../tasks/ledger.js";
|
|
10
|
+
import { activateWaitingTask, claimTaskAttempt, escalateTask, openRecurringTaskCycle, releaseTaskAttemptClaim, updateStoredTask, } from "../tasks/store.js";
|
|
11
11
|
import { discoverWorkspaceChannelIds } from "./channel-index.js";
|
|
12
12
|
import { isChannelId } from "./channel-paths.js";
|
|
13
13
|
/** Short debounce so a burst of nudges collapses into a single rescan. */
|
|
@@ -16,7 +16,6 @@ const NUDGE_DEBOUNCE_MS = 50;
|
|
|
16
16
|
const MIN_SLEEP_MS = 250;
|
|
17
17
|
/** Consecutive no-progress wakes before the governor pauses a task (spec 029, D5). */
|
|
18
18
|
const FUTILE_WAKE_LIMIT = 3;
|
|
19
|
-
const TERMINAL_STATUSES = TERMINAL_TASK_STATUSES;
|
|
20
19
|
export async function discoverTaskChannels(workspaceDir, knownChannelIds = []) {
|
|
21
20
|
const channels = new Set();
|
|
22
21
|
for (const channelId of knownChannelIds) {
|
|
@@ -43,6 +42,15 @@ function attemptKey(channelId, taskId) {
|
|
|
43
42
|
* and let a wake that changed real files count as stalled. The task's own effect tally stands in
|
|
44
43
|
* for the work itself instead — per task, not per channel, so a neighbour's activity (including
|
|
45
44
|
* the user chatting) neither certifies progress here nor hides a task that is spinning.
|
|
45
|
+
*
|
|
46
|
+
* `entry.plan` is absent for the same reason (spec 037, D5): checking off a Plan step is a
|
|
47
|
+
* model-reported claim, not evidence of an effect. If plan state fed the fingerprint, ticking a
|
|
48
|
+
* checkbox would reset the futile counter and buy the short retry tier — a governor bypass this
|
|
49
|
+
* driver must not offer. The Plan is a capsule/agenda display concern only.
|
|
50
|
+
*
|
|
51
|
+
* nextAction and blockedReason are also model-written explanations, not evidence of an effect.
|
|
52
|
+
* Including either lets a progress/set call reset the futile counter without changing the task's
|
|
53
|
+
* externally observable work.
|
|
46
54
|
*/
|
|
47
55
|
function taskFingerprint(entry, effects) {
|
|
48
56
|
const control = entry.frontmatter.control;
|
|
@@ -52,9 +60,10 @@ function taskFingerprint(entry, effects) {
|
|
|
52
60
|
entry.frontmatter.wake ?? "",
|
|
53
61
|
entry.frontmatter.schedule ?? "",
|
|
54
62
|
entry.frontmatter.recurrence ?? "",
|
|
55
|
-
control?.nextAction ?? "",
|
|
56
|
-
control?.blockedReason ?? "",
|
|
57
63
|
control?.verification.status ?? "",
|
|
64
|
+
control?.waitingFor ?? "",
|
|
65
|
+
entry.frontmatter.enabled === false ? "disabled" : "enabled",
|
|
66
|
+
control?.stop?.reason ?? "",
|
|
58
67
|
control?.cycleId ?? "",
|
|
59
68
|
`effects:${effects}`,
|
|
60
69
|
].join("\0");
|
|
@@ -100,22 +109,23 @@ function isEligible(attempt, fingerprint, effects, nowMs, settings) {
|
|
|
100
109
|
* collapsing them would silently drop the later one.
|
|
101
110
|
*/
|
|
102
111
|
function taskDispatchId(channelId, entry, nowMs) {
|
|
103
|
-
const occurrence = entry.frontmatter.wake ?? `t${nowMs}`;
|
|
112
|
+
const occurrence = entry.frontmatter.control?.cycleId ?? entry.frontmatter.wake ?? `t${nowMs}`;
|
|
104
113
|
return `task:${channelId}:${entry.id}:${occurrence}`;
|
|
105
114
|
}
|
|
106
115
|
export function createTaskDriverEvent(channelId, entry, nowMs, attemptGeneration) {
|
|
107
|
-
const
|
|
108
|
-
const
|
|
109
|
-
?
|
|
110
|
-
|
|
111
|
-
: ` This is a checker-only turn: read ${join(PLAYBOOKS_DIR, "task-closeout.md")} and do not continue implementation.`
|
|
116
|
+
const repairOnly = !entry.frontmatter.readable || entry.frontmatter.controlReadable === false;
|
|
117
|
+
const repair = repairOnly
|
|
118
|
+
? ` Task metadata is not readable; repair only the frontmatter/control in tasks/${entry.id}.md, then stop. ` +
|
|
119
|
+
`Do not execute the task goal or any external action. Read ${join(PLAYBOOKS_DIR, "task-driving.md")} for the repair path.`
|
|
112
120
|
: "";
|
|
113
|
-
const repair = entry.frontmatter.readable
|
|
114
|
-
? ""
|
|
115
|
-
: ` Its frontmatter is unreadable: also read ${join(PLAYBOOKS_DIR, "task-driving.md")}.`;
|
|
116
121
|
const control = entry.frontmatter.control;
|
|
117
122
|
const capsule = [
|
|
118
123
|
`Task capsule: title=${entry.title}; status=${entry.frontmatter.status ?? "active"};`,
|
|
124
|
+
// Surfacing the Plan's progress and current step here is the point of spec 037, D2/D4: the
|
|
125
|
+
// model no longer has to re-derive "what step am I on" from latestNote/nextAction each wake.
|
|
126
|
+
entry.plan
|
|
127
|
+
? `plan=${entry.plan.done}/${entry.plan.total} done, current=${entry.plan.current?.id ?? "none"};`
|
|
128
|
+
: "",
|
|
119
129
|
entry.latestNote ? `latest=${entry.latestNote};` : "",
|
|
120
130
|
control?.nextAction ? `next=${control.nextAction};` : "",
|
|
121
131
|
control ? `budget=${control.usage.attempts}/${control.budget.maxAttempts} attempts;` : "",
|
|
@@ -129,8 +139,10 @@ export function createTaskDriverEvent(channelId, entry, nowMs, attemptGeneration
|
|
|
129
139
|
userName: "TASK_DRIVER",
|
|
130
140
|
text: `[TASK_DRIVER:${entry.id}] Resume task ${entry.id}. ${capsule}${repair} ` +
|
|
131
141
|
`Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-driving.md")} before acting. ` +
|
|
132
|
-
|
|
133
|
-
|
|
142
|
+
(repairOnly
|
|
143
|
+
? "After the metadata is repaired, leave task work for a later wake. "
|
|
144
|
+
: "Advance the next concrete step under the task's current goal, control, acceptance, and verification state. ") +
|
|
145
|
+
`If complete or waiting, use the matching task_manage lifecycle/checkpoint action from the playbook. ` +
|
|
134
146
|
"For a recurring occurrence intentionally not run because it is duplicate or already satisfied, call task_manage skip with the reason, then respond with exactly [SILENT]. " +
|
|
135
147
|
"If no task state or tool action is needed and this wake produces no user-visible result, respond with exactly [SILENT].",
|
|
136
148
|
ts: String(nowMs),
|
|
@@ -140,26 +152,45 @@ export function createTaskDriverEvent(channelId, entry, nowMs, attemptGeneration
|
|
|
140
152
|
taskAttemptGeneration: attemptGeneration,
|
|
141
153
|
};
|
|
142
154
|
}
|
|
143
|
-
/**
|
|
155
|
+
/** Durable checker wake created by request-verification; it is a normal main-agent turn. */
|
|
156
|
+
export function createTaskVerificationEvent(channelId, entry, nowMs) {
|
|
157
|
+
const control = entry.frontmatter.control;
|
|
158
|
+
return {
|
|
159
|
+
type: channelId.startsWith("group_") ? "group" : "dm",
|
|
160
|
+
channelId,
|
|
161
|
+
user: "TASK_VERIFIER",
|
|
162
|
+
userName: "TASK_VERIFIER",
|
|
163
|
+
text: `[TASK_VERIFY:${entry.id}] Verify task ${entry.id} independently. ` +
|
|
164
|
+
`Read tasks/${entry.id}.md and the workspace verification instructions, then run a read-only ` +
|
|
165
|
+
`subagent with purpose=verify. Import its attestation with task_manage verify using the returned run id. ` +
|
|
166
|
+
`Do not modify the workspace or task contract; if verification fails, record the failure and leave the task recoverable.`,
|
|
167
|
+
ts: String(nowMs),
|
|
168
|
+
conversationId: "",
|
|
169
|
+
conversationType: channelId.startsWith("group_") ? "2" : "1",
|
|
170
|
+
dispatchId: `task:${channelId}:${entry.id}:verification:${control?.cycleId ?? `t${nowMs}`}`,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/** sleeping + a schedule cadence + a valid wake that is due → time to open the next cycle. */
|
|
144
174
|
function isCycleStartReady(entry, nowMs) {
|
|
145
|
-
return (entry.frontmatter.status === "
|
|
175
|
+
return (entry.frontmatter.status === "sleeping" &&
|
|
176
|
+
entry.frontmatter.enabled !== false &&
|
|
146
177
|
Boolean(entry.frontmatter.schedule) &&
|
|
147
178
|
entry.wakeMs !== undefined &&
|
|
148
179
|
entry.wakeMs <= nowMs);
|
|
149
180
|
}
|
|
150
|
-
/**
|
|
181
|
+
/** sleeping + schedule but no parseable wake → self-heal target (recompute wake, zero token). */
|
|
151
182
|
function needsWakeHeal(entry) {
|
|
152
|
-
return entry.frontmatter.status === "
|
|
183
|
+
return entry.frontmatter.status === "sleeping" && Boolean(entry.frontmatter.schedule) && entry.wakeMs === undefined;
|
|
153
184
|
}
|
|
154
|
-
function
|
|
185
|
+
export function taskGovernorReceipt(channelId, entry, reason, nowMs) {
|
|
155
186
|
return {
|
|
156
187
|
type: channelId.startsWith("group_") ? "group" : "dm",
|
|
157
188
|
channelId,
|
|
158
189
|
user: "TASK_DRIVER",
|
|
159
190
|
userName: "TASK_DRIVER",
|
|
160
|
-
text:
|
|
161
|
-
|
|
162
|
-
|
|
191
|
+
text: `任务 ${entry.id}(${entry.title})已停止自动执行:${reason}\n` +
|
|
192
|
+
`当前阶段:${entry.frontmatter.status ?? "active"}${entry.frontmatter.control?.cycleId ? `;周期:${entry.frontmatter.control.cycleId}` : ""}\n` +
|
|
193
|
+
`继续:/tasks resume ${entry.id}\n立即执行:/tasks run ${entry.id}\n不再需要:让 Agent cancel 该任务。`,
|
|
163
194
|
ts: String(nowMs),
|
|
164
195
|
conversationId: "",
|
|
165
196
|
conversationType: channelId.startsWith("group_") ? "2" : "1",
|
|
@@ -270,9 +301,13 @@ export class TaskDriver {
|
|
|
270
301
|
}
|
|
271
302
|
collectHorizons(entries, nowMs) {
|
|
272
303
|
for (const entry of entries) {
|
|
273
|
-
|
|
304
|
+
if (entry.frontmatter.enabled !== false)
|
|
305
|
+
this.noteHorizon(entry.wakeMs, nowMs);
|
|
274
306
|
const control = entry.frontmatter.control;
|
|
275
|
-
if (
|
|
307
|
+
if (entry.frontmatter.enabled !== false &&
|
|
308
|
+
control?.deadline &&
|
|
309
|
+
(entry.frontmatter.status === "active" || entry.frontmatter.status === "waiting") &&
|
|
310
|
+
!entry.frontmatter.archiveOutcome) {
|
|
276
311
|
this.noteHorizon(parseLocalTime(control.deadline), nowMs);
|
|
277
312
|
}
|
|
278
313
|
}
|
|
@@ -299,21 +334,58 @@ export class TaskDriver {
|
|
|
299
334
|
if (!channelId)
|
|
300
335
|
continue;
|
|
301
336
|
const channelDir = join(this.options.workspaceDir, channelId);
|
|
302
|
-
|
|
337
|
+
let entries = await readActiveTasks(join(channelDir, "tasks"), nowMs);
|
|
303
338
|
for (const entry of entries)
|
|
304
339
|
seen.add(attemptKey(channelId, entry.id));
|
|
305
340
|
this.collectHorizons(entries, nowMs);
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
341
|
+
for (const entry of entries) {
|
|
342
|
+
if (entry.frontmatter.enabled !== false &&
|
|
343
|
+
recurringTaskMissedOccurrence({
|
|
344
|
+
status: entry.frontmatter.status ?? "active",
|
|
345
|
+
schedule: entry.frontmatter.schedule,
|
|
346
|
+
control: entry.frontmatter.control,
|
|
347
|
+
}, now)) {
|
|
348
|
+
log.logWarning(`[${channelId}] Task ${entry.id} has a missed recurring occurrence; keeping the current cycle open`);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
// Zero-token self-heal: a sleeping recurring task with a missing/unparseable wake (usually a
|
|
309
352
|
// hand edit that bypassed the runtime) gets its next occurrence recomputed via the same
|
|
310
353
|
// `normalizeTaskFields` write-path invariant, rather than fail-open into an accidental cycle.
|
|
311
354
|
for (const entry of entries) {
|
|
355
|
+
if (entry.frontmatter.status !== "sleeping" || entry.frontmatter.enabled === false)
|
|
356
|
+
continue;
|
|
357
|
+
if (!entry.frontmatter.schedule) {
|
|
358
|
+
const reason = "sleeping recurring task has no schedule";
|
|
359
|
+
if (await escalateTask(channelDir, entry.id, reason)) {
|
|
360
|
+
const receipt = taskGovernorReceipt(channelId, entry, reason, nowMs);
|
|
361
|
+
try {
|
|
362
|
+
await this.options.notify?.(receipt);
|
|
363
|
+
}
|
|
364
|
+
catch (error) {
|
|
365
|
+
log.logWarning(`[${channelId}] Task governor receipt failed`, errorMessage(error));
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
const scheduleWake = nextTaskWake(entry.frontmatter.schedule, now);
|
|
371
|
+
if (!scheduleWake) {
|
|
372
|
+
const reason = `sleeping task has invalid schedule: ${entry.frontmatter.schedule}`;
|
|
373
|
+
if (await escalateTask(channelDir, entry.id, reason)) {
|
|
374
|
+
const receipt = taskGovernorReceipt(channelId, entry, reason, nowMs);
|
|
375
|
+
try {
|
|
376
|
+
await this.options.notify?.(receipt);
|
|
377
|
+
}
|
|
378
|
+
catch (error) {
|
|
379
|
+
log.logWarning(`[${channelId}] Task governor receipt failed`, errorMessage(error));
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
312
384
|
if (!needsWakeHeal(entry))
|
|
313
385
|
continue;
|
|
314
386
|
let healedWake;
|
|
315
387
|
await updateStoredTask(channelDir, entry.id, (task) => {
|
|
316
|
-
healedWake = normalizeTaskFields(task.fields).wake;
|
|
388
|
+
healedWake = normalizeTaskFields(task.fields, now).wake;
|
|
317
389
|
task.fields.wake = healedWake;
|
|
318
390
|
});
|
|
319
391
|
if (!healedWake) {
|
|
@@ -327,24 +399,46 @@ export class TaskDriver {
|
|
|
327
399
|
for (const candidate of entries) {
|
|
328
400
|
const status = candidate.frontmatter.status;
|
|
329
401
|
const control = candidate.frontmatter.control;
|
|
330
|
-
if (!control ||
|
|
402
|
+
if (!control || candidate.frontmatter.archiveOutcome || candidate.frontmatter.enabled === false)
|
|
331
403
|
continue;
|
|
332
|
-
const escalationReason = taskBudgetViolation(control, nowMs);
|
|
404
|
+
const escalationReason = taskBudgetViolation(control, nowMs, status);
|
|
333
405
|
if (!escalationReason)
|
|
334
406
|
continue;
|
|
335
407
|
governanceHandled = true;
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
408
|
+
if (await escalateTask(channelDir, candidate.id, escalationReason)) {
|
|
409
|
+
const receipt = taskGovernorReceipt(channelId, candidate, escalationReason, nowMs);
|
|
410
|
+
try {
|
|
411
|
+
await this.options.notify?.(receipt);
|
|
412
|
+
}
|
|
413
|
+
catch (error) {
|
|
414
|
+
log.logWarning(`[${channelId}] Task governor receipt failed`, errorMessage(error));
|
|
415
|
+
}
|
|
416
|
+
log.logWarning(`[${channelId}] Task driver disabled ${candidate.id} (governor)`, escalationReason);
|
|
343
417
|
}
|
|
344
418
|
break;
|
|
345
419
|
}
|
|
346
420
|
if (governanceHandled)
|
|
347
421
|
continue;
|
|
422
|
+
// Deterministic maintenance above must not wait for an idle channel. Only model dispatch
|
|
423
|
+
// and the transitions immediately preceding it are gated by the channel's busy state.
|
|
424
|
+
if (dispatched >= settings.maxDispatchesPerTick || this.options.isChannelActive(channelId))
|
|
425
|
+
continue;
|
|
426
|
+
// Timed waits become active atomically before dispatch. Sleeping due tasks use the same
|
|
427
|
+
// runtime cycle-open path as the first occurrence.
|
|
428
|
+
let hadDueWaiting = false;
|
|
429
|
+
for (const candidate of entries) {
|
|
430
|
+
if (candidate.frontmatter.status !== "waiting" || candidate.frontmatter.enabled === false)
|
|
431
|
+
continue;
|
|
432
|
+
if (candidate.wakeMs !== undefined && candidate.wakeMs <= nowMs) {
|
|
433
|
+
hadDueWaiting = true;
|
|
434
|
+
await activateWaitingTask(channelDir, candidate.id);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
// A failed activation means another writer won the transition (or disabled the
|
|
438
|
+
// task). Re-read before choosing a candidate so a stale waiting capsule can never
|
|
439
|
+
// be dispatched as if its atomic active transition had succeeded.
|
|
440
|
+
if (hadDueWaiting)
|
|
441
|
+
entries = await readActiveTasks(join(channelDir, "tasks"), nowMs);
|
|
348
442
|
// Actionable tasks and cycle-start-ready recurring tasks share one per-channel slot
|
|
349
443
|
// and the same round-robin fairness. A cycle-start-ready task is folded into its next
|
|
350
444
|
// cycle deterministically by the runtime (D2) and then dispatched as an ordinary wake.
|
|
@@ -361,8 +455,8 @@ export class TaskDriver {
|
|
|
361
455
|
continue;
|
|
362
456
|
// A cycle-start-ready recurring task is reopened in-process before dispatch: fold the
|
|
363
457
|
// previous cycle, reset per-cycle control, mark it active. If the write fails we skip
|
|
364
|
-
// this tick rather than dispatch a stale
|
|
365
|
-
if (
|
|
458
|
+
// this tick rather than dispatch a stale sleeping capsule.
|
|
459
|
+
if (isCycleStartReady(entry, nowMs)) {
|
|
366
460
|
let opened;
|
|
367
461
|
try {
|
|
368
462
|
opened = await openRecurringTaskCycle(channelDir, entry.id, now);
|
|
@@ -376,7 +470,10 @@ export class TaskDriver {
|
|
|
376
470
|
log.logWarning(`[${channelId}] Task driver could not open next cycle for ${entry.id}`);
|
|
377
471
|
continue;
|
|
378
472
|
}
|
|
379
|
-
|
|
473
|
+
// Re-read after the atomic open so the capsule contains the new Current Cycle/Plan,
|
|
474
|
+
// rather than the sleeping occurrence's just-closed note.
|
|
475
|
+
const refreshed = (await readActiveTasks(join(channelDir, "tasks"), nowMs)).find((candidate) => candidate.id === entry?.id);
|
|
476
|
+
entry = refreshed ?? {
|
|
380
477
|
...entry,
|
|
381
478
|
frontmatter: {
|
|
382
479
|
...entry.frontmatter,
|
|
@@ -390,6 +487,7 @@ export class TaskDriver {
|
|
|
390
487
|
log.logInfo(`[${channelId}] Task driver opened cycle ${opened.cycleId} for ${entry.id}`);
|
|
391
488
|
}
|
|
392
489
|
const key = attemptKey(channelId, entry.id);
|
|
490
|
+
const repairOnly = !entry.frontmatter.readable || entry.frontmatter.controlReadable === false;
|
|
393
491
|
const effects = this.options.getEffectCount?.(channelId, entry.id) ?? 0;
|
|
394
492
|
const fingerprint = taskFingerprint(entry, effects);
|
|
395
493
|
const previous = this.attempts.get(key);
|
|
@@ -399,24 +497,28 @@ export class TaskDriver {
|
|
|
399
497
|
// visible progress. Count consecutive such wakes (a changed fingerprint — including
|
|
400
498
|
// a progress note or a failure — resets the count); after the limit the governor
|
|
401
499
|
// pauses the task and notifies the user, so no silent loop burns tokens forever.
|
|
402
|
-
const futileCount = previous?.accepted && previous.fingerprint === fingerprint ? previous.futileCount + 1 : 0;
|
|
500
|
+
const futileCount = !repairOnly && previous?.accepted && previous.fingerprint === fingerprint ? previous.futileCount + 1 : 0;
|
|
403
501
|
if (futileCount >= FUTILE_WAKE_LIMIT) {
|
|
404
502
|
const reason = `task made no visible progress in ${FUTILE_WAKE_LIMIT} consecutive wakes`;
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
503
|
+
if (await escalateTask(channelDir, entry.id, reason)) {
|
|
504
|
+
const receipt = taskGovernorReceipt(channelId, entry, reason, nowMs);
|
|
505
|
+
try {
|
|
506
|
+
await this.options.notify?.(receipt);
|
|
507
|
+
}
|
|
508
|
+
catch (error) {
|
|
509
|
+
log.logWarning(`[${channelId}] Task governor receipt failed`, errorMessage(error));
|
|
510
|
+
}
|
|
409
511
|
this.attempts.delete(key);
|
|
410
512
|
this.lastDispatchedTaskId.set(channelId, entry.id);
|
|
411
|
-
|
|
412
|
-
lastDispatchOffset = offset;
|
|
413
|
-
log.logWarning(`[${channelId}] Task driver paused ${entry.id} (governor)`, reason);
|
|
513
|
+
log.logWarning(`[${channelId}] Task driver disabled ${entry.id} (governor)`, reason);
|
|
414
514
|
}
|
|
415
515
|
continue;
|
|
416
516
|
}
|
|
417
517
|
// Claiming an attempt only touches usage bookkeeping, which the fingerprint
|
|
418
518
|
// deliberately excludes, so there is nothing to recompute here.
|
|
419
|
-
const claim =
|
|
519
|
+
const claim = repairOnly ? undefined : await claimTaskAttempt(channelDir, entry.id, now);
|
|
520
|
+
if (claim)
|
|
521
|
+
entry.frontmatter.control = claim.control;
|
|
420
522
|
const event = createTaskDriverEvent(channelId, entry, nowMs, claim?.generation);
|
|
421
523
|
const accepted = await this.options.dispatch(event);
|
|
422
524
|
this.observeDispatch(event, accepted);
|
|
@@ -9,3 +9,12 @@
|
|
|
9
9
|
* orphaned event removed. Failures are logged and skipped — this must never block startup.
|
|
10
10
|
*/
|
|
11
11
|
export declare function migrateLegacyTaskScheduleEvents(workspaceDir: string): Promise<void>;
|
|
12
|
+
/**
|
|
13
|
+
* Deterministically upgrade active-directory v1 task files to the v2 state vocabulary.
|
|
14
|
+
*
|
|
15
|
+
* The reader already maps old values while a process is running; this pass makes that mapping
|
|
16
|
+
* durable at startup. It only rewrites task metadata/history notes and archives stale terminal
|
|
17
|
+
* files. It never dispatches a task or performs an external action, and every file is protected
|
|
18
|
+
* by the same per-task mutation lock as normal lifecycle writes.
|
|
19
|
+
*/
|
|
20
|
+
export declare function migrateLegacyTaskState(workspaceDir: string): Promise<void>;
|
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
import { readdir, readFile, unlink } from "node:fs/promises";
|
|
1
|
+
import { mkdir, readdir, readFile, rename, stat, unlink } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import * as log from "../log.js";
|
|
4
|
+
import { formatLocalTime } from "../shared/local-time.js";
|
|
4
5
|
import { parseTaskEventName, taskEventPrefix } from "../shared/task-events.js";
|
|
5
6
|
import { errorMessage } from "../shared/text-utils.js";
|
|
6
|
-
import {
|
|
7
|
+
import { createDefaultTaskControl } from "../tasks/control.js";
|
|
8
|
+
import { appendCurrentCycleNote, parseTaskFrontmatter } from "../tasks/ledger.js";
|
|
9
|
+
import { withTaskMutation } from "../tasks/mutation-lock.js";
|
|
10
|
+
import { readStoredTask, updateStoredTask, writeStoredTask } from "../tasks/store.js";
|
|
7
11
|
import { parseScheduledEventContent } from "./events.js";
|
|
8
12
|
import { discoverTaskChannels } from "./task-driver.js";
|
|
9
13
|
/**
|
|
@@ -68,3 +72,72 @@ export async function migrateLegacyTaskScheduleEvents(workspaceDir) {
|
|
|
68
72
|
}
|
|
69
73
|
}
|
|
70
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* Deterministically upgrade active-directory v1 task files to the v2 state vocabulary.
|
|
77
|
+
*
|
|
78
|
+
* The reader already maps old values while a process is running; this pass makes that mapping
|
|
79
|
+
* durable at startup. It only rewrites task metadata/history notes and archives stale terminal
|
|
80
|
+
* files. It never dispatches a task or performs an external action, and every file is protected
|
|
81
|
+
* by the same per-task mutation lock as normal lifecycle writes.
|
|
82
|
+
*/
|
|
83
|
+
export async function migrateLegacyTaskState(workspaceDir) {
|
|
84
|
+
const channels = await discoverTaskChannels(workspaceDir);
|
|
85
|
+
for (const channelId of channels) {
|
|
86
|
+
const channelDir = join(workspaceDir, channelId);
|
|
87
|
+
const dir = join(channelDir, "tasks");
|
|
88
|
+
let filenames;
|
|
89
|
+
try {
|
|
90
|
+
filenames = (await readdir(dir)).filter((name) => name.endsWith(".md")).sort();
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
for (const filename of filenames) {
|
|
96
|
+
const id = filename.slice(0, -".md".length);
|
|
97
|
+
try {
|
|
98
|
+
await withTaskMutation(channelDir, id, async () => {
|
|
99
|
+
const activePath = join(dir, filename);
|
|
100
|
+
const raw = await readFile(activePath, "utf-8");
|
|
101
|
+
const frontmatter = parseTaskFrontmatter(raw);
|
|
102
|
+
if (!frontmatter.readable)
|
|
103
|
+
return;
|
|
104
|
+
if (frontmatter.controlReadable === false)
|
|
105
|
+
return;
|
|
106
|
+
const document = await readStoredTask(channelDir, id, false, true);
|
|
107
|
+
if (!document)
|
|
108
|
+
return;
|
|
109
|
+
// Very old hand-written tasks may have no control block at all. Give them the
|
|
110
|
+
// v2 default before any active driver wake can spend work without governance.
|
|
111
|
+
document.fields.control ??= createDefaultTaskControl();
|
|
112
|
+
const legacyStatus = frontmatter.rawStatus;
|
|
113
|
+
if ((legacyStatus === "waiting" || legacyStatus === "awaiting-user" || legacyStatus === "blocked") &&
|
|
114
|
+
!document.fields.wake &&
|
|
115
|
+
document.fields.control &&
|
|
116
|
+
!document.fields.control.waitingFor) {
|
|
117
|
+
document.fields.control.waitingFor = "external-signal";
|
|
118
|
+
document.fields.control.blockedReason ??=
|
|
119
|
+
"Legacy waiting task requires review after the autonomy state upgrade.";
|
|
120
|
+
document.body = appendCurrentCycleNote(document.body, "Migration note: this task remains waiting after the autonomy state upgrade; review its external condition before resuming.");
|
|
121
|
+
}
|
|
122
|
+
if (document.fields.outcome) {
|
|
123
|
+
const fileStat = await stat(activePath);
|
|
124
|
+
document.fields.closedAt ??= formatLocalTime(new Date(fileStat.mtimeMs));
|
|
125
|
+
await writeStoredTask(document);
|
|
126
|
+
const archiveDir = join(dir, "archive");
|
|
127
|
+
await mkdir(archiveDir, { recursive: true });
|
|
128
|
+
await rename(activePath, join(archiveDir, filename));
|
|
129
|
+
log.logInfo(`Migrated legacy terminal task ${id} to archive`, document.fields.outcome);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
await writeStoredTask(document);
|
|
133
|
+
if (legacyStatus || frontmatter.rawControl !== undefined || frontmatter.enabled === false) {
|
|
134
|
+
log.logInfo(`Migrated task ${id} to TaskControl v2`, channelId);
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
log.logWarning(`Could not migrate task ${channelId}/${id}`, `${errorMessage(error)}. Use /tasks doctor to repair it.`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
@@ -309,16 +309,32 @@ function extractFindExecCommands(parsed) {
|
|
|
309
309
|
}
|
|
310
310
|
return inner;
|
|
311
311
|
}
|
|
312
|
+
/**
|
|
313
|
+
* How many suffix positions of a wrapper's arguments are treated as candidate command starts.
|
|
314
|
+
*
|
|
315
|
+
* The scan below is a superset heuristic, not a soundness requirement: the wrapper's own direct
|
|
316
|
+
* rule, `sh -c` bodies and `find -exec` are all matched separately and are unaffected by this
|
|
317
|
+
* bound. Without a bound the scan is quadratic in the argument count — every suffix is sliced and
|
|
318
|
+
* re-joined into a normalized command line — and it recurses, so a wrapper whose arguments contain
|
|
319
|
+
* further wrappers multiplied that cost up to `MAX_GUARD_DEPTH` times. Measured: ~6ms at 200
|
|
320
|
+
* arguments, ~36ms at 800, which a long file list reaches without trying.
|
|
321
|
+
*
|
|
322
|
+
* A real inner command starts within the first few tokens, after the wrapper's own flags; no
|
|
323
|
+
* wrapper in `WRAPPER_COMMANDS` takes anything close to 32 of them. Positions beyond this are
|
|
324
|
+
* operands of the inner command, which has already been inspected from its own start position.
|
|
325
|
+
*/
|
|
326
|
+
const MAX_WRAPPER_CANDIDATES = 32;
|
|
312
327
|
// For a generic wrapper, the inner command can sit anywhere after the wrapper's
|
|
313
328
|
// own options/operands (whose grammar varies per tool). Rather than parse each
|
|
314
|
-
// wrapper's flags precisely, evaluate
|
|
315
|
-
// command
|
|
329
|
+
// wrapper's flags precisely, evaluate the leading suffix positions as candidate
|
|
330
|
+
// command starts — this only ever adds detections, never relaxes them.
|
|
316
331
|
function extractWrapperCandidates(parsed) {
|
|
317
332
|
if (!WRAPPER_COMMANDS.has(parsed.command)) {
|
|
318
333
|
return [];
|
|
319
334
|
}
|
|
320
335
|
const candidates = [];
|
|
321
|
-
|
|
336
|
+
const limit = Math.min(parsed.args.length, MAX_WRAPPER_CANDIDATES);
|
|
337
|
+
for (let i = 0; i < limit; i++) {
|
|
322
338
|
candidates.push(parsed.args.slice(i));
|
|
323
339
|
}
|
|
324
340
|
return candidates;
|
|
@@ -351,6 +367,30 @@ function hasDangerousDeletionTarget(args) {
|
|
|
351
367
|
function joinedArgs(parsed) {
|
|
352
368
|
return parsed.args.join(" ");
|
|
353
369
|
}
|
|
370
|
+
/**
|
|
371
|
+
* `matchRule` runs once per atom per recursion level, so compiling the configured patterns inside
|
|
372
|
+
* it recompiled the same regexes many times for a single guarded command. The list comes from
|
|
373
|
+
* `security.json` and is rebuilt only when that file is reloaded, so caching on its identity is
|
|
374
|
+
* enough. Invalid patterns are dropped here, once, instead of throwing on every evaluation.
|
|
375
|
+
*/
|
|
376
|
+
const denyPatternCache = new WeakMap();
|
|
377
|
+
function compileDenyPatterns(patterns) {
|
|
378
|
+
const cached = denyPatternCache.get(patterns);
|
|
379
|
+
if (cached) {
|
|
380
|
+
return cached;
|
|
381
|
+
}
|
|
382
|
+
const compiled = [];
|
|
383
|
+
for (const pattern of patterns) {
|
|
384
|
+
try {
|
|
385
|
+
compiled.push({ pattern, regex: new RegExp(pattern, "i") });
|
|
386
|
+
}
|
|
387
|
+
catch {
|
|
388
|
+
// Ignore invalid user patterns.
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
denyPatternCache.set(patterns, compiled);
|
|
392
|
+
return compiled;
|
|
393
|
+
}
|
|
354
394
|
function matchRule(parsed, config) {
|
|
355
395
|
const argsText = joinedArgs(parsed);
|
|
356
396
|
const normalized = parsed.normalized;
|
|
@@ -470,20 +510,14 @@ function matchRule(parsed, config) {
|
|
|
470
510
|
};
|
|
471
511
|
}
|
|
472
512
|
}
|
|
473
|
-
for (const pattern of config.additionalDenyPatterns) {
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
matchedText: normalized,
|
|
482
|
-
};
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
catch {
|
|
486
|
-
// Ignore invalid user patterns.
|
|
513
|
+
for (const { pattern, regex } of compileDenyPatterns(config.additionalDenyPatterns)) {
|
|
514
|
+
if (regex.test(normalized)) {
|
|
515
|
+
return {
|
|
516
|
+
category: "configured-command-deny",
|
|
517
|
+
rule: pattern,
|
|
518
|
+
reason: "Command matched a configured deny pattern",
|
|
519
|
+
matchedText: normalized,
|
|
520
|
+
};
|
|
487
521
|
}
|
|
488
522
|
}
|
|
489
523
|
return null;
|