@oyasmi/pipiclaw 0.9.3-beta.5 → 0.9.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.en.md +1 -1
- package/README.md +1 -1
- package/dist/agent/channel-runner.d.ts +4 -8
- package/dist/agent/channel-runner.js +14 -34
- package/dist/agent/job-manager.d.ts +12 -0
- package/dist/agent/job-manager.js +42 -1
- package/dist/agent/prompt/sections.js +2 -2
- package/dist/agent/runner-factory.d.ts +2 -2
- package/dist/agent/types.d.ts +11 -7
- package/dist/channel/channel-index.d.ts +9 -2
- package/dist/channel/channel-index.js +25 -6
- package/dist/channel/project-scope-store.d.ts +20 -0
- package/dist/channel/project-scope-store.js +22 -7
- package/dist/commands/catalog.js +6 -12
- package/dist/events/event-commands.js +2 -2
- package/dist/events/events.d.ts +51 -30
- package/dist/events/events.js +70 -98
- package/dist/memory/journal.d.ts +2 -3
- package/dist/memory/journal.js +2 -3
- package/dist/memory/maintenance-tuning.d.ts +0 -1
- package/dist/memory/maintenance-tuning.js +0 -1
- package/dist/memory/scheduler.js +8 -16
- package/dist/memory/search.js +2 -3
- package/dist/memory/session-search.js +3 -9
- package/dist/memory/store.d.ts +1 -1
- package/dist/memory/store.js +9 -1
- package/dist/memory/task-digest.js +10 -11
- package/dist/memory/tombstones.js +2 -4
- package/dist/models/provider-login.d.ts +1 -1
- package/dist/models/provider-login.js +1 -1
- package/dist/playbooks/agent-delegation.md +6 -6
- package/dist/playbooks/background-jobs.md +1 -1
- package/dist/playbooks/event-scheduling.md +22 -13
- package/dist/playbooks/memory-and-learning.md +2 -2
- package/dist/playbooks/outbound-media.md +1 -1
- package/dist/playbooks/runtime-orientation.md +3 -3
- package/dist/playbooks/task-lead.md +82 -0
- package/dist/runtime/bootstrap.js +94 -187
- package/dist/runtime/durable-dispatch.js +30 -3
- package/dist/runtime/report-commands.d.ts +30 -0
- package/dist/runtime/report-commands.js +71 -0
- package/dist/runtime/subagent-commands.js +1 -1
- package/dist/runtime/task-commands.d.ts +0 -8
- package/dist/runtime/task-commands.js +48 -85
- package/dist/runtime/task-driver.d.ts +15 -10
- package/dist/runtime/task-driver.js +36 -41
- package/dist/runtime/task-migration.d.ts +23 -29
- package/dist/runtime/task-migration.js +364 -183
- package/dist/runtime/task-spawn.d.ts +24 -0
- package/dist/runtime/task-spawn.js +49 -0
- package/dist/runtime/task-wake.d.ts +33 -46
- package/dist/runtime/task-wake.js +15 -90
- package/dist/security/network.js +44 -9
- package/dist/settings.d.ts +1 -8
- package/dist/settings.js +1 -8
- package/dist/subagents/discovery.js +3 -15
- package/dist/subagents/external/run.d.ts +3 -1
- package/dist/subagents/external/run.js +2 -20
- package/dist/subagents/external/settlement.d.ts +4 -16
- package/dist/subagents/external/settlement.js +16 -67
- package/dist/subagents/runs.d.ts +15 -29
- package/dist/subagents/runs.js +70 -158
- package/dist/subagents/tool.d.ts +20 -4
- package/dist/subagents/tool.js +63 -87
- package/dist/subagents/verification-outcome.d.ts +13 -19
- package/dist/subagents/verification-outcome.js +8 -22
- package/dist/subagents/workspace-summary.d.ts +8 -0
- package/dist/subagents/workspace-summary.js +29 -0
- package/dist/tasks/board.d.ts +43 -0
- package/dist/tasks/board.js +134 -0
- package/dist/tasks/brief.d.ts +10 -5
- package/dist/tasks/brief.js +78 -26
- package/dist/tasks/budget.d.ts +13 -14
- package/dist/tasks/budget.js +21 -40
- package/dist/tasks/contract-input.d.ts +19 -0
- package/dist/tasks/contract-input.js +55 -0
- package/dist/tasks/create.d.ts +17 -0
- package/dist/tasks/create.js +36 -0
- package/dist/tasks/frontmatter.d.ts +20 -27
- package/dist/tasks/frontmatter.js +18 -31
- package/dist/tasks/ledger.d.ts +61 -117
- package/dist/tasks/ledger.js +78 -223
- package/dist/tasks/log.d.ts +62 -35
- package/dist/tasks/log.js +51 -29
- package/dist/tasks/session-path.d.ts +3 -3
- package/dist/tasks/session-path.js +4 -5
- package/dist/tasks/store.d.ts +27 -28
- package/dist/tasks/store.js +89 -83
- package/dist/tasks/ticket.d.ts +33 -66
- package/dist/tasks/ticket.js +31 -120
- package/dist/tasks/work-log.d.ts +20 -0
- package/dist/tasks/work-log.js +42 -0
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.js +1 -1
- package/dist/tools/event-manage.d.ts +16 -2
- package/dist/tools/event-manage.js +30 -12
- package/dist/tools/index.d.ts +5 -3
- package/dist/tools/index.js +5 -5
- package/dist/tools/registry.d.ts +6 -4
- package/dist/tools/registry.js +1 -4
- package/dist/tools/subagent-manage.js +4 -2
- package/dist/tools/task-manage/create.js +11 -27
- package/dist/tools/task-manage/lifecycle.d.ts +6 -7
- package/dist/tools/task-manage/lifecycle.js +23 -106
- package/dist/tools/task-manage/log-view.d.ts +3 -2
- package/dist/tools/task-manage/log-view.js +6 -6
- package/dist/tools/task-manage/schema.d.ts +10 -30
- package/dist/tools/task-manage/schema.js +33 -49
- package/dist/tools/task-manage/shared.d.ts +35 -42
- package/dist/tools/task-manage/shared.js +53 -192
- package/dist/tools/task-manage/step-end.d.ts +6 -6
- package/dist/tools/task-manage/step-end.js +61 -98
- package/dist/tools/task-manage/types.d.ts +8 -9
- package/dist/tools/task-manage.js +5 -5
- package/dist/tui/app.js +11 -38
- package/dist/tui/commands.d.ts +18 -8
- package/dist/tui/commands.js +2 -9
- package/dist/tui/turn-controller.d.ts +2 -14
- package/dist/tui/turn-controller.js +1 -17
- package/dist/web/client.js +9 -1
- package/examples/sub-agents/README.md +7 -4
- package/examples/sub-agents/agents/codex-flash.md +2 -2
- package/examples/sub-agents/agents/codex-high.md +1 -1
- package/examples/sub-agents/agents/codex-main.md +1 -1
- package/examples/sub-agents/agents/codex-review.md +23 -0
- package/examples/sub-agents/roles/verifier.md +1 -1
- package/package.json +1 -1
- package/dist/memory/maintenance-migration.d.ts +0 -5
- package/dist/memory/maintenance-migration.js +0 -91
- package/dist/memory/migrate.d.ts +0 -15
- package/dist/memory/migrate.js +0 -364
- package/dist/playbooks/task-loop.md +0 -90
- package/dist/tasks/artifact-subject.d.ts +0 -40
- package/dist/tasks/artifact-subject.js +0 -334
- package/dist/tasks/cycle.d.ts +0 -48
- package/dist/tasks/cycle.js +0 -94
- package/dist/tasks/rounds.d.ts +0 -41
- package/dist/tasks/rounds.js +0 -53
- package/dist/tasks/task-events.d.ts +0 -6
- package/dist/tasks/task-events.js +0 -14
- package/dist/tasks/task-schedule.d.ts +0 -18
- package/dist/tasks/task-schedule.js +0 -50
- package/dist/tasks/verification.d.ts +0 -114
- package/dist/tasks/verification.js +0 -226
package/dist/tasks/log.js
CHANGED
|
@@ -41,56 +41,74 @@ export async function resetTaskLogAppenders() {
|
|
|
41
41
|
*/
|
|
42
42
|
export async function appendTaskLog(channelDir, id, record) {
|
|
43
43
|
const withTs = { ts: record.ts ?? formatLocalTime(), ...record };
|
|
44
|
-
if (withTs.kind === "step")
|
|
44
|
+
if (withTs.kind === "step") {
|
|
45
45
|
withTs.note = clipText(withTs.note, NOTE_MAX_CHARS);
|
|
46
|
+
if (withTs.report)
|
|
47
|
+
withTs.report = clipText(withTs.report, NOTE_MAX_CHARS);
|
|
48
|
+
}
|
|
46
49
|
await appenderFor(taskLogPath(channelDir, id)).appendStrict(withTs);
|
|
47
50
|
}
|
|
51
|
+
const RECORD_KINDS = ["step", "dispatch", "settle", "expired", "close", "note"];
|
|
48
52
|
function toRecord(value) {
|
|
49
|
-
if (!isPlainObject(value) || typeof value.ts !== "string"
|
|
53
|
+
if (!isPlainObject(value) || typeof value.ts !== "string")
|
|
50
54
|
return undefined;
|
|
51
55
|
const kind = value.kind;
|
|
52
|
-
if (
|
|
56
|
+
if (typeof kind !== "string" || !RECORD_KINDS.includes(kind))
|
|
53
57
|
return undefined;
|
|
54
58
|
return value;
|
|
55
59
|
}
|
|
60
|
+
/** Rotated-shard paths for `basePath`, oldest first, then the current file — the chronological
|
|
61
|
+
* order records were actually written in. Only shards that exist are returned. */
|
|
62
|
+
function shardPaths(basePath) {
|
|
63
|
+
return [`${basePath}.2`, `${basePath}.1`, basePath].filter((path) => existsSync(path));
|
|
64
|
+
}
|
|
65
|
+
function parseLogLines(content, options, into) {
|
|
66
|
+
for (const line of content.split("\n")) {
|
|
67
|
+
if (!line.trim())
|
|
68
|
+
continue;
|
|
69
|
+
let parsed;
|
|
70
|
+
try {
|
|
71
|
+
parsed = JSON.parse(line);
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const record = toRecord(parsed);
|
|
77
|
+
if (!record)
|
|
78
|
+
continue;
|
|
79
|
+
if (options.kinds && !options.kinds.includes(record.kind))
|
|
80
|
+
continue;
|
|
81
|
+
into.push(record);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
56
84
|
/**
|
|
57
85
|
* Read the log back, newest-last. Unparseable lines are skipped rather than failing the read: a
|
|
58
86
|
* hand-edited or half-written line must not make a task's whole history unreadable.
|
|
87
|
+
*
|
|
88
|
+
* Reads every existing rotated shard (R9), not just the current file — `MAX_LOG_BYTES` rotation
|
|
89
|
+
* moves older records into `.1`/`.2` behind the caller's back, and a read that only looked at the
|
|
90
|
+
* current file made rotated-out history invisible to `task_log`, briefs, and and the board
|
|
91
|
+
* alike even though it was still on disk.
|
|
59
92
|
*/
|
|
60
93
|
export async function readTaskLog(channelDir, id, options = {}) {
|
|
61
94
|
// Fall back to the archived copy so `task_log` on a completed task returns its history rather
|
|
62
95
|
// than "暂无日志" — a task that finished still has a loop log worth reading.
|
|
63
|
-
const
|
|
96
|
+
const basePath = existsSync(taskLogPath(channelDir, id))
|
|
64
97
|
? taskLogPath(channelDir, id)
|
|
65
98
|
: taskArchiveLogPath(channelDir, id);
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
let content;
|
|
69
|
-
try {
|
|
70
|
-
content = await readFile(path, "utf-8");
|
|
71
|
-
}
|
|
72
|
-
catch {
|
|
99
|
+
const paths = shardPaths(basePath);
|
|
100
|
+
if (paths.length === 0)
|
|
73
101
|
return [];
|
|
74
|
-
}
|
|
75
102
|
const records = [];
|
|
76
|
-
for (const
|
|
77
|
-
|
|
78
|
-
continue;
|
|
79
|
-
let parsed;
|
|
103
|
+
for (const path of paths) {
|
|
104
|
+
let content;
|
|
80
105
|
try {
|
|
81
|
-
|
|
106
|
+
content = await readFile(path, "utf-8");
|
|
82
107
|
}
|
|
83
108
|
catch {
|
|
84
109
|
continue;
|
|
85
110
|
}
|
|
86
|
-
|
|
87
|
-
if (!record)
|
|
88
|
-
continue;
|
|
89
|
-
if (options.cycle && record.cycle !== options.cycle)
|
|
90
|
-
continue;
|
|
91
|
-
if (options.kinds && !options.kinds.includes(record.kind))
|
|
92
|
-
continue;
|
|
93
|
-
records.push(record);
|
|
111
|
+
parseLogLines(content, options, records);
|
|
94
112
|
}
|
|
95
113
|
return options.limit !== undefined && records.length > options.limit ? records.slice(-options.limit) : records;
|
|
96
114
|
}
|
|
@@ -98,12 +116,16 @@ export async function readTaskLog(channelDir, id, options = {}) {
|
|
|
98
116
|
export function renderTaskLogLine(record) {
|
|
99
117
|
switch (record.kind) {
|
|
100
118
|
case "step":
|
|
101
|
-
return `- [${record.ts}] step ${record.seq} → ${record.outcome}: ${record.note}`;
|
|
102
|
-
case "
|
|
103
|
-
return `- [${record.ts}]
|
|
119
|
+
return `- [${record.ts}] step ${record.seq} → ${record.outcome}: ${record.note}${record.report ? " · 已向用户汇报" : ""}`;
|
|
120
|
+
case "dispatch":
|
|
121
|
+
return `- [${record.ts}] 派发 ${record.ref}${record.item ? ` → ${record.item}` : ""}${record.agent ? ` (${record.agent}${record.purpose === "verify" ? ", verify" : ""})` : ""}`;
|
|
122
|
+
case "settle":
|
|
123
|
+
return `- [${record.ts}] 结算 ${record.ref}: ${record.status}${record.verdict ? ` VERDICT ${record.verdict.toUpperCase()}` : ""}${record.exitCode !== undefined ? ` exit ${record.exitCode}` : ""}${record.output ? ` · ${record.output}` : ""}`;
|
|
104
124
|
case "expired":
|
|
105
125
|
return `- [${record.ts}] 等待票过期(${record.ticket})→ ${record.action}`;
|
|
106
126
|
case "close":
|
|
107
|
-
return `- [${record.ts}]
|
|
127
|
+
return `- [${record.ts}] ${record.outcome === "done" ? "完成" : "取消"}:${record.note}`;
|
|
128
|
+
case "note":
|
|
129
|
+
return `- [${record.ts}] ${record.note}`;
|
|
108
130
|
}
|
|
109
131
|
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Where a task
|
|
3
|
-
* left behind when the
|
|
2
|
+
* Where a task's own agent session lives (spec 051, D3; one per task since spec 052, D1) —
|
|
3
|
+
* left behind when the task is archived. Kept out of `<channelDir>` root and under a dot-directory so
|
|
4
4
|
* `session_search`'s channel scan and `/new`'s session listing do not mistake a task transcript
|
|
5
5
|
* for the channel's conversation.
|
|
6
6
|
*/
|
|
7
7
|
export declare const TASK_SESSIONS_DIRNAME = ".sessions";
|
|
8
8
|
export declare function taskSessionsDir(channelDir: string): string;
|
|
9
|
-
export declare function taskSessionPath(channelDir: string, taskId: string
|
|
9
|
+
export declare function taskSessionPath(channelDir: string, taskId: string): string;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
2
|
import { normalizeTaskId } from "./ledger.js";
|
|
3
3
|
/**
|
|
4
|
-
* Where a task
|
|
5
|
-
* left behind when the
|
|
4
|
+
* Where a task's own agent session lives (spec 051, D3; one per task since spec 052, D1) —
|
|
5
|
+
* left behind when the task is archived. Kept out of `<channelDir>` root and under a dot-directory so
|
|
6
6
|
* `session_search`'s channel scan and `/new`'s session listing do not mistake a task transcript
|
|
7
7
|
* for the channel's conversation.
|
|
8
8
|
*/
|
|
@@ -10,7 +10,6 @@ export const TASK_SESSIONS_DIRNAME = ".sessions";
|
|
|
10
10
|
export function taskSessionsDir(channelDir) {
|
|
11
11
|
return join(channelDir, "tasks", TASK_SESSIONS_DIRNAME);
|
|
12
12
|
}
|
|
13
|
-
export function taskSessionPath(channelDir, taskId
|
|
14
|
-
|
|
15
|
-
return join(taskSessionsDir(channelDir), `${normalizeTaskId(taskId)}-${safeCycle}.jsonl`);
|
|
13
|
+
export function taskSessionPath(channelDir, taskId) {
|
|
14
|
+
return join(taskSessionsDir(channelDir), `${normalizeTaskId(taskId)}.jsonl`);
|
|
16
15
|
}
|
package/dist/tasks/store.d.ts
CHANGED
|
@@ -1,29 +1,15 @@
|
|
|
1
|
-
import { type TaskArchiveOutcome, type
|
|
1
|
+
import { type TaskArchiveOutcome, type TaskFrontmatter, type TaskPaused } from "./frontmatter.js";
|
|
2
2
|
import { type Ticket } from "./ticket.js";
|
|
3
3
|
export interface StoredTaskDocument {
|
|
4
4
|
id: string;
|
|
5
5
|
path: string;
|
|
6
|
-
fields:
|
|
6
|
+
fields: TaskFrontmatter;
|
|
7
7
|
body: string;
|
|
8
8
|
}
|
|
9
9
|
/**
|
|
10
|
-
* The contract's size
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* and every wake read all of it. The contract is injected whole into every step brief, so what it
|
|
14
|
-
* must guarantee is that **runtime-written history cannot grow it** — not that the file is under
|
|
15
|
-
* some number no matter what the user wrote.
|
|
16
|
-
*
|
|
17
|
-
* So the budget is enforced against `## 上次结果` only, the one section the runtime authors and
|
|
18
|
-
* whose full content is always recoverable from `task_log`. Everything else — Goal, DoD, Manual,
|
|
19
|
-
* Verification, Plan — is authored by the user or the planning turn, and the runtime does not get
|
|
20
|
-
* to delete it to hit a number. A contract that still exceeds the budget on authored text alone is
|
|
21
|
-
* written as-is and warned about.
|
|
22
|
-
*
|
|
23
|
-
* The first version clipped the body's tail instead, and the migration rehearsal on real data
|
|
24
|
-
* showed exactly why that was wrong: two tasks with a legitimately long `## Manual` silently lost
|
|
25
|
-
* their `## Verification` and `## Plan` sections — the verifier's instructions and the task's own
|
|
26
|
-
* agenda — to make room.
|
|
10
|
+
* The contract's size target. The contract is injected whole into every step brief, so a long one
|
|
11
|
+
* costs on every step. The runtime never rewrites the body (INV-6), so there is nothing it could
|
|
12
|
+
* clip: a contract over the target is written as-is and warned about once per write.
|
|
27
13
|
*/
|
|
28
14
|
export declare const MAX_CONTRACT_BYTES: number;
|
|
29
15
|
export declare function tasksDir(channelDir: string): string;
|
|
@@ -54,10 +40,15 @@ export declare function redeemTicket(channelDir: string, id: string, matches: (t
|
|
|
54
40
|
export declare function pauseTask(channelDir: string, id: string, paused: Omit<TaskPaused, "at"> & {
|
|
55
41
|
at?: string;
|
|
56
42
|
}): Promise<StoredTaskDocument | undefined>;
|
|
43
|
+
/**
|
|
44
|
+
* Lift a pause. A task that was paused *while parked on a ticket whose backstop has since passed*
|
|
45
|
+
* (the double-expiry stop) is reopened and its expiry count cleared: the user has looked at it,
|
|
46
|
+
* and resuming onto the same dead ticket would just expire — and pause — it a third time.
|
|
47
|
+
*/
|
|
57
48
|
export declare function resumeTask(channelDir: string, id: string): Promise<StoredTaskDocument | undefined>;
|
|
58
49
|
/**
|
|
59
50
|
* The backstop transition (D2): a parked task whose `by` has passed goes back to `open` so its
|
|
60
|
-
* next step can re-check reality, and the second expiry
|
|
51
|
+
* next step can re-check reality, and the second consecutive expiry stops the task and
|
|
61
52
|
* hands the user a deterministic receipt instead of burning another wake.
|
|
62
53
|
*
|
|
63
54
|
* Returns what the caller should do about it, or `undefined` when nothing applied.
|
|
@@ -69,13 +60,21 @@ export declare function expireTicket(channelDir: string, id: string, limit?: num
|
|
|
69
60
|
ticket: string;
|
|
70
61
|
} | undefined>;
|
|
71
62
|
/**
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
63
|
+
* `archiveTask` failed and could not fully put things back: `stranded` lists files that now live
|
|
64
|
+
* only at the archive path (`<archive path> -> <original path>`), plus any archive contract it
|
|
65
|
+
* could not remove. Callers must not delete anything archive-side on seeing this.
|
|
66
|
+
*/
|
|
67
|
+
export declare class ArchiveUndoError extends Error {
|
|
68
|
+
readonly cause: unknown;
|
|
69
|
+
readonly stranded: string[];
|
|
70
|
+
readonly undoFailures: string[];
|
|
71
|
+
constructor(cause: unknown, stranded: string[], undoFailures: string[]);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Move a closed task (and its log) into `tasks/archive/`. It never overwrites an existing archive
|
|
75
|
+
* entry (it throws before touching anything), and any failure after the first write undoes what it
|
|
76
|
+
* did so the task stays fully active: a caller can trust "resolved" to mean the contract and every
|
|
77
|
+
* log shard are in the archive, and "rejected" to mean the pre-call state still stands (or, if the
|
|
78
|
+
* undo itself failed, the error says so).
|
|
75
79
|
*/
|
|
76
|
-
export declare function openCycle(channelDir: string, id: string, now?: Date): Promise<{
|
|
77
|
-
document: StoredTaskDocument;
|
|
78
|
-
cycleId: string;
|
|
79
|
-
} | undefined>;
|
|
80
|
-
/** Move a closed task (and its log) into `tasks/archive/`. */
|
|
81
80
|
export declare function archiveTask(channelDir: string, id: string, outcome: TaskArchiveOutcome): Promise<void>;
|
package/dist/tasks/store.js
CHANGED
|
@@ -4,33 +4,19 @@ import { join } from "node:path";
|
|
|
4
4
|
import * as log from "../log.js";
|
|
5
5
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
6
6
|
import { formatLocalTime } from "../shared/local-time.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
7
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
8
|
+
import { createUsage } from "./budget.js";
|
|
9
|
+
import { normalizeTaskFrontmatter, parseTaskFrontmatter, } from "./frontmatter.js";
|
|
9
10
|
import { normalizeTaskId, renderTaskDocument, taskBody } from "./ledger.js";
|
|
10
11
|
import { appendTaskLog, taskLogPath } from "./log.js";
|
|
11
12
|
import { withTaskMutation } from "./mutation-lock.js";
|
|
12
|
-
import { describeTicket } from "./ticket.js";
|
|
13
|
+
import { describeTicket, ticketExpired } from "./ticket.js";
|
|
13
14
|
/**
|
|
14
|
-
* The contract's size
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* and every wake read all of it. The contract is injected whole into every step brief, so what it
|
|
18
|
-
* must guarantee is that **runtime-written history cannot grow it** — not that the file is under
|
|
19
|
-
* some number no matter what the user wrote.
|
|
20
|
-
*
|
|
21
|
-
* So the budget is enforced against `## 上次结果` only, the one section the runtime authors and
|
|
22
|
-
* whose full content is always recoverable from `task_log`. Everything else — Goal, DoD, Manual,
|
|
23
|
-
* Verification, Plan — is authored by the user or the planning turn, and the runtime does not get
|
|
24
|
-
* to delete it to hit a number. A contract that still exceeds the budget on authored text alone is
|
|
25
|
-
* written as-is and warned about.
|
|
26
|
-
*
|
|
27
|
-
* The first version clipped the body's tail instead, and the migration rehearsal on real data
|
|
28
|
-
* showed exactly why that was wrong: two tasks with a legitimately long `## Manual` silently lost
|
|
29
|
-
* their `## Verification` and `## Plan` sections — the verifier's instructions and the task's own
|
|
30
|
-
* agenda — to make room.
|
|
15
|
+
* The contract's size target. The contract is injected whole into every step brief, so a long one
|
|
16
|
+
* costs on every step. The runtime never rewrites the body (INV-6), so there is nothing it could
|
|
17
|
+
* clip: a contract over the target is written as-is and warned about once per write.
|
|
31
18
|
*/
|
|
32
19
|
export const MAX_CONTRACT_BYTES = 4 * 1024;
|
|
33
|
-
const LAST_RESULT_CLIP_NOTE = "…(更早的记录见 task_log)";
|
|
34
20
|
export function tasksDir(channelDir) {
|
|
35
21
|
return join(channelDir, "tasks");
|
|
36
22
|
}
|
|
@@ -52,44 +38,17 @@ export async function readStoredTask(channelDir, idInput, includeArchive = false
|
|
|
52
38
|
if (!path)
|
|
53
39
|
return undefined;
|
|
54
40
|
const content = await readFile(path, "utf-8");
|
|
55
|
-
const parsed =
|
|
41
|
+
const parsed = parseTaskFrontmatter(content);
|
|
56
42
|
return { id, path, fields: parsed.fields, body: taskBody(content) };
|
|
57
43
|
}
|
|
58
|
-
/** Clip a body that would push the contract over budget, keeping the head (the contract proper). */
|
|
59
|
-
/** Shrink `## 上次结果` toward the budget; returns the body unchanged when there is none. */
|
|
60
|
-
function clipLastResult(body, overBy) {
|
|
61
|
-
const existing = readLastResult(body);
|
|
62
|
-
if (!existing)
|
|
63
|
-
return body;
|
|
64
|
-
// Cut on a character boundary: slicing a Buffer could split a multi-byte codepoint and write a
|
|
65
|
-
// replacement character into a hand-editable file.
|
|
66
|
-
const buffer = Buffer.from(existing, "utf-8");
|
|
67
|
-
const keepBytes = Math.max(0, buffer.byteLength - overBy - Buffer.byteLength(LAST_RESULT_CLIP_NOTE, "utf-8"));
|
|
68
|
-
if (keepBytes <= 0)
|
|
69
|
-
return stripLastResult(body);
|
|
70
|
-
let clipped = new TextDecoder("utf-8", { fatal: false }).decode(buffer.subarray(0, keepBytes));
|
|
71
|
-
clipped = clipped.replace(/\uFFFD+$/, "");
|
|
72
|
-
const lastNewline = clipped.lastIndexOf("\n");
|
|
73
|
-
if (lastNewline > 0)
|
|
74
|
-
clipped = clipped.slice(0, lastNewline);
|
|
75
|
-
return writeLastResult(body, `${clipped.trimEnd()}${LAST_RESULT_CLIP_NOTE}`);
|
|
76
|
-
}
|
|
77
|
-
function enforceContractBudget(id, fields, body) {
|
|
78
|
-
const size = (candidate) => Buffer.byteLength(renderTaskDocument(fields, candidate), "utf-8");
|
|
79
|
-
if (size(body) <= MAX_CONTRACT_BYTES)
|
|
80
|
-
return body;
|
|
81
|
-
const clipped = clipLastResult(body, size(body) - MAX_CONTRACT_BYTES);
|
|
82
|
-
if (size(clipped) <= MAX_CONTRACT_BYTES)
|
|
83
|
-
return clipped;
|
|
84
|
-
// Authored text alone is over budget. Keep it — deleting a user's Manual or Verification to hit
|
|
85
|
-
// a number is worse than a large file — and say so once per write so it is not silently normal.
|
|
86
|
-
log.logWarning(`Task ${id} exceeds the ${MAX_CONTRACT_BYTES}-byte contract budget`, `${size(clipped)} bytes after clipping 上次结果; shorten Goal/DoD/Manual/Verification, or move detail into the loop log.`);
|
|
87
|
-
return clipped;
|
|
88
|
-
}
|
|
89
44
|
export async function writeStoredTask(document) {
|
|
90
45
|
const fields = normalizeTaskFrontmatter(document.fields);
|
|
91
|
-
const
|
|
92
|
-
|
|
46
|
+
const rendered = renderTaskDocument(fields, document.body);
|
|
47
|
+
const size = Buffer.byteLength(rendered, "utf-8");
|
|
48
|
+
if (size > MAX_CONTRACT_BYTES) {
|
|
49
|
+
log.logWarning(`Task ${document.id} exceeds the ${MAX_CONTRACT_BYTES}-byte contract target`, `${size} bytes; every step pays for it — shorten Goal/DoD, or move detail into the loop log.`);
|
|
50
|
+
}
|
|
51
|
+
await writeFileAtomically(document.path, rendered);
|
|
93
52
|
}
|
|
94
53
|
export async function updateStoredTask(channelDir, id, update, includeArchive = false) {
|
|
95
54
|
return withTaskMutation(channelDir, id, async () => {
|
|
@@ -130,6 +89,9 @@ export async function redeemTicket(channelDir, id, matches) {
|
|
|
130
89
|
redeemed = task.fields.ticket;
|
|
131
90
|
task.fields.state = "open";
|
|
132
91
|
task.fields.ticket = undefined;
|
|
92
|
+
// The wait ended normally, so the "consecutive expiries" count starts over (spec 052, D3).
|
|
93
|
+
if (task.fields.usage)
|
|
94
|
+
task.fields.usage = { ...task.fields.usage, expired: 0 };
|
|
133
95
|
});
|
|
134
96
|
return document && redeemed ? { document, ticket: redeemed } : undefined;
|
|
135
97
|
}
|
|
@@ -139,9 +101,20 @@ export async function pauseTask(channelDir, id, paused) {
|
|
|
139
101
|
task.fields.paused = { ...paused, at: paused.at ?? formatLocalTime() };
|
|
140
102
|
});
|
|
141
103
|
}
|
|
104
|
+
/**
|
|
105
|
+
* Lift a pause. A task that was paused *while parked on a ticket whose backstop has since passed*
|
|
106
|
+
* (the double-expiry stop) is reopened and its expiry count cleared: the user has looked at it,
|
|
107
|
+
* and resuming onto the same dead ticket would just expire — and pause — it a third time.
|
|
108
|
+
*/
|
|
142
109
|
export async function resumeTask(channelDir, id) {
|
|
143
110
|
return updateStoredTask(channelDir, id, (task) => {
|
|
144
111
|
task.fields.paused = undefined;
|
|
112
|
+
if (task.fields.state === "parked" && task.fields.ticket && ticketExpired(task.fields.ticket)) {
|
|
113
|
+
task.fields.state = "open";
|
|
114
|
+
task.fields.ticket = undefined;
|
|
115
|
+
if (task.fields.usage)
|
|
116
|
+
task.fields.usage = { ...task.fields.usage, expired: 0 };
|
|
117
|
+
}
|
|
145
118
|
});
|
|
146
119
|
}
|
|
147
120
|
export async function expireTicket(channelDir, id, limit = 2) {
|
|
@@ -152,9 +125,9 @@ export async function expireTicket(channelDir, id, limit = 2) {
|
|
|
152
125
|
if (task.fields.state !== "parked" || !ticket || task.fields.paused)
|
|
153
126
|
return;
|
|
154
127
|
summary = describeTicket(ticket);
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
|
|
128
|
+
const usage = task.fields.usage ?? createUsage();
|
|
129
|
+
const expired = usage.expired + 1;
|
|
130
|
+
task.fields.usage = { ...usage, expired };
|
|
158
131
|
if (expired >= limit) {
|
|
159
132
|
outcome = "paused";
|
|
160
133
|
task.fields.paused = {
|
|
@@ -171,35 +144,33 @@ export async function expireTicket(channelDir, id, limit = 2) {
|
|
|
171
144
|
if (!document || !outcome)
|
|
172
145
|
return undefined;
|
|
173
146
|
await appendTaskLog(channelDir, id, {
|
|
174
|
-
cycle: document.fields.cycle?.id ?? "-",
|
|
175
147
|
kind: "expired",
|
|
176
148
|
ticket: summary,
|
|
177
149
|
action: outcome,
|
|
178
150
|
});
|
|
179
151
|
return { document, outcome, ticket: summary };
|
|
180
152
|
}
|
|
153
|
+
const LOG_SUFFIXES = ["", ".1", ".2"];
|
|
181
154
|
/**
|
|
182
|
-
*
|
|
183
|
-
*
|
|
184
|
-
*
|
|
155
|
+
* `archiveTask` failed and could not fully put things back: `stranded` lists files that now live
|
|
156
|
+
* only at the archive path (`<archive path> -> <original path>`), plus any archive contract it
|
|
157
|
+
* could not remove. Callers must not delete anything archive-side on seeing this.
|
|
185
158
|
*/
|
|
186
|
-
export
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
task.body = openCycleBody(task.body, recurring);
|
|
194
|
-
task.fields.cycle = createCycle(cycleId, now);
|
|
195
|
-
task.fields.state = "open";
|
|
196
|
-
task.fields.ticket = undefined;
|
|
197
|
-
});
|
|
198
|
-
if (!document || !cycleId)
|
|
199
|
-
return undefined;
|
|
200
|
-
return { document, cycleId };
|
|
159
|
+
export class ArchiveUndoError extends Error {
|
|
160
|
+
constructor(cause, stranded, undoFailures) {
|
|
161
|
+
super(`${errorMessage(cause)} (undo of partial archive failed: ${undoFailures.join("; ")}${stranded.length > 0 ? `; still at archive path, move back by hand: ${stranded.join(", ")}` : ""})`);
|
|
162
|
+
this.cause = cause;
|
|
163
|
+
this.stranded = stranded;
|
|
164
|
+
this.undoFailures = undoFailures;
|
|
165
|
+
}
|
|
201
166
|
}
|
|
202
|
-
/**
|
|
167
|
+
/**
|
|
168
|
+
* Move a closed task (and its log) into `tasks/archive/`. It never overwrites an existing archive
|
|
169
|
+
* entry (it throws before touching anything), and any failure after the first write undoes what it
|
|
170
|
+
* did so the task stays fully active: a caller can trust "resolved" to mean the contract and every
|
|
171
|
+
* log shard are in the archive, and "rejected" to mean the pre-call state still stands (or, if the
|
|
172
|
+
* undo itself failed, the error says so).
|
|
173
|
+
*/
|
|
203
174
|
export async function archiveTask(channelDir, id, outcome) {
|
|
204
175
|
const normalized = normalizeTaskId(id);
|
|
205
176
|
const archiveDir = join(tasksDir(channelDir), "archive");
|
|
@@ -207,13 +178,48 @@ export async function archiveTask(channelDir, id, outcome) {
|
|
|
207
178
|
const document = await readStoredTask(channelDir, normalized);
|
|
208
179
|
if (!document)
|
|
209
180
|
return;
|
|
181
|
+
const archiveMd = archivedTaskPath(channelDir, normalized);
|
|
182
|
+
const archiveLog = join(archiveDir, `${normalized}.jsonl`);
|
|
183
|
+
for (const target of [archiveMd, ...LOG_SUFFIXES.map((suffix) => `${archiveLog}${suffix}`)]) {
|
|
184
|
+
if (existsSync(target))
|
|
185
|
+
throw new Error(`archive entry already exists, refusing to overwrite: ${target}`);
|
|
186
|
+
}
|
|
210
187
|
document.fields.outcome = outcome;
|
|
211
188
|
document.fields.closedAt = formatLocalTime();
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
//
|
|
189
|
+
// The loop log travels with its contract so an archived task stays inspectable — including
|
|
190
|
+
// whatever has already rotated into `.1`/`.2` (R9). Moving only the current file stranded
|
|
191
|
+
// those shards in the now-empty active `tasks/` dir, permanently split from the record they
|
|
192
|
+
// belong to and outside anywhere `readTaskLog` looks for an archived task.
|
|
215
193
|
const logFrom = taskLogPath(channelDir, normalized);
|
|
216
|
-
|
|
217
|
-
|
|
194
|
+
const movedLogs = [];
|
|
195
|
+
let wroteArchive = false;
|
|
196
|
+
try {
|
|
197
|
+
for (const suffix of LOG_SUFFIXES) {
|
|
198
|
+
const from = `${logFrom}${suffix}`;
|
|
199
|
+
if (!existsSync(from))
|
|
200
|
+
continue;
|
|
201
|
+
const to = `${archiveLog}${suffix}`;
|
|
202
|
+
await rename(from, to);
|
|
203
|
+
movedLogs.push([from, to]);
|
|
204
|
+
}
|
|
205
|
+
await writeStoredTask({ ...document, path: archiveMd });
|
|
206
|
+
wroteArchive = true;
|
|
207
|
+
await rm(taskPath(channelDir, normalized), { force: true });
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
const undoFailures = [];
|
|
211
|
+
if (wroteArchive || existsSync(archiveMd)) {
|
|
212
|
+
await rm(archiveMd, { force: true }).catch((e) => undoFailures.push(errorMessage(e)));
|
|
213
|
+
}
|
|
214
|
+
const stranded = [];
|
|
215
|
+
for (const [from, to] of movedLogs.reverse()) {
|
|
216
|
+
await rename(to, from).catch((e) => {
|
|
217
|
+
undoFailures.push(errorMessage(e));
|
|
218
|
+
stranded.push(`${to} -> ${from}`);
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
if (undoFailures.length > 0)
|
|
222
|
+
throw new ArchiveUndoError(error, stranded, undoFailures);
|
|
223
|
+
throw error;
|
|
218
224
|
}
|
|
219
225
|
}
|
package/dist/tasks/ticket.d.ts
CHANGED
|
@@ -1,102 +1,69 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The waiting ticket
|
|
2
|
+
* The waiting ticket — the only way a task may park (spec 051, D2; narrowed by spec 052, D3).
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* task
|
|
7
|
-
* of the real long-lived tasks on the author's machine died of exactly that: parked with no
|
|
8
|
-
* redeemable source, silent for 9 and 13 days respectively while the governor watched for tasks
|
|
9
|
-
* that spun too much.
|
|
4
|
+
* A ticket is a claim the runtime can check at write time, and it always carries `by`, a backstop
|
|
5
|
+
* instant after which the runtime reopens the task rather than leaving it parked forever: a
|
|
6
|
+
* parked task either gets redeemed, or the user hears about it. Three kinds are enough:
|
|
10
7
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
8
|
+
* - `time` — wait for a moment; the driver redeems it.
|
|
9
|
+
* - `work` — wait for the delegations and jobs this task has in flight; the first one to settle
|
|
10
|
+
* redeems it. The leader never has to pick "which run is the real blocker".
|
|
11
|
+
* - `ask` — wait for the user; `/tasks reply` redeems it.
|
|
12
|
+
*
|
|
13
|
+
* Waiting for an external condition is a background job (a sensor with a timeout) bound to the
|
|
14
|
+
* task, i.e. a `work` ticket — not a separate kind.
|
|
15
15
|
*/
|
|
16
|
-
export type TicketKind = "time" | "
|
|
16
|
+
export type TicketKind = "time" | "work" | "ask";
|
|
17
17
|
export type Ticket = {
|
|
18
18
|
kind: "time";
|
|
19
19
|
at: string;
|
|
20
20
|
by: string;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
kind: "run";
|
|
27
|
-
id: string;
|
|
28
|
-
by: string;
|
|
29
|
-
} | {
|
|
30
|
-
kind: "job";
|
|
31
|
-
id: string;
|
|
21
|
+
}
|
|
22
|
+
/** `refs` is display-only: redemption matches on `kind`, never on the ids. */
|
|
23
|
+
| {
|
|
24
|
+
kind: "work";
|
|
25
|
+
refs: string[];
|
|
32
26
|
by: string;
|
|
33
27
|
} | {
|
|
34
28
|
kind: "ask";
|
|
35
29
|
asked: string;
|
|
36
30
|
by: string;
|
|
37
|
-
} | {
|
|
38
|
-
kind: "signal";
|
|
39
|
-
event: string;
|
|
40
|
-
by: string;
|
|
41
31
|
};
|
|
42
|
-
/**
|
|
43
|
-
export interface
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
deadlineAt?: number;
|
|
48
|
-
maxWallTimeSec?: number;
|
|
49
|
-
}
|
|
50
|
-
/** The minimum a ticket resolver needs to know about a background job. */
|
|
51
|
-
export interface TicketJobRef {
|
|
52
|
-
taskId?: string;
|
|
53
|
-
status: string;
|
|
54
|
-
startedAt: number;
|
|
55
|
-
}
|
|
56
|
-
/** The minimum a ticket resolver needs to know about a scheduled event. */
|
|
57
|
-
export interface TicketEventRef {
|
|
58
|
-
type: "one-shot" | "periodic";
|
|
59
|
-
channelId: string;
|
|
60
|
-
schedule?: string;
|
|
32
|
+
/** A delegation or background job bound to this task that has not settled yet. */
|
|
33
|
+
export interface PendingWorkRef {
|
|
34
|
+
ref: string;
|
|
35
|
+
/** Epoch ms after which the owner itself gives up on the work. */
|
|
36
|
+
deadlineMs: number;
|
|
61
37
|
}
|
|
62
38
|
/**
|
|
63
|
-
* Everything `resolveTicket` may consult, injected rather than imported: the run/job
|
|
64
|
-
*
|
|
39
|
+
* Everything `resolveTicket` may consult, injected rather than imported: the run/job registries
|
|
40
|
+
* are stateful singletons, and keeping them out of this module is what makes the whole
|
|
65
41
|
* validation matrix unit-testable without a runtime.
|
|
66
42
|
*/
|
|
67
43
|
export interface TicketContext {
|
|
68
44
|
now: Date;
|
|
69
|
-
taskId
|
|
70
|
-
|
|
71
|
-
/** The task's own cron cadence; required for a `schedule` ticket. */
|
|
72
|
-
schedule?: string;
|
|
73
|
-
findRun(id: string): TicketRunRef | undefined;
|
|
74
|
-
findJob(id: string): TicketJobRef | undefined;
|
|
75
|
-
findEvent(name: string): TicketEventRef | undefined;
|
|
45
|
+
/** Unsettled runs and still-running jobs whose `taskId` is this task. */
|
|
46
|
+
pendingWork(): PendingWorkRef[];
|
|
76
47
|
}
|
|
77
48
|
/**
|
|
78
49
|
* Validate one model-supplied ticket and stamp its backstop.
|
|
79
50
|
*
|
|
80
|
-
* This is the **only** way a `Ticket` value comes into existence —
|
|
81
|
-
* and the
|
|
82
|
-
* field directly is a defect: it would produce a park with no verified source or no `by
|
|
83
|
-
* is precisely the failure this whole mechanism exists to make impossible.
|
|
51
|
+
* This is the **only** way a `Ticket` value comes into existence — `task_step_end`, `/tasks
|
|
52
|
+
* reply` and the converter all funnel through it. Anything that writes the `ticket` frontmatter
|
|
53
|
+
* field directly is a defect: it would produce a park with no verified source or no `by`.
|
|
84
54
|
*/
|
|
85
55
|
export declare function resolveTicket(input: unknown, ctx: TicketContext): Ticket;
|
|
86
|
-
/** Read a persisted ticket back. Returns `undefined` for anything not shaped like a
|
|
56
|
+
/** Read a persisted ticket back. Returns `undefined` for anything not shaped like a ticket. */
|
|
87
57
|
export declare function parseTicket(raw: string): Ticket | undefined;
|
|
88
58
|
/** Milliseconds of the ticket's backstop, or `undefined` when it is unparseable (never trusted). */
|
|
89
59
|
export declare function ticketBackstopMs(ticket: Ticket): number | undefined;
|
|
90
60
|
/**
|
|
91
61
|
* Whether this ticket's backstop has passed. An unparseable `by` counts as expired: a park whose
|
|
92
|
-
* deadline cannot be read is exactly the silent-forever state
|
|
93
|
-
* waking the task rather than toward leaving it buried.
|
|
62
|
+
* deadline cannot be read is exactly the silent-forever state the backstop forbids, so it fails
|
|
63
|
+
* toward waking the task rather than toward leaving it buried.
|
|
94
64
|
*/
|
|
95
65
|
export declare function ticketExpired(ticket: Ticket, now?: Date): boolean;
|
|
96
|
-
/**
|
|
97
|
-
* The moment a `time` ticket is *due* (as opposed to its backstop). Only `time` and `schedule`
|
|
98
|
-
* tickets are driver-polled; every other kind is pushed by its owner, so they have no due time.
|
|
99
|
-
*/
|
|
66
|
+
/** The moment a `time` ticket is *due*. Only `time` tickets are driver-polled; the rest are pushed by their owner. */
|
|
100
67
|
export declare function ticketDueMs(ticket: Ticket): number | undefined;
|
|
101
68
|
/** One-line summary for `/tasks`, receipts, and the step brief. */
|
|
102
69
|
export declare function describeTicket(ticket: Ticket): string;
|