@oyasmi/pipiclaw 0.8.10 → 0.8.11-beta.3

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 (106) hide show
  1. package/README.md +3 -3
  2. package/dist/agent/channel-runner.d.ts +11 -0
  3. package/dist/agent/channel-runner.js +58 -27
  4. package/dist/agent/commands.js +2 -3
  5. package/dist/agent/effect-ledger.d.ts +1 -1
  6. package/dist/agent/effect-ledger.js +2 -2
  7. package/dist/agent/prompt/sections.js +3 -3
  8. package/dist/agent/runner-factory.d.ts +2 -0
  9. package/dist/agent/session-events.js +1 -1
  10. package/dist/main.js +6 -0
  11. package/dist/memory/commands.js +6 -1
  12. package/dist/memory/consolidation.d.ts +8 -1
  13. package/dist/memory/consolidation.js +34 -6
  14. package/dist/memory/extraction.d.ts +11 -3
  15. package/dist/memory/extraction.js +19 -6
  16. package/dist/memory/files.d.ts +2 -0
  17. package/dist/memory/files.js +14 -0
  18. package/dist/memory/maintenance-gates.d.ts +3 -0
  19. package/dist/memory/maintenance-gates.js +5 -2
  20. package/dist/memory/maintenance-jobs.js +19 -2
  21. package/dist/memory/maintenance-state.d.ts +29 -0
  22. package/dist/memory/maintenance-state.js +100 -8
  23. package/dist/memory/metadata.d.ts +9 -0
  24. package/dist/memory/metadata.js +5 -0
  25. package/dist/memory/probation.d.ts +21 -0
  26. package/dist/memory/probation.js +48 -0
  27. package/dist/memory/promotion.d.ts +26 -1
  28. package/dist/memory/promotion.js +34 -4
  29. package/dist/memory/recall.js +38 -19
  30. package/dist/memory/session-corpus.js +12 -11
  31. package/dist/memory/session-search.js +25 -6
  32. package/dist/memory/sidecar-worker.js +2 -0
  33. package/dist/memory/task-digest.d.ts +3 -2
  34. package/dist/memory/task-digest.js +22 -8
  35. package/dist/models/auth-cli.d.ts +25 -0
  36. package/dist/models/auth-cli.js +344 -0
  37. package/dist/models/login-ui.d.ts +35 -0
  38. package/dist/models/login-ui.js +145 -0
  39. package/dist/models/provider-login.d.ts +41 -0
  40. package/dist/models/provider-login.js +126 -0
  41. package/dist/models/utils.d.ts +6 -0
  42. package/dist/models/utils.js +10 -0
  43. package/dist/playbooks/memory-and-learning.md +7 -1
  44. package/dist/playbooks/outbound-media.md +7 -33
  45. package/dist/playbooks/runtime-orientation.md +2 -0
  46. package/dist/playbooks/task-closeout.md +22 -35
  47. package/dist/playbooks/task-delegation.md +13 -35
  48. package/dist/playbooks/task-driving.md +36 -56
  49. package/dist/playbooks/task-planning.md +26 -45
  50. package/dist/runtime/bootstrap.js +48 -14
  51. package/dist/runtime/delivery.js +8 -2
  52. package/dist/runtime/dingtalk.d.ts +6 -3
  53. package/dist/runtime/dingtalk.js +6 -39
  54. package/dist/runtime/events.js +4 -3
  55. package/dist/runtime/proxy.d.ts +36 -0
  56. package/dist/runtime/proxy.js +68 -0
  57. package/dist/runtime/store.d.ts +8 -2
  58. package/dist/runtime/store.js +12 -6
  59. package/dist/runtime/task-commands.d.ts +0 -2
  60. package/dist/runtime/task-commands.js +99 -112
  61. package/dist/runtime/task-driver.d.ts +5 -0
  62. package/dist/runtime/task-driver.js +155 -53
  63. package/dist/runtime/task-migration.d.ts +9 -0
  64. package/dist/runtime/task-migration.js +75 -2
  65. package/dist/security/command-guard.js +51 -17
  66. package/dist/security/path-guard.js +72 -14
  67. package/dist/shared/open-browser.d.ts +6 -0
  68. package/dist/shared/open-browser.js +22 -0
  69. package/dist/shared/recoverable-error.d.ts +1 -1
  70. package/dist/shared/recoverable-error.js +1 -1
  71. package/dist/subagents/tool.js +2 -0
  72. package/dist/tasks/control.d.ts +38 -67
  73. package/dist/tasks/control.js +90 -152
  74. package/dist/tasks/ledger.d.ts +104 -22
  75. package/dist/tasks/ledger.js +419 -56
  76. package/dist/tasks/store.d.ts +11 -10
  77. package/dist/tasks/store.js +58 -27
  78. package/dist/tasks/transitions.d.ts +8 -36
  79. package/dist/tasks/transitions.js +29 -54
  80. package/dist/tasks/verification.d.ts +2 -2
  81. package/dist/tools/index.d.ts +2 -0
  82. package/dist/tools/index.js +1 -0
  83. package/dist/tools/memory-manage.js +8 -1
  84. package/dist/tools/read.js +19 -5
  85. package/dist/tools/registry.d.ts +1 -0
  86. package/dist/tools/registry.js +1 -0
  87. package/dist/tools/task-manage/lifecycle.d.ts +1 -7
  88. package/dist/tools/task-manage/lifecycle.js +76 -77
  89. package/dist/tools/task-manage/schema.d.ts +10 -5
  90. package/dist/tools/task-manage/schema.js +35 -21
  91. package/dist/tools/task-manage/shared.d.ts +1 -1
  92. package/dist/tools/task-manage/shared.js +29 -30
  93. package/dist/tools/task-manage/types.d.ts +7 -1
  94. package/dist/tools/task-manage/verification.d.ts +4 -5
  95. package/dist/tools/task-manage/verification.js +43 -15
  96. package/dist/tools/task-manage.d.ts +1 -1
  97. package/dist/tools/task-manage.js +9 -9
  98. package/dist/tui/app.js +1 -2
  99. package/dist/tui/commands.d.ts +1 -1
  100. package/dist/tui/commands.js +1 -1
  101. package/dist/tui/turn-controller.d.ts +1 -1
  102. package/dist/usage/ledger.d.ts +1 -1
  103. package/dist/usage/ledger.js +47 -22
  104. package/dist/usage/render.d.ts +1 -1
  105. package/dist/usage/render.js +8 -6
  106. package/package.json +7 -6
