@oyasmi/pipiclaw 0.9.2-beta.6 → 0.9.3-beta.1

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 (165) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +2 -0
  3. package/dist/agent/channel-runner.d.ts +43 -2
  4. package/dist/agent/channel-runner.js +135 -75
  5. package/dist/agent/job-manager.d.ts +76 -21
  6. package/dist/agent/job-manager.js +447 -63
  7. package/dist/agent/maintenance-context.js +4 -5
  8. package/dist/agent/prompt/manifest.d.ts +0 -2
  9. package/dist/agent/prompt/manifest.js +2 -3
  10. package/dist/agent/prompt/sections.js +3 -3
  11. package/dist/agent/session-events.js +4 -8
  12. package/dist/agent/turn-prompt.d.ts +7 -7
  13. package/dist/agent/turn-prompt.js +6 -9
  14. package/dist/agent/types.d.ts +12 -0
  15. package/dist/agent/types.js +1 -0
  16. package/dist/channel/channel-context.d.ts +13 -0
  17. package/dist/channel/channel-context.js +21 -1
  18. package/dist/commands/catalog.js +47 -20
  19. package/dist/memory/commands.d.ts +8 -0
  20. package/dist/memory/commands.js +113 -148
  21. package/dist/memory/index-budget.d.ts +27 -0
  22. package/dist/memory/index-budget.js +99 -0
  23. package/dist/memory/journal.d.ts +20 -0
  24. package/dist/memory/journal.js +78 -0
  25. package/dist/memory/lifecycle.d.ts +9 -15
  26. package/dist/memory/lifecycle.js +55 -145
  27. package/dist/memory/maintenance-gates.d.ts +13 -47
  28. package/dist/memory/maintenance-gates.js +13 -92
  29. package/dist/memory/maintenance-state.d.ts +10 -16
  30. package/dist/memory/maintenance-state.js +12 -59
  31. package/dist/memory/maintenance-tuning.d.ts +7 -27
  32. package/dist/memory/maintenance-tuning.js +11 -28
  33. package/dist/memory/migrate.d.ts +15 -0
  34. package/dist/memory/migrate.js +364 -0
  35. package/dist/memory/reflect-job.d.ts +43 -0
  36. package/dist/memory/reflect-job.js +117 -0
  37. package/dist/memory/reflect.d.ts +52 -0
  38. package/dist/memory/reflect.js +313 -0
  39. package/dist/memory/render.d.ts +14 -0
  40. package/dist/memory/render.js +28 -0
  41. package/dist/memory/review-log.d.ts +2 -1
  42. package/dist/memory/scheduler.d.ts +2 -3
  43. package/dist/memory/scheduler.js +14 -49
  44. package/dist/memory/search.d.ts +35 -0
  45. package/dist/memory/search.js +297 -0
  46. package/dist/memory/session-search.js +1 -1
  47. package/dist/memory/store.d.ts +108 -0
  48. package/dist/memory/store.js +418 -0
  49. package/dist/memory/task-digest.d.ts +2 -2
  50. package/dist/memory/task-digest.js +29 -36
  51. package/dist/memory/tombstones.d.ts +0 -11
  52. package/dist/memory/tombstones.js +6 -37
  53. package/dist/playbooks/agent-delegation.md +4 -2
  54. package/dist/playbooks/background-jobs.md +1 -1
  55. package/dist/playbooks/event-scheduling.md +6 -2
  56. package/dist/playbooks/memory-and-learning.md +18 -11
  57. package/dist/playbooks/outbound-media.md +1 -1
  58. package/dist/playbooks/runtime-orientation.md +9 -8
  59. package/dist/playbooks/task-loop.md +88 -0
  60. package/dist/runtime/bootstrap.d.ts +3 -3
  61. package/dist/runtime/bootstrap.js +66 -41
  62. package/dist/runtime/events.d.ts +9 -0
  63. package/dist/runtime/events.js +43 -4
  64. package/dist/runtime/task-commands.d.ts +14 -15
  65. package/dist/runtime/task-commands.js +249 -485
  66. package/dist/runtime/task-driver.d.ts +41 -29
  67. package/dist/runtime/task-driver.js +170 -317
  68. package/dist/runtime/task-migration.d.ts +34 -30
  69. package/dist/runtime/task-migration.js +229 -183
  70. package/dist/runtime/task-wake.d.ts +6 -3
  71. package/dist/runtime/task-wake.js +26 -19
  72. package/dist/settings.d.ts +0 -29
  73. package/dist/settings.js +12 -35
  74. package/dist/shared/markdown-sections.d.ts +0 -1
  75. package/dist/shared/markdown-sections.js +0 -3
  76. package/dist/subagents/discovery.d.ts +2 -2
  77. package/dist/subagents/discovery.js +21 -10
  78. package/dist/subagents/external/progress-tail.js +6 -1
  79. package/dist/subagents/external/run.js +1 -0
  80. package/dist/subagents/runs.d.ts +19 -2
  81. package/dist/subagents/runs.js +73 -4
  82. package/dist/subagents/tool.d.ts +10 -8
  83. package/dist/subagents/tool.js +55 -94
  84. package/dist/tasks/brief.d.ts +17 -0
  85. package/dist/tasks/brief.js +57 -0
  86. package/dist/tasks/budget.d.ts +26 -0
  87. package/dist/tasks/budget.js +59 -0
  88. package/dist/tasks/cycle.d.ts +48 -0
  89. package/dist/tasks/cycle.js +94 -0
  90. package/dist/tasks/frontmatter.d.ts +73 -0
  91. package/dist/tasks/frontmatter.js +175 -0
  92. package/dist/tasks/ledger.d.ts +66 -106
  93. package/dist/tasks/ledger.js +90 -546
  94. package/dist/tasks/log.d.ts +88 -0
  95. package/dist/tasks/log.js +97 -0
  96. package/dist/tasks/rounds.d.ts +43 -0
  97. package/dist/tasks/rounds.js +57 -0
  98. package/dist/tasks/session-path.d.ts +9 -0
  99. package/dist/tasks/session-path.js +16 -0
  100. package/dist/tasks/steer.d.ts +8 -0
  101. package/dist/tasks/steer.js +79 -0
  102. package/dist/tasks/store.d.ts +60 -35
  103. package/dist/tasks/store.js +166 -107
  104. package/dist/tasks/ticket.d.ts +102 -0
  105. package/dist/tasks/ticket.js +209 -0
  106. package/dist/tasks/verification.d.ts +16 -0
  107. package/dist/tasks/verification.js +40 -1
  108. package/dist/tools/index.d.ts +13 -4
  109. package/dist/tools/index.js +5 -10
  110. package/dist/tools/memory-manage.d.ts +6 -16
  111. package/dist/tools/memory-manage.js +108 -129
  112. package/dist/tools/presentation.js +2 -1
  113. package/dist/tools/registry.d.ts +11 -2
  114. package/dist/tools/registry.js +17 -6
  115. package/dist/tools/subagent-manage.d.ts +0 -9
  116. package/dist/tools/subagent-manage.js +8 -17
  117. package/dist/tools/task-manage/create.js +2 -2
  118. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  119. package/dist/tools/task-manage/lifecycle.js +139 -187
  120. package/dist/tools/task-manage/log-view.d.ts +8 -0
  121. package/dist/tools/task-manage/log-view.js +24 -0
  122. package/dist/tools/task-manage/schema.d.ts +38 -14
  123. package/dist/tools/task-manage/schema.js +46 -27
  124. package/dist/tools/task-manage/shared.d.ts +24 -31
  125. package/dist/tools/task-manage/shared.js +103 -141
  126. package/dist/tools/task-manage/step-end.d.ts +11 -0
  127. package/dist/tools/task-manage/step-end.js +136 -0
  128. package/dist/tools/task-manage/types.d.ts +23 -32
  129. package/dist/tools/task-manage.d.ts +4 -3
  130. package/dist/tools/task-manage.js +30 -15
  131. package/dist/tools/tool-details.d.ts +1 -1
  132. package/dist/tui/app.js +0 -2
  133. package/package.json +1 -1
  134. package/dist/agent/effect-ledger.d.ts +0 -32
  135. package/dist/agent/effect-ledger.js +0 -89
  136. package/dist/memory/bootstrap.d.ts +0 -17
  137. package/dist/memory/bootstrap.js +0 -120
  138. package/dist/memory/candidates.d.ts +0 -26
  139. package/dist/memory/candidates.js +0 -202
  140. package/dist/memory/consolidation.d.ts +0 -54
  141. package/dist/memory/consolidation.js +0 -292
  142. package/dist/memory/extraction.d.ts +0 -54
  143. package/dist/memory/extraction.js +0 -240
  144. package/dist/memory/files.d.ts +0 -71
  145. package/dist/memory/files.js +0 -419
  146. package/dist/memory/maintenance-jobs.d.ts +0 -41
  147. package/dist/memory/maintenance-jobs.js +0 -265
  148. package/dist/memory/metadata.d.ts +0 -57
  149. package/dist/memory/metadata.js +0 -142
  150. package/dist/memory/probation.d.ts +0 -17
  151. package/dist/memory/probation.js +0 -44
  152. package/dist/memory/promotion.d.ts +0 -38
  153. package/dist/memory/promotion.js +0 -36
  154. package/dist/memory/recall.d.ts +0 -59
  155. package/dist/memory/recall.js +0 -746
  156. package/dist/memory/session.d.ts +0 -24
  157. package/dist/memory/session.js +0 -273
  158. package/dist/playbooks/task-driving.md +0 -92
  159. package/dist/playbooks/task-planning.md +0 -58
  160. package/dist/tasks/control.d.ts +0 -56
  161. package/dist/tasks/control.js +0 -169
  162. package/dist/tasks/transitions.d.ts +0 -16
  163. package/dist/tasks/transitions.js +0 -48
  164. package/dist/tools/task-manage/verification.d.ts +0 -19
  165. package/dist/tools/task-manage/verification.js +0 -91
