@oyasmi/pipiclaw 0.9.2 → 0.9.3-beta.2

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 (178) hide show
  1. package/README.en.md +250 -0
  2. package/README.md +3 -1
  3. package/dist/agent/channel-runner.d.ts +59 -2
  4. package/dist/agent/channel-runner.js +177 -76
  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 +19 -0
  40. package/dist/memory/render.js +35 -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/memory/transcript.js +12 -5
  54. package/dist/playbooks/agent-delegation.md +37 -9
  55. package/dist/playbooks/background-jobs.md +1 -1
  56. package/dist/playbooks/event-scheduling.md +6 -2
  57. package/dist/playbooks/memory-and-learning.md +36 -12
  58. package/dist/playbooks/outbound-media.md +1 -1
  59. package/dist/playbooks/runtime-orientation.md +9 -8
  60. package/dist/playbooks/task-loop.md +110 -0
  61. package/dist/runtime/bootstrap.d.ts +3 -3
  62. package/dist/runtime/bootstrap.js +66 -41
  63. package/dist/runtime/events.d.ts +9 -0
  64. package/dist/runtime/events.js +43 -4
  65. package/dist/runtime/task-commands.d.ts +14 -15
  66. package/dist/runtime/task-commands.js +249 -485
  67. package/dist/runtime/task-driver.d.ts +41 -29
  68. package/dist/runtime/task-driver.js +170 -317
  69. package/dist/runtime/task-migration.d.ts +34 -30
  70. package/dist/runtime/task-migration.js +229 -183
  71. package/dist/runtime/task-wake.d.ts +6 -3
  72. package/dist/runtime/task-wake.js +26 -19
  73. package/dist/settings.d.ts +0 -29
  74. package/dist/settings.js +12 -35
  75. package/dist/shared/markdown-sections.d.ts +0 -1
  76. package/dist/shared/markdown-sections.js +0 -3
  77. package/dist/subagents/discovery.d.ts +2 -2
  78. package/dist/subagents/discovery.js +21 -10
  79. package/dist/subagents/external/progress-tail.js +6 -1
  80. package/dist/subagents/external/run.js +1 -0
  81. package/dist/subagents/runs.d.ts +19 -2
  82. package/dist/subagents/runs.js +73 -4
  83. package/dist/subagents/tool.d.ts +10 -8
  84. package/dist/subagents/tool.js +55 -94
  85. package/dist/tasks/brief.d.ts +17 -0
  86. package/dist/tasks/brief.js +57 -0
  87. package/dist/tasks/budget.d.ts +26 -0
  88. package/dist/tasks/budget.js +59 -0
  89. package/dist/tasks/cycle.d.ts +48 -0
  90. package/dist/tasks/cycle.js +94 -0
  91. package/dist/tasks/frontmatter.d.ts +73 -0
  92. package/dist/tasks/frontmatter.js +175 -0
  93. package/dist/tasks/ledger.d.ts +66 -106
  94. package/dist/tasks/ledger.js +90 -546
  95. package/dist/tasks/log.d.ts +88 -0
  96. package/dist/tasks/log.js +97 -0
  97. package/dist/tasks/rounds.d.ts +41 -0
  98. package/dist/tasks/rounds.js +53 -0
  99. package/dist/tasks/session-path.d.ts +9 -0
  100. package/dist/tasks/session-path.js +16 -0
  101. package/dist/tasks/steer.d.ts +8 -0
  102. package/dist/tasks/steer.js +79 -0
  103. package/dist/tasks/store.d.ts +60 -35
  104. package/dist/tasks/store.js +166 -107
  105. package/dist/tasks/ticket.d.ts +102 -0
  106. package/dist/tasks/ticket.js +209 -0
  107. package/dist/tasks/verification.d.ts +47 -0
  108. package/dist/tasks/verification.js +60 -1
  109. package/dist/tools/index.d.ts +13 -4
  110. package/dist/tools/index.js +5 -10
  111. package/dist/tools/memory-manage.d.ts +6 -16
  112. package/dist/tools/memory-manage.js +108 -129
  113. package/dist/tools/presentation.js +2 -1
  114. package/dist/tools/registry.d.ts +11 -2
  115. package/dist/tools/registry.js +17 -6
  116. package/dist/tools/subagent-manage.d.ts +0 -9
  117. package/dist/tools/subagent-manage.js +8 -17
  118. package/dist/tools/task-manage/create.js +2 -2
  119. package/dist/tools/task-manage/lifecycle.d.ts +9 -4
  120. package/dist/tools/task-manage/lifecycle.js +136 -188
  121. package/dist/tools/task-manage/log-view.d.ts +8 -0
  122. package/dist/tools/task-manage/log-view.js +24 -0
  123. package/dist/tools/task-manage/schema.d.ts +38 -14
  124. package/dist/tools/task-manage/schema.js +46 -27
  125. package/dist/tools/task-manage/shared.d.ts +35 -31
  126. package/dist/tools/task-manage/shared.js +130 -141
  127. package/dist/tools/task-manage/step-end.d.ts +11 -0
  128. package/dist/tools/task-manage/step-end.js +134 -0
  129. package/dist/tools/task-manage/types.d.ts +23 -32
  130. package/dist/tools/task-manage.d.ts +4 -3
  131. package/dist/tools/task-manage.js +30 -15
  132. package/dist/tools/tool-details.d.ts +1 -1
  133. package/dist/tui/app.js +0 -2
  134. package/examples/sub-agents/README.md +54 -38
  135. package/examples/sub-agents/builder-hard.md +21 -12
  136. package/examples/sub-agents/builder.md +24 -16
  137. package/examples/sub-agents/explorer.md +17 -15
  138. package/examples/sub-agents/git-committer.md +8 -6
  139. package/examples/sub-agents/planner.md +17 -16
  140. package/examples/sub-agents/reviewer.md +11 -9
  141. package/examples/sub-agents/verifier.md +22 -16
  142. package/examples/sub-agents/worker.md +22 -6
  143. package/package.json +1 -1
  144. package/dist/agent/effect-ledger.d.ts +0 -32
  145. package/dist/agent/effect-ledger.js +0 -89
  146. package/dist/memory/bootstrap.d.ts +0 -17
  147. package/dist/memory/bootstrap.js +0 -120
  148. package/dist/memory/candidates.d.ts +0 -26
  149. package/dist/memory/candidates.js +0 -202
  150. package/dist/memory/consolidation.d.ts +0 -54
  151. package/dist/memory/consolidation.js +0 -292
  152. package/dist/memory/extraction.d.ts +0 -54
  153. package/dist/memory/extraction.js +0 -240
  154. package/dist/memory/files.d.ts +0 -71
  155. package/dist/memory/files.js +0 -419
  156. package/dist/memory/maintenance-jobs.d.ts +0 -41
  157. package/dist/memory/maintenance-jobs.js +0 -265
  158. package/dist/memory/metadata.d.ts +0 -57
  159. package/dist/memory/metadata.js +0 -142
  160. package/dist/memory/probation.d.ts +0 -17
  161. package/dist/memory/probation.js +0 -44
  162. package/dist/memory/promotion.d.ts +0 -38
  163. package/dist/memory/promotion.js +0 -36
  164. package/dist/memory/recall.d.ts +0 -59
  165. package/dist/memory/recall.js +0 -746
  166. package/dist/memory/session.d.ts +0 -24
  167. package/dist/memory/session.js +0 -273
  168. package/dist/playbooks/task-driving.md +0 -92
  169. package/dist/playbooks/task-planning.md +0 -58
  170. package/dist/tasks/control.d.ts +0 -56
  171. package/dist/tasks/control.js +0 -169
  172. package/dist/tasks/transitions.d.ts +0 -16
  173. package/dist/tasks/transitions.js +0 -48
  174. package/dist/tools/task-manage/verification.d.ts +0 -19
  175. package/dist/tools/task-manage/verification.js +0 -91
  176. package/examples/sub-agents/documenter.md +0 -50
  177. package/examples/sub-agents/log-sifter.md +0 -47
  178. package/examples/sub-agents/scout.md +0 -34
