@oyasmi/pipiclaw 0.9.3-beta.5 → 0.9.3-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/agent/channel-runner.d.ts +4 -8
  4. package/dist/agent/channel-runner.js +14 -34
  5. package/dist/agent/job-manager.d.ts +12 -0
  6. package/dist/agent/job-manager.js +42 -1
  7. package/dist/agent/prompt/sections.js +2 -2
  8. package/dist/agent/runner-factory.d.ts +2 -2
  9. package/dist/agent/types.d.ts +11 -7
  10. package/dist/channel/project-scope-store.d.ts +20 -0
  11. package/dist/channel/project-scope-store.js +22 -7
  12. package/dist/commands/catalog.js +6 -12
  13. package/dist/events/event-commands.js +2 -2
  14. package/dist/events/events.d.ts +51 -30
  15. package/dist/events/events.js +70 -98
  16. package/dist/memory/journal.d.ts +2 -3
  17. package/dist/memory/journal.js +2 -3
  18. package/dist/memory/maintenance-tuning.d.ts +0 -1
  19. package/dist/memory/maintenance-tuning.js +0 -1
  20. package/dist/memory/scheduler.js +8 -16
  21. package/dist/memory/search.js +2 -3
  22. package/dist/memory/session-search.js +3 -9
  23. package/dist/memory/store.d.ts +1 -1
  24. package/dist/memory/store.js +9 -1
  25. package/dist/memory/task-digest.js +10 -11
  26. package/dist/memory/tombstones.js +2 -4
  27. package/dist/models/provider-login.d.ts +1 -1
  28. package/dist/models/provider-login.js +1 -1
  29. package/dist/playbooks/agent-delegation.md +6 -6
  30. package/dist/playbooks/background-jobs.md +1 -1
  31. package/dist/playbooks/event-scheduling.md +22 -13
  32. package/dist/playbooks/memory-and-learning.md +2 -2
  33. package/dist/playbooks/outbound-media.md +1 -1
  34. package/dist/playbooks/runtime-orientation.md +3 -3
  35. package/dist/playbooks/task-lead.md +82 -0
  36. package/dist/runtime/bootstrap.js +95 -187
  37. package/dist/runtime/durable-dispatch.js +30 -3
  38. package/dist/runtime/report-commands.d.ts +30 -0
  39. package/dist/runtime/report-commands.js +71 -0
  40. package/dist/runtime/subagent-commands.js +1 -1
  41. package/dist/runtime/task-commands.d.ts +0 -8
  42. package/dist/runtime/task-commands.js +48 -85
  43. package/dist/runtime/task-driver.d.ts +13 -9
  44. package/dist/runtime/task-driver.js +34 -39
  45. package/dist/runtime/task-migration.d.ts +18 -29
  46. package/dist/runtime/task-migration.js +195 -183
  47. package/dist/runtime/task-spawn.d.ts +24 -0
  48. package/dist/runtime/task-spawn.js +49 -0
  49. package/dist/runtime/task-wake.d.ts +33 -46
  50. package/dist/runtime/task-wake.js +15 -90
  51. package/dist/security/network.js +44 -9
  52. package/dist/settings.d.ts +1 -8
  53. package/dist/settings.js +1 -8
  54. package/dist/subagents/discovery.js +3 -15
  55. package/dist/subagents/external/run.d.ts +3 -1
  56. package/dist/subagents/external/run.js +2 -20
  57. package/dist/subagents/external/settlement.d.ts +4 -16
  58. package/dist/subagents/external/settlement.js +16 -67
  59. package/dist/subagents/runs.d.ts +15 -29
  60. package/dist/subagents/runs.js +70 -158
  61. package/dist/subagents/tool.d.ts +20 -4
  62. package/dist/subagents/tool.js +63 -87
  63. package/dist/subagents/verification-outcome.d.ts +13 -19
  64. package/dist/subagents/verification-outcome.js +8 -22
  65. package/dist/subagents/workspace-summary.d.ts +8 -0
  66. package/dist/subagents/workspace-summary.js +29 -0
  67. package/dist/tasks/board.d.ts +43 -0
  68. package/dist/tasks/board.js +134 -0
  69. package/dist/tasks/brief.d.ts +10 -5
  70. package/dist/tasks/brief.js +78 -26
  71. package/dist/tasks/budget.d.ts +13 -14
  72. package/dist/tasks/budget.js +21 -40
  73. package/dist/tasks/contract-input.d.ts +19 -0
  74. package/dist/tasks/contract-input.js +55 -0
  75. package/dist/tasks/create.d.ts +17 -0
  76. package/dist/tasks/create.js +36 -0
  77. package/dist/tasks/frontmatter.d.ts +20 -27
  78. package/dist/tasks/frontmatter.js +18 -31
  79. package/dist/tasks/ledger.d.ts +61 -117
  80. package/dist/tasks/ledger.js +78 -223
  81. package/dist/tasks/log.d.ts +62 -35
  82. package/dist/tasks/log.js +51 -29
  83. package/dist/tasks/session-path.d.ts +3 -3
  84. package/dist/tasks/session-path.js +4 -5
  85. package/dist/tasks/store.d.ts +11 -29
  86. package/dist/tasks/store.js +39 -83
  87. package/dist/tasks/ticket.d.ts +33 -66
  88. package/dist/tasks/ticket.js +31 -120
  89. package/dist/tasks/work-log.d.ts +20 -0
  90. package/dist/tasks/work-log.js +42 -0
  91. package/dist/tools/bash.d.ts +1 -1
  92. package/dist/tools/bash.js +1 -1
  93. package/dist/tools/event-manage.d.ts +16 -2
  94. package/dist/tools/event-manage.js +30 -12
  95. package/dist/tools/index.d.ts +5 -3
  96. package/dist/tools/index.js +5 -5
  97. package/dist/tools/registry.d.ts +6 -4
  98. package/dist/tools/registry.js +1 -4
  99. package/dist/tools/subagent-manage.js +4 -2
  100. package/dist/tools/task-manage/create.js +11 -27
  101. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  102. package/dist/tools/task-manage/lifecycle.js +23 -106
  103. package/dist/tools/task-manage/log-view.d.ts +3 -2
  104. package/dist/tools/task-manage/log-view.js +6 -6
  105. package/dist/tools/task-manage/schema.d.ts +10 -30
  106. package/dist/tools/task-manage/schema.js +33 -49
  107. package/dist/tools/task-manage/shared.d.ts +35 -42
  108. package/dist/tools/task-manage/shared.js +53 -192
  109. package/dist/tools/task-manage/step-end.d.ts +6 -6
  110. package/dist/tools/task-manage/step-end.js +61 -98
  111. package/dist/tools/task-manage/types.d.ts +8 -9
  112. package/dist/tools/task-manage.js +5 -5
  113. package/dist/tui/app.js +11 -38
  114. package/dist/tui/commands.d.ts +18 -8
  115. package/dist/tui/commands.js +2 -9
  116. package/dist/tui/turn-controller.d.ts +2 -14
  117. package/dist/tui/turn-controller.js +1 -17
  118. package/dist/web/client.js +9 -1
  119. package/examples/sub-agents/README.md +7 -4
  120. package/examples/sub-agents/agents/codex-flash.md +2 -2
  121. package/examples/sub-agents/agents/codex-high.md +1 -1
  122. package/examples/sub-agents/agents/codex-main.md +1 -1
  123. package/examples/sub-agents/agents/codex-review.md +23 -0
  124. package/examples/sub-agents/roles/verifier.md +1 -1
  125. package/package.json +1 -1
  126. package/dist/memory/maintenance-migration.d.ts +0 -5
  127. package/dist/memory/maintenance-migration.js +0 -91
  128. package/dist/memory/migrate.d.ts +0 -15
  129. package/dist/memory/migrate.js +0 -364
  130. package/dist/playbooks/task-loop.md +0 -90
  131. package/dist/tasks/artifact-subject.d.ts +0 -40
  132. package/dist/tasks/artifact-subject.js +0 -334
  133. package/dist/tasks/cycle.d.ts +0 -48
  134. package/dist/tasks/cycle.js +0 -94
  135. package/dist/tasks/rounds.d.ts +0 -41
  136. package/dist/tasks/rounds.js +0 -53
  137. package/dist/tasks/task-events.d.ts +0 -6
  138. package/dist/tasks/task-events.js +0 -14
  139. package/dist/tasks/task-schedule.d.ts +0 -18
  140. package/dist/tasks/task-schedule.js +0 -50
  141. package/dist/tasks/verification.d.ts +0 -114
  142. package/dist/tasks/verification.js +0 -226