@@ -141,6 +141,7 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = formatL
141
141
  blockedByPolicy: 0,
142
142
  blockedByTombstone: 0,
143
143
  skippedDuplicate: 0,
144
+ promotedFromProbation: 0,
144
145
  };
145
146
  if (ops.length === 0) {
146
147
  return result;
@@ -158,6 +159,7 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = formatL
158
159
  const tombstoneHashes = new Set(tombstones.map((tombstone) => tombstone.contentHash));
159
160
  const tombstoneSourceIds = new Set(tombstones.flatMap((tombstone) => tombstone.sourceEntryIds ?? []));
160
161
  const activeContentHashes = new Set(existingEntries.map((entry) => hashMemoryContent(entry.content)));
162
+ const activeEntryIdByContentHash = new Map(existingEntries.map((entry) => [hashMemoryContent(entry.content), entry.id]));
161
163
  const appliedSourceCorrelationIds = new Set(Object.values(currentMetadata.entries).flatMap((entry) => entry.sourceCorrelationIds));
162
164
  const removals = new Set();
163
165
  const replacements = new Map();
@@ -184,6 +186,18 @@ export async function applyChannelMemoryOps(channelDir, ops, timestamp = formatL
184
186
  const contentHash = hashMemoryContent(op.content);
185
187
  if (activeContentHashes.has(contentHash)) {
186
188
  result.skippedDuplicate++;
189
+ // A durable write (explicit `probationUntil: null`) restating a fact that is
190
+ // already stored, possibly on probation, is itself evidence the fact matters —
191
+ // promote the existing entry in place (spec 037, D7 path 2). A probationary
192
+ // restatement leaves the existing entry's deadline untouched: seeing the same
193
+ // medium-necessity thing twice does not by itself earn it a permanent slot.
194
+ if (op.metadata?.probationUntil === null) {
195
+ const existingId = activeEntryIdByContentHash.get(contentHash);
196
+ if (existingId) {
197
+ metadataUpdates.push({ id: existingId, metadata: { probationUntil: null } });
198
+ result.promotedFromProbation++;
199
+ }
200
+ }
187
201
  continue;
188
202
  }
189
203
  const id = generateMemoryEntryId();
@@ -41,6 +41,8 @@ export interface StructuralMaintenanceMaterial {
41
41
  historyFoldingNeeded: boolean;
42
42
  hasMemoryContent: boolean;
43
43
  hasHistoryContent: boolean;
44
+ /** Active entries whose probation lapsed or `expiresAt` was reached (spec 037, D8). */
45
+ expiredEntryCount: number;
44
46
  }
45
47
  export interface StructuralMaintenanceGateInput {
46
48
  now: Date;
@@ -52,6 +54,7 @@ export interface StructuralMaintenanceGateInput {
52
54
  export interface StructuralMaintenanceGateDecision extends MaintenanceGateDecision {
53
55
  runMemoryCleanup: boolean;
54
56
  runHistoryFolding: boolean;
57
+ runProbationExpiry: boolean;
55
58
  }
56
59
  export declare function shouldRunSessionRefresh(input: SessionRefreshGateInput): MaintenanceGateDecision;
57
60
  export declare function shouldRunMemoryCheckpoint(input: MemoryCheckpointGateInput): MaintenanceGateDecision;
@@ -96,6 +96,7 @@ export async function shouldRunStructuralMaintenance(input) {
96
96
  skipReason,
97
97
  runMemoryCleanup: false,
98
98
  runHistoryFolding: false,
99
+ runProbationExpiry: false,
99
100
  });
100
101
  if (input.channelActive) {
101
102
  return denyStructural("channel-active");
@@ -107,12 +108,13 @@ export async function shouldRunStructuralMaintenance(input) {
107
108
  return denyStructural("backoff-active");
108
109
  }
109
110
  const material = await input.material();
110
- if (!material.hasMemoryContent && !material.hasHistoryContent) {
111
+ const runProbationExpiry = material.expiredEntryCount > 0;
112
+ if (!material.hasMemoryContent && !material.hasHistoryContent && !runProbationExpiry) {
111
113
  return denyStructural("empty-template-files");
112
114
  }
113
115
  const runMemoryCleanup = material.memoryCleanupNeeded;
114
116
  const runHistoryFolding = material.historyFoldingNeeded;
115
- if (!runMemoryCleanup && !runHistoryFolding) {
117
+ if (!runMemoryCleanup && !runHistoryFolding && !runProbationExpiry) {
116
118
  return denyStructural("nothing-to-maintain");
117
119
  }
118
120
  return {
@@ -120,5 +122,6 @@ export async function shouldRunStructuralMaintenance(input) {
120
122
  jobKind,
121
123
  runMemoryCleanup,
122
124
  runHistoryFolding,
125
+ runProbationExpiry,
123
126
  };
124
127
  }
@@ -5,6 +5,8 @@ import { cleanupChannelMemory, foldChannelHistory, getStructuralMaintenanceStats
5
5
  import { readChannelHistory, readChannelMemory } from "./files.js";
6
6
  import { shouldRunMemoryCheckpoint, shouldRunSessionRefresh, shouldRunStructuralMaintenance, } from "./maintenance-gates.js";
7
7
  import { readMemoryMaintenanceState, updateMemoryMaintenanceState } from "./maintenance-state.js";
8
+ import { readMemoryMetadata } from "./metadata.js";
9
+ import { collectExpiredEntryIds, expireMemoryEntries } from "./probation.js";
8
10
  import { appendMemoryReviewLog } from "./review-log.js";
9
11
  import { updateChannelSessionMemory } from "./session.js";
10
12
  import { buildIncrementalMemorySourceWindow } from "./source-window.js";
@@ -222,21 +224,35 @@ export async function runStructuralMaintenanceJob(input) {
222
224
  const now = input.now ?? new Date();
223
225
  const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
224
226
  const loadFiles = once(() => Promise.all([readChannelMemory(input.channelDir), readChannelHistory(input.channelDir)]));
227
+ const loadExpiredCount = once(async () => {
228
+ const metadata = await readMemoryMetadata(input.channelDir);
229
+ return collectExpiredEntryIds(metadata, now).length;
230
+ });
225
231
  const decision = await shouldRunStructuralMaintenance({
226
232
  now,
227
233
  state,
228
234
  maintenance: input.settings.memoryMaintenance,
229
235
  channelActive: input.channelActive,
230
- material: async () => getStructuralMaintenanceStats(...(await loadFiles())),
236
+ material: async () => ({
237
+ ...getStructuralMaintenanceStats(...(await loadFiles())),
238
+ expiredEntryCount: await loadExpiredCount(),
239
+ }),
231
240
  });
232
241
  if (!decision.allowed) {
233
242
  await appendJobReviewLog(input.channelDir, input.channelId, "structural-maintenance-job", { skipped: [{ target: "structural-maintenance", reason: decision.skipReason }] }, now);
234
243
  return skipped(decision.jobKind, decision.skipReason ?? "skipped");
235
244
  }
236
- const [currentMemory, currentHistory] = await loadFiles();
237
245
  try {
238
246
  const correlationId = `structural-maintenance:${formatLocalTime(now)}`;
239
247
  const options = makeRunOptions(input, correlationId);
248
+ // Probation/expiresAt eviction runs first, deterministically, before the LLM cleanup
249
+ // pass sees the file — no point spending a cleanup prompt on entries about to be
250
+ // invalidated (spec 037, D8).
251
+ const expiredCount = decision.runProbationExpiry ? await expireMemoryEntries(input.channelDir, now) : 0;
252
+ const [cachedMemory, currentHistory] = await loadFiles();
253
+ // `loadFiles`'s cached read predates the expiry write above, so a fresh read is needed
254
+ // whenever expiry actually changed the file; otherwise the cache is still accurate.
255
+ const currentMemory = expiredCount > 0 ? await readChannelMemory(input.channelDir) : cachedMemory;
240
256
  const cleanedMemory = decision.runMemoryCleanup
241
257
  ? await cleanupChannelMemory(options, currentMemory, {
242
258
  cleanupShrinkGuardMinRatio: input.settings.memoryMaintenance.cleanupShrinkGuardMinRatio,
@@ -252,6 +268,7 @@ export async function runStructuralMaintenanceJob(input) {
252
268
  await appendJobReviewLog(input.channelDir, input.channelId, "structural-maintenance-job", {
253
269
  correlationId,
254
270
  actions: [
271
+ ...(expiredCount > 0 ? [{ target: "MEMORY.md", action: "expire", entries: expiredCount }] : []),
255
272
  ...(cleanedMemory ? [{ target: "MEMORY.md", action: "rewrite" }] : []),
256
273
  ...(foldedHistory ? [{ target: "HISTORY.md", action: "rewrite" }] : []),
257
274
  ],
@@ -25,4 +25,33 @@ export declare function getMemoryMaintenanceStateDir(appHomeDir: string): string
25
25
  export declare function getMemoryMaintenanceStatePath(appHomeDir: string, channelId: string): string;
26
26
  export declare function readMemoryMaintenanceState(appHomeDir: string, channelId: string): Promise<MemoryMaintenanceState>;
27
27
  export declare function updateMemoryMaintenanceState(appHomeDir: string, channelId: string, update: (state: MemoryMaintenanceState) => MemoryMaintenanceState): Promise<MemoryMaintenanceState>;
28
+ /** Apply a single activity event. The buffered path folds a whole burst through the same core. */
28
29
  export declare function applyMemoryActivityToState(state: MemoryMaintenanceState, event: MemoryActivityEvent): MemoryMaintenanceState;
30
+ /**
31
+ * Buffers activity events and writes them out in batches.
32
+ *
33
+ * Activity is recorded on *every* tool call, and each write used to be a read-modify-write of a
34
+ * JSON file through `writeFileAtomically` — two fsyncs apiece. A thirty-step turn paid that thirty
35
+ * times, on storage whose fsync latency the runtime does not control.
36
+ *
37
+ * Batching is safe because nothing consumes this state promptly: every gate in
38
+ * `maintenance-gates.ts` denies outright while the channel is active, and `eligibleAfter` holds
39
+ * maintenance off for `minIdleMinutesBeforeLlmWork` after that. The scheduler then polls once a
40
+ * minute. So the state only has to be accurate by the time a channel goes *idle* — which is why
41
+ * the runner also flushes explicitly at the end of every turn, on top of the debounce here. The
42
+ * debounce bounds what a crash can lose to a few seconds of counters, never a checkpoint: those
43
+ * are written directly, and the serial queue keeps a flush from reordering against them.
44
+ */
45
+ export interface MemoryActivityRecorder {
46
+ record(event: MemoryActivityEvent): void;
47
+ /** Write out buffered activity for one channel, or for all of them when `channelId` is omitted. */
48
+ flush(channelId?: string): Promise<void>;
49
+ }
50
+ export declare const DEFAULT_ACTIVITY_FLUSH_DEBOUNCE_MS = 5000;
51
+ export interface CreateMemoryActivityRecorderOptions {
52
+ appHomeDir: string;
53
+ /** Override the flush debounce; tests use a short one. */
54
+ debounceMs?: number;
55
+ onError?: (channelId: string, error: unknown) => void;
56
+ }
57
+ export declare function createMemoryActivityRecorder(options: CreateMemoryActivityRecorderOptions): MemoryActivityRecorder;
@@ -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))