@@ -65,3 +65,50 @@ export declare function parseVerificationVerdict(output: string): VerificationVe
65
65
  export declare function getVerificationSubjectHashOptions(attestation: Pick<VerificationAttestation, "subjectMode" | "subjectBaseCommit" | "subjectBaselineUntrackedPaths">): WorkspaceSubjectHashOptions | undefined;
66
66
  export declare function writeVerificationAttestation(channelDir: string, input: Omit<VerificationAttestation, "version" | "bodyHash">): Promise<VerificationAttestation>;
67
67
  export declare function readVerificationAttestation(channelDir: string, runId: string, options?: VerificationAttestationReadOptions): Promise<VerificationAttestation>;
68
+ /**
69
+ * Everything `task_verify` used to check before it would import an attestation (spec 051, D7).
70
+ *
71
+ * The checks are unchanged; only the caller moved. Importing a verifier's verdict is bookkeeping
72
+ * the runtime already has the facts for at settlement, so it happens there — but it must still
73
+ * fail closed, because the task Markdown is agent-writable and proves nothing on its own (spec
74
+ * 040's threat model). Returns the reason it is not acceptable, or `undefined` when it is.
75
+ */
76
+ export declare function attestationRejectionReason(input: {
77
+ channelDir: string;
78
+ taskId: string;
79
+ runId: string;
80
+ taskBody: string;
81
+ trustedWorkingDirectory?: string;
82
+ fallbackWorkingDirectory?: string;
83
+ }): Promise<string | undefined>;
84
+ /**
85
+ * How a cycle's rework rounds are consumed when deciding whether a task may close (spec 051, D7).
86
+ *
87
+ * Recording a round at settlement proved the attestation *then*. It cannot prove it *now*: the
88
+ * task Markdown and the workspace are both agent-writable between the verifier's PASS and the
89
+ * close, so a contract edit or a further code change after the PASS would sail through a check
90
+ * that only asks "did a PASS ever land in this cycle". That was the shape of the hole — both
91
+ * close entry points asked exactly that.
92
+ *
93
+ * Two rules, deliberately simple:
94
+ * - The candidate is the cycle's *last* round, not any PASS in it. A later FAIL is newer evidence
95
+ * about the same artifact and must not be overridden by an earlier PASS.
96
+ * - That candidate's attestation is re-checked against the contract and the checkout as they are
97
+ * at close time, reusing `attestationRejectionReason` rather than a second proof model.
98
+ */
99
+ export interface CompletionVerificationInput {
100
+ channelDir: string;
101
+ taskId: string;
102
+ taskBody: string;
103
+ cycleId: string | undefined;
104
+ /**
105
+ * The checkout persisted for a verify run, from the sub-agent run registry. The attestation
106
+ * file names its own `subjectDir`, but that file is evidence, not the authority for which
107
+ * checkout was verified — so a run whose record is gone fails closed rather than falling back
108
+ * to whatever directory the daemon happens to be in.
109
+ */
110
+ findRunWorkingDirectory: (runId: string) => string | undefined;
111
+ fallbackWorkingDirectory?: string;
112
+ }
113
+ /** Why this task may not be closed as done, or `undefined` when its verification still holds. */
114
+ export declare function completionVerificationBlockReason(input: CompletionVerificationInput): Promise<string | undefined>;
@@ -5,7 +5,10 @@ import { isAbsolute, join, win32 } from "node:path";
5
5
  import { writeFileAtomically } from "../shared/atomic-file.js";
