@oyasmi/pipiclaw 0.9.2 → 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,54 +1,45 @@
1
1
  import type { Static } from "typebox";
2
- import type { TaskControl } from "../../tasks/control.js";
3
- import type { taskCloseSchema, taskCreateSchema, taskUpdateSchema, taskVerifySchema } from "./schema.js";
2
+ import type { taskCloseSchema, taskCreateSchema, taskLogSchema, taskStepEndSchema, taskUpdateSchema } from "./schema.js";
4
3
  export interface TaskManageResult {
5
- action: "create" | "update" | "close" | "verify" | "list";
4
+ action: "create" | "update" | "close" | "list" | "log" | "step_end";
6
5
  id?: string;
7
6
  path?: string;
8
- status?: string;
7
+ state?: string;
9
8
  archived?: boolean;
10
9
  deletedEvents?: string[];
11
10
  tasks?: Array<{
12
11
  id: string;
13
12
  title: string;
14
- status: string;
15
- enabled: boolean;
16
- wake?: string;
17
- actionable: boolean;
18
- control?: TaskControl;
13
+ state: string;
14
+ paused: boolean;
15
+ ticket?: string;
16
+ cycle?: string;
17
+ steps?: number;
18
+ rounds?: number;
19
19
  }>;
20
+ /** Rendered log lines, for `task_log`. */
21
+ entries?: string[];
20
22
  notice: string;
21
23
  }
22
24
  /**
23
- * Five request types, derived from the five schemas the model actually sees (spec 046, D3.3) —
24
- * the spec 036 D8 "derive from schema" discipline, doubled: each action's required fields are now
25
- * non-optional in the type, not merely documented as "required for X" in a shared schema's prose.
26
- *
27
- * `status`/`outcome` stay plain strings where the underlying schema uses a literal union: they are
28
- * validated in code against the transition table so a legacy or closing value gets a fixable error
29
- * naming the right tool, rather than a bare schema rejection.
25
+ * One request type per schema the model actually sees (spec 046, D3.3): each action's required
26
+ * fields are non-optional in the type rather than documented as "required for X" in shared prose.
30
27
  */
31
- export type TaskCreateRequest = Omit<Static<typeof taskCreateSchema>, "status"> & {
32
- status?: string;
33
- };
34
- export type TaskUpdateRequest = Omit<Static<typeof taskUpdateSchema>, "status"> & {
35
- status?: string;
36
- };
28
+ export type TaskCreateRequest = Static<typeof taskCreateSchema>;
29
+ export type TaskUpdateRequest = Static<typeof taskUpdateSchema>;
37
30
  export type TaskCloseRequest = Static<typeof taskCloseSchema>;
38
- export type TaskVerifyRequest = Static<typeof taskVerifySchema>;
31
+ export type TaskLogRequest = Static<typeof taskLogSchema>;
32
+ export type TaskStepEndRequest = Static<typeof taskStepEndSchema>;
39
33
  export interface TaskManageToolOptions {
40
34
  workspaceDir: string;
41
35
  channelDir: string;
42
36
  channelId: string;
43
37
  /** Project checkout whose artifact state an independent verifier binds to. */
44
38
  workingDirectory?: string;
45
- }
46
- export interface TaskFields {
47
- status: string;
48
- enabled?: boolean;
49
- wake?: string;
50
- schedule?: string;
51
- control?: TaskControl;
52
- outcome?: "completed" | "cancelled";
53
- closedAt?: string;
39
+ /** Present only inside a task session: which task's loop this tool set belongs to. */
40
+ taskId?: string;
41
+ /** Present only inside a task session: the cycle the current step belongs to. */
42
+ cycleId?: string;
43
+ /** Tools this step has completed so far; feeds the loop log's idle-step evidence (D6). */
44
+ getToolsUsed?: () => string[];
54
45
  }
@@ -1,9 +1,10 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
- import { taskCloseSchema, taskCreateSchema, taskListSchema, taskUpdateSchema, taskVerifySchema } from "./task-manage/schema.js";
2
+ import { taskCloseSchema, taskCreateSchema, taskListSchema, taskLogSchema, taskStepEndSchema, taskUpdateSchema } from "./task-manage/schema.js";
3
3
  import type { TaskManageToolOptions } from "./task-manage/types.js";