@@ -1,5 +1,5 @@
1
1
  import { realpathSync, statSync } from "node:fs";
2
- import { mkdir } from "node:fs/promises";
2
+ import { mkdir, readFile } from "node:fs/promises";
3
3
  import { join, resolve } from "node:path";
4
4
  import { Agent } from "@earendil-works/pi-agent-core";
5
5
  import { clampThinkingLevel, streamSimple } from "@earendil-works/pi-ai/compat";
@@ -7,15 +7,16 @@ import { convertToLlm } from "@earendil-works/pi-coding-agent";
7
7
  import { Type } from "typebox";
8
8
  import { getChannelDir } from "../channel/channel-paths.js";
9
9
  import * as log from "../log.js";
10
- import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, readChannelSession, } from "../memory/files.js";
11
- import { recallRelevantMemory } from "../memory/recall.js";
10
+ import { buildChannelIndexForBootstrap, CHANNEL_INDEX_MAX_UNITS, clipJournalTailForBootstrap, clipWorkspaceMemoryForBootstrap, JOURNAL_TAIL_MAX_UNITS, WORKSPACE_MEMORY_MAX_UNITS, } from "../memory/index-budget.js";
11
+ import { getJournalDir, readJournalDay } from "../memory/journal.js";
12
+ import { renderMemoryBootstrap } from "../memory/render.js";
13
+ import { getChannelMemoryDir, getChannelMemoryIndexPath, listMemoryEntries } from "../memory/store.js";
12
14
  import { formatModelReference } from "../models/utils.js";