6
6
  import { parseLocalTime } from "../shared/local-time.js";
7
7
  import { errorMessage } from "../shared/text-utils.js";
8
- import { readStoredTask, taskBodyHash } from "./store.js";
8
+ import { workspaceSubjectHash } from "./artifact-subject.js";
9
+ import { taskBodyHash } from "./ledger.js";
10
+ import { readCycleRounds } from "./rounds.js";
11
+ import { readStoredTask } from "./store.js";
9
12
  const FULL_COMMIT_PATTERN = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/i;
10
13
  function attestationFilename(runId) {
11
14
  return `${createHash("sha256").update(runId).digest("hex")}.json`;
@@ -165,3 +168,59 @@ export async function readVerificationAttestation(channelDir, runId, options) {
165
168
  const boundSubjectDir = bindSubjectDirectory(runId, attestation.subjectDir, options);
166
169
  return boundSubjectDir === attestation.subjectDir ? attestation : { ...attestation, subjectDir: boundSubjectDir };
167
170
  }
171
+ /**
172
+ * Everything `task_verify` used to check before it would import an attestation (spec 051, D7).
173
+ *
174
+ * The checks are unchanged; only the caller moved. Importing a verifier's verdict is bookkeeping
175
+ * the runtime already has the facts for at settlement, so it happens there — but it must still
176
+ * fail closed, because the task Markdown is agent-writable and proves nothing on its own (spec
177
+ * 040's threat model). Returns the reason it is not acceptable, or `undefined` when it is.
178
+ */
179
+ export async function attestationRejectionReason(input) {
180
+ let attestation;
181
+ try {
182
+ attestation = await readVerificationAttestation(input.channelDir, input.runId, {
183
+ trustedWorkingDirectory: input.trustedWorkingDirectory,
184
+ });
185
+ }
186
+ catch (error) {
187
+ return errorMessage(error);
188
+ }
189
+ if (attestation.taskId !== input.taskId) {
190
+ return `attestation belongs to task "${attestation.taskId}"`;
191
+ }
192
+ if (attestation.workspaceChanged) {
193
+ return "verifier changed protected workspace content";
194
+ }
195
+ if (attestation.bodyHash !== taskBodyHash(input.taskBody)) {
196
+ return "task contract changed after verification";
197
+ }
198
+ if (attestation.subjectHash) {
199
+ const subjectDir = attestation.subjectDir ?? input.trustedWorkingDirectory ?? input.fallbackWorkingDirectory ?? process.cwd();
200
+ const currentSubject = await workspaceSubjectHash(subjectDir, getVerificationSubjectHashOptions(attestation));
201
+ if (!currentSubject)
202
+ return "artifact subject checkout could not be read";
203
+ if (currentSubject !== attestation.subjectHash)
204
+ return "artifact subject changed after verification";
205
+ }
206
+ return undefined;
207
+ }
208
+ /** Why this task may not be closed as done, or `undefined` when its verification still holds. */
209
+ export async function completionVerificationBlockReason(input) {
210
+ const rounds = await readCycleRounds(input.channelDir, input.taskId, input.cycleId);
211
+ const latest = rounds.at(-1);
212
+ if (!latest)
213
+ return "no verification round has landed in this cycle";
214
+ if (latest.verdict !== "pass") {
215
+ return `the latest verification round (#${latest.n}) is a FAIL${latest.reason ? `: ${latest.reason}` : ""}`;
216
+ }
217
+ const rejection = await attestationRejectionReason({
218
+ channelDir: input.channelDir,
219
+ taskId: input.taskId,
220
+ runId: latest.verifyRunId,
221
+ taskBody: input.taskBody,
222
+ trustedWorkingDirectory: input.findRunWorkingDirectory(latest.verifyRunId),
223
+ fallbackWorkingDirectory: input.fallbackWorkingDirectory,
224
+ });
225
+ return rejection ? `the PASS from round #${latest.n} no longer holds: ${rejection}` : undefined;
226
+ }
@@ -3,10 +3,9 @@ import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import type { MediaSender } from "../channel/channel-context.js";
4
4
  import type { Executor } from "../executor.js";
5
5
  import type { FileStore } from "../file-store.js";
6
- import type { MemoryCandidateStore } from "../memory/candidates.js";
7
6
  import type { ProjectScope } from "../security/project-scope.js";
8
7
  import type { SecurityConfig } from "../security/types.js";
9
- import type { PipiclawMemoryRecallSettings, PipiclawSessionSearchSettings } from "../settings.js";
8
+ import type { PipiclawSessionSearchSettings } from "../settings.js";
10
9
  import { type SubAgentDiscoveryResult } from "../subagents/discovery.js";
11
10
  import type { PipiclawToolsConfig } from "./config.js";
12
11
  export interface CreatePipiclawToolsOptions {
@@ -22,13 +21,23 @@ export interface CreatePipiclawToolsOptions {
22
21
  channelDir: string;
23
22
  channelId: string;
24
23
  getSubAgentDiscovery: () => SubAgentDiscoveryResult;
25
- getMemoryRecallSettings: () => PipiclawMemoryRecallSettings;
26
24
  getSubAgentModelReference?: () => string | null;
27
25
  getSessionSearchSettings: () => PipiclawSessionSearchSettings;
28
- memoryCandidateStore: MemoryCandidateStore;
29
26
  securityConfig?: SecurityConfig;
30
27
  toolsConfig?: PipiclawToolsConfig;
31
28
  /** Transport-provided attachment port; when present, enables the `send_media` tool. */
32
29
  mediaSender?: MediaSender;
30
+ /**
31
+ * Present only while this tool set belongs to a task loop step (spec 051, D3). It enables
32
+ * `task_step_end` and removes the three tools a task must not use: `task_create` (a task does
33
+ * not spawn tasks), `memory_save` (task state is not a channel fact — this was memory v2's
34
+ * single biggest pollution source) and `event_manage`.
35
+ */
36
+ taskLoop?: {
37
+ taskId: string;
38
+ cycleId: string;
39
+ };
40
+ /** Tools completed in the current turn; only `task_step_end` reads it. */
41
+ getToolsUsed?: () => string[];
33
42
  }
34
43
  export declare function createPipiclawTools(options: CreatePipiclawToolsOptions): AgentTool<any>[];
@@ -25,6 +25,7 @@ export function createPipiclawTools(options) {
25
25
  // registry so this set, the sub-agent set, and the prompt hints share one source.
26
26
  // The `subagent` tool is appended separately: it is never available to sub-agents
27
27
  // and keeping it out of the registry avoids a registry ↔ subagents/tool import cycle.
28
+ const taskLoopExcluded = new Set(["task_create", "memory_save", "event_manage"]);
28
29
  const leafTools = buildToolSet({
29
30
  executor: options.executor,
30
31
  fileStore: options.fileStore,
@@ -41,8 +42,9 @@ export function createPipiclawTools(options) {
41
42
  getAvailableModels: options.getAvailableModels,
42
43
  resolveApiKey: options.resolveApiKey,
43
44
  getSessionSearchSettings: options.getSessionSearchSettings,
44
- memoryCandidateStore: options.memoryCandidateStore,
45
45
  mediaSender: options.mediaSender,
46
+ taskLoop: options.taskLoop,
47
+ getToolsUsed: options.getToolsUsed,
46
48
  });
47
49
  const subAgentToolOptions = {
48
50
  executor: options.executor,
@@ -57,9 +59,7 @@ export function createPipiclawTools(options) {
57
59
  projectBoundary: options.projectScope.boundary,
58
60
  channelDir: options.channelDir,
59
61
  getSubAgentDiscovery: options.getSubAgentDiscovery,
60
- getMemoryRecallSettings: options.getMemoryRecallSettings,
61
62
  getSubAgentModelReference: options.getSubAgentModelReference,
62
- memoryCandidateStore: options.memoryCandidateStore,
63
63
  securityConfig,
64
64
  webConfig: toolsConfig.tools.web,
65
65
  rtkEnabled: toolsConfig.tools.rtk.enabled,
@@ -76,14 +76,8 @@ export function createPipiclawTools(options) {
76
76
  workingDirectory: options.projectScope.projectRoot,
77
77
  projectBoundary: options.projectScope.boundary,
78
78
  securityConfig,
79
- // Spec 042 D7: follow_up builds its envelope through the same buildContextualBlocks
80
- // the initial dispatch uses, which needs these to resolve a memory: relevant recall.
81
- getCurrentModel: options.getCurrentModel,
82
- resolveApiKey: options.resolveApiKey,
83
- getMemoryRecallSettings: options.getMemoryRecallSettings,
84
- memoryCandidateStore: options.memoryCandidateStore,
85
79
  };
86
- return [
80
+ const all = [
87
81
  ...leafTools,
88
82
  // Bound to the same `details` contract as the registry's tools; it is registered here
89
83
  // rather than in TOOL_REGISTRY only to avoid a registry ↔ subagents/tool import cycle.
@@ -96,4 +90,5 @@ export function createPipiclawTools(options) {
96
90
  withToolDetails(createSubAgentListTool(subAgentManageOptions), "subagent_list"),
97
91
  withToolDetails(createSubAgentRunTool(subAgentManageOptions), "subagent_run"),
98
92
  ];
93
+ return options.taskLoop ? all.filter((tool) => !taskLoopExcluded.has(tool.name)) : all;
99
94
  }
@@ -1,34 +1,24 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
- import type { Api, Model } from "@earendil-works/pi-ai";
3
2
  import { Type } from "typebox";
4
- import type { MemoryCandidateStore } from "../memory/candidates.js";
5
3
  import { type ChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
6
- /**
7
- * Spec 047, P4: the old single `memory_manage` routed three fully disjoint payloads through an
8
- * `op` enum. Splitting into one tool per payload shape drops the `op` routing prose and the
9
- * "Required for save:" prefixes, and lets each op's one required field be schema-required
10
- * instead of `Type.Optional` + a hand-rolled `rejectMissingArgument`. The streamed-argument
11
- * truncation that `rejectMissingArgument` guarded against (M-write-03) is now caught by the SDK
12
- * validator before `execute`; spec 047 D4.2 makes that rejection surface as a recoverable
13
- * rejection rather than a user-visible error.
14
- */
4
+ import { type MemoryType } from "../memory/store.js";
15
5
  declare const memorySaveSchema: Type.TObject<{
16
6
  content: Type.TString;
17
- supersedes: Type.TOptional<Type.TString>;
7
+ name: Type.TOptional<Type.TString>;
8
+ type: Type.TOptional<Type.TUnion<Type.TLiteral<MemoryType>[]>>;
9
+ details: Type.TOptional<Type.TString>;
10
+ replaces: Type.TOptional<Type.TString>;
18
11
  }>;
19
12
  declare const memorySearchSchema: Type.TObject<{
20
13
  query: Type.TString;
21
14
  }>;
22
15
  declare const memoryForgetSchema: Type.TObject<{
23
- target: Type.TString;
16
+ name: Type.TString;
24
17
  }>;
25
18
  export interface MemoryManageToolOptions {
26
19
  channelId: string;
27
20
  channelDir: string;
28
21
  workspaceDir: string;
29
- memoryCandidateStore: MemoryCandidateStore;
30
- getCurrentModel: () => Model<Api>;
31
- resolveApiKey: (model: Model<Api>) => Promise<string>;
32
22
  channelMemoryQueue?: ChannelMemoryQueue;
33
23
  }
34
24
  export declare function createMemorySaveTool(options: MemoryManageToolOptions): AgentTool<typeof memorySaveSchema>;
@@ -1,182 +1,160 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
1
3
  import { Type } from "typebox";
2
4
  import * as log from "../log.js";
3
5
  import { getDefaultChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
4
- import { applyChannelMemoryOps, getChannelMemoryPath, parseChannelMemoryEntries } from "../memory/files.js";
5
- import { recallRelevantMemory } from "../memory/recall.js";
6
6
  import { appendMemoryReviewLog } from "../memory/review-log.js";
7
+ import { findNearDuplicateEntries, searchMemory } from "../memory/search.js";
7
8
  import { containsSecret } from "../memory/secret-redaction.js";
9
+ import { applyMemoryOps, isValidMemoryName, listMemoryEntries, readMemoryEntry, } from "../memory/store.js";
8
10
  import { hashMemoryContent } from "../memory/tombstones.js";
9
- import { readOptionalTextFile } from "../shared/fs-utils.js";
10
11
  import { RecoverableToolError } from "../shared/recoverable-error.js";
11
12
  import { errorMessage } from "../shared/text-utils.js";
12
13
  /**
13
- * Spec 047, P4: the old single `memory_manage` routed three fully disjoint payloads through an
14
- * `op` enum. Splitting into one tool per payload shape drops the `op` routing prose and the
15
- * "Required for save:" prefixes, and lets each op's one required field be schema-required
16
- * instead of `Type.Optional` + a hand-rolled `rejectMissingArgument`. The streamed-argument
17
- * truncation that `rejectMissingArgument` guarded against (M-write-03) is now caught by the SDK
18
- * validator before `execute`; spec 047 D4.2 makes that rejection surface as a recoverable
19
- * rejection rather than a user-visible error.
14
+ * Spec 050, D3: three tools, semantics narrowed. All three act only on the channel `memory/`
15
+ * directory; workspace MEMORY.md is read-only to tools (D11).
20
16
  */
17
+ const MEMORY_TYPES = ["user", "feedback", "project", "reference"];
21
18
  const memorySaveSchema = Type.Object({
22
19
  content: Type.String({
23
- description: "The durable fact as a single self-contained, keyword-rich sentence on one line, written so future keyword search can find it.",
20
+ description: "The durable fact as one self-contained line. Becomes the memory's description and index entry.",
24
21
  }),
25
- supersedes: Type.Optional(Type.String({
26
- description: "Only after this tool reported a similar existing entry: the entry id being replaced, " +
27
- 'or "none" to keep both.',
22
+ name: Type.Optional(Type.String({
23
+ description: "Short kebab-case handle, e.g. `deploy-window-thursday`. Auto-generated if omitted.",
24
+ })),
25
+ type: Type.Optional(Type.Union(MEMORY_TYPES.map((t) => Type.Literal(t)), {
26
+ description: "user (who the user is), feedback (how to work / lessons), project (facts, decisions, constraints), reference (pointers). Default: project.",
27
+ })),
28
+ details: Type.Optional(Type.String({ description: "Optional long form, shown only when the file is opened with `read`." })),
29
+ replaces: Type.Optional(Type.String({
30
+ description: 'Only after this tool reported a similar entry: the `name` of the entry to replace, or "none" to keep both.',
28
31
  })),
29
32
  });
30
33
  const memorySearchSchema = Type.Object({
31
- query: Type.String({ description: "What to look for in this channel's stored memory." }),
34
+ query: Type.String({
35
+ description: "What to look for across this channel's memory, journal, and workspace MEMORY.md.",
36
+ }),
32
37
  });
33
38
  const memoryForgetSchema = Type.Object({
34
- target: Type.String({
35
- description: "Text identifying the stored entry to remove. Must match exactly one entry; use memory_search first to confirm the wording.",
39
+ name: Type.String({
40
+ description: "The exact `name` of the memory to remove (see the memory index or memory_search).",
36
41
  }),
37
42
  });
38
- /**
39
- * Above this recall score, an existing entry is similar enough that saving alongside it — rather
40
- * than superseding it — risks two contradictory durable facts competing at recall time. Set high
41
- * on purpose: a false positive interrupts every plain save, a false negative just means the old
42
- * conflict-resolution instruction ("say 'forget the old one'") still applies. Starts at the same
43
- * value `recall.ts` uses to gate its own model rerank (`HIGH_CONFIDENCE_SCORE`) — a score that
44
- * strong elsewhere in the pipeline is a reasonable place to start being strict here too.
45
- */
46
- const SAVE_CONFLICT_SCORE = 8;
47
43
  function textResult(text, details) {
48
44
  return { content: [{ type: "text", text }], details };
49
45
  }
46
+ async function readWorkspaceMemory(workspaceDir) {
47
+ try {
48
+ return await readFile(join(workspaceDir, "MEMORY.md"), "utf-8");
49
+ }
50
+ catch {
51
+ return "";
52
+ }
53
+ }
50
54
  function buildMemoryClosures(options) {
51
55
  const queue = options.channelMemoryQueue ?? getDefaultChannelMemoryQueue();
52
- async function save({ content, supersedes }) {
53
- const trimmed = content.trim();
54
- if (!trimmed) {
56
+ async function save(args) {
57
+ const content = args.content.trim();
58
+ if (!content) {
55
59
  throw new RecoverableToolError("memory_save requires a non-empty content; nothing was saved.");
56
60
  }
57
- if (containsSecret(trimmed)) {
58
- return textResult("This content looks like a credential or secret, so it was not saved. Store the secret in an approved secret manager and remember only its location.", { op: "save", saved: false, blockedReason: "secret" });
61
+ if (containsSecret(content) || (args.details && containsSecret(args.details))) {
62
+ return textResult("This looks like a credential or secret, so it was not saved. Store the secret in an approved secret manager and remember only its location.", { saved: false, blockedReason: "secret" });
59
63
  }
60
- if (!supersedes) {
61
- // Reuse the recall scoring pipeline (already the point-query path for `search`) as a
62
- // deterministic, no-cost conflict check before writing a second fact that might
63
- // contradict one already stored.
64
- const model = options.getCurrentModel();
65
- const { items } = await recallRelevantMemory({
66
- query: trimmed,
67
- channelId: options.channelId,
68
- workspaceDir: options.workspaceDir,
69
- channelDir: options.channelDir,
70
- allowedSources: ["channel-memory"],
71
- maxCandidates: 3,
72
- maxInjected: 3,
73
- maxChars: 1200,
74
- rerankWithModel: false,
75
- model,
76
- resolveApiKey: options.resolveApiKey,
77
- candidateStore: options.memoryCandidateStore,
78
- });
79
- const similar = items.filter((item) => item.entryId && item.score >= SAVE_CONFLICT_SCORE);
64
+ if (args.name && !isValidMemoryName(args.name)) {
65
+ throw new RecoverableToolError(`"${args.name}" is not a valid memory name. Use lowercase letters, digits, and hyphens only (e.g. deploy-window-thursday).`);
66
+ }
67
+ const entries = await listMemoryEntries(options.channelDir);
68
+ if (!args.replaces) {
69
+ const similar = findNearDuplicateEntries(content, entries);
80
70
  if (similar.length > 0) {
81
71
  throw new RecoverableToolError(`Nothing was saved yet. This channel already stores ${similar.length} similar entr${similar.length === 1 ? "y" : "ies"}:\n` +
82
- similar.map((item) => `- ${item.entryId}: ${item.content}`).join("\n") +
83
- '\nRe-issue the save with "supersedes" set to the entry id this replaces, or to "none" if both facts are true at the same time.');
72
+ similar.map((entry) => `- ${entry.name}: ${entry.description}`).join("\n") +
73
+ '\nRe-issue the save with "replaces" set to the name this replaces, or to "none" if both facts are true at once.');
84
74
  }
85
75
  }
86
- // The model no longer classifies explicit saves (spec 047, P2): background consolidation
87
- // (`extraction.ts`) still writes real kinds; a model save is recorded as `fact`.
88
- const metadata = {
89
- kind: "fact",
90
- sourceType: "user",
91
- probationUntil: null,
92
- };
93
- // Serialize through the shared channel memory queue so this never races with background
94
- // consolidation/maintenance on the same channel's files.
95
- const result = await queue.run(options.channelId, () => applyChannelMemoryOps(options.channelDir, [
96
- supersedes && supersedes !== "none"
97
- ? { op: "supersede", targetId: supersedes, content: trimmed, metadata }
98
- : // A user explicitly saying "remember this" is never probationary, and restating a
99
- // fact the runtime had already put on probation promotes it (spec 037, D7).
100
- { op: "add", content: trimmed, metadata },
76
+ const replaces = args.replaces && args.replaces !== "none" ? args.replaces : undefined;
77
+ const result = await queue.run(options.channelId, () => applyMemoryOps(options.channelDir, [
78
+ replaces
79
+ ? {
80
+ op: "update",
81
+ name: replaces,
82
+ description: content,
83
+ type: args.type,
84
+ details: args.details,
85
+ expires: null,
86
+ }
87
+ : {
88
+ op: "add",
89
+ description: content,
90
+ source: "user",
91
+ name: args.name,
92
+ type: args.type ?? "project",
93
+ details: args.details,
94
+ },
101
95
  ]));
102
- options.memoryCandidateStore.invalidate(getChannelMemoryPath(options.channelDir));
103
- const message = result.added > 0 || result.superseded > 0
104
- ? "Saved to channel memory."
105
- : "That memory is already present; no duplicate was added.";
106
- return textResult(message, {
107
- op: "save",
108
- saved: result.added > 0 || result.superseded > 0 || result.skippedDuplicate > 0,
109
- });
96
+ if (replaces && result.updated.length === 0 && result.missingTarget > 0) {
97
+ throw new RecoverableToolError(`No memory named "${replaces}" exists in this channel. Check the name, or omit "replaces" to save a new entry.`);
98
+ }
99
+ await appendMemoryReviewLog(options.channelDir, {
100
+ timestamp: new Date().toISOString(),
101
+ channelId: options.channelId,
102
+ reason: "memory-save",
103
+ actions: [{ op: replaces ? "update" : "add", name: replaces ?? result.added[0] }],
104
+ }).catch(() => { });
105
+ const savedName = replaces ?? result.added[0];
106
+ return textResult(replaces ? `Replaced channel memory \`${savedName}\`.` : `Saved to channel memory as \`${savedName}\`.`, { saved: result.added.length > 0 || result.updated.length > 0, name: savedName });
110
107
  }
111
108
  async function search({ query }) {
112
109
  const trimmed = query.trim();
113
110
  if (!trimmed) {
114
111
  throw new RecoverableToolError("memory_search requires a non-empty query.");
115
112
  }
116
- // Reuse the recall scoring pipeline (single source of scoring truth) but scoped to the
117
- // distilled durable files and with model rerank off, so this stays a cheap deterministic
118
- // point-query distinct from the passive per-turn recall injection.
119
- const model = options.getCurrentModel();
120
- const { items } = await recallRelevantMemory({
121
- query: trimmed,
122
- channelId: options.channelId,
123
- workspaceDir: options.workspaceDir,
124
- channelDir: options.channelDir,
125
- allowedSources: ["channel-memory", "channel-history"],
126
- maxCandidates: 8,
127
- maxInjected: 8,
128
- maxChars: 4000,
129
- rerankWithModel: false,
130
- model,
131
- resolveApiKey: options.resolveApiKey,
132
- candidateStore: options.memoryCandidateStore,
133
- });
134
- if (items.length === 0) {
135
- return textResult(`No stored memory matched "${trimmed}". Try a broader query, or the fact may not be saved yet.`, { op: "search", resultCount: 0 });
113
+ const [entries, workspaceMemory] = await Promise.all([
114
+ listMemoryEntries(options.channelDir),
115
+ readWorkspaceMemory(options.workspaceDir),
116
+ ]);
117
+ const hits = searchMemory({ query: trimmed, entries, workspaceMemory });
118
+ if (hits.length === 0) {
119
+ return textResult(`No stored memory matched "${trimmed}". Try a broader query, or the fact may not be saved yet.`, {
120
+ resultCount: 0,
121
+ });
136
122
  }
137
- const rendered = items
138
- .map((item, index) => `${index + 1}. [${item.source}/${item.title}] ${item.content}`)
123
+ const rendered = hits
124
+ .map((hit) => {
125
+ const where = hit.kind === "memory"
126
+ ? `memory/${hit.label}`
127
+ : hit.kind === "journal"
128
+ ? `journal ${hit.date}`
129
+ : `workspace MEMORY.md › ${hit.label}`;
130
+ return `- [${where}] ${hit.line}`;
131
+ })
139
132
  .join("\n");
140
- return textResult(`Found ${items.length} stored memory entr${items.length === 1 ? "y" : "ies"}:\n\n${rendered}`, {
141
- op: "search",
142
- resultCount: items.length,
133
+ return textResult(`Found ${hits.length} match${hits.length === 1 ? "" : "es"}:\n\n${rendered}`, {
134
+ resultCount: hits.length,
143
135
  });
144
136
  }
145
- async function forget({ target }) {
146
- const trimmed = target.trim();
137
+ async function forget({ name }) {
138
+ const trimmed = name.trim();
147
139
  if (!trimmed) {
148
- throw new RecoverableToolError("memory_forget requires a non-empty target.");
140
+ throw new RecoverableToolError("memory_forget requires a non-empty name.");
149
141
  }
150
- const memoryPath = getChannelMemoryPath(options.channelDir);
151
- const existing = await readOptionalTextFile(memoryPath);
152
- const entries = parseChannelMemoryEntries(existing);
153
- const needle = trimmed.toLowerCase();
154
- const matches = entries.filter((entry) => entry.content === trimmed || entry.content.toLowerCase().includes(needle));
155
- if (matches.length === 0) {
156
- return textResult(`No stored memory entry matched "${trimmed}"; nothing was removed.`, {
157
- op: "forget",
142
+ const entry = await readMemoryEntry(options.channelDir, trimmed);
143
+ if (!entry) {
144
+ return textResult(`No memory named "${trimmed}" exists in this channel; nothing was removed.`, {
158
145
  forgotten: false,
159
146
  });
160
147
  }
161
- if (matches.length > 1) {
162
- // Never guess which entry to delete; make the model disambiguate.
163
- const candidates = matches.map((entry, index) => `${index + 1}. ${entry.content}`).join("\n");
164
- throw new RecoverableToolError(`"${trimmed}" matched ${matches.length} entries; be more specific so only one is removed:\n${candidates}`);
165
- }
166
- const removed = matches[0];
167
- await queue.run(options.channelId, () => applyChannelMemoryOps(options.channelDir, [{ op: "forget", targetId: removed.id, reason: "user forget" }]));
168
- options.memoryCandidateStore.invalidate(memoryPath);
169
- // Audit by id/hash only. Copying the forgotten text into the review log would
170
- // create a second active disclosure surface for the very content being removed.
148
+ await queue.run(options.channelId, () => applyMemoryOps(options.channelDir, [{ op: "delete", name: trimmed, reason: "user forget" }]));
171
149
  await appendMemoryReviewLog(options.channelDir, {
172
150
  timestamp: new Date().toISOString(),
173
151
  channelId: options.channelId,
174
- reason: "user-forget",
175
- actions: [{ op: "forget", entryId: removed.id, contentHash: hashMemoryContent(removed.content) }],
152
+ reason: "memory-forget",
153
+ actions: [{ op: "forget", name: trimmed, contentHash: hashMemoryContent(entry.description) }],
176
154
  }).catch((error) => {
177
155
  log.logWarning(`Failed to append memory review log for channel ${options.channelId}`, errorMessage(error));
178
156
  });
179
- return textResult("Removed the entry from active channel memory. Its exact content and source transcript window are tombstoned against automatic replay; if the fact is stated again later, it may be learned as new. Original session history and retention backups are unchanged.", { op: "forget", forgotten: true, entryId: removed.id });
157
+ return textResult(`Removed \`${trimmed}\` from channel memory. Its content is tombstoned against automatic replay; if the fact is stated again later it may be re-learned. Journal and session history are unchanged.`, { forgotten: true, name: trimmed });
180
158
  }
181
159
  return { save, search, forget };
182
160
  }
@@ -185,8 +163,8 @@ export function createMemorySaveTool(options) {
185
163
  return {
186
164
  name: "memory_save",
187
165
  label: "memory_save",
188
- description: "Save a durable fact into this channel's MEMORY.md when the user asks you to remember it. Prefer this over editing " +
189
- "MEMORY.md directly. Not for transient task state.",
166
+ description: "Save a durable fact into this channel's memory when the user asks you to remember it. Not for transient task state — " +
167
+ "put in-progress work in the journal or a task instead.",
190
168
  parameters: memorySaveSchema,
191
169
  execute: async (_toolCallId, args) => save(args),
192
170
  };
@@ -196,7 +174,8 @@ export function createMemorySearchTool(options) {
196
174
  return {
197
175
  name: "memory_search",
198
176
  label: "memory_search",
199
- description: "Search this channel's stored durable memory on demand mid-task.",
177
+ description: "Search this channel's stored memory, journal, and the workspace MEMORY.md on demand. The memory index is only " +
178
+ "injected at the start of a session, so use this when you suspect something was recorded since.",
200
179
  parameters: memorySearchSchema,
201
180
  execute: async (_toolCallId, args) => search(args),
202
181
  };
@@ -206,7 +185,7 @@ export function createMemoryForgetTool(options) {
206
185
  return {
207
186
  name: "memory_forget",
208
187
  label: "memory_forget",
209
- description: "Forget a stored memory entry the user explicitly asked you to drop. Tombstones it against automatic replay.",
188
+ description: "Forget a stored memory entry by name. Tombstones its content against automatic replay.",
210
189
  parameters: memoryForgetSchema,
211
190
  execute: async (_toolCallId, args) => forget(args),
212
191
  };
@@ -81,7 +81,8 @@ const DESCRIBERS = {
81
81
  task_create: (args) => `创建任务 ${str(args, "id") ?? "?"}`,
82
82
  task_update: (args) => `更新任务 ${str(args, "id") ?? "?"}`,
83
83
  task_close: (args) => `关闭任务 ${str(args, "id") ?? "?"}(${str(args, "outcome") ?? "?"})`,
84
- task_verify: (args) => `导入验收 ${str(args, "id") ?? "?"}`,
84
+ task_log: (args) => `读取任务日志 ${str(args, "id") ?? "?"}`,
85
+ task_step_end: (args) => `结束任务步骤(${str(args, "outcome") ?? "?"})`,
85
86
  subagent: (args) => {
86
87
  const who = str(args, "agent") ?? "?";
87
88
  const task = str(args, "task");
@@ -4,7 +4,6 @@ import type { ChannelJobManager } from "../agent/job-manager.js";
4
4
  import type { MediaSender } from "../channel/channel-context.js";
5
5
  import type { Executor } from "../executor.js";
6
6
  import type { FileStore } from "../file-store.js";
7
- import type { MemoryCandidateStore } from "../memory/candidates.js";
8
7
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
9
8
  import type { PipiclawSessionSearchSettings } from "../settings.js";
10
9
  import type { PipiclawToolsConfig, PipiclawWebToolsConfig } from "./config.js";
@@ -44,12 +43,22 @@ export interface ToolBuildContext {
44
43
  getAvailableModels?: () => Model<Api>[];
45
44
  resolveApiKey?: (model: Model<Api>) => Promise<string>;
46
45
  getSessionSearchSettings?: () => PipiclawSessionSearchSettings;
47
- memoryCandidateStore?: MemoryCandidateStore;
48
46
  /**
49
47
  * Present only on the main path, and only when the driving transport can deliver
50
48
  * files. Gates the `send_media` tool; sub-agents never receive it.
51
49
  */
52
50
  mediaSender?: MediaSender;
51
+ /**
52
+ * Present only inside a task loop step (spec 051, D3): which task this tool set belongs to,
53
+ * and the cycle it is running in. `task_step_end` is registered only when this is set, so the
54
+ * chat surface can never end a step that is not running.
55
+ */
56
+ taskLoop?: {
57
+ taskId: string;
58
+ cycleId: string;
59
+ };
60
+ /** Tools completed in the current turn; only the task loop reads it. */
61
+ getToolsUsed?: () => string[];
53
62
  }
54
63
  export interface ToolRegistration {
55
64
  /** Also the tool's `details.kind`: the name is the authoritative discriminator. */