4
- export type { TaskCloseRequest, TaskCreateRequest, TaskManageResult, TaskManageToolOptions, TaskUpdateRequest, TaskVerifyRequest, } from "./task-manage/types.js";
4
+ export type { TaskCloseRequest, TaskCreateRequest, TaskLogRequest, TaskManageResult, TaskManageToolOptions, TaskStepEndRequest, TaskUpdateRequest, } from "./task-manage/types.js";
5
5
  export declare function createTaskListTool(options: TaskManageToolOptions): AgentTool<typeof taskListSchema>;
6
6
  export declare function createTaskCreateTool(options: TaskManageToolOptions): AgentTool<typeof taskCreateSchema>;
7
7
  export declare function createTaskUpdateTool(options: TaskManageToolOptions): AgentTool<typeof taskUpdateSchema>;
8
8
  export declare function createTaskCloseTool(options: TaskManageToolOptions): AgentTool<typeof taskCloseSchema>;
9
- export declare function createTaskVerifyTool(options: TaskManageToolOptions): AgentTool<typeof taskVerifySchema>;
9
+ export declare function createTaskLogTool(options: TaskManageToolOptions): AgentTool<typeof taskLogSchema>;
10
+ export declare function createTaskStepEndTool(options: TaskManageToolOptions): AgentTool<typeof taskStepEndSchema>;
@@ -2,14 +2,17 @@ import { normalizeTaskId } from "../tasks/ledger.js";
2
2
  import { withTaskMutation } from "../tasks/mutation-lock.js";
3
3
  import { createTask } from "./task-manage/create.js";
4
4
  import { closeTask, listTasks, updateTask } from "./task-manage/lifecycle.js";
5
- import { taskCloseSchema, taskCreateSchema, taskListSchema, taskUpdateSchema, taskVerifySchema, } from "./task-manage/schema.js";
6
- import { verifyTask } from "./task-manage/verification.js";
5
+ import { readTaskLogTool } from "./task-manage/log-view.js";
6
+ import { taskCloseSchema, taskCreateSchema, taskListSchema, taskLogSchema, taskStepEndSchema, taskUpdateSchema, } from "./task-manage/schema.js";
7
+ import { endTaskStep } from "./task-manage/step-end.js";
7
8
  /**
8
- * Five tools, one per payload shape (spec 046, D3.1) — replaces the single `task_manage`
9
- * dispatcher. Each factory only wires its own schema and, for the four that carry an `id`, the
10
- * same per-task serial lock `manageTask` used to apply centrally (spec 029, D7): a task file
11
- * write must never race another write to the same task, and that guarantee has to travel with
12
- * the split, not get silently dropped in the split (spec 046, D3.4).
9
+ * One tool per payload shape (spec 046, D3.1). Each factory wires only its own schema and, for
10
+ * the ones that carry an `id`, the same per-task serial lock (spec 029, D7): a task file write
11
+ * must never race another write to the same task, and that guarantee travels with the split.
12
+ *
13
+ * Spec 051 retired `task_verify` — importing a verifier's attestation is bookkeeping the runtime
14
+ * does at settlement, not a decision worth a tool call — and added `task_log` (read the loop log)
15
+ * and `task_step_end` (the loop's only closing move, registered only inside a task session).
13
16
  */