@@ -2,29 +2,30 @@ import type { ChannelEvent } from "../channel/channel-event.js";
2
2
  import type { Executor } from "../executor.js";
3
3
  import type { DingTalkBot } from "../runtime/dingtalk.js";
4
4
  import type { SecurityConfig } from "../security/types.js";
5
+ import { type TaskCreateInput } from "../tasks/contract-input.js";
5
6
  export interface EventAction {
6
7
  type: "bash";
7
8
  command: string;
8
9
  timeout?: number;
9
10
  }
10
- export interface OneShotEvent {
11
+ /**
12
+ * What an event delivers when it fires: a chat `text`, or a `task` template that spawns a fresh
13
+ * task instance (spec 052, D2). Exactly one is present — `parseScheduledEventContent` enforces it.
14
+ */
15
+ interface EventPayload {
16
+ text?: string;
17
+ task?: TaskCreateInput;
18
+ }
19
+ export interface OneShotEvent extends EventPayload {
11
20
  type: "one-shot";
12
21
  channelId: string;
13
- text: string;
14
22
  at: string;
15
23
  preAction?: EventAction;
16
24
  }
17
- export interface PeriodicEvent {
25
+ export interface PeriodicEvent extends EventPayload {
18
26
  type: "periodic";
19
27
  channelId: string;
20
- text: string;
21
28
  schedule: string;
22
- /**
23
- * Legacy field only. Pre-027 events carried an IANA `timezone`; it is no longer part of
24
- * the contract (cron follows the host timezone) but is preserved here on load so the
25
- * watcher can warn when it disagrees with the host, without rejecting or rewriting the file.
26
- */
27
- legacyTimezone?: string;
28
29
  preAction?: EventAction;
29
30
  }
30
31
  export type ScheduledEvent = OneShotEvent | PeriodicEvent;
@@ -54,11 +55,43 @@ export interface EventHistoryRecord {
54
55
  accepted: boolean;
55
56
  };
56
57
  }
58
+ /** One occurrence of a template event asking for a task instance (spec 052, D2). */
59
+ export interface SpawnTaskRequest {
60
+ /** The event's name (filename without `.json`); becomes the instance's `origin`. */
61
+ eventName: string;
62
+ channelId: string;
63
+ template: TaskCreateInput;
64
+ /** The moment this occurrence was due — deterministic per occurrence, so a replay maps to the same instance. */
65
+ occurrence: Date;
66
+ }
67
+ export type SpawnTaskResult =
68
+ /** A new instance was created. */
69
+ {
70
+ outcome: "spawned";
71
+ id: string;
72
+ }
73
+ /** This occurrence's instance already exists: an idempotent replay. */
74
+ | {
75
+ outcome: "exists";
76
+ id: string;
77
+ }
78
+ /** Another instance of the same event is still running; the user was told. */
79
+ | {
80
+ outcome: "skipped";
81
+ id: string;
82
+ };
57
83
  export interface EventsWatcherOptions {
58
84
  historyPath?: string;
85
+ /**
86
+ * Creates the task instance a template event asks for. Injected by the runtime so the events
87
+ * subsystem never reads or writes task files (spec 052, INV-8).
88
+ */
89
+ spawnTask?: (request: SpawnTaskRequest) => Promise<SpawnTaskResult>;
59
90
  /** Persist synthetic work before it enters the in-memory channel queue. */
60
91
  dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
61
92
  }
93
+ /** The one-line description of what an event delivers, for history records and listings. */
94
+ export declare function describeEventPayload(event: Pick<ScheduledEvent, "text" | "task">): string;
62
95
  export declare function parseScheduledEventContent(content: string, filename: string): ScheduledEvent;
63
96
  export declare class EventsWatcher {
64
97
  private eventsDir;
@@ -104,27 +137,14 @@ export declare class EventsWatcher {
104
137
  private wasWrittenAfterStart;
105
138
  private handleOneShot;
106
139
  private handlePeriodic;
140
+ private execute;
107
141
  /**
108
- * A task-owned event outlives its task whenever close-out fails or the task file is deleted
109
- * by hand, and then wakes the channel forever about work that no longer exists. Checking the
110
- * owner at trigger time turns that permanent noise into self-healing (spec 031, D5).
111
- *
112
- * The name alone is ambiguous (a channelId may contain dots, and so may a task id), so the
113
- * owning channel is taken from the event definition and the id is parsed with the same
114
- * last-dot rule the rest of the task-event code uses (`parseTaskEventName`), not a hand-rolled
115
- * split that would cut a dotted task id short.
116
- */
117
- private orphanedOwnerReason;
118
- /**
119
- * Redeem the owning task's `signal` ticket, if this is a task-owned event and that task is
120
- * parked on a ticket naming exactly this event. Returns whether the ticket was redeemed.
121
- *
122
- * The name match is strict (INV-7): a ticket only accepts the event it names, so an unrelated
123
- * task-owned event can never resume a task, and a task parked on anything else still gets its
124
- * ordinary chat wake.
142
+ * Deliver a template event: ask the runtime for a fresh task instance (spec 052, D2). The
143
+ * occurrence is the one this trigger was *due* for — a one-shot's `at`, a periodic's cron tick —
144
+ * so a post-restart replay of the same occurrence lands on the same instance instead of making a
145
+ * second one.
125
146
  */
126
- private redeemTaskSignal;
127
- private execute;
147
+ private spawnTaskInstance;
128
148
  private runPreAction;
129
149
  private deleteFile;
130
150
  private getInvalidMarkerPath;
@@ -135,4 +155,5 @@ export declare class EventsWatcher {
135
155
  /**
136
156
  * Create and start an events watcher.
137
157
  */
138
- export declare function createEventsWatcher(workspaceDir: string, bot: DingTalkBot, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"], historyPath?: string, dispatch?: EventsWatcherOptions["dispatch"]): EventsWatcher;
158
+ export declare function createEventsWatcher(workspaceDir: string, bot: DingTalkBot, executor: Executor, commandGuardConfig?: SecurityConfig["commandGuard"], historyPath?: string, dispatch?: EventsWatcherOptions["dispatch"], spawnTask?: EventsWatcherOptions["spawnTask"]): EventsWatcher;
159
+ export {};
@@ -2,7 +2,6 @@ import { Cron } from "croner";
2
2
  import { chmodSync, existsSync, mkdirSync, readdirSync, statSync, unlinkSync, watch, writeFileSync, } from "fs";
3
3
  import { readFile } from "fs/promises";
4
4
  import { dirname, join, resolve } from "path";
5
- import { getChannelDir } from "../channel/channel-paths.js";
6
5
  import * as log from "../log.js";
7
6
  import { guardCommand } from "../security/command-guard.js";
8
7
  import { writeFileAtomicallySync } from "../shared/atomic-file.js";
@@ -10,9 +9,7 @@ import { createJsonlAppender } from "../shared/jsonl-appender.js";
10
9
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
11
10
  import { clipText, errorMessage, eventNameFromFilename } from "../shared/text-utils.js";
12
11
  import { isPlainObject } from "../shared/type-guards.js";
13
- import { parseTaskFrontmatterV4 } from "../tasks/frontmatter.js";
14
- import { redeemTicket } from "../tasks/store.js";
15
- import { parseTaskEventName } from "../tasks/task-events.js";
12
+ import { validateTaskContractInput } from "../tasks/contract-input.js";
16
13
  import { MAX_EVENT_FILES, MAX_ONE_SHOT_DELAY_MS, validateScheduledEvent } from "./event-validation.js";
17
14
  // ============================================================================
18
15
  // EventsWatcher
@@ -23,16 +20,36 @@ const RETRY_BASE_MS = 100;
23
20
  const SCAN_CONCURRENCY = 4;
24
21
  const DEFAULT_PRE_ACTION_TIMEOUT_MS = 10_000;
25
22
  const TEXT_PREVIEW_MAX_CHARS = 160;
23
+ /** The one-line description of what an event delivers, for history records and listings. */
24
+ export function describeEventPayload(event) {
25
+ return event.task ? `任务模板:${event.task.title}` : (event.text ?? "");
26
+ }
26
27
  function truncateTextPreview(text) {
27
28
  return clipText(text, TEXT_PREVIEW_MAX_CHARS, { headRatio: 1, omitHint: "…", collapseWhitespace: true });
28
29
  }
29
30
  function readRequiredString(data, field, filename) {
30
31
  const value = data[field];
31
32
  if (typeof value !== "string" || value.trim().length === 0) {
32
- throw new Error(`Missing required fields (type, channelId, text) in ${filename}`);
33
+ throw new Error(`Missing required fields (type, channelId, and text or task) in ${filename}`);
33
34
  }
34
35
  return value;
35
36
  }
37
+ /** `text` xor `task`: a chat message, or a template for a task instance (spec 052, D2). */
38
+ function parsePayload(data, filename) {
39
+ const hasText = typeof data.text === "string" && data.text.trim().length > 0;
40
+ const hasTask = data.task !== undefined;
41
+ if (hasText === hasTask) {
42
+ throw new Error(`An event needs exactly one of 'text' (a chat message) or 'task' (a task template) in ${filename}`);
43
+ }
44
+ if (hasText)
45
+ return { text: data.text };
46
+ try {
47
+ return { task: validateTaskContractInput(data.task) };
48
+ }
49
+ catch (error) {
50
+ throw new Error(`Invalid 'task' template in ${filename}: ${errorMessage(error)}`);
51
+ }
52
+ }
36
53
  function parsePreAction(data, filename) {
37
54
  if (!data.preAction)
38
55
  return undefined;
@@ -60,11 +77,11 @@ function parsePreAction(data, filename) {
60
77
  export function parseScheduledEventContent(content, filename) {
61
78
  const data = JSON.parse(content);
62
79
  if (!isPlainObject(data)) {
63
- throw new Error(`Missing required fields (type, channelId, text) in ${filename}`);
80
+ throw new Error(`Missing required fields (type, channelId, and text or task) in ${filename}`);
64
81
  }
65
82
  const type = readRequiredString(data, "type", filename);
66
83
  const channelId = readRequiredString(data, "channelId", filename);
67
- const text = readRequiredString(data, "text", filename);
84
+ const payload = parsePayload(data, filename);
68
85
  const preAction = parsePreAction(data, filename);
69
86
  switch (type) {
70
87
  // Removed in spec 031 (D4): an event that fires the moment it is written is a
@@ -78,21 +95,17 @@ export function parseScheduledEventContent(content, filename) {
78
95
  if (typeof data.at !== "string" || data.at.trim().length === 0) {
79
96
  throw new Error(`Missing 'at' field for one-shot event in ${filename}`);
80
97
  }
81
- return { type, channelId, text, at: data.at, ...(preAction ? { preAction } : {}) };
98
+ return { type, channelId, ...payload, at: data.at, ...(preAction ? { preAction } : {}) };
82
99
  }
83
100
  case "periodic": {
84
101
  if (typeof data.schedule !== "string" || data.schedule.trim().length === 0) {
85
102
  throw new Error(`Missing 'schedule' field for periodic event in ${filename}`);
86
103
  }
87
- // A legacy `timezone` is tolerated (never a parse error) and carried through only for
88
- // the host-mismatch warning; the cron itself is always host-timezone.
89
- const legacyTimezone = typeof data.timezone === "string" && data.timezone.trim().length > 0 ? data.timezone : undefined;
90
104
  return {
91
105
  type,
92
106
  channelId,
93
- text,
107
+ ...payload,
94
108
  schedule: data.schedule,
95
- ...(legacyTimezone ? { legacyTimezone } : {}),
96
109
  ...(preAction ? { preAction } : {}),
97
110
  };
98
111
  }
@@ -220,7 +233,7 @@ export class EventsWatcher {
220
233
  channelId: event.channelId,
221
234
  action,
222
235
  result,
223
- textPreview: truncateTextPreview(event.text),
236
+ textPreview: truncateTextPreview(describeEventPayload(event)),
224
237
  ...(event.type === "one-shot" ? { at: event.at } : {}),
225
238
  ...(event.type === "periodic" ? { schedule: event.schedule } : {}),
226
239
  ...extra,
@@ -446,15 +459,6 @@ export class EventsWatcher {
446
459
  this.timers.set(filename, timer);
447
460
  }
448
461
  handlePeriodic(filename, event) {
449
- if (event.legacyTimezone) {
450
- const hostTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
451
- if (event.legacyTimezone !== hostTimezone) {
452
- log.logWarning(`Event ${filename} carries a legacy timezone ${event.legacyTimezone} that differs from the host ${hostTimezone}`, "The cron is now interpreted in the host timezone; trigger times may shift.");
453
- this.appendEventHistory(filename, event, "loaded", "ok", {
454
- reason: `legacy timezone ${event.legacyTimezone} ignored; using host ${hostTimezone}`,
455
- });
456
- }
457
- }
458
462
  try {
459
463
  const cron = new Cron(event.schedule, { protect: true, catch: true }, async () => {
460
464
  try {
@@ -483,69 +487,7 @@ export class EventsWatcher {
483
487
  this.markInvalid(filename, `Invalid cron schedule: ${event.schedule}\n${String(err)}`);
484
488
  }
485
489
  }
486
- /**
487
- * A task-owned event outlives its task whenever close-out fails or the task file is deleted
488
- * by hand, and then wakes the channel forever about work that no longer exists. Checking the
489
- * owner at trigger time turns that permanent noise into self-healing (spec 031, D5).
490
- *
491
- * The name alone is ambiguous (a channelId may contain dots, and so may a task id), so the
492
- * owning channel is taken from the event definition and the id is parsed with the same
493
- * last-dot rule the rest of the task-event code uses (`parseTaskEventName`), not a hand-rolled
494
- * split that would cut a dotted task id short.
495
- */
496
- async orphanedOwnerReason(filename, event) {
497
- const parsed = parseTaskEventName(eventNameFromFilename(filename), event.channelId);
498
- if (!parsed)
499
- return undefined;
500
- const taskId = parsed.id;
501
- const taskPath = join(getChannelDir(dirname(this.eventsDir), event.channelId), "tasks", `${taskId}.md`);
502
- let content;
503
- try {
504
- content = await readFile(taskPath, "utf-8");
505
- }
506
- catch {
507
- return `owning task ${taskId} no longer exists`;
508
- }
509
- const frontmatter = parseTaskFrontmatterV4(content);
510
- return frontmatter.fields.outcome
511
- ? `owning task ${taskId} is archived (${frontmatter.fields.outcome})`
512
- : undefined;
513
- }
514
- /**
515
- * Redeem the owning task's `signal` ticket, if this is a task-owned event and that task is
516
- * parked on a ticket naming exactly this event. Returns whether the ticket was redeemed.
517
- *
518
- * The name match is strict (INV-7): a ticket only accepts the event it names, so an unrelated
519
- * task-owned event can never resume a task, and a task parked on anything else still gets its
520
- * ordinary chat wake.
521
- */
522
- async redeemTaskSignal(filename, event) {
523
- const name = eventNameFromFilename(filename);
524
- const parsed = parseTaskEventName(name, event.channelId);
525
- if (!parsed)
526
- return false;
527
- const channelDir = getChannelDir(dirname(this.eventsDir), event.channelId);
528
- try {
529
- const redeemed = await redeemTicket(channelDir, parsed.id, (ticket) => ticket.kind === "signal" && ticket.event === name);
530
- if (!redeemed)
531
- return false;
532
- log.logInfo(`Event ${name} redeemed the signal ticket for task ${parsed.id}`);
533
- return true;
534
- }
535
- catch (error) {
536
- log.logWarning(`Could not redeem signal ticket for task ${parsed.id}`, errorMessage(error));
537
- return false;
538
- }
539
- }
540
490
  async execute(filename, event, deleteAfter = true, occurrence = new Date()) {
541
- const orphaned = await this.orphanedOwnerReason(filename, event);
542
- if (orphaned) {
543
- log.logInfo(`Retiring orphaned task event: ${filename} (${orphaned})`);
544
- this.appendEventHistory(filename, event, "skipped", "skipped", { reason: orphaned });
545
- this.cancelScheduled(filename);
546
- this.deleteFile(filename);
547
- return;
548
- }
549
491
  if (event.preAction) {
550
492
  try {
551
493
  this.appendEventHistory(filename, event, "pre_action_started", "ok", {
@@ -586,16 +528,8 @@ export class EventsWatcher {
586
528
  return;
587
529
  }
588
530
  }
589
- // Spec 051, D8: the *only* touchpoint between the events subsystem and the task loop. When a
590
- // task-owned sensor fires and the owning task is parked on a `signal` ticket naming this very
591
- // event, redeem the ticket and stop — the task's own loop takes it from here, and delivering
592
- // a chat wake as well would both duplicate the work and route it into the wrong session.
593
- // Anything else (an ordinary event, or a task that is not waiting on this signal) falls
594
- // through to the unchanged delivery path below.
595
- if (await this.redeemTaskSignal(filename, event)) {
596
- this.appendEventHistory(filename, event, "triggered", "ok", { reason: "redeemed task signal ticket" });
597
- if (deleteAfter)
598
- this.deleteFile(filename);
531
+ if (event.task) {
532
+ await this.spawnTaskInstance(filename, event, event.task, deleteAfter, occurrence);
599
533
  return;
600
534
  }
601
535
  let scheduleInfo;
@@ -612,7 +546,7 @@ export class EventsWatcher {
612
546
  const periodicContract = event.type === "periodic"
613
547
  ? " This is a periodic runtime wake. If it produces no user-visible change or result, reply with exactly [SILENT]."
614
548
  : "";
615
- const message = `[EVENT:${filename}:${event.type}:${scheduleInfo}] ${event.text}${periodicContract}`;
549
+ const message = `[EVENT:${filename}:${event.type}:${scheduleInfo}] ${event.text ?? ""}${periodicContract}`;
616
550
  // Create synthetic ChannelEvent
617
551
  const syntheticEvent = {
618
552
  type: "dm",
@@ -647,6 +581,44 @@ export class EventsWatcher {
647
581
  this.markInvalid(filename, `Event queue was full at ${new Date().toISOString()}; this occurrence was not delivered.`);
648
582
  }
649
583
  }
584
+ /**
585
+ * Deliver a template event: ask the runtime for a fresh task instance (spec 052, D2). The
586
+ * occurrence is the one this trigger was *due* for — a one-shot's `at`, a periodic's cron tick —
587
+ * so a post-restart replay of the same occurrence lands on the same instance instead of making a
588
+ * second one.
589
+ */
590
+ async spawnTaskInstance(filename, event, template, deleteAfter, occurrence) {
591
+ const spawn = this.options.spawnTask;
592
+ const due = event.type === "one-shot" ? new Date(parseLocalTime(event.at) ?? occurrence.getTime()) : occurrence;
593
+ try {
594
+ if (!spawn)
595
+ throw new Error("this runtime cannot create task instances");
596
+ const result = await spawn({
597
+ eventName: eventNameFromFilename(filename),
598
+ channelId: event.channelId,
599
+ template,
600
+ occurrence: due,
601
+ });
602
+ const delivered = result.outcome === "spawned";
603
+ this.appendEventHistory(filename, event, delivered ? "enqueued" : "skipped", "ok", {
604
+ reason: result.outcome === "spawned"
605
+ ? `spawned task ${result.id}`
606
+ : result.outcome === "exists"
607
+ ? `task ${result.id} already exists for this occurrence`
608
+ : `previous instance ${result.id} is still running`,
609
+ });
610
+ if (deleteAfter)
611
+ this.deleteFile(filename);
612
+ }
613
+ catch (err) {
614
+ const reason = errorMessage(err);
615
+ log.logWarning(`Could not spawn a task for event: ${filename}`, reason);
616
+ this.appendEventHistory(filename, event, "skipped", "error", { reason });
617
+ if (deleteAfter) {
618
+ this.markInvalid(filename, `Could not create the task instance at ${new Date().toISOString()}: ${reason}`);
619
+ }
620
+ }
621
+ }
650
622
  async runPreAction(action, filename) {
651
623
  const startedAt = Date.now();
652
624
  if (this.commandGuardConfig?.enabled) {
@@ -726,7 +698,7 @@ export class EventsWatcher {
726
698
  /**
727
699
  * Create and start an events watcher.
728
700
  */
729
- export function createEventsWatcher(workspaceDir, bot, executor, commandGuardConfig, historyPath, dispatch) {
701
+ export function createEventsWatcher(workspaceDir, bot, executor, commandGuardConfig, historyPath, dispatch, spawnTask) {
730
702
  const eventsDir = join(workspaceDir, "events");
731
- return new EventsWatcher(eventsDir, bot, executor, commandGuardConfig, { historyPath, dispatch });
703
+ return new EventsWatcher(eventsDir, bot, executor, commandGuardConfig, { historyPath, dispatch, spawnTask });
732
704
  }
@@ -1,7 +1,6 @@
1
1
  /**
2
- * Spec 050, D5: `journal/YYYY-MM-DD.md`, append-only, one file per local day. Replaces
3
- * `SESSION.md` (current state) and `HISTORY.md` (folded older history) — a day is never
4
- * folded or rewritten, only appended to, so it stays a plain, growing record.
2
+ * Spec 050, D5: `journal/YYYY-MM-DD.md`, append-only, one file per local day — never folded or
3
+ * rewritten, so it stays a plain, growing record.
5
4
  */
6
5
  export declare function getJournalDir(channelDir: string): string;
7
6
  export declare function getJournalPath(channelDir: string, date: string): string;
@@ -4,9 +4,8 @@ import { writeFileAtomically } from "../shared/atomic-file.js";
4
4
  import { localDayKey } from "../shared/local-time.js";
5
5
  import { isNodeError, readOptionalTextFile } from "../shared/os.js";
6
6
  /**
7
- * Spec 050, D5: `journal/YYYY-MM-DD.md`, append-only, one file per local day. Replaces
8
- * `SESSION.md` (current state) and `HISTORY.md` (folded older history) — a day is never
9
- * folded or rewritten, only appended to, so it stays a plain, growing record.
7
+ * Spec 050, D5: `journal/YYYY-MM-DD.md`, append-only, one file per local day — never folded or
8
+ * rewritten, so it stays a plain, growing record.
10
9
  */
11
10
  export function getJournalDir(channelDir) {
12
11
  return join(channelDir, "journal");
@@ -11,7 +11,6 @@ export interface MemoryMaintenanceTuning {
11
11
  minIdleMinutesBeforeLlmWork: number;
12
12
  /** Idle cadence of the reflect pass. */
13
13
  reflectIntervalMinutes: number;
14
- maxConcurrentChannels: number;
15
14
  failureBackoffMinutes: number;
16
15
  }
17
16
  export declare function getMemoryMaintenanceTuning(env?: NodeJS.ProcessEnv): MemoryMaintenanceTuning;
@@ -9,7 +9,6 @@
9
9
  const PRODUCTION_TUNING = {
10
10
  minIdleMinutesBeforeLlmWork: 10,
11
11
  reflectIntervalMinutes: 20,
12
- maxConcurrentChannels: 1,
13
12
  failureBackoffMinutes: 30,
14
13
  };
15
14
  /**
@@ -60,9 +60,6 @@ export async function discoverMemoryMaintenanceChannels(input) {
60
60
  ...(await listStateChannels(input.appHomeDir)),
61
61
  ]);
62
62
  }
63
- function normalizeMaxConcurrentChannels(value) {
64
- return Number.isFinite(value) ? Math.max(1, Math.floor(value)) : 1;
65
- }
66
63
  export class MemoryMaintenanceScheduler {
67
64
  constructor(options) {
68
65
  this.options = options;
@@ -103,30 +100,25 @@ export class MemoryMaintenanceScheduler {
103
100
  workspaceDir: this.options.workspaceDir,
104
101
  knownChannelIds: this.options.getKnownChannelIds?.(),
105
102
  });
106
- const maxConcurrent = normalizeMaxConcurrentChannels(settings.memoryMaintenance.maxConcurrentChannels);
107
103
  if (channelIds.length === 0) {
108
104
  return;
109
105
  }
110
- const selected = [];
111
- let scanned = 0;
106
+ // One channel per tick, round-robin: a reflect pass is an LLM call, and the first due
107
+ // channel is as good a place to spend it as any.
108
+ let selected;
112
109
  let index = this.nextChannelIndex % channelIds.length;
113
- while (scanned < channelIds.length && selected.length < maxConcurrent) {
110
+ for (let scanned = 0; scanned < channelIds.length && !selected; scanned++) {
114
111
  const channelId = channelIds[index];
115
112
  if (channelId &&
116
113
  !this.options.isChannelActive(channelId) &&
117
- (await mightReflectBeDue({
118
- appHomeDir: this.options.appHomeDir,
119
- channelId,
120
- settings,
121
- now,
122
- }))) {
123
- selected.push(channelId);
114
+ (await mightReflectBeDue({ appHomeDir: this.options.appHomeDir, channelId, settings, now }))) {
115
+ selected = channelId;
124
116
  }
125
117
  index = (index + 1) % channelIds.length;
126
- scanned++;
127
118
  }
128
119
  this.nextChannelIndex = index;
129
- await Promise.all(selected.map((channelId) => this.runChannelOnce(channelId, now)));
120
+ if (selected)
121
+ await this.runChannelOnce(selected, now);
130
122
  }
131
123
  finally {
132
124
  this.running = false;
@@ -24,9 +24,8 @@ export function recencyBoostByAge(timestamp, weights) {
24
24
  return 0;
25
25
  }
26
26
  /**
27
- * Spec 050, D3/D4: the lexical tokenizer, moved here from the retired `recall.ts`. It now serves
28
- * exactly two callers — `memory_search` and `memory_save`'s deterministic near-duplicate guard.
29
- * Per-turn recall scoring, intent seeding, and the usage-count boost are gone.
27
+ * Spec 050, D3/D4: the lexical tokenizer. It serves exactly two callers — `memory_search` and
28
+ * `memory_save`'s deterministic near-duplicate guard.
30
29
  */
31
30
  const TOKEN_PART_REGEX = /[\p{Script=Han}]+|[\p{L}\p{N}_./-]+/gu;
32
31
  const ASCII_SPLIT_REGEX = /[._/-]+/g;
@@ -53,15 +53,9 @@ function scoreDocument(document, lowerQuery, queryTokens) {
53
53
  matches.push(token);
54
54
  }
55
55
  }
56
- // `recall.ts` deliberately dropped a coverage-ratio term (`matched / queryTokens.length`) in
57
- // favor of absolute specificity-weighted evidence, because normalizing by query length made
58
- // detailed messages score worse the more context they gave (see the long comment on
59
- // `MIN_MATCH_EVIDENCE` there). This scorer still uses coverage, kept as a small, capped (0-2)
60
- // tiebreaker behind the dominant `matchedTokens * 1.4` term rather than removed outright:
61
- // `session_search` is an explicit on-demand query over raw transcript chunks, not the passive
62
- // per-turn injection recall.ts drives, so it has no eval pinning its current ranking and no
63
- // reported failure mode from this term. Changing it blind, without that guardrail, risks
64
- // swapping one unverified scoring bias for another.
56
+ // Coverage (`matched / queryTokens.length`) is a small, capped (0-2) tiebreaker behind the
57
+ // dominant `matchedTokens * 1.4` term. Normalizing by query length alone would make detailed
58
+ // queries score worse the more context they give, so it must stay a tiebreaker.
65
59
  const coverage = queryTokens.length > 0 ? matchedTokens / queryTokens.length : 0;
66
60
  const exactHit = Boolean(lowerQuery) && lowerText.includes(lowerQuery);
67
61
  const score = matchedTokens * 1.4 + coverage * 2 + (exactHit ? 1 : 0) + computeRecencyBoost(document.timestamp);
@@ -27,7 +27,7 @@ export interface MemoryEntry {
27
27
  malformed: boolean;
28
28
  }
29
29
  export interface MemoryTombstoneRecord {
30
- /** The entry name at deletion time; may be absent for records carried over from v1. */
30
+ /** The entry name at deletion time; may be absent. */
31
31
  name?: string;
32
32
  contentHash: string;
33
33
  deletedAt: string;
@@ -335,13 +335,21 @@ export async function applyMemoryOps(channelDir, ops, options = {}) {
335
335
  result.missingTarget++;
336
336
  continue;
337
337
  }
338
- await rm(getMemoryEntryPath(channelDir, op.name), { force: true });
338
+ // Tombstone first, delete second (R8): the tombstone is what stops the background
339
+ // reflect pass from silently re-learning a fact the user just deleted. Deleting the file
340
+ // first meant a failure between the two steps (disk full, permissions) left the fact
341
+ // gone with no tombstone recorded — by the time the caller retried, the source file no
342
+ // longer existed to recompute the hash from, so the fact could quietly come back.
343
+ // Recording the tombstone before the delete means the worst case after a failure here is
344
+ // the reverse — file still present, already tombstoned — which is recoverable: the file
345
+ // is still there to retry deleting, and it is already protected from re-learning either way.
339
346
  await appendMemoryTombstoneRecord(channelDir, {
340
347
  name: op.name,
341
348
  contentHash: hashMemoryContent(entry.description),
342
349
  deletedAt: today,
343
350
  reason: op.reason?.trim() || "deleted",
344
351
  });
352
+ await rm(getMemoryEntryPath(channelDir, op.name), { force: true });
345
353
  byName.delete(op.name);
346
354
  liveNames.delete(op.name);
347
355
  result.deleted.push(op.name);
@@ -30,16 +30,16 @@ function renderLine(entry, now) {
30
30
  const by = relativeTime(parseLocalTime(ticket.by), now);
31
31
  parts.push(`${describeTicket(ticket)}${due ? ` · due ${due}` : ""}${by ? ` · 兜底 ${by}` : ""}`);
32
32
  }
33
- const cycle = entry.fields.cycle;
34
- if (cycle) {
35
- const cost = cycle.usd > 0 ? ` · $${cycle.usd.toFixed(2)}${cycle.usdEstimated ? "≈" : ""}` : "";
36
- parts.push(`${cycle.id} · ${cycle.steps} 步 · ${cycle.rounds} 轮${cost}`);
33
+ // The agenda shows Work Items progress and the current item, not the full list — the complete
34
+ // section is read from the task file by the loop itself, staying well inside the 600-unit
35
+ // budget this block competes for (spec 025/026).
36
+ if (entry.items) {
37
+ parts.push(`items ${entry.items.done}/${entry.items.total} · @${entry.items.current?.id ?? "-"}`);
37
38
  }
38
- // spec 037, D4: the agenda shows Plan progress and the current step, not the full Plan — the
39
- // complete section is read from the task file by the loop itself, staying well inside the
40
- // 600-unit budget this block competes for (spec 025/026).
41
- if (entry.plan) {
42
- parts.push(`plan ${entry.plan.done}/${entry.plan.total} · @${entry.plan.current?.id ?? "-"}`);
39
+ const usage = entry.fields.usage;
40
+ if (usage) {
41
+ const cost = usage.usd > 0 ? ` · $${usage.usd.toFixed(2)}${usage.usdEstimated ? "≈" : ""}` : "";
42
+ parts.push(`${usage.steps} 步${cost}`);
43
43
  }
44
44
  return `- ${parts.join(" · ")}`;
45
45
  }
@@ -52,8 +52,7 @@ export async function buildTaskDigest(options) {
52
52
  const now = options.now ?? Date.now();
53
53
  const tasksDir = join(options.channelDir, "tasks");
54
54
  const all = await readActiveTasks(tasksDir, now);
55
- // A legacy terminal file may briefly remain in the active directory while startup migration
56
- // is running. It is already non-actionable at the ledger layer and must not enter prompt context.
55
+ // A closed task that has not been archived yet is non-actionable and must not enter prompt context.
57
56
  const agenda = all.filter((entry) => !entry.fields.outcome);
58
57
  if (agenda.length === 0)
59
58
  return "";
@@ -1,9 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  /**
3
- * The one piece of the v1 tombstone module that survived spec 050: a normalized content hash,
4
- * shared by `store.ts` (the v2 `.tombstones.jsonl`), `migrate.ts` (carrying v1 tombstones over
5
- * by hash), and the memory tools/commands (audit log entries that must not carry the forgotten
6
- * text itself).
3
+ * A normalized content hash, shared by `store.ts` (`.tombstones.jsonl`) and the memory
4
+ * tools/commands (audit log entries that must not carry the forgotten text itself).
7
5
  */
8
6
  function normalizeMemoryContent(content) {
9
7
  return content.normalize("NFKC").replace(/\s+/g, " ").trim().toLowerCase();
@@ -2,7 +2,7 @@
2
2
  * Transport-neutral provider login/logout/status orchestration. Imports no
3
3
  * terminal code — the human-machine interface is the injected `LoginUi`, so a
4
4
  * future TUI `/login` can supply a different implementation without touching
5
- * this file (see docs/specs/039-provider-login-cli/design.md §10).
5
+ * this file (see docs/archive/specs/039-provider-login-cli/design.md §10).
6
6
  */
7
7
  import { type Api, type AuthEvent, type AuthPrompt, type AuthType, type Model } from "@earendil-works/pi-ai";
8
8
  import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
@@ -2,7 +2,7 @@
2
2
  * Transport-neutral provider login/logout/status orchestration. Imports no
3
3
  * terminal code — the human-machine interface is the injected `LoginUi`, so a
4
4
  * future TUI `/login` can supply a different implementation without touching
5
- * this file (see docs/specs/039-provider-login-cli/design.md §10).
5
+ * this file (see docs/archive/specs/039-provider-login-cli/design.md §10).
6
6
  */
7
7
  import { ModelsError, } from "@earendil-works/pi-ai";
8
8
  export class LoginCancelledError extends Error {