13
15
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
14
- import { formatLocalTime } from "../shared/local-time.js";
15
- import { splitH1Sections } from "../shared/markdown-sections.js";
16
+ import { formatLocalTime, localDayKey } from "../shared/local-time.js";
16
17
  import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
17
18
  import { RecoverableToolError } from "../shared/recoverable-error.js";
18
- import { clipText, errorMessage, extractAssistantText } from "../shared/text-utils.js";
19
+ import { errorMessage, extractAssistantText } from "../shared/text-utils.js";
19
20
  import { addUsage, createEmptyUsageTotals } from "../shared/types.js";
20
21
  import { sleepUnref } from "../shared/with-timeout.js";
21
22
  import { workspaceSubjectHash, workspaceSubjectSnapshot } from "../tasks/artifact-subject.js";
@@ -60,8 +61,8 @@ const subagentInlineSchema = Type.Object({
60
61
  effort: Type.Optional(Type.Union([Type.Literal("quick"), Type.Literal("standard"), Type.Literal("deep")], {
61
62
  description: 'Execution budget preset (turns, tool calls, wall time). "standard" is the default; "quick" for narrow lookups, "deep" for long analyses.',
62
63
  })),
63
- context: Type.Optional(Type.Union([Type.Literal("none"), Type.Literal("session"), Type.Literal("relevant")], {
64
- description: 'What context to inject. "none" (default) runs fully isolated; "session" adds current session state; "relevant" adds session state plus recalled memory.',
64
+ context: Type.Optional(Type.Union([Type.Literal("none"), Type.Literal("index")], {
65
+ description: 'What context to inject. "none" (default) runs fully isolated; "index" adds the workspace background, the channel memory index, and today\'s journal tail.',
65
66
  })),
66
67
  thinkingLevel: Type.Optional(Type.Union([
67
68
  Type.Literal("off"),
@@ -82,17 +83,6 @@ const subagentInlineSchema = Type.Object({
82
83
  purpose: purposeField,
83
84
  taskId: taskIdField,
84
85
  });
85
- const DEFAULT_SUBAGENT_MEMORY_RECALL_SETTINGS = {
86
- enabled: true,
87
- maxCandidates: 12,
88
- maxInjected: 5,
89
- maxChars: 5000,
90
- rerankWithModel: true,
91
- };
92
- const SESSION_SECTION_ORDER = ["Current State", "User Intent", "Active Files", "Errors & Corrections", "Next Steps"];
93
- const MAX_SESSION_SECTION_CHARS = 280;
94
- const MAX_SESSION_CONTEXT_CHARS = 1800;
95
- const MAX_RECALL_CONTEXT_CHARS = 2200;
96
86
  const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
97
87
  /**
98
88
  * Reply budget for what a sub-agent hands back to its parent (spec 032 D4), measured in the
@@ -242,8 +232,8 @@ function buildDispatchedText(runId, agentName, runtimeLabel, workingDirectory) {
242
232
  * precondition, so a failure here degrades to no context blocks rather than failing a dispatch
243
233
  * that would otherwise have run fine.
244
234
  */
245
- async function resolveContextualBlocks(task, config, options, currentModel) {
246
- return buildContextualBlocks(task, config, options, currentModel).catch((error) => {
235
+ async function resolveContextualBlocks(config, options) {
236
+ return buildContextualBlocks(config, options).catch((error) => {
247
237
  log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
248
238
  return [];
249
239
  });
@@ -289,18 +279,18 @@ function finalizeSubAgentOutput(runContext, finalText) {
289
279
  }
290
280
  /**
291
281
  * Sub-agents share the main agent's `write`/`edit` tools but only receive the runtime
292
- * context (task text), never the "don't touch MEMORY.md/HISTORY.md/SESSION.md, use
293
- * memory_save instead" rule the main agent gets in its system prompt (the memory tools
294
- * itself is withheld from sub-agents). Denying these paths at the path-guard level closes
295
- * that gap structurally instead of relying on a sub-agent to infer an instruction it never
296
- * received — a stray write/edit here would race the shared memory serial queue
297
- * (channel-maintenance-queue) and silently corrupt durable memory.
282
+ * context (task text), never the "the MEMORY.md index is generated, write memory only through
283
+ * memory_save" rule the main agent gets in its system prompt (the memory tools themselves are
284
+ * withheld from sub-agents). Denying these paths at the path-guard level closes that gap
285
+ * structurally instead of relying on a sub-agent to infer an instruction it never received — a
286
+ * stray write/edit here would race the shared memory serial queue (channel-maintenance-queue)
287
+ * and silently corrupt durable memory.
298
288
  */
299
289
  function withSubagentMemoryWriteDeny(securityConfig, channelDir, workspaceDir) {
300
290
  const protectedPaths = [
301
- getChannelMemoryPath(channelDir),
302
- getChannelHistoryPath(channelDir),
303
- getChannelSessionPath(channelDir),
291
+ getChannelMemoryDir(channelDir),
292
+ getJournalDir(channelDir),
293
+ getChannelMemoryIndexPath(channelDir),
304
294
  ];
305
295
  // The role directory gets the same structural denial (spec 040, D8.1): a sub-agent's write/edit
306
296
  // tools are exactly as capable of writing a self-authorizing `runtime: external` role file as
@@ -401,35 +391,13 @@ export function buildSubAgentTask(task, config, runtimeContext, contextBlocks, r
401
391
  }
402
392
  return lines.join("\n");
403
393
  }
404
- function buildSessionContextBlock(sessionMarkdown) {
405
- const sections = splitH1Sections(sessionMarkdown);
406
- if (sections.length === 0) {
407
- return "";
408
- }
409
- const selectedSections = SESSION_SECTION_ORDER.flatMap((heading) => sections.filter((section) => section.heading.toLowerCase() === heading.toLowerCase()));
410
- if (selectedSections.length === 0) {
411
- return "";
412
- }
413
- const lines = ["Relevant session state:"];
414
- let usedChars = lines[0].length;
415
- for (const section of selectedSections) {
416
- const clipped = clipText(section.content, MAX_SESSION_SECTION_CHARS, { headRatio: 1, omitHint: "..." });
417
- const block = `- ${section.heading}: ${clipped}`;
418
- if (usedChars + block.length > MAX_SESSION_CONTEXT_CHARS) {
419
- break;
420
- }
421
- lines.push(block);
422
- usedChars += block.length + 1;
423
- }
424
- return lines.length > 1 ? lines.join("\n") : "";
425
- }
426
- function stripRuntimeContextWrapper(renderedText) {
427
- return renderedText
428
- .replace(/^<runtime_context>\s*/i, "")
429
- .replace(/\s*<\/runtime_context>$/i, "")
430
- .trim();
431
- }
432
- export async function buildContextualBlocks(task, config, options, currentModel) {
394
+ /**
395
+ * Spec 050, D12: `memory: index` injects the same three sections the main agent's first-turn
396
+ * bootstrap does — workspace MEMORY.md, the channel index, today's journal tail — at half the
397
+ * main agent's budget. No per-call LLM recall: a sub-agent task is short-lived, so there is no
398
+ * "first turn" to bootstrap once and reuse; it gets the same snapshot every dispatch.
399
+ */
400
+ export async function buildContextualBlocks(config, options) {
433
401
  if (config.contextMode !== "contextual") {
434
402
  return [];
435
403
  }
@@ -440,39 +408,31 @@ export async function buildContextualBlocks(task, config, options, currentModel)
440
408
  if (config.memory === "none") {
441
409
  return blocks;
442
410
  }
443
- const sessionMarkdown = await readChannelSession(options.channelDir);
444
- const sessionBlock = buildSessionContextBlock(sessionMarkdown);
445
- if (sessionBlock) {
446
- blocks.push(sessionBlock);
447
- }
448
- if (config.memory !== "relevant") {
449
- return blocks;
450
- }
451
- const recallSettings = {
452
- ...DEFAULT_SUBAGENT_MEMORY_RECALL_SETTINGS,
453
- ...options.getMemoryRecallSettings?.(),
411
+ const today = localDayKey();
412
+ const readOptionalFile = async (path) => {
413
+ try {
414
+ return await readFile(path, "utf-8");
415
+ }
416
+ catch {
417
+ return "";
418
+ }
454
419
  };
455
- if (!recallSettings.enabled) {
456
- return blocks;
457
- }
458
- const recallQuery = [task.trim(), config.description.trim(), ...config.paths].filter(Boolean).join("\n");
459
- const recalled = await recallRelevantMemory({
460
- query: recallQuery,
461
- channelId: options.runtimeContext.channelId,
462
- workspaceDir: options.workspaceDir,
463
- channelDir: options.channelDir,
464
- maxCandidates: recallSettings.maxCandidates,
465
- maxInjected: recallSettings.maxInjected,
466
- maxChars: Math.min(recallSettings.maxChars, MAX_RECALL_CONTEXT_CHARS),
467
- rerankWithModel: recallSettings.rerankWithModel,
468
- model: currentModel,
469
- resolveApiKey: options.resolveApiKey,
470
- allowedSources: ["workspace-memory", "channel-memory", "channel-history"],
471
- candidateStore: options.memoryCandidateStore,
420
+ const [entries, workspaceMemory, journalToday] = await Promise.all([
421
+ listMemoryEntries(options.channelDir).catch(() => []),
422
+ readOptionalFile(join(options.workspaceDir, "MEMORY.md")),
423
+ readJournalDay(options.channelDir, today).catch(() => ""),
424
+ ]);
425
+ const index = buildChannelIndexForBootstrap(entries, CHANNEL_INDEX_MAX_UNITS / 2);
426
+ const bootstrap = renderMemoryBootstrap({
427
+ workspaceMemory: clipWorkspaceMemoryForBootstrap(workspaceMemory, WORKSPACE_MEMORY_MAX_UNITS / 2),
428
+ channelIndex: entries.length > 0 ? index.text : "",
429
+ journal: (() => {
430
+ const text = clipJournalTailForBootstrap(journalToday, JOURNAL_TAIL_MAX_UNITS / 2);
431
+ return text ? { date: today, text } : undefined;
432
+ })(),
472
433
  });
473
- const recalledText = stripRuntimeContextWrapper(recalled.renderedText);
474
- if (recalledText) {
475
- blocks.push(recalledText);
434
+ if (bootstrap) {
435
+ blocks.push(bootstrap);
476
436
  }
477
437
  return blocks;
478
438
  }
@@ -569,7 +529,7 @@ async function dispatchSubAgentRun(options, currentModel, config, warning, param
569
529
  * always 0, so there is no inline-wait branch to share with the internal path.
570
530
  */
571
531
  async function dispatchExternalRun(input) {
572
- const { options, currentModel, config, runLabel, runContext, leaseKey, params } = input;
532
+ const { options, config, runLabel, runContext, leaseKey, params } = input;
573
533
  if (!config.harness) {
574
534
  releaseWorkspaceLease(leaseKey, runContext.runId);
575
535
  throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
@@ -579,7 +539,7 @@ async function dispatchExternalRun(input) {
579
539
  // D9/T5: external roles get the same task envelope internal workers do — runtime
580
540
  // paths, injected context blocks, and (for purpose=verify) the verification
581
541
  // protocol — rather than the raw task text (spec 040 gap closed post-review).
582
- const contextualBlocks = await resolveContextualBlocks(params.task, config, options, currentModel);
542
+ const contextualBlocks = await resolveContextualBlocks(config, options);
583
543
  const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext);
584
544
  launchResult = await launchExternalRun({
585
545
  runId: runContext.runId,
@@ -653,7 +613,7 @@ async function dispatchExternalRun(input) {
653
613
  * placeholder while the run keeps going in the background.
654
614
  */
655
615
  async function dispatchInternalRun(input) {
656
- const { options, currentModel, config, runLabel, mutatesNote, runContext, leaseKey, params, onUpdate, runManager } = input;
616
+ const { options, config, runLabel, mutatesNote, runContext, leaseKey, params, onUpdate, runManager } = input;
657
617
  const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
658
618
  let apiKey;
659
619
  try {
@@ -690,6 +650,7 @@ async function dispatchInternalRun(input) {
690
650
  taskId: runContext.taskId,
691
651
  workingDirectory: runContext.workingDirectory,
692
652
  artifactDir: runContext.artifactDir,
653
+ channelDir: options.channelDir,
693
654
  leaseKey,
694
655
  mutates: config.mutates,
695
656
  });
@@ -838,7 +799,7 @@ async function dispatchInternalRun(input) {
838
799
  */
839
800
  async function runToCompletion() {
840
801
  try {
841
- const contextualBlocks = await resolveContextualBlocks(params.task, config, options, currentModel);
802
+ const contextualBlocks = await resolveContextualBlocks(config, options);
842
803
  if (externallyCancelled) {
843
804
  failureReason = failureReason || "Cancelled by request.";
844
805
  }
@@ -0,0 +1,17 @@
1
+ /** How many loop-log lines a step brief carries. Older records stay addressable via `task_log`. */
2
+ export declare const BRIEF_LOG_LINES = 8;
3
+ export interface TaskBriefInput {
4
+ channelDir: string;
5
+ taskId: string;
6
+ /** Why this step is running: new cycle, ticket redeemed, ticket expired, previous step continued. */
7
+ reason?: string;
8
+ }
9
+ /**
10
+ * The turn input for one task loop step (spec 051, D3).
11
+ *
12
+ * The contract is injected whole because it is small by construction (INV-6, 4 KB); the history
13
+ * is the last few log lines rather than the 24 KB of closed cycles v3 pasted into every wake. Any
14
+ * pending `/tasks steer` or `/tasks reply` is consumed here and put first — it is the one thing in
15
+ * the brief that is genuinely new since the previous step.
16
+ */
17
+ export declare function buildTaskStepBrief(input: TaskBriefInput): Promise<string | undefined>;
@@ -0,0 +1,57 @@
1
+ import { effectiveBudget } from "./budget.js";
2
+ import { readTaskLog, renderTaskLogLine } from "./log.js";
3
+ import { consumeTaskSteer } from "./steer.js";
4
+ import { readStoredTask } from "./store.js";
5
+ import { describeTicket } from "./ticket.js";
6
+ /** How many loop-log lines a step brief carries. Older records stay addressable via `task_log`. */
7
+ export const BRIEF_LOG_LINES = 8;
8
+ /**
9
+ * The turn input for one task loop step (spec 051, D3).
10
+ *
11
+ * The contract is injected whole because it is small by construction (INV-6, 4 KB); the history
12
+ * is the last few log lines rather than the 24 KB of closed cycles v3 pasted into every wake. Any
13
+ * pending `/tasks steer` or `/tasks reply` is consumed here and put first — it is the one thing in
14
+ * the brief that is genuinely new since the previous step.
15
+ */
16
+ export async function buildTaskStepBrief(input) {
17
+ const document = await readStoredTask(input.channelDir, input.taskId);
18
+ if (!document)
19
+ return undefined;
20
+ const steer = await consumeTaskSteer(input.channelDir, input.taskId);
21
+ const log = await readTaskLog(input.channelDir, input.taskId, {
22
+ cycle: document.fields.cycle?.id,
23
+ limit: BRIEF_LOG_LINES,
24
+ });
25
+ const blocks = [`[TASK_STEP:${input.taskId}]`];
26
+ if (input.reason)
27
+ blocks.push(input.reason);
28
+ if (steer)
29
+ blocks.push(`<user_guidance>\n${steer}\n</user_guidance>`);
30
+ blocks.push(`<task_contract id="${input.taskId}">\n${document.body.trim()}\n</task_contract>`);
31
+ if (log.length > 0) {
32
+ blocks.push(`<task_log recent="${log.length}">\n${log.map(renderTaskLogLine).join("\n")}\n</task_log>`);
33
+ }
34
+ blocks.push(`<task_state>\n${renderState(document.fields)}\n</task_state>`);
35
+ blocks.push("推进这个任务的下一个具体步骤,然后必须调用 task_step_end 收尾:" +
36
+ "continue(还能继续)/ park(等一个真实来源)/ done(本周期完成)/ blocked(需要用户决定)。" +
37
+ "默认不向用户发言;确实需要告诉用户时用 notify。");
38
+ return blocks.join("\n\n");
39
+ }
40
+ function renderState(fields) {
41
+ const budget = effectiveBudget(fields);
42
+ const cycle = fields.cycle;
43
+ const lines = [`state: ${fields.state}`];
44
+ if (fields.schedule)
45
+ lines.push(`schedule: ${fields.schedule}`);
46
+ if (fields.verify === "required")
47
+ lines.push("verify: required(完成前需要一次独立验收 PASS)");
48
+ if (fields.ticket)
49
+ lines.push(`ticket: ${describeTicket(fields.ticket)}(兜底 ${fields.ticket.by})`);
50
+ if (cycle) {
51
+ lines.push(`cycle ${cycle.id}: ${cycle.steps}/${budget.steps} 步 · ${cycle.rounds}/${budget.rounds} 轮 · ` +
52
+ `$${cycle.usd.toFixed(2)}/$${budget.usd}${cycle.usdEstimated ? "(含估算)" : ""}`);
53
+ }
54
+ if (budget.until)
55
+ lines.push(`deadline: ${budget.until}`);
56
+ return lines.join("\n");
57
+ }
@@ -0,0 +1,26 @@
1
+ import type { TaskBudget, TaskCycle, TaskFrontmatterV4 } from "./frontmatter.js";
2
+ /**
3
+ * The cycle budget (spec 051, D6) — what replaced the governor.
4
+ *
5
+ * v3 tried to *infer* whether a task deserved to keep running, from a ten-field ledger
6
+ * fingerprint plus a process-local tally of "effectful" tool calls whose own source comment
7
+ * admitted `echo x` qualified. It fired twice in four months. A budget is the honest version of
8
+ * the same intent: four numbers the task carries, the loop spends, and the user can see and top
9
+ * up. When one runs out the task stops and says so — no guessing about whether the work was real.
10
+ */
11
+ export declare const DEFAULT_TASK_BUDGET: TaskBudget;
12
+ /** Two consecutive steps that called no tool at all: the loop is talking to itself. */
13
+ export declare const IDLE_STEP_LIMIT = 2;
14
+ export declare function effectiveBudget(fields: TaskFrontmatterV4): TaskBudget;
15
+ export type BudgetBreach = "steps" | "wallMin" | "usd" | "rounds" | "until";
16
+ export interface BudgetStatus {
17
+ breach?: BudgetBreach;
18
+ reason?: string;
19
+ }
20
+ /**
21
+ * Whether this cycle has run out of any of its four dimensions. Checked before a step is queued,
22
+ * so a task that is already over budget never spends one more model call to find out.
23
+ */
24
+ export declare function checkBudget(fields: TaskFrontmatterV4, now?: Date): BudgetStatus;
25
+ /** Add one step's measured cost to the cycle counters. */
26
+ export declare function accrueStep(cycle: TaskCycle, usd: number, estimated: boolean): TaskCycle;
@@ -0,0 +1,59 @@
1
+ import { parseLocalTime } from "../shared/local-time.js";
2
+ /**
3
+ * The cycle budget (spec 051, D6) — what replaced the governor.
4
+ *
5
+ * v3 tried to *infer* whether a task deserved to keep running, from a ten-field ledger
6
+ * fingerprint plus a process-local tally of "effectful" tool calls whose own source comment
7
+ * admitted `echo x` qualified. It fired twice in four months. A budget is the honest version of
8
+ * the same intent: four numbers the task carries, the loop spends, and the user can see and top
9
+ * up. When one runs out the task stops and says so — no guessing about whether the work was real.
10
+ */
11
+ export const DEFAULT_TASK_BUDGET = {
12
+ steps: 40,
13
+ wallMin: 180,
14
+ usd: 8,
15
+ rounds: 4,
16
+ };
17
+ /** Two consecutive steps that called no tool at all: the loop is talking to itself. */
18
+ export const IDLE_STEP_LIMIT = 2;
19
+ export function effectiveBudget(fields) {
20
+ return { ...DEFAULT_TASK_BUDGET, ...fields.budget };
21
+ }
22
+ /**
23
+ * Whether this cycle has run out of any of its four dimensions. Checked before a step is queued,
24
+ * so a task that is already over budget never spends one more model call to find out.
25
+ */
26
+ export function checkBudget(fields, now = new Date()) {
27
+ const cycle = fields.cycle;
28
+ if (!cycle)
29
+ return {};
30
+ const budget = effectiveBudget(fields);
31
+ if (cycle.steps >= budget.steps) {
32
+ return { breach: "steps", reason: `本周期已用满 ${budget.steps} 步` };
33
+ }
34
+ if (cycle.rounds >= budget.rounds) {
35
+ return { breach: "rounds", reason: `本周期已返工 ${cycle.rounds} 轮(上限 ${budget.rounds})` };
36
+ }
37
+ if (cycle.usd >= budget.usd) {
38
+ const estimated = cycle.usdEstimated ? "(含估算)" : "";
39
+ return { breach: "usd", reason: `本周期成本已达 $${cycle.usd.toFixed(2)}${estimated}(上限 $${budget.usd})` };
40
+ }
41
+ const startedMs = parseLocalTime(cycle.startedAt);
42
+ if (startedMs !== undefined && now.getTime() - startedMs >= budget.wallMin * 60_000) {
43
+ return { breach: "wallMin", reason: `本周期已运行超过 ${budget.wallMin} 分钟` };
44
+ }
45
+ const untilMs = budget.until ? parseLocalTime(budget.until) : undefined;
46
+ if (untilMs !== undefined && untilMs <= now.getTime()) {
47
+ return { breach: "until", reason: `已超过期限 ${budget.until}` };
48
+ }
49
+ return {};
50
+ }
51
+ /** Add one step's measured cost to the cycle counters. */
52
+ export function accrueStep(cycle, usd, estimated) {
53
+ return {
54
+ ...cycle,
55
+ steps: cycle.steps + 1,
56
+ usd: cycle.usd + Math.max(0, usd),
57
+ usdEstimated: cycle.usdEstimated || estimated,
58
+ };
59
+ }
@@ -0,0 +1,48 @@
1
+ import type { TaskCycle } from "./frontmatter.js";
2
+ /**
3
+ * Cycle boundaries (spec 051, §3.2).
4
+ *
5
+ * A cycle is the unit of work a task session's context is scoped to: opened when a one-shot task
6
+ * is created or a recurring task's schedule fires, closed when the loop reports `done`. v3 marked
7
+ * boundaries by shuffling `## Current Cycle` into `## History` inside the task file; v4 keeps the
8
+ * per-cycle record in `<id>.jsonl` and leaves exactly one paragraph — `## 上次结果` — in the
9
+ * contract, overwritten each time.
10
+ */
11
+ export declare const LAST_RESULT_SECTION_NAMES: readonly ["上次结果", "Last Result"];
12
+ /** Cap for the one historical paragraph the contract carries; the rest lives in the log (INV-6). */
13
+ export declare const MAX_LAST_RESULT_CHARS = 1200;
14
+ /**
15
+ * A stable cycle id for a runtime-opened cycle: `c-YYYY-MM-DD`, disambiguated with `-N` when the
16
+ * same task opens more than one cycle on the same local day.
17
+ */
18
+ export declare function nextCycleId(previousCycleId: string | undefined, occurrence?: Date): string;
19
+ /** Fresh counters for a newly opened cycle. */
20
+ export declare function createCycle(id: string, now?: Date): TaskCycle;
21
+ /**
22
+ * Body transformation for opening a cycle. Only recurring tasks reset their Plan: for a one-shot
23
+ * task the Plan is the single run's agenda and unchecking it would erase real progress, while for
24
+ * a recurring task the same steps genuinely start over each occurrence.
25
+ */
26
+ export declare function openCycleBody(body: string, recurring: boolean): string;
27
+ /**
28
+ * Upsert `## 上次结果` — the contract's single, overwritten historical paragraph. Over-long text
29
+ * is clipped with a pointer to `task_log`, because the contract has a hard size budget and the
30
+ * complete record is already durable in the loop log.
31
+ */
32
+ export declare function writeLastResult(body: string, text: string): string;
33
+ /** Remove `## 上次结果` entirely. The full record is always still in the loop log. */
34
+ export declare function stripLastResult(body: string): string;
35
+ /** The rendered `## 上次结果` text, if any — used by `/tasks show` and the step brief. */
36
+ export declare function readLastResult(body: string): string | undefined;
37
+ /** Compose the `## 上次结果` paragraph from a cycle close. */
38
+ export declare function renderCloseSummary(input: {
39
+ cycleId: string;
40
+ outcome: "done" | "cancelled";
41
+ summary: string;
42
+ evidence?: string;
43
+ residualRisk?: string;
44
+ steps: number;
45
+ rounds: number;
46
+ usd: number;
47
+ usdEstimated: boolean;
48
+ }): string;
@@ -0,0 +1,94 @@
1
+ import { formatLocalTime } from "../shared/local-time.js";
2
+ import { findTaskSectionBounds, resetTaskPlanForCycle } from "./ledger.js";
3
+ /**
4
+ * Cycle boundaries (spec 051, §3.2).
5
+ *
6
+ * A cycle is the unit of work a task session's context is scoped to: opened when a one-shot task
7
+ * is created or a recurring task's schedule fires, closed when the loop reports `done`. v3 marked
8
+ * boundaries by shuffling `## Current Cycle` into `## History` inside the task file; v4 keeps the
9
+ * per-cycle record in `<id>.jsonl` and leaves exactly one paragraph — `## 上次结果` — in the
10
+ * contract, overwritten each time.
11
+ */
12
+ export const LAST_RESULT_SECTION_NAMES = ["上次结果", "Last Result"];
13
+ const LAST_RESULT_HEADING = "## 上次结果";
14
+ /** Cap for the one historical paragraph the contract carries; the rest lives in the log (INV-6). */
15
+ export const MAX_LAST_RESULT_CHARS = 1_200;
16
+ /**
17
+ * A stable cycle id for a runtime-opened cycle: `c-YYYY-MM-DD`, disambiguated with `-N` when the
18
+ * same task opens more than one cycle on the same local day.
19
+ */
20
+ export function nextCycleId(previousCycleId, occurrence = new Date()) {
21
+ const base = `c-${occurrence.getFullYear()}-${String(occurrence.getMonth() + 1).padStart(2, "0")}-${String(occurrence.getDate()).padStart(2, "0")}`;
22
+ if (!previousCycleId || !previousCycleId.startsWith(base))
23
+ return base;
24
+ const suffix = previousCycleId.slice(base.length + 1);
25
+ const previousCount = suffix ? Number.parseInt(suffix, 10) : 1;
26
+ const nextCount = Number.isFinite(previousCount) && previousCount >= 1 ? previousCount + 1 : 2;
27
+ return `${base}-${nextCount}`;
28
+ }
29
+ /** Fresh counters for a newly opened cycle. */
30
+ export function createCycle(id, now = new Date()) {
31
+ return { id, startedAt: formatLocalTime(now), steps: 0, rounds: 0, usd: 0, usdEstimated: false, expired: 0 };
32
+ }
33
+ /**
34
+ * Body transformation for opening a cycle. Only recurring tasks reset their Plan: for a one-shot
35
+ * task the Plan is the single run's agenda and unchecking it would erase real progress, while for
36
+ * a recurring task the same steps genuinely start over each occurrence.
37
+ */
38
+ export function openCycleBody(body, recurring) {
39
+ return recurring ? resetTaskPlanForCycle(body) : body;
40
+ }
41
+ /**
42
+ * Upsert `## 上次结果` — the contract's single, overwritten historical paragraph. Over-long text
43
+ * is clipped with a pointer to `task_log`, because the contract has a hard size budget and the
44
+ * complete record is already durable in the loop log.
45
+ */
46
+ export function writeLastResult(body, text) {
47
+ const clipped = text.length > MAX_LAST_RESULT_CHARS
48
+ ? `${text.slice(0, MAX_LAST_RESULT_CHARS).trimEnd()}…(完整记录见 task_log)`
49
+ : text;
50
+ const lines = body.split("\n");
51
+ const bounds = findTaskSectionBounds(lines, LAST_RESULT_SECTION_NAMES);
52
+ const block = [LAST_RESULT_HEADING, "", clipped, ""];
53
+ if (bounds) {
54
+ lines.splice(bounds.headingIndex, bounds.end - bounds.headingIndex, ...block);
55
+ return lines.join("\n");
56
+ }
57
+ return `${body.replace(/\n+$/, "")}\n\n${block.join("\n")}`;
58
+ }
59
+ /** Remove `## 上次结果` entirely. The full record is always still in the loop log. */
60
+ export function stripLastResult(body) {
61
+ const lines = body.split("\n");
62
+ const bounds = findTaskSectionBounds(lines, LAST_RESULT_SECTION_NAMES);
63
+ if (!bounds)
64
+ return body;
65
+ lines.splice(bounds.headingIndex, bounds.end - bounds.headingIndex);
66
+ return lines
67
+ .join("\n")
68
+ .replace(/\n{3,}/g, "\n\n")
69
+ .trimEnd();
70
+ }
71
+ /** The rendered `## 上次结果` text, if any — used by `/tasks show` and the step brief. */
72
+ export function readLastResult(body) {
73
+ const lines = body.split("\n");
74
+ const bounds = findTaskSectionBounds(lines, LAST_RESULT_SECTION_NAMES);
75
+ if (!bounds)
76
+ return undefined;
77
+ const text = lines
78
+ .slice(bounds.headingIndex + 1, bounds.end)
79
+ .join("\n")
80
+ .trim();
81
+ return text || undefined;
82
+ }
83
+ /** Compose the `## 上次结果` paragraph from a cycle close. */
84
+ export function renderCloseSummary(input) {
85
+ const cost = `$${input.usd.toFixed(2)}${input.usdEstimated ? "(含估算)" : ""}`;
86
+ return [
87
+ `- ${input.cycleId} ${input.outcome === "done" ? "完成" : "取消"}:${input.summary}`,
88
+ input.evidence ? `- 证据:${input.evidence}` : undefined,
89
+ input.residualRisk ? `- 剩余风险:${input.residualRisk}` : undefined,
90
+ `- 用量:${input.steps} 步 / ${input.rounds} 轮 / ${cost}`,
91
+ ]
92
+ .filter(Boolean)
93
+ .join("\n");
94
+ }
@@ -0,0 +1,73 @@
1
+ import { type Ticket } from "./ticket.js";
2
+ /**
3
+ * The v4 task frontmatter (spec 051, §12.2).
4
+ *
5
+ * v3 spread one question across pairs of fields that had to agree — `enabled: false` had to match
6
+ * `control.stop`, `status: active` had to not carry a future `wake` — and `/tasks doctor` existed
7
+ * largely to find the pairs that had drifted. v4 removes the pairs instead of diagnosing them:
8
+ * `paused` present *is* paused, and `state: "parked"` ⟺ `ticket` present (INV-1), enforced on
9
+ * every read and every write rather than checked after the fact.
10
+ */
11
+ export type TaskState = "open" | "parked" | "done";
12
+ export interface TaskPaused {
13
+ by: "user" | "runtime";
14
+ reason: string;
15
+ at: string;
16
+ }
17
+ /** Live counters for the cycle in flight. Reset by `openCycle`, read by the budget and `/tasks`. */
18
+ export interface TaskCycle {
19
+ id: string;
20
+ startedAt: string;
21
+ steps: number;
22
+ rounds: number;
23
+ usd: number;
24
+ /** True once any cost in this cycle came from an estimate rather than reported usage (D10). */
25
+ usdEstimated: boolean;
26
+ /** Ticket backstops that expired in this cycle; the second one notifies the user (D2). */
27
+ expired: number;
28
+ }
29
+ export interface TaskBudget {
30
+ steps: number;
31
+ wallMin: number;
32
+ usd: number;
33
+ rounds: number;
34
+ /** Absolute local-time stop, the v4 home of v3's `control.deadline`. */
35
+ until?: string;
36
+ }
37
+ export type TaskArchiveOutcome = "completed" | "cancelled";
38
+ export interface TaskFrontmatterV4 {
39
+ state: TaskState;
40
+ paused?: TaskPaused;
41
+ schedule?: string;
42
+ /** Present iff `state === "parked"` (INV-1). */
43
+ ticket?: Ticket;
44
+ cycle?: TaskCycle;
45
+ budget?: Partial<TaskBudget>;
46
+ verify?: "required";
47
+ /** Archive-only. */
48
+ outcome?: TaskArchiveOutcome;
49
+ closedAt?: string;
50
+ }
51
+ export interface ParsedTaskFrontmatter {
52
+ fields: TaskFrontmatterV4;
53
+ /** false => the block could not be read at all; the task is surfaced rather than skipped. */
54
+ readable: boolean;
55
+ /** True when a v3 `control:`/`status:` line is present — the migrator's only trigger. */
56
+ legacy: boolean;
57
+ }
58
+ /**
59
+ * Read the leading frontmatter block. Unreadable input fails **open** to a live `open` task: a
60
+ * corrupt file has to surface as work the runtime tries to touch, not silently disappear from the
61
+ * ledger — the same fail-open stance v3 took, for the same reason.
62
+ */
63
+ export declare function parseTaskFrontmatterV4(content: string): ParsedTaskFrontmatter;
64
+ /**
65
+ * Enforce INV-1 on every write and read: `parked` requires a ticket, and a ticket only means
66
+ * anything while parked. Doing it here rather than at each call site is what makes "a parked task
67
+ * always has a redeemable, backstopped source" a property of the file format instead of a rule
68
+ * every writer has to remember.
69
+ */
70
+ export declare function normalizeTaskFrontmatter(fields: TaskFrontmatterV4): TaskFrontmatterV4;
71
+ export declare function renderTaskFrontmatter(fields: TaskFrontmatterV4): string;
72
+ /** Whether the driver may schedule a step for this task right now. */
73
+ export declare function isTaskRunnable(fields: TaskFrontmatterV4): boolean;