@oyasmi/pipiclaw 0.7.4 → 0.7.5

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.
@@ -9,6 +9,7 @@ import { getChannelMemoryPath } from "../memory/files.js";
9
9
  import { MemoryLifecycle } from "../memory/lifecycle.js";
10
10
  import { applyMemoryActivityToState, updateMemoryMaintenanceState, } from "../memory/maintenance-state.js";
11
11
  import { recallRelevantMemory } from "../memory/recall.js";
12
+ import { buildTaskDigest } from "../memory/task-digest.js";
12
13
  import { getApiKeyForModel } from "../models/api-keys.js";
13
14
  import { findExactModelReferenceMatch, formatModelReference, resolveInitialModel } from "../models/utils.js";
14
15
  import { createExecutor } from "../sandbox.js";
@@ -173,6 +174,7 @@ export class ChannelRunner {
173
174
  await mkdir(this.channelDir, { recursive: true });
174
175
  let promptText = preserveRawInput ? clippedInput : userMessage;
175
176
  let recalledContextText = "";
177
+ let taskDigestText = "";
176
178
  let durableMemoryBootstrapText = "";
177
179
  if (!preserveRawInput) {
178
180
  const recallSettings = this.settingsManager.getMemoryRecallSettings();
@@ -196,6 +198,17 @@ export class ChannelRunner {
196
198
  promptText = `${recall.renderedText}\n\n<user_message>\n${promptText}\n</user_message>`;
197
199
  }
198
200
  }
201
+ const taskDigestSettings = this.settingsManager.getTaskDigestSettings();
202
+ if (taskDigestSettings.enabled) {
203
+ taskDigestText = await buildTaskDigest({
204
+ channelDir: this.channelDir,
205
+ maxTasks: taskDigestSettings.maxTasks,
206
+ maxChars: taskDigestSettings.maxChars,
207
+ });
208
+ if (taskDigestText) {
209
+ promptText = `${taskDigestText}\n\n${promptText}`;
210
+ }
211
+ }
199
212
  if (this.firstTurnMemoryBootstrapPending) {
200
213
  durableMemoryBootstrapText = await this.buildFirstTurnMemoryBootstrap();
201
214
  if (durableMemoryBootstrapText) {
@@ -210,6 +223,7 @@ export class ChannelRunner {
210
223
  systemPrompt: this.agent.state.systemPrompt,
211
224
  messages: this.session.messages,
212
225
  durableMemoryBootstrap: durableMemoryBootstrapText || undefined,
226
+ taskDigest: taskDigestText || undefined,
213
227
  recalledContext: recalledContextText || undefined,
214
228
  newUserMessage: promptText,
215
229
  };
@@ -1,4 +1,4 @@
1
- export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "status" | "usage";
1
+ export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage";
2
2
  export interface BuiltInCommand {
3
3
  name: BuiltInCommandName;
4
4
  args: string;
@@ -24,6 +24,11 @@ These are handled directly by the DingTalk transport/runtime layer.
24
24
  Example: \`/events show weekly-review\`
25
25
  Example: \`/events delete weekly-review\`
26
26
  Example: \`/events history weekly-review\`
27
+ - \`/tasks [show <id>|archive]\`
28
+ View the channel's task ledger (read-only); to change a task, just tell me in plain language
29
+ Example: \`/tasks\`
30
+ Example: \`/tasks show weekly-report\`
31
+ Example: \`/tasks archive\`
27
32
  - \`/status\`
28
33
  Show runtime status: run state, current model, context usage, uptime, version
29
34
  Example: \`/status\`
@@ -70,6 +75,7 @@ export function parseBuiltInCommand(text) {
70
75
  case "followup":
71
76
  case "stop":
72
77
  case "events":
78
+ case "tasks":
73
79
  case "status":
74
80
  case "usage":
75
81
  return { name: rawName, args, rawText };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Builds the `<task_agenda>` block injected into each main-agent turn (spec 020 §2).
3
+ *
4
+ * Unlike memory recall — which is relevance-gated because candidate memory can be large —
5
+ * the agenda is deterministic and always-on: the candidate set is a handful of task
6
+ * frontmatters, and the in-flight agenda is universally relevant to an agent that drives
7
+ * work across turns. The block is bounded (maxTasks / maxChars) and framed as background
8
+ * reference, not instruction, so it can never turn an unrelated user turn into task work.
9
+ */
10
+ export interface TaskDigestOptions {
11
+ /** The channel directory; tasks live in `<channelDir>/tasks/`. */
12
+ channelDir: string;
13
+ maxTasks: number;
14
+ maxChars: number;
15
+ now?: number;
16
+ }
17
+ /**
18
+ * Render the in-flight task agenda, or `""` when there is nothing actionable to show.
19
+ * Only status ≠ done tasks are included (a done periodic task is sleeping, not on the agenda).
20
+ */
21
+ export declare function buildTaskDigest(options: TaskDigestOptions): Promise<string>;
@@ -0,0 +1,66 @@
1
+ import { join } from "node:path";
2
+ import { readActiveTasks } from "../shared/task-ledger.js";
3
+ function relativeWake(wakeMs, now) {
4
+ if (wakeMs === undefined)
5
+ return "wake —";
6
+ const diffMs = wakeMs - now;
7
+ if (diffMs <= 0)
8
+ return "wake due";
9
+ const minutes = Math.round(diffMs / 60000);
10
+ if (minutes < 60)
11
+ return `wake ${minutes}m`;
12
+ const hours = Math.round(minutes / 60);
13
+ if (hours < 24)
14
+ return `wake ${hours}h`;
15
+ return `wake ${Math.round(hours / 24)}d`;
16
+ }
17
+ function renderLine(entry, now) {
18
+ const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "open") : "⚠ unreadable frontmatter";
19
+ const parts = [`${entry.id} — ${entry.title}`, status, relativeWake(entry.wakeMs, now)];
20
+ if (entry.latestNote) {
21
+ const note = entry.latestNote.length > 80 ? `${entry.latestNote.slice(0, 79)}…` : entry.latestNote;
22
+ parts.push(note);
23
+ }
24
+ return `- ${parts.join(" · ")}`;
25
+ }
26
+ /**
27
+ * Render the in-flight task agenda, or `""` when there is nothing actionable to show.
28
+ * Only status ≠ done tasks are included (a done periodic task is sleeping, not on the agenda).
29
+ */
30
+ export async function buildTaskDigest(options) {
31
+ const now = options.now ?? Date.now();
32
+ const tasksDir = join(options.channelDir, "tasks");
33
+ const all = await readActiveTasks(tasksDir, now);
34
+ // done periodic tasks are asleep; only non-done tasks form the agenda.
35
+ const agenda = all.filter((entry) => entry.frontmatter.status !== "done" || !entry.frontmatter.readable);
36
+ if (agenda.length === 0)
37
+ return "";
38
+ const shown = agenda.slice(0, Math.max(1, options.maxTasks));
39
+ const omitted = agenda.length - shown.length;
40
+ const header = [
41
+ "<task_agenda>",
42
+ "Your in-flight tasks for this channel (background reference, not a new instruction).",
43
+ "Act on these only if the user's message is about them, or if there is nothing else to",
44
+ "do this turn. Full detail lives in the matching tasks/<id>.md file.",
45
+ "",
46
+ ];
47
+ const lines = shown.map((entry) => renderLine(entry, now));
48
+ if (omitted > 0)
49
+ lines.push(`- (+${omitted} more)`);
50
+ const footer = ["</task_agenda>"];
51
+ let rendered = [...header, ...lines, ...footer].join("\n");
52
+ if (rendered.length <= options.maxChars)
53
+ return rendered;
54
+ // Over budget: drop lines from the end until it fits, keeping actionable-first order.
55
+ const kept = [];
56
+ for (const line of lines) {
57
+ const candidate = [...header, ...kept, line, `- (+${agenda.length - kept.length - 1} more)`, ...footer].join("\n");
58
+ if (candidate.length > options.maxChars && kept.length > 0)
59
+ break;
60
+ kept.push(line);
61
+ }
62
+ const droppedCount = agenda.length - kept.length;
63
+ const tail = droppedCount > 0 ? [`- (+${droppedCount} more)`] : [];
64
+ rendered = [...header, ...kept, ...tail, ...footer].join("\n");
65
+ return rendered;
66
+ }
@@ -15,12 +15,13 @@ import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
15
15
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
16
16
  import { getUsageLedger } from "../usage/ledger.js";
17
17
  import { parseUsageMode, renderUsageReport } from "../usage/render.js";
18
- import { ensureChannelDir } from "./channel-paths.js";
18
+ import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
19
19
  import { createDingTalkContext } from "./delivery.js";
20
20
  import { DingTalkBot, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, } from "./dingtalk.js";
21
21
  import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
22
22
  import { createEventsWatcher } from "./events.js";
23
23
  import { ChannelStore } from "./store.js";
24
+ import { handleTasksCommand as runTasksCommand } from "./task-commands.js";
24
25
  const DEFAULT_SOUL = `# SOUL.md
25
26
 
26
27
  Configure Pipiclaw's identity, voice, and communication style here.
@@ -466,6 +467,13 @@ export function createRuntimeContext(options) {
466
467
  });
467
468
  await bot.sendPlain(event.channelId, response);
468
469
  },
470
+ async handleTasksCommand(event, bot, args) {
471
+ const response = await runTasksCommand({
472
+ args,
473
+ channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
474
+ });
475
+ await bot.sendPlain(event.channelId, response);
476
+ },
469
477
  async handleStatusCommand(event, bot) {
470
478
  const response = renderStatus({
471
479
  state: channelStates.get(event.channelId),
@@ -555,6 +563,10 @@ export function createRuntimeContext(options) {
555
563
  await handler.handleEventsCommand(event, bot, builtInCommand.args);
556
564
  return;
557
565
  }
566
+ if (builtInCommand.name === "tasks") {
567
+ await handler.handleTasksCommand(event, bot, builtInCommand.args);
568
+ return;
569
+ }
558
570
  if (builtInCommand.name === "status") {
559
571
  await handler.handleStatusCommand(event, bot);
560
572
  return;
@@ -41,6 +41,7 @@ export interface DingTalkHandler {
41
41
  handleEvent(event: DingTalkEvent, bot: DingTalkBot, isEvent?: boolean): Promise<void>;
42
42
  handleStop(channelId: string, bot: DingTalkBot): Promise<void>;
43
43
  handleEventsCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
44
+ handleTasksCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
44
45
  handleStatusCommand(event: DingTalkEvent, bot: DingTalkBot): Promise<void>;
45
46
  handleUsageCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
46
47
  handleBusyMessage(event: DingTalkEvent, bot: DingTalkBot, mode: BusyMessageMode, queueText: string): Promise<BusyMessageResult>;
@@ -990,6 +990,10 @@ export class DingTalkBot {
990
990
  await this.handler.handleEventsCommand(event, this, builtInCommand.args);
991
991
  return;
992
992
  }
993
+ if (builtInCommand?.name === "tasks") {
994
+ await this.handler.handleTasksCommand(event, this, builtInCommand.args);
995
+ return;
996
+ }
993
997
  if (builtInCommand?.name === "status") {
994
998
  await this.handler.handleStatusCommand(event, this);
995
999
  return;
@@ -999,11 +1003,11 @@ export class DingTalkBot {
999
1003
  return;
1000
1004
  }
1001
1005
  if (builtInCommand) {
1002
- await this.sendPlain(channelId, `A task is already running. Use \`/stop\`, \`/steer <message>\`, \`/followup <message>\`, \`/events <action>\`, \`/status\`, or \`/usage\`. Plain messages default to ${this.busyMessageDefault}.`);
1006
+ await this.sendPlain(channelId, `A task is already running. Use \`/stop\`, \`/steer <message>\`, \`/followup <message>\`, \`/events <action>\`, \`/tasks\`, \`/status\`, or \`/usage\`. Plain messages default to ${this.busyMessageDefault}.`);
1003
1007
  return;
1004
1008
  }
1005
1009
  if (isSlashCommand) {
1006
- await this.sendPlain(channelId, "A task is already running. Only `/stop`, `/steer <message>`, `/followup <message>`, and `/events <action>` are available while streaming.");
1010
+ await this.sendPlain(channelId, "A task is already running. Only `/stop`, `/steer <message>`, `/followup <message>`, `/events <action>`, and `/tasks` are available while streaming.");
1007
1011
  return;
1008
1012
  }
1009
1013
  const result = await this.handler.handleBusyMessage(event, this, this.busyMessageDefault, content);
@@ -3,4 +3,9 @@ export interface HandleEventsCommandOptions {
3
3
  workspaceDir: string;
4
4
  historyPath: string;
5
5
  }
6
+ export declare function normalizeEventName(name: string): string;
7
+ export declare function resolveEventPath(workspaceDir: string, name: string): {
8
+ eventName: string;
9
+ eventPath: string;
10
+ };
6
11
  export declare function handleEventsCommand(options: HandleEventsCommandOptions): Promise<string>;
@@ -45,7 +45,7 @@ function parseEventsCommand(args) {
45
45
  function eventsDir(workspaceDir) {
46
46
  return join(workspaceDir, "events");
47
47
  }
48
- function normalizeEventName(name) {
48
+ export function normalizeEventName(name) {
49
49
  const trimmed = name.trim();
50
50
  const normalized = trimmed.endsWith(".json") ? trimmed.slice(0, -".json".length) : trimmed;
51
51
  if (!normalized || normalized === "." || normalized === ".." || !EVENT_NAME_PATTERN.test(normalized)) {
@@ -53,7 +53,7 @@ function normalizeEventName(name) {
53
53
  }
54
54
  return normalized;
55
55
  }
56
- function resolveEventPath(workspaceDir, name) {
56
+ export function resolveEventPath(workspaceDir, name) {
57
57
  const eventName = normalizeEventName(name);
58
58
  const dir = resolve(eventsDir(workspaceDir));
59
59
  const eventPath = resolve(dir, `${eventName}.json`);
@@ -0,0 +1,6 @@
1
+ export interface HandleTasksCommandOptions {
2
+ args: string;
3
+ /** The channel directory; tasks live in `<channelDir>/tasks/`. */
4
+ channelDir: string;
5
+ }
6
+ export declare function handleTasksCommand(options: HandleTasksCommandOptions): Promise<string>;
@@ -0,0 +1,133 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readdir, readFile } from "node:fs/promises";
3
+ import { join, resolve, sep } from "node:path";
4
+ import { extractTaskTitle, normalizeTaskId, readActiveTasks } from "../shared/task-ledger.js";
5
+ function usage() {
6
+ return `# Tasks
7
+
8
+ Usage:
9
+
10
+ - \`/tasks\` — list active tasks in this channel
11
+ - \`/tasks show <id>\` — show a single task file (active or archived)
12
+ - \`/tasks archive\` — list archived (closed) tasks`;
13
+ }
14
+ function parseTasksCommand(args) {
15
+ const parts = args.trim().split(/\s+/).filter(Boolean);
16
+ const action = parts[0];
17
+ if (!action || action === "list") {
18
+ if (parts.length > 1)
19
+ throw new Error("Usage: /tasks list");
20
+ return { action: "list" };
21
+ }
22
+ if (action === "show") {
23
+ const id = parts[1];
24
+ if (!id || parts.length > 2)
25
+ throw new Error("Usage: /tasks show <id>");
26
+ return { action: "show", id };
27
+ }
28
+ if (action === "archive") {
29
+ if (parts.length > 1)
30
+ throw new Error("Usage: /tasks archive");
31
+ return { action: "archive" };
32
+ }
33
+ throw new Error(`Unknown /tasks action: ${action}`);
34
+ }
35
+ function tasksDir(channelDir) {
36
+ return join(channelDir, "tasks");
37
+ }
38
+ /** Resolve `<tasksDir>/[archive/]<id>.md`, rejecting any path that escapes the tasks dir. */
39
+ function resolveTaskPath(dir, id, subdir) {
40
+ const base = resolve(dir);
41
+ const target = resolve(base, subdir ?? "", `${id}.md`);
42
+ const expected = subdir ? join(base, subdir, `${id}.md`) : join(base, `${id}.md`);
43
+ if (target !== expected || !target.startsWith(`${base}${sep}`)) {
44
+ throw new Error(`Invalid task id: ${id}`);
45
+ }
46
+ return target;
47
+ }
48
+ function relativeWake(wakeMs, now) {
49
+ if (wakeMs === undefined)
50
+ return "—";
51
+ const iso = new Date(wakeMs).toISOString();
52
+ const diffMs = wakeMs - now;
53
+ if (diffMs <= 0)
54
+ return `${iso} (due)`;
55
+ const minutes = Math.round(diffMs / 60000);
56
+ const rel = minutes < 60 ? `${minutes}m` : minutes < 1440 ? `${Math.round(minutes / 60)}h` : `${Math.round(minutes / 1440)}d`;
57
+ return `${iso} (${rel})`;
58
+ }
59
+ async function listTasks(channelDir) {
60
+ const dir = tasksDir(channelDir);
61
+ const now = Date.now();
62
+ const entries = await readActiveTasks(dir, now);
63
+ if (entries.length === 0) {
64
+ return "# Tasks\n\nNo active tasks.";
65
+ }
66
+ const blocks = entries.map((entry) => {
67
+ const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "open") : "⚠ unreadable frontmatter";
68
+ const detail = [` status: ${status}`, `wake: ${relativeWake(entry.wakeMs, now)}`];
69
+ if (entry.frontmatter.recurrence)
70
+ detail.push(`recurrence: ${entry.frontmatter.recurrence}`);
71
+ return `- ${entry.id} — ${entry.title}\n${detail.join(" ")}`;
72
+ });
73
+ return `# Tasks: ${entries.length} active\n\n${blocks.join("\n")}`;
74
+ }
75
+ async function showTask(channelDir, id) {
76
+ const dir = tasksDir(channelDir);
77
+ const taskId = normalizeTaskId(id);
78
+ const activePath = resolveTaskPath(dir, taskId);
79
+ const archivePath = resolveTaskPath(dir, taskId, "archive");
80
+ const path = existsSync(activePath) ? activePath : existsSync(archivePath) ? archivePath : undefined;
81
+ if (!path) {
82
+ return `Task not found: ${taskId}`;
83
+ }
84
+ const location = path === archivePath ? " (archived)" : "";
85
+ const content = await readFile(path, "utf-8");
86
+ return `# Task: ${taskId}${location}\n\n\`\`\`markdown\n${content}\n\`\`\``;
87
+ }
88
+ async function listArchive(channelDir) {
89
+ const dir = join(tasksDir(channelDir), "archive");
90
+ if (!existsSync(dir)) {
91
+ return "# Archived Tasks\n\nNo archived tasks.";
92
+ }
93
+ const filenames = (await readdir(dir)).filter((filename) => filename.endsWith(".md")).sort();
94
+ if (filenames.length === 0) {
95
+ return "# Archived Tasks\n\nNo archived tasks.";
96
+ }
97
+ const blocks = [];
98
+ for (const filename of filenames) {
99
+ const id = filename.slice(0, -".md".length);
100
+ try {
101
+ const content = await readFile(join(dir, filename), "utf-8");
102
+ blocks.push(`- ${id} — ${extractTaskTitle(content, id)}`);
103
+ }
104
+ catch {
105
+ blocks.push(`- ${id}`);
106
+ }
107
+ }
108
+ return `# Archived Tasks: ${blocks.length}\n\n${blocks.join("\n")}`;
109
+ }
110
+ export async function handleTasksCommand(options) {
111
+ let command;
112
+ try {
113
+ command = parseTasksCommand(options.args);
114
+ }
115
+ catch (error) {
116
+ const message = error instanceof Error ? error.message : String(error);
117
+ return `${message}\n\n${usage()}`;
118
+ }
119
+ try {
120
+ switch (command.action) {
121
+ case "list":
122
+ return await listTasks(options.channelDir);
123
+ case "show":
124
+ return await showTask(options.channelDir, command.id);
125
+ case "archive":
126
+ return await listArchive(options.channelDir);
127
+ }
128
+ }
129
+ catch (error) {
130
+ const message = error instanceof Error ? error.message : String(error);
131
+ return `Could not ${command.action} tasks: ${message}`;
132
+ }
133
+ }
@@ -60,6 +60,11 @@ export interface PipiclawMemoryRecallSettings {
60
60
  maxChars: number;
61
61
  rerankWithModel: boolean | "auto";
62
62
  }
63
+ export interface PipiclawTaskDigestSettings {
64
+ enabled: boolean;
65
+ maxTasks: number;
66
+ maxChars: number;
67
+ }
63
68
  export interface PipiclawSessionMemorySettings {
64
69
  enabled: boolean;
65
70
  minTurnsBetweenUpdate: number;
@@ -118,6 +123,7 @@ export interface PipiclawSettings {
118
123
  compaction?: Partial<PipiclawCompactionSettings>;
119
124
  retry?: Partial<PipiclawRetrySettings>;
120
125
  memoryRecall?: Partial<PipiclawMemoryRecallSettings>;
126
+ taskDigest?: Partial<PipiclawTaskDigestSettings>;
121
127
  sessionMemory?: Partial<PipiclawSessionMemorySettings>;
122
128
  memoryGrowth?: Partial<PipiclawMemoryGrowthSettings>;
123
129
  memoryMaintenance?: Partial<PipiclawMemoryMaintenanceSettings>;
@@ -156,6 +162,7 @@ export declare class PipiclawSettingsManager {
156
162
  setCompactionEnabled(enabled: boolean): void;
157
163
  getRetrySettings(): PipiclawRetrySettings;
158
164
  getMemoryRecallSettings(): PipiclawMemoryRecallSettings;
165
+ getTaskDigestSettings(): PipiclawTaskDigestSettings;
159
166
  getSessionMemorySettings(): PipiclawSessionMemorySettings;
160
167
  getMemoryGrowthSettings(): PipiclawMemoryGrowthSettings;
161
168
  getMemoryMaintenanceSettings(): PipiclawMemoryMaintenanceSettings;
package/dist/settings.js CHANGED
@@ -29,6 +29,13 @@ const DEFAULT_MEMORY_RECALL = {
29
29
  maxChars: 5000,
30
30
  rerankWithModel: "auto",
31
31
  };
32
+ // Cheap and high-value: reading a handful of task frontmatters and always surfacing
33
+ // the in-flight agenda is worth more than the tokens it costs, so it defaults on.
34
+ const DEFAULT_TASK_DIGEST = {
35
+ enabled: true,
36
+ maxTasks: 8,
37
+ maxChars: 1000,
38
+ };
32
39
  const DEFAULT_SESSION_MEMORY = {
33
40
  enabled: true,
34
41
  minTurnsBetweenUpdate: 2,
@@ -167,6 +174,12 @@ export class PipiclawSettingsManager {
167
174
  ...this.settings.memoryRecall,
168
175
  };
169
176
  }
177
+ getTaskDigestSettings() {
178
+ return {
179
+ ...DEFAULT_TASK_DIGEST,
180
+ ...this.settings.taskDigest,
181
+ };
182
+ }
170
183
  getSessionMemorySettings() {
171
184
  return {
172
185
  ...DEFAULT_SESSION_MEMORY,
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Shared reader for the task ledger (`workspace/<channelId>/tasks/*.md`).
3
+ *
4
+ * This is the in-repo half of the frontmatter contract documented in `docs/tasks.md`
5
+ * ("Frontmatter 契约(单一事实源)"). The heartbeat sensor `tasks-pending.mjs` is the
6
+ * out-of-repo half (a dependency-free script in workspace/skills). Both MUST agree on
7
+ * `actionable`, so the parsing here is a deliberate, literal mirror of that script:
8
+ * three flat `key: value` fields, done-vs-not-done, wake gating, fail-open on unreadable
9
+ * frontmatter. `/tasks`, the task digest, and `task_manage list` all read through here.
10
+ */
11
+ export interface TaskFrontmatter {
12
+ /** false => frontmatter could not be read (fail-open: the task is treated as actionable). */
13
+ readable: boolean;
14
+ status?: string;
15
+ wake?: string;
16
+ recurrence?: string;
17
+ }
18
+ export interface TaskLedgerEntry {
19
+ /** Filename without `.md`; the task id. */
20
+ id: string;
21
+ /** First `# ` heading in the body, or the id when none. */
22
+ title: string;
23
+ frontmatter: TaskFrontmatter;
24
+ /** status ≠ done AND (no valid wake OR wake ≤ now). Matches the sensor exactly. */
25
+ actionable: boolean;
26
+ /** Milliseconds since epoch parsed from `wake`, or undefined when unset/unparseable. */
27
+ wakeMs?: number;
28
+ /** First bullet/line under a "当前周期"/"current cycle" heading, if any (digest only). */
29
+ latestNote?: string;
30
+ }
31
+ /** Validate/normalize a task id (filename without `.md`), rejecting path traversal. */
32
+ export declare function normalizeTaskId(id: string): string;
33
+ /** The document body after the leading frontmatter block, or the whole content when there is none. */
34
+ export declare function taskBody(content: string): string;
35
+ /** Parse the leading `---` frontmatter block into the three known fields. */
36
+ export declare function parseTaskFrontmatter(content: string): TaskFrontmatter;
37
+ /**
38
+ * The single shared judgement: is there work to do on this task right now?
39
+ * Unreadable frontmatter is fail-open (actionable) so a corrupt ledger surfaces
40
+ * rather than being silently skipped — identical to the sensor's behaviour.
41
+ */
42
+ export declare function isTaskActionable(frontmatter: TaskFrontmatter, now: number): boolean;
43
+ /** First `# ` heading after the frontmatter block, or the id when there is none. */
44
+ export declare function extractTaskTitle(content: string, fallbackId: string): string;
45
+ /** Actionable first; then earliest wake first (unset wake sorts as "ready now"); then id. */
46
+ export declare function compareTaskEntries(a: TaskLedgerEntry, b: TaskLedgerEntry): number;
47
+ /**
48
+ * Read every `.md` file in `tasks/` (root only — the `archive/` subdirectory is not
49
+ * scanned), returning entries sorted actionable-first. A file that cannot be read is
50
+ * still returned (fail-open: `readable: false`, `actionable: true`) so problems surface.
51
+ * Missing directory → empty list.
52
+ */
53
+ export declare function readActiveTasks(tasksDir: string, now?: number): Promise<TaskLedgerEntry[]>;
@@ -0,0 +1,149 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ const FRONTMATTER_FIELDS = ["status", "wake", "recurrence"];
4
+ const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
5
+ /** Validate/normalize a task id (filename without `.md`), rejecting path traversal. */
6
+ export function normalizeTaskId(id) {
7
+ const trimmed = id.trim();
8
+ const normalized = trimmed.endsWith(".md") ? trimmed.slice(0, -".md".length) : trimmed;
9
+ if (!normalized || normalized === "." || normalized === ".." || !TASK_ID_PATTERN.test(normalized)) {
10
+ throw new Error(`Invalid task id: ${id}`);
11
+ }
12
+ return normalized;
13
+ }
14
+ /** The document body after the leading frontmatter block, or the whole content when there is none. */
15
+ export function taskBody(content) {
16
+ if (!content.startsWith("---"))
17
+ return content;
18
+ const end = content.indexOf("\n---", 3);
19
+ if (end === -1)
20
+ return content;
21
+ const after = content.indexOf("\n", end + 1);
22
+ return after === -1 ? "" : content.slice(after + 1);
23
+ }
24
+ /** Parse the leading `---` frontmatter block into the three known fields. */
25
+ export function parseTaskFrontmatter(content) {
26
+ if (!content.startsWith("---"))
27
+ return { readable: false };
28
+ const end = content.indexOf("\n---", 3);
29
+ if (end === -1)
30
+ return { readable: false };
31
+ const block = content.slice(3, end);
32
+ const frontmatter = { readable: true };
33
+ for (const line of block.split("\n")) {
34
+ const idx = line.indexOf(":");
35
+ if (idx === -1)
36
+ continue;
37
+ const key = line.slice(0, idx).trim();
38
+ if (FRONTMATTER_FIELDS.includes(key)) {
39
+ const value = line.slice(idx + 1).trim();
40
+ frontmatter[key] = value || undefined;
41
+ }
42
+ }
43
+ return frontmatter;
44
+ }
45
+ /**
46
+ * The single shared judgement: is there work to do on this task right now?
47
+ * Unreadable frontmatter is fail-open (actionable) so a corrupt ledger surfaces
48
+ * rather than being silently skipped — identical to the sensor's behaviour.
49
+ */
50
+ export function isTaskActionable(frontmatter, now) {
51
+ if (!frontmatter.readable)
52
+ return true;
53
+ if (frontmatter.status === "done")
54
+ return false;
55
+ if (frontmatter.wake) {
56
+ const wakeAt = new Date(frontmatter.wake).getTime();
57
+ if (Number.isFinite(wakeAt) && wakeAt > now)
58
+ return false;
59
+ }
60
+ return true;
61
+ }
62
+ /** First `# ` heading after the frontmatter block, or the id when there is none. */
63
+ export function extractTaskTitle(content, fallbackId) {
64
+ for (const line of taskBody(content).split("\n")) {
65
+ const match = /^#\s+(.+?)\s*$/.exec(line);
66
+ if (match)
67
+ return match[1];
68
+ }
69
+ return fallbackId;
70
+ }
71
+ /** First non-empty bullet/line under a "当前周期"/"current cycle" heading. */
72
+ function extractLatestNote(content) {
73
+ const lines = content.split("\n");
74
+ let inSection = false;
75
+ for (const line of lines) {
76
+ if (/^#{1,6}\s/.test(line)) {
77
+ inSection = /当前周期|current cycle/i.test(line);
78
+ continue;
79
+ }
80
+ if (!inSection)
81
+ continue;
82
+ const trimmed = line.replace(/^\s*[-*]\s+/, "").trim();
83
+ if (trimmed)
84
+ return trimmed;
85
+ }
86
+ return undefined;
87
+ }
88
+ function wakeMsOf(frontmatter) {
89
+ if (!frontmatter.wake)
90
+ return undefined;
91
+ const at = new Date(frontmatter.wake).getTime();
92
+ return Number.isFinite(at) ? at : undefined;
93
+ }
94
+ /** Actionable first; then earliest wake first (unset wake sorts as "ready now"); then id. */
95
+ export function compareTaskEntries(a, b) {
96
+ if (a.actionable !== b.actionable)
97
+ return a.actionable ? -1 : 1;
98
+ const aw = a.wakeMs ?? Number.NEGATIVE_INFINITY;
99
+ const bw = b.wakeMs ?? Number.NEGATIVE_INFINITY;
100
+ if (aw !== bw)
101
+ return aw - bw;
102
+ return a.id.localeCompare(b.id);
103
+ }
104
+ function toEntry(id, content, now) {
105
+ const frontmatter = parseTaskFrontmatter(content);
106
+ return {
107
+ id,
108
+ title: extractTaskTitle(content, id),
109
+ frontmatter,
110
+ actionable: isTaskActionable(frontmatter, now),
111
+ wakeMs: wakeMsOf(frontmatter),
112
+ latestNote: extractLatestNote(content),
113
+ };
114
+ }
115
+ /**
116
+ * Read every `.md` file in `tasks/` (root only — the `archive/` subdirectory is not
117
+ * scanned), returning entries sorted actionable-first. A file that cannot be read is
118
+ * still returned (fail-open: `readable: false`, `actionable: true`) so problems surface.
119
+ * Missing directory → empty list.
120
+ */
121
+ export async function readActiveTasks(tasksDir, now = Date.now()) {
122
+ let dirents;
123
+ try {
124
+ dirents = await readdir(tasksDir, { withFileTypes: true });
125
+ }
126
+ catch {
127
+ return [];
128
+ }
129
+ const entries = [];
130
+ for (const dirent of dirents) {
131
+ if (!dirent.isFile() || !dirent.name.endsWith(".md"))
132
+ continue;
133
+ const id = dirent.name.slice(0, -".md".length);
134
+ try {
135
+ const content = await readFile(join(tasksDir, dirent.name), "utf-8");
136
+ entries.push(toEntry(id, content, now));
137
+ }
138
+ catch {
139
+ entries.push({
140
+ id,
141
+ title: id,
142
+ frontmatter: { readable: false },
143
+ actionable: true,
144
+ });
145
+ }
146
+ }
147
+ entries.sort(compareTaskEntries);
148
+ return entries;
149
+ }