@oyasmi/pipiclaw 0.8.10 → 0.8.11-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 (56) hide show
  1. package/dist/agent/channel-runner.d.ts +10 -0
  2. package/dist/agent/channel-runner.js +56 -27
  3. package/dist/memory/commands.js +6 -1
  4. package/dist/memory/consolidation.d.ts +8 -1
  5. package/dist/memory/consolidation.js +34 -6
  6. package/dist/memory/extraction.d.ts +11 -3
  7. package/dist/memory/extraction.js +19 -6
  8. package/dist/memory/files.d.ts +2 -0
  9. package/dist/memory/files.js +14 -0
  10. package/dist/memory/maintenance-gates.d.ts +3 -0
  11. package/dist/memory/maintenance-gates.js +5 -2
  12. package/dist/memory/maintenance-jobs.js +19 -2
  13. package/dist/memory/maintenance-state.d.ts +29 -0
  14. package/dist/memory/maintenance-state.js +100 -8
  15. package/dist/memory/metadata.d.ts +9 -0
  16. package/dist/memory/metadata.js +5 -0
  17. package/dist/memory/probation.d.ts +21 -0
  18. package/dist/memory/probation.js +48 -0
  19. package/dist/memory/promotion.d.ts +26 -1
  20. package/dist/memory/promotion.js +34 -4
  21. package/dist/memory/recall.js +38 -19
  22. package/dist/memory/session-corpus.js +12 -11
  23. package/dist/memory/session-search.js +25 -6
  24. package/dist/memory/sidecar-worker.js +2 -0
  25. package/dist/memory/task-digest.js +6 -0
  26. package/dist/playbooks/memory-and-learning.md +7 -1
  27. package/dist/playbooks/task-driving.md +2 -2
  28. package/dist/playbooks/task-planning.md +14 -0
  29. package/dist/runtime/bootstrap.js +1 -1
  30. package/dist/runtime/delivery.js +8 -2
  31. package/dist/runtime/dingtalk.d.ts +5 -2
  32. package/dist/runtime/dingtalk.js +6 -39
  33. package/dist/runtime/store.d.ts +8 -2
  34. package/dist/runtime/store.js +12 -6
  35. package/dist/runtime/task-commands.js +15 -1
  36. package/dist/runtime/task-driver.js +10 -0
  37. package/dist/security/command-guard.js +51 -17
  38. package/dist/security/path-guard.js +72 -14
  39. package/dist/subagents/tool.js +2 -0
  40. package/dist/tasks/ledger.d.ts +74 -5
  41. package/dist/tasks/ledger.js +261 -7
  42. package/dist/tools/memory-manage.js +8 -1
  43. package/dist/tools/read.js +19 -5
  44. package/dist/tools/task-manage/lifecycle.js +8 -2
  45. package/dist/tools/task-manage/schema.d.ts +6 -0
  46. package/dist/tools/task-manage/schema.js +14 -0
  47. package/dist/tools/task-manage/shared.js +1 -0
  48. package/dist/tui/app.js +1 -1
  49. package/dist/tui/commands.d.ts +1 -1
  50. package/dist/tui/commands.js +1 -1
  51. package/dist/tui/turn-controller.d.ts +1 -1
  52. package/dist/usage/ledger.d.ts +1 -1
  53. package/dist/usage/ledger.js +47 -22
  54. package/dist/usage/render.d.ts +1 -1
  55. package/dist/usage/render.js +8 -6
  56. package/package.json +6 -6
@@ -89,24 +89,116 @@ export async function updateMemoryMaintenanceState(appHomeDir, channelId, update
89
89
  return next;
90
90
  });
91
91
  }