14
17
  async function withLock(options, id, mutate) {
15
18
  return withTaskMutation(options.channelDir, normalizeTaskId(id), mutate);
@@ -30,7 +33,7 @@ export function createTaskCreateTool(options) {
30
33
  return {
31
34
  name: "task_create",
32
35
  label: "task_create",
33
- description: "Create a persistent task: goal, DoD, and optional plan, manual, verification plan, and schedule.",
36
+ description: "Create a persistent task: goal, DoD, and optional plan, manual, verification plan, schedule, budget.",
34
37
  parameters: taskCreateSchema,
35
38
  execute: async (_toolCallId, args) => {
36
39
  const result = await withLock(options, args.id, () => createTask(options, args));
@@ -42,7 +45,7 @@ export function createTaskUpdateTool(options) {
42
45
  return {
43
46
  name: "task_update",
44
47
  label: "task_update",
45
- description: "With `note`: checkpoint an open task cycle. Without: metadata-only edit (status/wake/schedule/planSteps/control), also the only path that repairs a bad control line.",
48
+ description: "Edit a task's plan steps, cadence, budget, or verification requirement. Progress goes to task_step_end.",
46
49
  parameters: taskUpdateSchema,
47
50
  execute: async (_toolCallId, args) => {
48
51
  const result = await withLock(options, args.id, () => updateTask(options, args));
@@ -62,14 +65,26 @@ export function createTaskCloseTool(options) {
62
65
  },
63
66
  };
64
67
  }
65
- export function createTaskVerifyTool(options) {
68
+ export function createTaskLogTool(options) {
66
69
  return {
67
- name: "task_verify",
68
- label: "task_verify",
69
- description: "Import a purpose=verify sub-agent's attestation by run id.",
70
- parameters: taskVerifySchema,
70
+ name: "task_log",
71
+ label: "task_log",
72
+ description: "Read a task's loop log: steps, verification rounds, expiries and cycle closes.",
73
+ parameters: taskLogSchema,
71
74
  execute: async (_toolCallId, args) => {
72
- const result = await withLock(options, args.id, () => verifyTask(options, args));
75
+ const result = await readTaskLogTool(options, args);
76
+ return { content: [{ type: "text", text: JSON.stringify(result) }], details: { ...result } };
77
+ },
78
+ };
79
+ }
80
+ export function createTaskStepEndTool(options) {
81
+ return {
82
+ name: "task_step_end",
83
+ label: "task_step_end",
84
+ description: "End this task step: continue (more work now), park (wait on a ticket), done (close the cycle), or blocked (ask the user).",
85
+ parameters: taskStepEndSchema,
86
+ execute: async (_toolCallId, args) => {
87
+ const result = await withLock(options, options.taskId ?? "", () => endTaskStep(options, args));
73
88
  return { content: [{ type: "text", text: JSON.stringify(result) }], details: { ...result } };
74
89
  },
75
90
  };
@@ -18,7 +18,7 @@ export { RecoverableToolError } from "../shared/recoverable-error.js";
18
18
  * Every tool that can appear in a tool set. Equal to the registry's tool names plus
19
19
  * `subagent`, which is registered separately (see the note on TOOL_REGISTRY).
20
20
  */
21
- export type ToolDetailsKind = "read" | "bash" | "edit" | "grep" | "glob" | "write" | "web_search" | "web_fetch" | "send_media" | "session_search" | "memory_save" | "memory_search" | "memory_forget" | "skill" | "event_manage" | "task_list" | "task_create" | "task_update" | "task_close" | "task_verify" | "job" | "subagent" | "subagent_inline" | "subagent_list" | "subagent_run";
21
+ export type ToolDetailsKind = "read" | "bash" | "edit" | "grep" | "glob" | "write" | "web_search" | "web_fetch" | "send_media" | "session_search" | "memory_save" | "memory_search" | "memory_forget" | "skill" | "event_manage" | "task_list" | "task_create" | "task_update" | "task_close" | "task_log" | "task_step_end" | "job" | "subagent" | "subagent_inline" | "subagent_list" | "subagent_run";
22
22
  /** The fields every tool result's `details` carries. Tool-specific fields extend this. */
23
23
  export interface ToolDetails {
24
24
  /** Which tool produced this result. Stamped by `withToolDetails`; never written by hand. */
package/dist/tui/app.js CHANGED
@@ -13,7 +13,6 @@ import { ensureChannelDir } from "../channel/channel-paths.js";
13
13
  import { ChannelStore } from "../channel/store.js";
14
14
  import { renderBuiltInHelp } from "../commands/catalog.js";
15
15
  import * as log from "../log.js";
16
- import { ensureChannelMemoryFilesSync } from "../memory/files.js";
17
16
  import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, printBootstrapSummary, readCliVersion, } from "../runtime/app-home.js";
18
17
  import { prepareAppServices } from "../runtime/bootstrap.js";
19
18
  import { finalDeliveryOf, progressStyleOf } from "../runtime/dingtalk.js";
@@ -101,7 +100,6 @@ export async function runTuiApp(options) {
101
100
  log.configureLogging(settingsManager.getLoggingSettings());
102
101
  log.logStartup(paths.workspaceDir);
103
102
  const channelDir = ensureChannelDir(paths.workspaceDir, channelId);
104
- ensureChannelMemoryFilesSync(channelDir);
105
103
  const store = new ChannelStore({ workingDir: paths.workspaceDir });
106
104
  const buildRunner = () => createRunner(channelId, channelDir, {
107
105
  appHomeDir: paths.appHomeDir,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oyasmi/pipiclaw",
3
- "version": "0.9.2",
3
+ "version": "0.9.3-beta.1",
4
4
  "description": "An AI assistant runtime for coding and team workflows, with DingTalk AI Cards, sub-agents, memory, and scheduled events.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,32 +0,0 @@
1
- export declare function noteChannelEffect(channelId: string): void;
2
- export declare function channelEffectCount(channelId: string): number;
3
- /**
4
- * Credit one task-driver turn's effects to that task.
5
- *
6
- * The channel tally above answers "how much has happened here", which is the wrong question for
7
- * the governor: it also counts the user's small talk, so every task in a busy channel looked like
8
- * it had just made progress (continue at once, futile counter reset) while a genuinely spinning
9
- * task hid behind its neighbours. The caller measures one turn as a delta of the channel tally —
10
- * turns are serialized per channel — and credits it to the task that turn was dispatched for.
11
- */
12
- export declare function noteTaskEffects(channelId: string, taskId: string, delta: number): void;
13
- /** Effects produced by this task's own driver turns so far (spec 031, D7). */
14
- export declare function taskEffectCount(channelId: string, taskId: string): number;
15
- /** Test seam: drop all tallies. */
16
- export declare function resetChannelEffects(): void;
17
- /**
18
- * Whether a completed tool call counts as an effect.
19
- *
20
- * `bash` is the awkward case: the same tool runs `ls` and `rm -rf`, and the runtime cannot tell
21
- * them apart. It used to count only a background launch, which produced the wrong answer for the
22
- * single most important shape this runtime has — a turn that synchronously drives an external
23
- * coding agent, then records what came back. That turn changes no file the runtime can see and
24
- * usually ends `[SILENT]`, so it scored zero effects and, after three of them, got its task disabled
25
- * by the governor: the hardest-working wake was the one most likely to be judged idle.
26
- *
27
- * A synchronous command that exited 0 and returned output therefore counts too. That is
28
- * bypassable — `echo x` qualifies — but the alternative was a false negative on real work, and the
29
- * counter never was the stop-loss: `budget.maxAttempts` bounds a task no matter how productive it
30
- * claims to look. What "futile" now means is the honest thing: a wake that executed nothing at all.
31
- */
32
- export declare function isEffectfulTool(toolName: string, details: unknown): boolean;
@@ -1,89 +0,0 @@
1
- import { isRecord } from "../shared/type-guards.js";
2
- /**
3
- * Per-channel tally of externally visible effects (spec 031, D7).
4
- *
5
- * The task governor has to answer "did that wake accomplish anything?". It used to answer by
6
- * diffing the task file's own metadata — including the model-written progress note — which made
7
- * the check both bypassable and unfair: a model that appended a note every wake looked productive
8
- * forever, while a model that changed code without writing a note looked stalled and got disabled.
9
- *
10
- * Effects are counted here instead, and only for things that change the world outside the task
11
- * ledger: writes, outbound media, sub-agent runs, background job launches, and a user-visible
12
- * reply. Self-report tools (`task_create`/`task_update`/`task_close`/`task_verify`, `memory_save`/`memory_search`/`memory_forget`) and read-only tools deliberately do
13
- * not count — a claim of progress is not evidence of it.
14
- *
15
- * The tally lives in process memory, exactly like the driver's futile counter it feeds; a restart
16
- * resets both, which costs at most one extra round of patience before the governor intervenes.
17
- *
18
- * Two tallies are kept: one per channel (raw, the measurement point) and one per task, credited
19
- * a turn at a time by the runtime. The governor reads the second — see `noteTaskEffects`.
20
- */
21
- const counts = new Map();
22
- const taskCounts = new Map();
23
- /** Tools whose successful completion is, by itself, a visible change to the world. */
24
- const EFFECT_TOOLS = new Set(["write", "edit", "send_media", "subagent", "subagent_inline"]);
25
- export function noteChannelEffect(channelId) {
26
- counts.set(channelId, (counts.get(channelId) ?? 0) + 1);
27
- }
28
- export function channelEffectCount(channelId) {
29
- return counts.get(channelId) ?? 0;
30
- }
31
- function taskKey(channelId, taskId) {
32
- return `${channelId}\0${taskId}`;
33
- }
34
- /**
35
- * Credit one task-driver turn's effects to that task.
36
- *
37
- * The channel tally above answers "how much has happened here", which is the wrong question for
38
- * the governor: it also counts the user's small talk, so every task in a busy channel looked like
39
- * it had just made progress (continue at once, futile counter reset) while a genuinely spinning
40
- * task hid behind its neighbours. The caller measures one turn as a delta of the channel tally —
41
- * turns are serialized per channel — and credits it to the task that turn was dispatched for.
42
- */
43
- export function noteTaskEffects(channelId, taskId, delta) {
44
- if (delta <= 0)
45
- return;
46
- const key = taskKey(channelId, taskId);
47
- taskCounts.set(key, (taskCounts.get(key) ?? 0) + delta);
48
- }
49
- /** Effects produced by this task's own driver turns so far (spec 031, D7). */
50
- export function taskEffectCount(channelId, taskId) {
51
- return taskCounts.get(taskKey(channelId, taskId)) ?? 0;
52
- }
53
- /** Test seam: drop all tallies. */
54
- export function resetChannelEffects() {
55
- counts.clear();
56
- taskCounts.clear();
57
- }
58
- /**
59
- * Whether a completed tool call counts as an effect.
60
- *
61
- * `bash` is the awkward case: the same tool runs `ls` and `rm -rf`, and the runtime cannot tell
62
- * them apart. It used to count only a background launch, which produced the wrong answer for the
63
- * single most important shape this runtime has — a turn that synchronously drives an external
64
- * coding agent, then records what came back. That turn changes no file the runtime can see and
65
- * usually ends `[SILENT]`, so it scored zero effects and, after three of them, got its task disabled
66
- * by the governor: the hardest-working wake was the one most likely to be judged idle.
67
- *
68
- * A synchronous command that exited 0 and returned output therefore counts too. That is
69
- * bypassable — `echo x` qualifies — but the alternative was a false negative on real work, and the
70
- * counter never was the stop-loss: `budget.maxAttempts` bounds a task no matter how productive it
71
- * claims to look. What "futile" now means is the honest thing: a wake that executed nothing at all.
72
- */
73
- export function isEffectfulTool(toolName, details) {
74
- if (toolName === "subagent_run") {
75
- // Spec 047, F6/D3.2: op=follow_up dispatches a new external run — as much a visible change
76
- // to the world as `subagent` itself. show/cancel are not. The discriminator is `resumedFrom`
77
- // in `details` rather than `op`, because only a successful dispatch sets it: every follow_up
78
- // failure path throws or returns a RecoverableToolError, so a rejection can never count.
79
- return isRecord(details) && typeof details.resumedFrom === "string";
80
- }
81
- if (toolName === "bash") {
82
- if (!isRecord(details))
83
- return false;
84
- if (details.async !== undefined)
85
- return true;
86
- return details.exitCode === 0 && details.producedOutput === true;
87
- }
88
- return EFFECT_TOOLS.has(toolName);
89
- }
@@ -1,17 +0,0 @@
1
- /**
2
- * Automatic-context share for the first-turn durable snapshot (spec 026 §5.3).
3
- * It is a fallback, not a full memory dump: turn-specific recall carries the rest.
4
- */
5
- export declare const FIRST_TURN_BOOTSTRAP_MAX_UNITS = 400;
6
- export interface FirstTurnMemoryBootstrapOptions {
7
- channelMemory: string;
8
- workspaceMemory: string;
9
- maxChars?: number;
10
- maxUnits?: number;
11
- }
12
- export interface FirstTurnMemoryBootstrapResult {
13
- renderedText: string;
14
- includedCandidateIds: string[];
15
- }
16
- export declare function buildFirstTurnMemoryBootstrap(options: FirstTurnMemoryBootstrapOptions): string;
17
- export declare function buildFirstTurnMemoryBootstrapResult(options: FirstTurnMemoryBootstrapOptions): FirstTurnMemoryBootstrapResult;
@@ -1,120 +0,0 @@
1
- import { splitH2Sections } from "../shared/markdown-sections.js";
2
- import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
3
- import { stripCrAndTrim } from "../shared/text-utils.js";
4
- import { buildMemoryCandidateId } from "./candidates.js";
5
- import { parseChannelMemoryEntries } from "./files.js";
6
- const FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS = 3_000;
7
- /**
8
- * Automatic-context share for the first-turn durable snapshot (spec 026 §5.3).
9
- * It is a fallback, not a full memory dump: turn-specific recall carries the rest.
10
- */
11
- export const FIRST_TURN_BOOTSTRAP_MAX_UNITS = 400;
12
- const MIN_SECTION_CHARS = 600;
13
- const MIN_SECTION_UNITS = 100;
14
- const CHANNEL_MEMORY_WEIGHT = 0.6;
15
- const ZERO_BUDGET = { chars: 0, units: 0 };
16
- function hasVisibleContent(content) {
17
- return content.replace(/<!--[\s\S]*?-->/g, "").trim().length > 0;
18
- }
19
- /** Keep `text` within both the char and unit ceilings, head/tail (or head-only when headRatio ≥ 1). */
20
- function clipToBudget(text, budget, headRatio) {
21
- return clipTextByPromptUnits(text, budget.units, {
22
- headRatio,
23
- maxChars: budget.chars,
24
- marker: "\n\n[... omitted for length ...]\n\n",
25
- }).text;
26
- }
27
- // Channel MEMORY.md is "structured sections up top, `## Update <ts>` blocks appended
28
- // at the tail". A plain head clip would drop the newest facts, so pick sections by
29
- // priority (structured first, then newest Update blocks) but render in document order
30
- // for readability. A section is kept only if it fits both the char and unit budget.
31
- function selectChannelMemoryForBootstrap(content, budget) {
32
- const sections = splitH2Sections(content).filter((section) => hasVisibleContent(section.content));
33
- if (sections.length === 0) {
34
- return clipToBudget(content, budget, 1);
35
- }
36
- const renderSection = (section) => `## ${section.heading}\n\n${section.content}`;
37
- const structured = sections.filter((section) => !section.heading.startsWith("Update "));
38
- const updatesNewestFirst = sections.filter((section) => section.heading.startsWith("Update ")).reverse();
39
- const byPriority = [...structured, ...updatesNewestFirst];
40
- const chosen = new Set();
41
- let usedChars = 0;
42
- let usedUnits = 0;
43
- for (const section of byPriority) {
44
- const text = renderSection(section);
45
- const separatorChars = chosen.size > 0 ? 2 : 0;
46
- const costChars = separatorChars + text.length;
47
- const costUnits = countPromptUnits(text); // section separators are whitespace → 0 units
48
- if (usedChars + costChars <= budget.chars && usedUnits + costUnits <= budget.units) {
49
- chosen.add(section);
50
- usedChars += costChars;
51
- usedUnits += costUnits;
52
- }
53
- }
54
- if (chosen.size === 0) {
55
- return clipToBudget(renderSection(byPriority[0]), budget, 0.5);
56
- }
57
- return sections
58
- .filter((section) => chosen.has(section))
59
- .map(renderSection)
60
- .join("\n\n");
61
- }
62
- /** Split the total budget across channel (60%) and workspace memory in both dimensions. */
63
- function splitBudget(max) {
64
- const channelChars = Math.max(MIN_SECTION_CHARS, Math.floor(max.chars * CHANNEL_MEMORY_WEIGHT));
65
- const workspaceChars = Math.max(MIN_SECTION_CHARS, max.chars - channelChars);
66
- const channelUnits = Math.max(MIN_SECTION_UNITS, Math.floor(max.units * CHANNEL_MEMORY_WEIGHT));
67
- const workspaceUnits = Math.max(MIN_SECTION_UNITS, max.units - channelUnits);
68
- const channel = {
69
- chars: channelChars + Math.max(0, max.chars - channelChars - workspaceChars),
70
- units: channelUnits + Math.max(0, max.units - channelUnits - workspaceUnits),
71
- };
72
- return [channel, { chars: workspaceChars, units: workspaceUnits }];
73
- }
74
- function allocateBudgets(channelMemory, workspaceMemory, max) {
75
- if (!channelMemory && !workspaceMemory) {
76
- return [ZERO_BUDGET, ZERO_BUDGET];
77
- }
78
- if (!channelMemory) {
79
- return [ZERO_BUDGET, max];
80
- }
81
- if (!workspaceMemory) {
82
- return [max, ZERO_BUDGET];
83
- }
84
- return splitBudget(max);
85
- }
86
- export function buildFirstTurnMemoryBootstrap(options) {
87
- return buildFirstTurnMemoryBootstrapResult(options).renderedText;
88
- }
89
- export function buildFirstTurnMemoryBootstrapResult(options) {
90
- const max = {
91
- chars: options.maxChars ?? FIRST_TURN_MEMORY_SNAPSHOT_MAX_CHARS,
92
- units: options.maxUnits ?? FIRST_TURN_BOOTSTRAP_MAX_UNITS,
93
- };
94
- const channelMemory = stripCrAndTrim(options.channelMemory);
95
- const workspaceMemory = stripCrAndTrim(options.workspaceMemory);
96
- if (!channelMemory && !workspaceMemory) {
97
- return { renderedText: "", includedCandidateIds: [] };
98
- }
99
- const [channelBudget, workspaceBudget] = allocateBudgets(channelMemory, workspaceMemory, max);
100
- const sections = [
101
- "<durable_memory_snapshot>",
102
- "Durable memory bootstrap for the first user turn in this session.",
103
- "Use it as background context together with any turn-specific recalled snippets.",
104
- ];
105
- const includedCandidateIds = [];
106
- if (channelMemory) {
107
- const selectedChannelMemory = channelBudget.chars > 0 ? selectChannelMemoryForBootstrap(channelMemory, channelBudget) : channelMemory;
108
- sections.push("", "[Channel MEMORY.md]");
109
- sections.push(selectedChannelMemory);
110
- includedCandidateIds.push(...parseChannelMemoryEntries(selectedChannelMemory).map((entry) => entry.id));
111
- }
112
- if (workspaceMemory) {
113
- const selectedWorkspaceMemory = workspaceBudget.chars > 0 ? clipToBudget(workspaceMemory, workspaceBudget, 1) : workspaceMemory;
114
- sections.push("", "[Workspace MEMORY.md]");
115
- sections.push(selectedWorkspaceMemory);
116
- includedCandidateIds.push(...splitH2Sections(selectedWorkspaceMemory).map((section) => buildMemoryCandidateId("workspace-memory", section.heading)));
117
- }
118
- sections.push("</durable_memory_snapshot>");
119
- return { renderedText: sections.join("\n"), includedCandidateIds };
120
- }
@@ -1,26 +0,0 @@
1
- export interface MemoryCandidate {
2
- id: string;
3
- source: "workspace-memory" | "channel-memory" | "channel-session" | "channel-history";
4
- path: string;
5
- title: string;
6
- content: string;
7
- searchText?: string;
8
- timestamp?: string;
9
- sectionKind?: string;
10
- priority: number;
11
- entryId?: string;
12
- }
13
- export interface BuildMemoryCandidatesOptions {
14
- workspaceDir: string;
15
- channelDir: string;
16
- }
17
- export declare function buildMemoryCandidateId(source: MemoryCandidate["source"], title: string, timestamp?: string): string;
18
- export declare class MemoryCandidateStore {
19
- private files;
20
- private inflight;
21
- invalidate(path?: string): void;
22
- getCandidates(options: BuildMemoryCandidatesOptions): Promise<MemoryCandidate[]>;
23
- private loadFileCandidates;
24
- }
25
- export declare function createMemoryCandidateStore(): MemoryCandidateStore;
26
- export declare function buildMemoryCandidates(options: BuildMemoryCandidatesOptions, store?: MemoryCandidateStore): Promise<MemoryCandidate[]>;