92
- export function applyMemoryActivityToState(state, event) {
93
- const next = {
94
- ...state,
95
- channelId: event.channelId,
92
+ function mergeMemoryActivity(pending, event) {
93
+ const next = pending ?? {
96
94
  lastActivityAt: event.timestamp,
97
- eligibleAfter: event.eligibleAfter ?? state.eligibleAfter,
98
- lastSessionEntryId: event.latestSessionEntryId ?? state.lastSessionEntryId,
95
+ toolCalls: 0,
96
+ turns: 0,
97
+ dirty: false,
99
98
  };
99
+ next.lastActivityAt = event.timestamp;
100
+ next.eligibleAfter = event.eligibleAfter ?? next.eligibleAfter;
101
+ next.latestSessionEntryId = event.latestSessionEntryId ?? next.latestSessionEntryId;
100
102
  if (event.kind === "tool-call") {
101
103
  next.dirty = true;
102
- next.toolCallsSinceSessionRefresh += 1;
104
+ next.toolCalls += 1;
103
105
  }
104
106
  if (event.kind === "assistant-turn-completed") {
105
107
  next.dirty = true;
106
- next.turnsSinceSessionRefresh += 1;
108
+ next.turns += 1;
107
109
  }
108
110
  if (event.kind === "boundary") {
109
111
  next.dirty = true;
110
112
  }
111
113
  return next;
112
114
  }
115
+ function applyPendingActivityToState(state, channelId, pending) {
116
+ return {
117
+ ...state,
118
+ channelId,
119
+ lastActivityAt: pending.lastActivityAt,
120
+ eligibleAfter: pending.eligibleAfter ?? state.eligibleAfter,
121
+ lastSessionEntryId: pending.latestSessionEntryId ?? state.lastSessionEntryId,
122
+ dirty: state.dirty || pending.dirty,
123
+ toolCallsSinceSessionRefresh: state.toolCallsSinceSessionRefresh + pending.toolCalls,
124
+ turnsSinceSessionRefresh: state.turnsSinceSessionRefresh + pending.turns,
125
+ };
126
+ }
127
+ /** Apply a single activity event. The buffered path folds a whole burst through the same core. */
128
+ export function applyMemoryActivityToState(state, event) {
129
+ return applyPendingActivityToState(state, event.channelId, mergeMemoryActivity(undefined, event));
130
+ }
131
+ export const DEFAULT_ACTIVITY_FLUSH_DEBOUNCE_MS = 5_000;
132
+ export function createMemoryActivityRecorder(options) {
133
+ const debounceMs = options.debounceMs ?? DEFAULT_ACTIVITY_FLUSH_DEBOUNCE_MS;
134
+ const pending = new Map();
135
+ const timers = new Map();
136
+ /** The most recent write per channel, so `flush` can await work another caller started. */
137
+ const inFlight = new Map();
138
+ const cancelTimer = (channelId) => {
139
+ const timer = timers.get(channelId);
140
+ if (timer) {
141
+ clearTimeout(timer);
142
+ timers.delete(channelId);
143
+ }
144
+ };
145
+ const flushChannel = (channelId) => {
146
+ cancelTimer(channelId);
147
+ const delta = pending.get(channelId);
148
+ if (!delta) {
149
+ return inFlight.get(channelId) ?? Promise.resolve();
150
+ }
151
+ // Cleared before the await so events arriving during the write start a fresh batch
152
+ // instead of being swallowed by this one.
153
+ pending.delete(channelId);
154
+ const write = updateMemoryMaintenanceState(options.appHomeDir, channelId, (state) => applyPendingActivityToState(state, channelId, delta))
155
+ .then(() => undefined)
156
+ .catch((error) => {
157
+ // Put the delta back so the counters are not silently lost; the next event (or
158
+ // flush) retries it, folded in front of anything buffered while this write ran.
159
+ pending.set(channelId, mergeBack(delta, pending.get(channelId)));
160
+ options.onError?.(channelId, error);
161
+ })
162
+ .finally(() => {
163
+ if (inFlight.get(channelId) === write) {
164
+ inFlight.delete(channelId);
165
+ }
166
+ });
167
+ inFlight.set(channelId, write);
168
+ return write;
169
+ };
170
+ return {
171
+ record(event) {
172
+ pending.set(event.channelId, mergeMemoryActivity(pending.get(event.channelId), event));
173
+ if (timers.has(event.channelId)) {
174
+ return;
175
+ }
176
+ const timer = setTimeout(() => {
177
+ timers.delete(event.channelId);
178
+ void flushChannel(event.channelId);
179
+ }, debounceMs);
180
+ // Buffered counters are never a reason to keep the process alive.
181
+ timer.unref?.();
182
+ timers.set(event.channelId, timer);
183
+ },
184
+ async flush(channelId) {
185
+ const channelIds = channelId ? [channelId] : new Set([...pending.keys(), ...inFlight.keys()]);
186
+ await Promise.all([...channelIds].map((id) => flushChannel(id)));
187
+ },
188
+ };
189
+ }
190
+ /** Fold a failed batch back in front of whatever accumulated while it was in flight. */
191
+ function mergeBack(failed, current) {
192
+ if (!current) {
193
+ return failed;
194
+ }
195
+ return {
196
+ // `current` is the newer batch, so it wins on every last-write-wins field.
197
+ lastActivityAt: current.lastActivityAt,
198
+ eligibleAfter: current.eligibleAfter ?? failed.eligibleAfter,
199
+ latestSessionEntryId: current.latestSessionEntryId ?? failed.latestSessionEntryId,
200
+ toolCalls: failed.toolCalls + current.toolCalls,
201
+ turns: failed.turns + current.turns,
202
+ dirty: failed.dirty || current.dirty,
203
+ };
204
+ }
@@ -13,6 +13,13 @@ export interface MemoryWriteMetadataInput {
13
13
  expiresAt?: string;
14
14
  sensitivity?: MemorySensitivity;
15
15
  sourceCorrelationId?: string;
16
+ /**
17
+ * Probationary write deadline (spec 037, D6/D7): `undefined` leaves any existing value alone,
18
+ * a string sets/renews it, `null` explicitly clears it (promotion to durable). Distinct from
19
+ * `undefined` because "keep previous" and "durable now" are different intents — a durable
20
+ * supersede replacing a probationary entry in place must clear it, not silently inherit it.
21
+ */
22
+ probationUntil?: string | null;
16
23
  }
17
24
  export interface MemoryEntryMetadata {
18
25
  id: string;
@@ -36,6 +43,8 @@ export interface MemoryEntryMetadata {
36
43
  lastRecalledAt?: string;
37
44
  queryFingerprints: string[];
38
45
  recallByDay: Record<string, number>;
46
+ /** Set only while this entry is on probation (spec 037, D7); absent = durable. */
47
+ probationUntil?: string;
39
48
  }
40
49
  export interface MemoryMetadataFile {
41
50
  schemaVersion: 1;
@@ -79,6 +79,7 @@ export async function syncMemoryMetadata(channelDir, activeEntries, updates = []
79
79
  lastRecalledAt: previous?.lastRecalledAt,
80
80
  queryFingerprints: previous?.queryFingerprints ?? [],
81
81
  recallByDay: previous?.recallByDay ?? {},
82
+ probationUntil: hint?.probationUntil === null ? undefined : (hint?.probationUntil ?? previous?.probationUntil),
82
83
  };
83
84
  }
84
85
  for (const update of updates) {
@@ -126,6 +127,10 @@ export async function recordMemoryRecall(channelDir, entryIds, query, timestamp
126
127
  lastRecalledAt: timestamp,
127
128
  queryFingerprints: fingerprints,
128
129
  recallByDay: { ...recallByDay, [day]: (recallByDay[day] ?? 0) + 1 },
130
+ // Being recalled at all is the evidence a probationary entry needs to earn its
131
+ // permanent place (spec 037, D7) — this write was already happening on every
132
+ // recall, so promotion rides along for free.
133
+ probationUntil: undefined,
129
134
  };
130
135
  changed = true;
131
136
  }
@@ -0,0 +1,21 @@
1
+ import { readMemoryMetadata } from "./metadata.js";
2
+ /**
3
+ * How long a probationary memory entry survives without being recalled (spec 037, D7/D8).
4
+ * A code constant, not a setting: the durable/probation split is an algorithm parameter, same
5
+ * class as `minMemoryAutoWriteConfidence` before it (spec 035's `RETIRED_SETTINGS_KEYS`).
6
+ */
7
+ export declare const MEMORY_PROBATION_DAYS = 30;
8
+ export declare function probationDeadline(now?: Date): string;
9
+ /**
10
+ * Active entries whose probation lapsed, or whose (otherwise unconsumed) `expiresAt` was
11
+ * reached. Both are "this entry's time is up" — they share one eviction path even though their
12
+ * semantics differ: `probationUntil` is cancelled by use, `expiresAt` is unconditional.
13
+ */
14
+ export declare function collectExpiredEntryIds(metadata: Awaited<ReturnType<typeof readMemoryMetadata>>, now?: Date): string[];
15
+ /**
16
+ * Evict every expired entry via `invalidate`, never `forget` (spec 037, D8): probation lapsing
17
+ * means "not needed right now", not "must never be written again" — a tombstone would permanently
18
+ * block the same fact from being relearned later, which is the wrong failure mode for a
19
+ * confidence-gated background write.
20
+ */
21
+ export declare function expireMemoryEntries(channelDir: string, now?: Date): Promise<number>;
@@ -0,0 +1,48 @@
1
+ import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
2
+ import { applyChannelMemoryOps } from "./files.js";
3
+ import { readMemoryMetadata } from "./metadata.js";
4
+ /**
5
+ * How long a probationary memory entry survives without being recalled (spec 037, D7/D8).
6
+ * A code constant, not a setting: the durable/probation split is an algorithm parameter, same
7
+ * class as `minMemoryAutoWriteConfidence` before it (spec 035's `RETIRED_SETTINGS_KEYS`).
8
+ */
9
+ export const MEMORY_PROBATION_DAYS = 30;
10
+ export function probationDeadline(now = new Date()) {
11
+ return formatLocalTime(new Date(now.getTime() + MEMORY_PROBATION_DAYS * 24 * 60 * 60 * 1000));
12
+ }
13
+ function isPast(value, nowMs) {
14
+ if (!value)
15
+ return false;
16
+ const ms = parseLocalTime(value);
17
+ return ms !== undefined && ms <= nowMs;
18
+ }
19
+ /**
20
+ * Active entries whose probation lapsed, or whose (otherwise unconsumed) `expiresAt` was
21
+ * reached. Both are "this entry's time is up" — they share one eviction path even though their
22
+ * semantics differ: `probationUntil` is cancelled by use, `expiresAt` is unconditional.
23
+ */
24
+ export function collectExpiredEntryIds(metadata, now = new Date()) {
25
+ const nowMs = now.getTime();
26
+ return Object.values(metadata.entries)
27
+ .filter((entry) => entry.status === "active" && (isPast(entry.probationUntil, nowMs) || isPast(entry.expiresAt, nowMs)))
28
+ .map((entry) => entry.id);
29
+ }
30
+ /**
31
+ * Evict every expired entry via `invalidate`, never `forget` (spec 037, D8): probation lapsing
32
+ * means "not needed right now", not "must never be written again" — a tombstone would permanently
33
+ * block the same fact from being relearned later, which is the wrong failure mode for a
34
+ * confidence-gated background write.
35
+ */
36
+ export async function expireMemoryEntries(channelDir, now = new Date()) {
37
+ const metadata = await readMemoryMetadata(channelDir);
38
+ const expiredIds = collectExpiredEntryIds(metadata, now);
39
+ if (expiredIds.length === 0)
40
+ return 0;
41
+ const ops = expiredIds.map((targetId) => ({
42
+ op: "invalidate",
43
+ targetId,
44
+ reason: "probation expired without being recalled",
45
+ }));
46
+ const result = await applyChannelMemoryOps(channelDir, ops, formatLocalTime(now));
47
+ return result.invalidated;
48
+ }
@@ -10,4 +10,29 @@ export interface MemoryPromotionCandidate {
10
10
  necessity: "low" | "medium" | "high";
11
11
  }
12
12
  export declare const DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE = 0.85;
13
- export declare function shouldAutoWriteMemory(candidate: MemoryPromotionCandidate, threshold?: number): boolean;
13
+ /**
14
+ * Confidence bar for a `necessity: "medium"` candidate to enter the durable file at all — as a
15
+ * probationary entry, not permanently (spec 037, D6). Higher than the durable bar: "not
16
+ * necessary but useful" needs more certainty to earn a slot than "necessary".
17
+ */
18
+ export declare const MEMORY_PROBATION_WRITE_CONFIDENCE = 0.9;
19
+ /** Per consolidation run, how many probationary entries may be written (spec 037, D6). */
20
+ export declare const MAX_PROBATION_WRITES_PER_RUN = 5;
21
+ export type MemoryWriteTier = "durable" | "probationary";
22
+ /**
23
+ * Classify a memory candidate into a write tier, or `undefined` to reject it.
24
+ *
25
+ * `necessity` (would future turns break without this?) and `confidence` (how sure is the
26
+ * model?) are orthogonal axes. The gate used to AND them at the strictest tier, which meant a
27
+ * new employee's day-to-day operating knowledge — almost all "medium" necessity — could never
28
+ * be written at all (spec 037 background, L1). Splitting into two tiers lets medium-necessity,
29
+ * high-confidence material in on probation: it must be *used* once (a recall) to become durable,
30
+ * or it expires (`src/memory/probation.ts`). This keeps the durable bar exactly as strict as
31
+ * before — `high` + 0.85 is unchanged — while giving genuinely useful-but-not-critical knowledge
32
+ * a path in.
33
+ *
34
+ * `supersede`/`invalidate` can never land on probation: a durable entry must only be overwritten
35
+ * or removed by something at least as durable, or the overwrite/removal itself could silently
36
+ * expire and resurrect the stale content it was meant to replace.
37
+ */
38
+ export declare function classifyMemoryWrite(candidate: MemoryPromotionCandidate, durableThreshold?: number, probationThreshold?: number): MemoryWriteTier | undefined;
@@ -1,6 +1,36 @@
1
1
  export const DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE = 0.85;
2
- export function shouldAutoWriteMemory(candidate, threshold = DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE) {
3
- return (candidate.confidence >= threshold &&
4
- candidate.necessity === "high" &&
5
- (candidate.op === "invalidate" ? Boolean(candidate.targetId) : Boolean(candidate.content?.trim())));
2
+ /**
3
+ * Confidence bar for a `necessity: "medium"` candidate to enter the durable file at all — as a
4
+ * probationary entry, not permanently (spec 037, D6). Higher than the durable bar: "not
5
+ * necessary but useful" needs more certainty to earn a slot than "necessary".
6
+ */
7
+ export const MEMORY_PROBATION_WRITE_CONFIDENCE = 0.9;
8
+ /** Per consolidation run, how many probationary entries may be written (spec 037, D6). */
9
+ export const MAX_PROBATION_WRITES_PER_RUN = 5;
10
+ /**
11
+ * Classify a memory candidate into a write tier, or `undefined` to reject it.
12
+ *
13
+ * `necessity` (would future turns break without this?) and `confidence` (how sure is the
14
+ * model?) are orthogonal axes. The gate used to AND them at the strictest tier, which meant a
15
+ * new employee's day-to-day operating knowledge — almost all "medium" necessity — could never
16
+ * be written at all (spec 037 background, L1). Splitting into two tiers lets medium-necessity,
17
+ * high-confidence material in on probation: it must be *used* once (a recall) to become durable,
18
+ * or it expires (`src/memory/probation.ts`). This keeps the durable bar exactly as strict as
19
+ * before — `high` + 0.85 is unchanged — while giving genuinely useful-but-not-critical knowledge
20
+ * a path in.
21
+ *
22
+ * `supersede`/`invalidate` can never land on probation: a durable entry must only be overwritten
23
+ * or removed by something at least as durable, or the overwrite/removal itself could silently
24
+ * expire and resurrect the stale content it was meant to replace.
25
+ */
26
+ export function classifyMemoryWrite(candidate, durableThreshold = DEFAULT_MEMORY_AUTO_WRITE_CONFIDENCE, probationThreshold = MEMORY_PROBATION_WRITE_CONFIDENCE) {
27
+ const hasPayload = candidate.op === "invalidate" ? Boolean(candidate.targetId) : Boolean(candidate.content?.trim());
28
+ if (!hasPayload)
29
+ return undefined;
30
+ if (candidate.necessity === "high" && candidate.confidence >= durableThreshold)
31
+ return "durable";
32
+ if (candidate.op === "add" && candidate.necessity === "medium" && candidate.confidence >= probationThreshold) {
33
+ return "probationary";
34
+ }
35
+ return undefined;
6
36
  }
@@ -266,6 +266,9 @@ function tokenSpecificity(token) {
266
266
  // Candidates are cached objects reused across turns by the MemoryCandidateStore, so keying
267
267
  // off the object identity keeps tokenization off the hot path for unchanged memory files.
268
268
  const candidateTokenCache = new WeakMap();
269
+ // Same idea for the exact-match pass: it lowercases the full body of every candidate, which
270
+ // without this allocated a throwaway copy of the entire memory corpus on every turn.
271
+ const candidateLowerCache = new WeakMap();
269
272
  function getCandidateTokens(candidate) {
270
273
  const cached = candidateTokenCache.get(candidate);
271
274
  if (cached) {
@@ -278,6 +281,19 @@ function getCandidateTokens(candidate) {
278
281
  candidateTokenCache.set(candidate, index);
279
282
  return index;
280
283
  }
284
+ function getCandidateLowerFields(candidate) {
285
+ const cached = candidateLowerCache.get(candidate);
286
+ if (cached) {
287
+ return cached;
288
+ }
289
+ const fields = {
290
+ title: candidate.title.toLowerCase(),
291
+ content: (candidate.searchText ?? candidate.content).toLowerCase(),
292
+ path: candidate.path.toLowerCase(),
293
+ };
294
+ candidateLowerCache.set(candidate, fields);
295
+ return fields;
296
+ }
281
297
  function buildDocumentFrequency(candidates) {
282
298
  const frequencies = new Map();
283
299
  for (const candidate of candidates) {
@@ -320,28 +336,30 @@ function computeMatchEvidence(queryTokens, candidate, documentFrequencies, total
320
336
  }
321
337
  return { mass, matchedCount };
322
338
  }
323
- function computeExactMatchBoost(query, candidate) {
324
- const normalizedQuery = query.trim().toLowerCase();
339
+ /** `normalizedQuery` is lowercased and length-checked once by the caller, not per candidate. */
340
+ function computeExactMatchBoost(normalizedQuery, candidate) {
325
341
  if (!normalizedQuery) {
326
342
  return 0;
327
343
  }
328
- const minLength = containsHanText(normalizedQuery) ? 2 : 4;
329
- if (normalizedQuery.length < minLength) {
330
- return 0;
331
- }
344
+ const fields = getCandidateLowerFields(candidate);
332
345
  let boost = 0;
333
- const scoringFields = [
334
- [candidate.title, 4],
335
- [candidate.searchText ?? candidate.content, 3],
336
- [candidate.path, 1.5],
337
- ];
338
- for (const [field, value] of scoringFields) {
339
- if (field.toLowerCase().includes(normalizedQuery)) {
340
- boost += value;
341
- }
342
- }
346
+ if (fields.title.includes(normalizedQuery))
347
+ boost += 4;
348
+ if (fields.content.includes(normalizedQuery))
349
+ boost += 3;
350
+ if (fields.path.includes(normalizedQuery))
351
+ boost += 1.5;
343
352
  return boost;
344
353
  }
354
+ /**
355
+ * The query as `computeExactMatchBoost` wants it, or `""` when it is too short to be evidence
356
+ * on its own (a 2-char Han fragment is meaningful, a 2-char Latin one is not).
357
+ */
358
+ function normalizeExactMatchQuery(query) {
359
+ const normalizedQuery = query.trim().toLowerCase();
360
+ const minLength = containsHanText(normalizedQuery) ? 2 : 4;
361
+ return normalizedQuery.length >= minLength ? normalizedQuery : "";
362
+ }
345
363
  function computeRecencyBoost(timestamp) {
346
364
  if (!timestamp)
347
365
  return 0;
@@ -404,9 +422,9 @@ function compareScoredCandidates(a, b) {
404
422
  b.candidate.priority - a.candidate.priority ||
405
423
  a.candidate.title.localeCompare(b.candidate.title));
406
424
  }
407
- function scoreCandidate(query, queryTokens, intents, candidate, documentFrequencies, totalCandidates) {
425
+ function scoreCandidate(exactMatchQuery, queryTokens, intents, candidate, documentFrequencies, totalCandidates) {
408
426
  const evidence = computeMatchEvidence(queryTokens, candidate, documentFrequencies, totalCandidates);
409
- const totalEvidence = evidence.mass + computeExactMatchBoost(query, candidate);
427
+ const totalEvidence = evidence.mass + computeExactMatchBoost(exactMatchQuery, candidate);
410
428
  if (totalEvidence < MIN_MATCH_EVIDENCE) {
411
429
  return null;
412
430
  }
@@ -593,10 +611,11 @@ export async function recallRelevantMemory(request) {
593
611
  }
594
612
  const queryTokens = tokenize(query);
595
613
  const queryIntents = detectQueryIntents(query);
614
+ const exactMatchQuery = normalizeExactMatchQuery(query);
596
615
  const documentFrequencies = buildDocumentFrequency(eligibleCandidates);
597
616
  const totalCandidates = eligibleCandidates.length;
598
617
  const scored = eligibleCandidates
599
- .map((candidate) => scoreCandidate(query, queryTokens, queryIntents, candidate, documentFrequencies, totalCandidates))
618
+ .map((candidate) => scoreCandidate(exactMatchQuery, queryTokens, queryIntents, candidate, documentFrequencies, totalCandidates))
600
619
  .filter((candidate) => candidate !== null)
601
620
  .sort(compareScoredCandidates);
602
621
  const shortlist = seedIntentCandidates(request, eligibleCandidates, scored, queryIntents, queryTokens, documentFrequencies, totalCandidates)
@@ -198,21 +198,22 @@ async function listChannelSessionJsonlFiles(channelDir, maxFiles) {
198
198
  }
199
199
  throw error;
200
200
  }
201
- const candidates = [];
202
- for (const name of names) {
203
- if (!name.endsWith(".jsonl") || IGNORED_JSONL_FILES.has(name)) {
204
- continue;
205
- }
201
+ // Stat in parallel: this is one round trip per session file in the channel directory, and
202
+ // awaiting them one at a time made the corpus build scale with the file count rather than
203
+ // with the slowest stat.
204
+ const stated = await Promise.all(names
205
+ .filter((name) => name.endsWith(".jsonl") && !IGNORED_JSONL_FILES.has(name))
206
+ .map(async (name) => {
206
207
  const path = join(channelDir, name);
207
208
  try {
208
209
  const stats = await stat(path);
209
- if (!stats.isFile()) {
210
- continue;
211
- }
212
- candidates.push({ path, mtimeMs: stats.mtimeMs });
210
+ return stats.isFile() ? { path, mtimeMs: stats.mtimeMs } : null;
213
211
  }
214
- catch { }
215
- }
212
+ catch {
213
+ return null;
214
+ }
215
+ }));
216
+ const candidates = stated.filter((entry) => entry !== null);
216
217
  return candidates
217
218
  .sort((a, b) => b.mtimeMs - a.mtimeMs)
218
219
  .slice(0, Math.max(0, maxFiles))
@@ -42,11 +42,26 @@ function computeRecencyBoost(timestamp) {
42
42
  }
43
43
  return 0;
44
44
  }
45
- function scoreDocument(document, query, queryTokens) {
46
- const text = document.text;
47
- const lowerText = text.toLowerCase();
48
- const lowerQuery = query.trim().toLowerCase();
49
- const documentTokens = new Set(tokenizeRecallText(text));
45
+ /**
46
+ * Tokenizing a document is by far the most expensive part of a search — a few milliseconds for a
47
+ * multi-kilobyte transcript hit, times every document in the corpus. The corpus itself is already
48
+ * cached for {@link CORPUS_CACHE_TTL_MS}, so keying off the document's object identity keeps every
49
+ * search inside that window from re-deriving tokens it has already derived. Entries disappear with
50
+ * the cached corpus that owns them.
51
+ */
52
+ const documentTokenCache = new WeakMap();
53
+ function getDocumentTokens(document) {
54
+ const cached = documentTokenCache.get(document);
55
+ if (cached) {
56
+ return cached;
57
+ }
58
+ const tokens = new Set(tokenizeRecallText(document.text));
59
+ documentTokenCache.set(document, tokens);
60
+ return tokens;
61
+ }
62
+ function scoreDocument(document, lowerQuery, queryTokens) {
63
+ const lowerText = document.text.toLowerCase();
64
+ const documentTokens = getDocumentTokens(document);
50
65
  const matches = [];
51
66
  let matchedTokens = 0;
52
67
  for (const token of queryTokens) {
@@ -143,9 +158,13 @@ export async function searchChannelSessions(request) {
143
158
  .filter((document) => roleFilter.size === 0 || roleFilter.has(document.role))
144
159
  .sort(sortRecentDocuments)
145
160
  .slice(0, maxChunks);
161
+ // Both derived once, not per document: `tokenizeRecallText` is milliseconds on real input and
162
+ // this loop runs over the whole corpus.
163
+ const queryTokens = query ? tokenizeRecallText(query) : [];
164
+ const lowerQuery = query.toLowerCase();
146
165
  const selected = query
147
166
  ? documents
148
- .map((document) => scoreDocument(document, query, tokenizeRecallText(query)))
167
+ .map((document) => scoreDocument(document, lowerQuery, queryTokens))
149
168
  .filter((entry) => entry.score > 0)
150
169
  .sort((a, b) => b.score - a.score)
151
170
  .slice(0, limit)
@@ -1,4 +1,5 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
+ import { streamSimple } from "@earendil-works/pi-ai/compat";
2
3
  import { convertToLlm } from "@earendil-works/pi-coding-agent";
3
4
  import { formatModelReference } from "../models/utils.js";
4
5
  import { extractAssistantText } from "../shared/text-utils.js";
@@ -94,6 +95,7 @@ export async function runSidecarTask(task) {
94
95
  },
95
96
  convertToLlm,
96
97
  getApiKey: async () => apiKey,
98
+ streamFn: streamSimple,
97
99
  });
98
100
  const abortWorker = () => {
99
101
  try {
@@ -34,6 +34,12 @@ function renderLine(entry, now) {
34
34
  if (control.nextAction)
35
35
  parts.push(`next ${control.nextAction}`);
36
36
  }
37
+ // spec 037, D4: the agenda shows Plan progress and the current step, not the full Plan — the
38
+ // complete section is only read from the task file at wake time (task-driver.ts's capsule),
39
+ // staying well inside the 600-unit budget this block competes for (spec 025/026).
40
+ if (entry.plan) {
41
+ parts.push(`plan ${entry.plan.done}/${entry.plan.total} · @${entry.plan.current?.id ?? "-"}`);
42
+ }
37
43
  if (entry.latestNote) {
38
44
  const note = entry.latestNote.length > 80 ? `${entry.latestNote.slice(0, 79)}…` : entry.latestNote;
39
45
  parts.push(note);
@@ -25,10 +25,16 @@ priority: 20
25
25
 
26
26
  ## 什么时候立即写 durable memory
27
27
 
28
- 用户明确说“记住、以后默认、偏好、不要再做、忘掉”时,立即调用 `memory_manage`,不要等待后台 consolidation。只保存未来仍有用的事实;一次性进度、猜测、临时计划放 task 或留在当前会话。
28
+ 用户明确说”记住、以后默认、偏好、不要再做、忘掉”时,立即调用 `memory_manage`,不要等待后台 consolidation。只保存未来仍有用的事实;一次性进度、猜测、临时计划放 task 或留在当前会话。这条路径写入的记忆立即是永久的,不受下面的试用期约束。
29
29
 
30
30
  查找时先用具体关键词。忘记或替换旧规则时用 `forget`,不要追加一条互相矛盾的新记忆。
31
31
 
32
+ ## 后台自动写入与试用期
33
+
34
+ 后台 consolidation 按两档写入 channel `MEMORY.md`:明确会导致未来回合出错的硬约束(`necessity: high`)直接永久写入;日常运作知识——谁负责哪块、术语默认含义、发布或命名惯例、流程签批人(`necessity: medium`)——以**试用期**条目写入,默认 30 天。试用期条目在这期间被召回一次即转正为永久;从未被用到则到期后自动失效。失效不是遗忘:内容仍可在之后被重新学到,只是这一次没被用上。
35
+
36
+ 不要把这套阈值当作可调节的旋钮——它是代码常量,不在 `settings.json` 里。
37
+
32
38
  ## ENVIRONMENT.md
33
39
 
34
40
  记录未来回合需要知道的机器事实,例如安装的工具、重要环境变量来源、代码仓库之外修改的配置、运行前提。不要放聊天摘要、任务进度、密钥值或用户偏好。
@@ -10,7 +10,7 @@ priority: 41
10
10
  ## 每次唤醒先恢复真相
11
11
 
12
12
  1. 打开消息指定的 `tasks/<id>.md`,不要只依赖唤醒文本、旧对话或记忆。
13
- 2. 核对 status、最新 Current Cycle note、`nextAction`、`wake`、deadline / attempt budget、`sideEffects` 和 verification。
13
+ 2. 核对 status、最新 Current Cycle note、`nextAction`、`wake`、deadline / attempt budget、`sideEffects` 和 verification。有 Plan 时看当前步骤(胶囊里的 `plan=` 字段已经给出,正文里也能看到第一个 `[ ]`/`[!]`),不要重新猜"上次做到哪了"。
14
14
  3. 检查上一步产物**是否已经存在**。派发语义是 at-least-once,宕机或租约重放可能让同一步再次到达。
15
15
  4. 只推进一个清晰的下一阶段;不要在未知状态下重复外部动作。
16
16
 
@@ -18,7 +18,7 @@ deadline 或 attempt budget 耗尽会令任务被治理器暂停(`paused` + `p
18
18
 
19
19
  ## 回合结束必须留下确定性状态
20
20
 
21
- 仍开放且正文或进展发生变化时,用 `task_manage progress` 一次性记录:发生了什么、看到了什么证据、下一步是什么、status 与 `wake`。
21
+ 仍开放且正文或进展发生变化时,用 `task_manage progress` 一次性记录:发生了什么、看到了什么证据、下一步是什么、status 与 `wake`。有 Plan 的任务,步骤完成、受阻或需要新增时,在同一次 `progress` 调用里带上 `planSteps`(如 `[{id:"P2", status:"done"}]`),不要单独用 `write`/`edit` 改 Plan 段——变更会自动折进这条 note,不需要重复写一遍。
22
22
 
23
23
  以下生命周期动作本身就是原子 checkpoint,不要再追加 progress:`candidate`、`done`、`skip`、`cancel`。
24
24
 
@@ -36,6 +36,20 @@ priority: 40
36
36
 
37
37
  DoD 描述最终可验收结果,不把未执行动作写成 `[x] skipped`。存在条件分支时,用一个结果项表达“完成 A,或在条件不成立时交付 B 并附理由”;执行哪条路径由 evidence 证明。
38
38
 
39
+ ## 计划(Plan):手段层,不是第二份 DoD
40
+
41
+ 预计需要 5 步以上,或会跨 3 次以上唤醒才能完成时,创建阶段用 `plan` 参数给出初始步骤(一行一步),或后续用 `task_manage progress` 的 `planSteps` 追加。控制在 3–9 步,每步应有可独立验证的产出,不要把 DoD 逐条照抄成步骤——DoD 是**要交付什么**,Plan 是**打算怎么做**,两者粒度不同才有意义。步骤可选地用 `→ dod:1,2` 声明它覆盖哪些 DoD 项;`/tasks doctor` 会检查引用是否有效、是否有 DoD 项完全没有步骤覆盖。
42
+
43
+ 步骤只有四态:`[ ]` 待办、`[x]` 完成、`[!]` 阻塞(写清楚等什么)、`[~]` 放弃(连同一句为什么,不要直接删行)。**没有"进行中"态**——当前步骤由 runtime 从文档顺序自动推导(第一个待办或阻塞项),每次唤醒的任务胶囊和 `<task_agenda>` 都会显示它,不需要自己申报。
44
+
45
+ 更新步骤状态只用 `task_manage progress` 的 `planSteps`(`[{id, status?, text?}]`),不要用 `write`/`edit` 手改 Plan 段——那样会绕开唤醒胶囊的推导逻辑且容易打乱格式。改动会自动折进这次 `progress` 的 Current Cycle 记录里,不需要额外记一遍。
46
+
47
+ Plan 与契约段(Goal/DoD/Manual/Verification)分开:**改 Plan 步骤状态不会使已有的独立验收 PASS 或外部审批失效**,因为它是任务的手段而非承诺。反过来,Plan 也不是新增的验收门——`done` 只看 DoD,不检查 Plan 是否全部勾完。
48
+
49
+ 发现打法需要大改(不只是勾一步)时,直接调用 `planSteps` 重写受影响的步骤即可,同样不必大改正文;只有需要重新组织整个正文结构时才用 `edit`。
50
+
51
+ `nextAction` 和 Plan 不要互相重复:`nextAction` 是"当前步骤内接下来那个具体动作",Plan 是"整个任务的步骤阶梯"。跨任务可复用的方法与返工教训继续写进 Manual,不要塞进某一步的文案里。
52
+
39
53
  ## 六个状态与时间
40
54
 
41
55
  每个状态只对应一种 driver 行为:
@@ -524,7 +524,7 @@ export function createRuntimeContext(options) {
524
524
  await bot.sendPlain(event.channelId, response);
525
525
  },
526
526
  async handleUsageCommand(event, bot, args) {
527
- const response = renderUsageReport(getUsageLedger(), event.channelId, parseUsageMode(args), new Date());
527
+ const response = await renderUsageReport(getUsageLedger(), event.channelId, parseUsageMode(args), new Date());
528
528
  await bot.sendPlain(event.channelId, response);
529
529
  },
530
530
  // Read-only prompt accounting; safe mid-turn, so it is answered here rather than by
@@ -254,8 +254,14 @@ class ChannelDeliveryController {
254
254
  }
255
255
  else if (mode === "finalize-existing") {
256
256
  if (content || this.cardWarmupTriggered) {
257
- const finalProgressText = this.progressStyle === "rolling" ? this.buildSummaryText() : progressText;
258
- touchedRemote = await this.bot.replaceCard(this.event.channelId, content || this.progressStyle === "rolling" ? finalProgressText : NO_CONTENT, true);
257
+ const isRolling = this.progressStyle === "rolling";
258
+ const finalProgressText = isRolling ? this.buildSummaryText() : progressText;
259
+ // A warmed-but-empty card in full mode has nothing to show, so it finalizes
260
+ // blank; rolling mode always has its closing summary to put there.
261
+ // (`||` binds tighter than `?:` — this used to read as one condition and
262
+ // was a standing invitation to misparse it.)
263
+ const finalCardText = content || isRolling ? finalProgressText : NO_CONTENT;
264
+ touchedRemote = await this.bot.replaceCard(this.event.channelId, finalCardText, true);
259
265
  if (!touchedRemote) {
260
266
  this.bot.discardCard(this.event.channelId);
261
267
  }
@@ -160,6 +160,9 @@ export declare class DingTalkBot implements MediaSender {
160
160
  discardCard(channelId: string): void;
161
161
  /**
162
162
  * Send a normal message natively mapping DM and Group to correct endpoints (fallback when no card).
163
+ *
164
+ * Only the message shape is decided here; the DM-vs-group routing and the POST itself belong to
165
+ * `sendRobotMessage`, which every other outbound message type already goes through.
163
166
  */
164
167
  sendPlain(channelId: string, text: string): Promise<boolean>;
165
168
  /**
@@ -178,8 +181,8 @@ export declare class DingTalkBot implements MediaSender {
178
181
  private uploadMedia;
179
182
  /**
180
183
  * POST a robot message with an arbitrary msgKey/msgParam, routing DM vs group
181
- * to the correct endpoint. Shared by the media path; `sendPlain` predates this
182
- * and keeps its own inlined copy to avoid a regression-prone refactor.
184
+ * to the correct endpoint. The single outbound path for every non-card message:
185
+ * plain text/markdown, images, and files.
183
186
  */
184
187
  private sendRobotMessage;
185
188
  private createCard;