@cortexkit/pi-magic-context 0.49.82 → 0.49.83
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.
- package/dist/index.js +272 -197
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -917,6 +917,7 @@ var CANONICAL_DREAM_TASKS = [
|
|
|
917
917
|
"promote-primers",
|
|
918
918
|
"refresh-primers"
|
|
919
919
|
];
|
|
920
|
+
var MIN_POOL_TO_CLASSIFY = 10;
|
|
920
921
|
function availableDreamTasks(smartNotesEnabled = true) {
|
|
921
922
|
return CANONICAL_DREAM_TASKS.filter((task) => smartNotesEnabled || task !== "evaluate-smart-notes");
|
|
922
923
|
}
|
|
@@ -3621,7 +3622,7 @@ function startHostStallProfilerSwitch() {
|
|
|
3621
3622
|
// package.json
|
|
3622
3623
|
var package_default = {
|
|
3623
3624
|
name: "@cortexkit/pi-magic-context",
|
|
3624
|
-
version: "0.49.
|
|
3625
|
+
version: "0.49.83",
|
|
3625
3626
|
type: "module",
|
|
3626
3627
|
description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
|
|
3627
3628
|
main: "dist/index.js",
|
|
@@ -4361,6 +4362,91 @@ function backoffMs(failureCount) {
|
|
|
4361
4362
|
return minutes * 60 * 1000;
|
|
4362
4363
|
}
|
|
4363
4364
|
|
|
4365
|
+
// ../plugin/src/features/magic-context/dreamer/map-memories-retry.ts
|
|
4366
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
4367
|
+
|
|
4368
|
+
// ../plugin/src/features/magic-context/dreamer/storage-dream-state.ts
|
|
4369
|
+
var getDreamStateStatements = new WeakMap;
|
|
4370
|
+
var setDreamStateStatements = new WeakMap;
|
|
4371
|
+
var deleteDreamStateStatements = new WeakMap;
|
|
4372
|
+
function getGetDreamStateStatement(db) {
|
|
4373
|
+
let stmt = getDreamStateStatements.get(db);
|
|
4374
|
+
if (!stmt) {
|
|
4375
|
+
stmt = db.prepare("SELECT value FROM dream_state WHERE key = ?");
|
|
4376
|
+
getDreamStateStatements.set(db, stmt);
|
|
4377
|
+
}
|
|
4378
|
+
return stmt;
|
|
4379
|
+
}
|
|
4380
|
+
function getSetDreamStateStatement(db) {
|
|
4381
|
+
let stmt = setDreamStateStatements.get(db);
|
|
4382
|
+
if (!stmt) {
|
|
4383
|
+
stmt = db.prepare("INSERT INTO dream_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value");
|
|
4384
|
+
setDreamStateStatements.set(db, stmt);
|
|
4385
|
+
}
|
|
4386
|
+
return stmt;
|
|
4387
|
+
}
|
|
4388
|
+
function getDeleteDreamStateStatement(db) {
|
|
4389
|
+
let stmt = deleteDreamStateStatements.get(db);
|
|
4390
|
+
if (!stmt) {
|
|
4391
|
+
stmt = db.prepare("DELETE FROM dream_state WHERE key = ?");
|
|
4392
|
+
deleteDreamStateStatements.set(db, stmt);
|
|
4393
|
+
}
|
|
4394
|
+
return stmt;
|
|
4395
|
+
}
|
|
4396
|
+
function getDreamState(db, key) {
|
|
4397
|
+
const row = getGetDreamStateStatement(db).get(key);
|
|
4398
|
+
return typeof row?.value === "string" ? row.value : null;
|
|
4399
|
+
}
|
|
4400
|
+
function setDreamState(db, key, value) {
|
|
4401
|
+
getSetDreamStateStatement(db).run(key, value);
|
|
4402
|
+
}
|
|
4403
|
+
function deleteDreamState(db, key) {
|
|
4404
|
+
getDeleteDreamStateStatement(db).run(key);
|
|
4405
|
+
}
|
|
4406
|
+
|
|
4407
|
+
// ../plugin/src/features/magic-context/dreamer/map-memories-retry.ts
|
|
4408
|
+
function mapMemoryRetryKey(project) {
|
|
4409
|
+
return `map-memories:retry:${project}`;
|
|
4410
|
+
}
|
|
4411
|
+
function readMapMemoryRetries(db, project) {
|
|
4412
|
+
try {
|
|
4413
|
+
const parsed = JSON.parse(getDreamState(db, mapMemoryRetryKey(project)) ?? "{}");
|
|
4414
|
+
if (!isRecord(parsed))
|
|
4415
|
+
return {};
|
|
4416
|
+
const retries = {};
|
|
4417
|
+
for (const [id, value] of Object.entries(parsed)) {
|
|
4418
|
+
if (isRecord(value) && typeof value.content === "string" && typeof value.failures === "number" && typeof value.deferUntil === "number") {
|
|
4419
|
+
retries[id] = {
|
|
4420
|
+
content: value.content,
|
|
4421
|
+
failures: value.failures,
|
|
4422
|
+
deferUntil: value.deferUntil
|
|
4423
|
+
};
|
|
4424
|
+
}
|
|
4425
|
+
}
|
|
4426
|
+
return retries;
|
|
4427
|
+
} catch {
|
|
4428
|
+
return {};
|
|
4429
|
+
}
|
|
4430
|
+
}
|
|
4431
|
+
function contentKey(memory) {
|
|
4432
|
+
return createHash3("sha256").update(`${memory.category}
|
|
4433
|
+
${memory.content}`).digest("hex");
|
|
4434
|
+
}
|
|
4435
|
+
function isMapMemoryDeferred(memory, retries, now = Date.now()) {
|
|
4436
|
+
const retry = retries[memory.id];
|
|
4437
|
+
return !!retry && retry.deferUntil > now && retry.content === contentKey(memory);
|
|
4438
|
+
}
|
|
4439
|
+
function nextMapMemoryRetry(memory, prior) {
|
|
4440
|
+
const content = contentKey(memory);
|
|
4441
|
+
const failures = (prior?.content === content ? prior.failures : 0) + 1;
|
|
4442
|
+
const maxWaitHours = 7 * 24;
|
|
4443
|
+
return {
|
|
4444
|
+
content,
|
|
4445
|
+
failures,
|
|
4446
|
+
deferUntil: failures < 2 ? 0 : Date.now() + Math.min(maxWaitHours, 2 ** (failures - 2)) * 3600000
|
|
4447
|
+
};
|
|
4448
|
+
}
|
|
4449
|
+
|
|
4364
4450
|
// ../plugin/src/features/magic-context/dreamer/task-gates.ts
|
|
4365
4451
|
function countActiveMemories(db, projectPath) {
|
|
4366
4452
|
const row = db.prepare("SELECT COUNT(*) AS cnt FROM memories WHERE project_path = ? AND status IN ('active','permanent')").get(projectPath);
|
|
@@ -4377,16 +4463,24 @@ function countLiveMemories(db, projectPath, options = {}) {
|
|
|
4377
4463
|
const row = options.category ? db.prepare(`${sql} AND category = ?`).get(projectPath, Date.now(), options.category) : db.prepare(sql).get(projectPath, Date.now());
|
|
4378
4464
|
return row?.cnt ?? 0;
|
|
4379
4465
|
}
|
|
4466
|
+
var UNMAPPED_LIVE_MEMORIES_SQL = `FROM memories m
|
|
4467
|
+
WHERE m.project_path = ?
|
|
4468
|
+
AND m.status IN ('active','permanent')
|
|
4469
|
+
AND (m.expires_at IS NULL OR m.expires_at > ?)
|
|
4470
|
+
AND NOT EXISTS (SELECT 1 FROM memory_verifications v WHERE v.memory_id = m.id)`;
|
|
4380
4471
|
function countUnmappedActiveMemories(db, projectPath) {
|
|
4381
|
-
const
|
|
4382
|
-
|
|
4383
|
-
|
|
4384
|
-
|
|
4385
|
-
|
|
4386
|
-
|
|
4387
|
-
|
|
4388
|
-
|
|
4389
|
-
|
|
4472
|
+
const now = Date.now();
|
|
4473
|
+
const row = db.prepare(`SELECT COUNT(*) AS cnt ${UNMAPPED_LIVE_MEMORIES_SQL}`).get(projectPath, now);
|
|
4474
|
+
const total = row?.cnt ?? 0;
|
|
4475
|
+
if (total === 0)
|
|
4476
|
+
return 0;
|
|
4477
|
+
const retries = readMapMemoryRetries(db, projectPath);
|
|
4478
|
+
const waitingIds = Object.entries(retries).filter(([, retry]) => retry.deferUntil > now).map(([id]) => id);
|
|
4479
|
+
if (waitingIds.length === 0)
|
|
4480
|
+
return total;
|
|
4481
|
+
const waiting = db.prepare(`SELECT m.id, m.category, m.content ${UNMAPPED_LIVE_MEMORIES_SQL}
|
|
4482
|
+
AND m.id IN (SELECT CAST(value AS INTEGER) FROM json_each(?))`).all(projectPath, now, JSON.stringify(waitingIds));
|
|
4483
|
+
return total - waiting.filter((memory) => isMapMemoryDeferred(memory, retries, now)).length;
|
|
4390
4484
|
}
|
|
4391
4485
|
function countCompartmentsSince(db, projectPath, since) {
|
|
4392
4486
|
const row = db.prepare(`SELECT COUNT(*) AS cnt
|
|
@@ -4569,7 +4663,7 @@ function getDreamTaskBacklog(db, projectPath, task, options = {}) {
|
|
|
4569
4663
|
case "classify-memories": {
|
|
4570
4664
|
const total = countLiveMemories(db, projectPath);
|
|
4571
4665
|
return {
|
|
4572
|
-
pending: countLiveMemories(db, projectPath, { unclassifiedOnly: true }),
|
|
4666
|
+
pending: total >= MIN_POOL_TO_CLASSIFY ? countLiveMemories(db, projectPath, { unclassifiedOnly: true }) : 0,
|
|
4573
4667
|
total
|
|
4574
4668
|
};
|
|
4575
4669
|
}
|
|
@@ -4675,6 +4769,9 @@ function getDreamTaskBacklogs(db, projectPath, tasks = CANONICAL_DREAM_TASKS, op
|
|
|
4675
4769
|
cache.eligibleProjects.clear();
|
|
4676
4770
|
cache.eligibleProjects.set(projectPath, eligible);
|
|
4677
4771
|
}
|
|
4772
|
+
if (eligible && tasks.includes("map-memories")) {
|
|
4773
|
+
eligible = !Object.values(readMapMemoryRetries(db, projectPath)).some(({ deferUntil }) => deferUntil > 0);
|
|
4774
|
+
}
|
|
4678
4775
|
const optionKey = (value) => value === undefined ? "omitted" : value === null ? "null" : `number:${value}`;
|
|
4679
4776
|
const key = JSON.stringify([
|
|
4680
4777
|
getHarness2(),
|
|
@@ -4710,7 +4807,7 @@ function evaluateTaskGate(task, ctx) {
|
|
|
4710
4807
|
case "compress-cues":
|
|
4711
4808
|
return countLiveMemories(db, project) > 0;
|
|
4712
4809
|
case "classify-memories":
|
|
4713
|
-
return countLiveMemories(db, project)
|
|
4810
|
+
return countLiveMemories(db, project) >= MIN_POOL_TO_CLASSIFY;
|
|
4714
4811
|
case "retrospective":
|
|
4715
4812
|
return countProjectSessionsSince(db, project, ctx.retrospectiveWatermarkMs ?? null) > 0;
|
|
4716
4813
|
case "maintain-docs":
|
|
@@ -4767,7 +4864,7 @@ function openOpenCodeDb() {
|
|
|
4767
4864
|
}
|
|
4768
4865
|
|
|
4769
4866
|
// ../plugin/src/features/magic-context/dreamer/task-executor.ts
|
|
4770
|
-
import { createHash as
|
|
4867
|
+
import { createHash as createHash12 } from "node:crypto";
|
|
4771
4868
|
import { existsSync as existsSync9, readFileSync as readFileSync8 } from "node:fs";
|
|
4772
4869
|
|
|
4773
4870
|
// ../plugin/src/agents/dreamer.ts
|
|
@@ -4906,7 +5003,7 @@ class HiddenCompletionRefusal extends Error {
|
|
|
4906
5003
|
}
|
|
4907
5004
|
}
|
|
4908
5005
|
// ../plugin/src/features/magic-context/dreamer/provider-output-failure.ts
|
|
4909
|
-
import { createHash as
|
|
5006
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
4910
5007
|
var MAX_NEAR_ZERO_OUTPUT_TOKENS = 32;
|
|
4911
5008
|
|
|
4912
5009
|
class DreamerProviderOutputFailureError extends Error {
|
|
@@ -4968,7 +5065,7 @@ function providerOutputFailureFromInvalidManifest(messages, responseText) {
|
|
|
4968
5065
|
return null;
|
|
4969
5066
|
if (!isAccountPoolQuotaNotice(responseText) && completion.outputTokens > MAX_NEAR_ZERO_OUTPUT_TOKENS)
|
|
4970
5067
|
return null;
|
|
4971
|
-
const fingerprint =
|
|
5068
|
+
const fingerprint = createHash4("sha256").update(normalized).digest("hex").slice(0, 16);
|
|
4972
5069
|
return new DreamerProviderOutputFailureError(fingerprint, completion.outputTokens, completion.reasoningTokens, responseText);
|
|
4973
5070
|
}
|
|
4974
5071
|
|
|
@@ -6447,7 +6544,7 @@ function parseFields(json) {
|
|
|
6447
6544
|
}
|
|
6448
6545
|
|
|
6449
6546
|
// ../plugin/src/features/magic-context/mural/compress-cues.ts
|
|
6450
|
-
import { createHash as
|
|
6547
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
6451
6548
|
|
|
6452
6549
|
// ../plugin/src/hooks/magic-context/compartment-runner-historian.ts
|
|
6453
6550
|
import { mkdirSync, unlinkSync as unlinkSync2, writeFileSync } from "node:fs";
|
|
@@ -10475,45 +10572,6 @@ function sanitizeDumpName(value) {
|
|
|
10475
10572
|
return value.replace(/[^a-zA-Z0-9._-]/g, "-");
|
|
10476
10573
|
}
|
|
10477
10574
|
|
|
10478
|
-
// ../plugin/src/features/magic-context/dreamer/storage-dream-state.ts
|
|
10479
|
-
var getDreamStateStatements = new WeakMap;
|
|
10480
|
-
var setDreamStateStatements = new WeakMap;
|
|
10481
|
-
var deleteDreamStateStatements = new WeakMap;
|
|
10482
|
-
function getGetDreamStateStatement(db) {
|
|
10483
|
-
let stmt = getDreamStateStatements.get(db);
|
|
10484
|
-
if (!stmt) {
|
|
10485
|
-
stmt = db.prepare("SELECT value FROM dream_state WHERE key = ?");
|
|
10486
|
-
getDreamStateStatements.set(db, stmt);
|
|
10487
|
-
}
|
|
10488
|
-
return stmt;
|
|
10489
|
-
}
|
|
10490
|
-
function getSetDreamStateStatement(db) {
|
|
10491
|
-
let stmt = setDreamStateStatements.get(db);
|
|
10492
|
-
if (!stmt) {
|
|
10493
|
-
stmt = db.prepare("INSERT INTO dream_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value");
|
|
10494
|
-
setDreamStateStatements.set(db, stmt);
|
|
10495
|
-
}
|
|
10496
|
-
return stmt;
|
|
10497
|
-
}
|
|
10498
|
-
function getDeleteDreamStateStatement(db) {
|
|
10499
|
-
let stmt = deleteDreamStateStatements.get(db);
|
|
10500
|
-
if (!stmt) {
|
|
10501
|
-
stmt = db.prepare("DELETE FROM dream_state WHERE key = ?");
|
|
10502
|
-
deleteDreamStateStatements.set(db, stmt);
|
|
10503
|
-
}
|
|
10504
|
-
return stmt;
|
|
10505
|
-
}
|
|
10506
|
-
function getDreamState(db, key) {
|
|
10507
|
-
const row = getGetDreamStateStatement(db).get(key);
|
|
10508
|
-
return typeof row?.value === "string" ? row.value : null;
|
|
10509
|
-
}
|
|
10510
|
-
function setDreamState(db, key, value) {
|
|
10511
|
-
getSetDreamStateStatement(db).run(key, value);
|
|
10512
|
-
}
|
|
10513
|
-
function deleteDreamState(db, key) {
|
|
10514
|
-
getDeleteDreamStateStatement(db).run(key);
|
|
10515
|
-
}
|
|
10516
|
-
|
|
10517
10575
|
// ../plugin/src/features/magic-context/dreamer/lease.ts
|
|
10518
10576
|
var LEASE_DURATION_MS = 2 * 60 * 1000;
|
|
10519
10577
|
var DREAMING_LEASE_KEY = "dreaming";
|
|
@@ -11218,7 +11276,7 @@ async function applyCuesThroughModule(args, chunk, manifestText, signal) {
|
|
|
11218
11276
|
log2(`[dreamer] compress-cues: skipped cue for memory ${entry.id} (${failure.reason}; rejection ${rejectionCount}/${CUE_REJECTION_LATCH_THRESHOLD})`);
|
|
11219
11277
|
}
|
|
11220
11278
|
}
|
|
11221
|
-
const commandId = `mural-cues:${route.moduleCommandId}:${
|
|
11279
|
+
const commandId = `mural-cues:${route.moduleCommandId}:${createHash5("sha256").update(chunk.map((candidate) => candidate.memory.id).join(",")).digest("hex").slice(0, 24)}`;
|
|
11222
11280
|
let response;
|
|
11223
11281
|
try {
|
|
11224
11282
|
response = await route.moduleClient.call({
|
|
@@ -11835,7 +11893,7 @@ function applyReviewVerdict(args, leaseKey, parsed, result) {
|
|
|
11835
11893
|
}
|
|
11836
11894
|
|
|
11837
11895
|
// ../plugin/src/features/magic-context/dreamer/classify.ts
|
|
11838
|
-
import { createHash as
|
|
11896
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
11839
11897
|
|
|
11840
11898
|
// ../plugin/src/plugin/rust-tool-backends.ts
|
|
11841
11899
|
function isRustAuthorityDrainingError(error) {
|
|
@@ -12008,7 +12066,6 @@ async function readFailedChildMessages(client, sessionId, directory) {
|
|
|
12008
12066
|
}
|
|
12009
12067
|
|
|
12010
12068
|
// ../plugin/src/features/magic-context/dreamer/classify.ts
|
|
12011
|
-
var MIN_POOL_TO_CLASSIFY = 10;
|
|
12012
12069
|
var FULL_POOL_CEILING = 100;
|
|
12013
12070
|
var STAGE3_ANCHOR_COUNT = 30;
|
|
12014
12071
|
var CLASSIFY_CHUNK_SIZE = 100;
|
|
@@ -12273,7 +12330,7 @@ async function runClassifyThroughModule(args, chunk, anchors, signal, runOnHost)
|
|
|
12273
12330
|
if (entry.qualifier)
|
|
12274
12331
|
modelVariants[entry.model] = entry.qualifier;
|
|
12275
12332
|
}
|
|
12276
|
-
const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${
|
|
12333
|
+
const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${createHash6("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`;
|
|
12277
12334
|
const runTask = (hostCompletion) => args.moduleClient?.call({
|
|
12278
12335
|
sessionId: args.moduleSessionId,
|
|
12279
12336
|
projectRoot: args.moduleProjectRoot,
|
|
@@ -12475,7 +12532,7 @@ function recordInvocation(args, startedAt, params) {
|
|
|
12475
12532
|
|
|
12476
12533
|
// ../plugin/src/features/magic-context/dreamer/docs-proposals.ts
|
|
12477
12534
|
import { execFileSync } from "node:child_process";
|
|
12478
|
-
import { createHash as
|
|
12535
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
12479
12536
|
import {
|
|
12480
12537
|
existsSync as existsSync6,
|
|
12481
12538
|
mkdirSync as mkdirSync2,
|
|
@@ -12490,7 +12547,7 @@ import {
|
|
|
12490
12547
|
import { tmpdir } from "node:os";
|
|
12491
12548
|
import { join as join8 } from "node:path";
|
|
12492
12549
|
var FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
|
|
12493
|
-
var hash = (text) =>
|
|
12550
|
+
var hash = (text) => createHash7("sha256").update(text).digest("hex");
|
|
12494
12551
|
var proposalDir = (projectDir) => join8(projectDir, ".cortexkit/magic-context/docs-update-proposals");
|
|
12495
12552
|
function docsBaseHashes(projectDir) {
|
|
12496
12553
|
return Object.fromEntries(FILES.map((name) => [
|
|
@@ -13561,7 +13618,7 @@ function throwIfAborted2(signal) {
|
|
|
13561
13618
|
}
|
|
13562
13619
|
|
|
13563
13620
|
// ../plugin/src/features/magic-context/smart-notes/compiler.ts
|
|
13564
|
-
import { createHash as
|
|
13621
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
13565
13622
|
|
|
13566
13623
|
// ../plugin/src/features/magic-context/smart-notes/compiler-prompt.ts
|
|
13567
13624
|
var SMART_NOTE_COMPILER_SYSTEM_PROMPT = `You are the Magic Context smart-note compiler for the magic-context system.
|
|
@@ -14342,7 +14399,7 @@ function manifestAdvisoryWarnings(code, manifest) {
|
|
|
14342
14399
|
return warnings;
|
|
14343
14400
|
}
|
|
14344
14401
|
function hashCheck(surfaceCondition, compiledCheck, manifest, checkCron) {
|
|
14345
|
-
return
|
|
14402
|
+
return createHash8("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
|
|
14346
14403
|
}
|
|
14347
14404
|
function extractJsonObject(output) {
|
|
14348
14405
|
const fenced = output.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
@@ -15058,7 +15115,7 @@ function snapshotMaintainDocsFiles(docsDir) {
|
|
|
15058
15115
|
}
|
|
15059
15116
|
|
|
15060
15117
|
// ../plugin/src/features/magic-context/dreamer/map-memories.ts
|
|
15061
|
-
import { createHash as
|
|
15118
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
15062
15119
|
|
|
15063
15120
|
// ../plugin/src/features/magic-context/dreamer/map-memories-prompt.ts
|
|
15064
15121
|
import { execFile as execFile2 } from "node:child_process";
|
|
@@ -15268,37 +15325,6 @@ var MAP_BATCH_SIZE = 5;
|
|
|
15268
15325
|
var MAP_BATCH_FLOOR_MS = 240000;
|
|
15269
15326
|
var CONSECUTIVE_TIMEOUT_LIMIT2 = 2;
|
|
15270
15327
|
var MAX_INDEPENDENT_REQUEUE_PER_RUN = MAP_BATCH_SIZE;
|
|
15271
|
-
function retryKey(project) {
|
|
15272
|
-
return `map-memories:retry:${project}`;
|
|
15273
|
-
}
|
|
15274
|
-
function readRetries(db, project) {
|
|
15275
|
-
try {
|
|
15276
|
-
const parsed = JSON.parse(getDreamState(db, retryKey(project)) ?? "{}");
|
|
15277
|
-
if (!isRecord(parsed))
|
|
15278
|
-
return {};
|
|
15279
|
-
const retries = {};
|
|
15280
|
-
for (const [id, value] of Object.entries(parsed)) {
|
|
15281
|
-
if (isRecord(value) && typeof value.content === "string" && typeof value.failures === "number" && typeof value.deferUntil === "number") {
|
|
15282
|
-
retries[id] = {
|
|
15283
|
-
content: value.content,
|
|
15284
|
-
failures: value.failures,
|
|
15285
|
-
deferUntil: value.deferUntil
|
|
15286
|
-
};
|
|
15287
|
-
}
|
|
15288
|
-
}
|
|
15289
|
-
return retries;
|
|
15290
|
-
} catch {
|
|
15291
|
-
return {};
|
|
15292
|
-
}
|
|
15293
|
-
}
|
|
15294
|
-
function contentKey(memory) {
|
|
15295
|
-
return createHash8("sha256").update(`${memory.category}
|
|
15296
|
-
${memory.content}`).digest("hex");
|
|
15297
|
-
}
|
|
15298
|
-
function isDeferred(memory, retries) {
|
|
15299
|
-
const retry = retries[memory.id];
|
|
15300
|
-
return !!retry && retry.content === contentKey(memory) && retry.deferUntil > Date.now();
|
|
15301
|
-
}
|
|
15302
15328
|
function assistantText(messages) {
|
|
15303
15329
|
const joined = messages.filter((message) => isRecord(message) && (message.role === "assistant" || isRecord(message.info) && message.info.role === "assistant")).map((message) => extractLatestAssistantText([message]) ?? (isRecord(message) && Array.isArray(message.content) ? message.content.filter(isRecord).filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join(`
|
|
15304
15330
|
`) : "")).join(`
|
|
@@ -15367,8 +15393,8 @@ function selectMapMemoryInputs(db, projectIdentity, repoDir, includeDeferred = f
|
|
|
15367
15393
|
if (requeue.length >= MAX_INDEPENDENT_REQUEUE_PER_RUN)
|
|
15368
15394
|
break;
|
|
15369
15395
|
}
|
|
15370
|
-
const retries =
|
|
15371
|
-
return [...unmappedInputs, ...requeue].filter((memory) => includeDeferred || !
|
|
15396
|
+
const retries = readMapMemoryRetries(db, projectIdentity);
|
|
15397
|
+
return [...unmappedInputs, ...requeue].filter((memory) => includeDeferred || !isMapMemoryDeferred(memory, retries));
|
|
15372
15398
|
}
|
|
15373
15399
|
async function mapMemories(args) {
|
|
15374
15400
|
const result = {
|
|
@@ -15379,12 +15405,12 @@ async function mapMemories(args) {
|
|
|
15379
15405
|
complete: true
|
|
15380
15406
|
};
|
|
15381
15407
|
const allInputs = selectMapMemoryInputs(args.db, args.projectIdentity, args.sessionDirectory, true);
|
|
15382
|
-
const retries =
|
|
15408
|
+
const retries = readMapMemoryRetries(args.db, args.projectIdentity);
|
|
15383
15409
|
const activeIds = new Set(allInputs.map((memory) => String(memory.id)));
|
|
15384
15410
|
for (const id of Object.keys(retries))
|
|
15385
15411
|
if (!activeIds.has(id))
|
|
15386
15412
|
delete retries[id];
|
|
15387
|
-
const inputs = allInputs.filter((memory) => !
|
|
15413
|
+
const inputs = allInputs.filter((memory) => !isMapMemoryDeferred(memory, retries));
|
|
15388
15414
|
result.remaining = allInputs.length;
|
|
15389
15415
|
result.complete = result.remaining === 0;
|
|
15390
15416
|
if (inputs.length === 0) {
|
|
@@ -15401,6 +15427,7 @@ async function mapMemories(args) {
|
|
|
15401
15427
|
try {
|
|
15402
15428
|
let consecutiveTimeouts = 0;
|
|
15403
15429
|
let timeoutStreakElapsedMs = [];
|
|
15430
|
+
const countedMisses = new Set;
|
|
15404
15431
|
for (let i = 0;i < batches.length; i += 1) {
|
|
15405
15432
|
const remainingMs = Math.max(0, args.deadline - Date.now());
|
|
15406
15433
|
if (remainingMs <= 0) {
|
|
@@ -15423,22 +15450,19 @@ async function mapMemories(args) {
|
|
|
15423
15450
|
}
|
|
15424
15451
|
const committed = outcome.mapped + outcome.independent;
|
|
15425
15452
|
const committedIds = new Set(outcome.committedIds);
|
|
15453
|
+
const missedIds = new Set(outcome.missedIds);
|
|
15426
15454
|
runLeaseGuardedWrite(args.db, args.holderId, args.leaseKey, () => {
|
|
15427
15455
|
for (const memory of batch.inputs) {
|
|
15428
15456
|
if (committedIds.has(memory.id)) {
|
|
15429
15457
|
delete retries[memory.id];
|
|
15430
15458
|
continue;
|
|
15431
15459
|
}
|
|
15432
|
-
|
|
15433
|
-
|
|
15434
|
-
|
|
15435
|
-
|
|
15436
|
-
content,
|
|
15437
|
-
failures,
|
|
15438
|
-
deferUntil: failures < 2 ? 0 : Date.now() + Math.min(24, 2 ** (failures - 2)) * 3600000
|
|
15439
|
-
};
|
|
15460
|
+
if (missedIds.has(memory.id) && !countedMisses.has(memory.id)) {
|
|
15461
|
+
countedMisses.add(memory.id);
|
|
15462
|
+
retries[memory.id] = nextMapMemoryRetry(memory, retries[memory.id]);
|
|
15463
|
+
}
|
|
15440
15464
|
}
|
|
15441
|
-
setDreamState(args.db,
|
|
15465
|
+
setDreamState(args.db, mapMemoryRetryKey(args.projectIdentity), JSON.stringify(retries));
|
|
15442
15466
|
});
|
|
15443
15467
|
result.mapped += outcome.mapped;
|
|
15444
15468
|
result.independent += outcome.independent;
|
|
@@ -15450,7 +15474,7 @@ async function mapMemories(args) {
|
|
|
15450
15474
|
if (outcome.requeue?.length) {
|
|
15451
15475
|
if (!batch.isOmissionRetry) {
|
|
15452
15476
|
batches.push({
|
|
15453
|
-
inputs: outcome.requeue.filter((memory) => !
|
|
15477
|
+
inputs: outcome.requeue.filter((memory) => !isMapMemoryDeferred(memory, retries)),
|
|
15454
15478
|
isOmissionRetry: true
|
|
15455
15479
|
});
|
|
15456
15480
|
log2(`[dreamer] map-memories: committed ${committed}/${batch.inputs.length} mapping(s); requeueing ${outcome.requeue.length} omitted id(s) in a targeted retry`);
|
|
@@ -15538,11 +15562,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
|
|
|
15538
15562
|
stage = "apply";
|
|
15539
15563
|
const outcome = await applyParsedBatchMappings(args, batch, run.validated, budgetFinalized, true);
|
|
15540
15564
|
logBatchUsage(run.completion.messages ?? [], outcome.mapped + outcome.independent, startedAt);
|
|
15541
|
-
|
|
15542
|
-
return {
|
|
15543
|
-
...outcome,
|
|
15544
|
-
requeue: budgetFinalized ? [] : batch.filter((memory) => !returnedIds.has(memory.id))
|
|
15545
|
-
};
|
|
15565
|
+
return completedMapBatch(outcome, batch, run.validated, budgetFinalized);
|
|
15546
15566
|
}
|
|
15547
15567
|
const client = args.client;
|
|
15548
15568
|
if (!client)
|
|
@@ -15596,11 +15616,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
|
|
|
15596
15616
|
stage = "apply";
|
|
15597
15617
|
const outcome = await applyParsedBatchMappings(args, batch, run.validated, budgetFinalized, true);
|
|
15598
15618
|
logBatchUsage(run.output, outcome.mapped + outcome.independent, startedAt);
|
|
15599
|
-
|
|
15600
|
-
return {
|
|
15601
|
-
...outcome,
|
|
15602
|
-
requeue: budgetFinalized ? [] : batch.filter((memory) => !returnedIds.has(memory.id))
|
|
15603
|
-
};
|
|
15619
|
+
return completedMapBatch(outcome, batch, run.validated, budgetFinalized);
|
|
15604
15620
|
} catch (error) {
|
|
15605
15621
|
const desc = describeError(error);
|
|
15606
15622
|
log2(`[dreamer] map-memories batch failed: ${desc.brief}`, desc.stackHead ? { stackHead: desc.stackHead } : undefined);
|
|
@@ -15642,6 +15658,17 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
|
|
|
15642
15658
|
});
|
|
15643
15659
|
}
|
|
15644
15660
|
}
|
|
15661
|
+
function completedMapBatch(outcome, batch, parsed, budgetFinalized) {
|
|
15662
|
+
if (budgetFinalized)
|
|
15663
|
+
return outcome;
|
|
15664
|
+
const decided = new Set(parsed.map(({ id }) => id));
|
|
15665
|
+
const committed = new Set(outcome.committedIds);
|
|
15666
|
+
return {
|
|
15667
|
+
...outcome,
|
|
15668
|
+
missedIds: batch.filter(({ id }) => !decided.has(id)).map(({ id }) => id),
|
|
15669
|
+
requeue: batch.filter(({ id }) => !committed.has(id))
|
|
15670
|
+
};
|
|
15671
|
+
}
|
|
15645
15672
|
async function applyParsedBatchMappings(args, batch, parsed, budgetFinalized = false, allowPartial = false) {
|
|
15646
15673
|
const batchIds = new Set(batch.map((memory) => memory.id));
|
|
15647
15674
|
const valid = parsed.filter((entry) => batchIds.has(entry.id));
|
|
@@ -15733,7 +15760,7 @@ async function applyParsedBatchMappings(args, batch, parsed, budgetFinalized = f
|
|
|
15733
15760
|
name: "memory.set_mapping",
|
|
15734
15761
|
arguments: {
|
|
15735
15762
|
memory_project: args.projectIdentity,
|
|
15736
|
-
command_id: `${args.moduleRoute.moduleCommandId}:${
|
|
15763
|
+
command_id: `${args.moduleRoute.moduleCommandId}:${createHash9("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
|
|
15737
15764
|
rows
|
|
15738
15765
|
}
|
|
15739
15766
|
}
|
|
@@ -16637,6 +16664,33 @@ ${buildFrictionGatePrompt({ userLines })}`;
|
|
|
16637
16664
|
function retrospectiveGatePromptTokens(messages) {
|
|
16638
16665
|
return estimateTokens(retrospectiveGatePrompt(messages));
|
|
16639
16666
|
}
|
|
16667
|
+
function admitRetrospectiveCohorts(rows, firstUnreadTs, maxMessages, promptInputLimitTokens) {
|
|
16668
|
+
const kept = [];
|
|
16669
|
+
let start = 0;
|
|
16670
|
+
for (let first = rows[start];first && first.ts < firstUnreadTs; first = rows[start]) {
|
|
16671
|
+
const ts = first.ts;
|
|
16672
|
+
let end = start + 1;
|
|
16673
|
+
while (end < rows.length && rows[end]?.ts === ts)
|
|
16674
|
+
end += 1;
|
|
16675
|
+
const cohort = rows.slice(start, end);
|
|
16676
|
+
const tooManyRows = end > maxMessages;
|
|
16677
|
+
const tooManyTokens = !tooManyRows && promptInputLimitTokens !== undefined && retrospectiveGatePromptTokens([...kept, ...cohort]) > promptInputLimitTokens;
|
|
16678
|
+
if (tooManyRows || tooManyTokens) {
|
|
16679
|
+
return {
|
|
16680
|
+
kept,
|
|
16681
|
+
budgetTruncated: tooManyTokens,
|
|
16682
|
+
...kept.length === 0 ? { oversized: { ts, rows: cohort } } : {}
|
|
16683
|
+
};
|
|
16684
|
+
}
|
|
16685
|
+
kept.push(...cohort);
|
|
16686
|
+
start = end;
|
|
16687
|
+
}
|
|
16688
|
+
return { kept, budgetTruncated: false };
|
|
16689
|
+
}
|
|
16690
|
+
function logSkippedRetrospectiveCohort(sessionIds, ts, count, lowerBound) {
|
|
16691
|
+
const sessions = [...new Set(sessionIds)].join(",");
|
|
16692
|
+
log2(`[dreamer] retrospective: oversized timestamp cohort sessionIds=${sessions} timestamp=${ts} ${lowerBound ? "skippedAtLeast" : "skipped"}=${count}`);
|
|
16693
|
+
}
|
|
16640
16694
|
async function readRetrospectiveScanWindow(provider, projectIdentity, watermarkMs, overlapUserCount, options) {
|
|
16641
16695
|
const maxMessages = options?.maxMessagesPerRun ?? RETROSPECTIVE_MAX_MESSAGES_PER_RUN;
|
|
16642
16696
|
const capPerSession = options?.capPerSession ?? RETROSPECTIVE_MAX_MESSAGES_PER_SESSION;
|
|
@@ -16666,59 +16720,57 @@ async function readRetrospectiveScanWindow(provider, projectIdentity, watermarkM
|
|
|
16666
16720
|
if (sessionsToRead.length > 0) {
|
|
16667
16721
|
sinceReads.push(...await Promise.all(sessionsToRead.map((session) => provider.readUserMessagesSince(session.sessionId, scanSinceMs, capPerSession))));
|
|
16668
16722
|
}
|
|
16669
|
-
|
|
16670
|
-
|
|
16671
|
-
|
|
16672
|
-
|
|
16673
|
-
|
|
16674
|
-
|
|
16675
|
-
|
|
16676
|
-
|
|
16677
|
-
|
|
16678
|
-
|
|
16679
|
-
|
|
16680
|
-
|
|
16681
|
-
|
|
16682
|
-
|
|
16683
|
-
|
|
16684
|
-
|
|
16685
|
-
if (!row)
|
|
16686
|
-
continue;
|
|
16687
|
-
const candidate = [...keptSince, row];
|
|
16688
|
-
if (retrospectiveGatePromptTokens(candidate) <= promptInputLimitTokens) {
|
|
16689
|
-
keptSince.push(row);
|
|
16690
|
-
continue;
|
|
16691
|
-
}
|
|
16692
|
-
budgetDropped = countCandidates.slice(index);
|
|
16693
|
-
break;
|
|
16723
|
+
const allSince = sinceReads.flatMap((read) => read.messages).filter((message) => message.ts > scanSinceMs).map(clampRetrospectiveMessage).sort((a, b) => a.ts - b.ts || a.ordinal - b.ordinal);
|
|
16724
|
+
let unknownBoundary = !!firstExcludedSession && firstExcludedPendingTs === undefined;
|
|
16725
|
+
let firstUnreadTs = firstExcludedPendingTs ?? Number.POSITIVE_INFINITY;
|
|
16726
|
+
const oversizedSessions = new Map;
|
|
16727
|
+
for (const [index, read] of sinceReads.entries()) {
|
|
16728
|
+
if (!read.truncated)
|
|
16729
|
+
continue;
|
|
16730
|
+
const unreadTs = read.firstOmittedTs ?? read.messages.at(-1)?.ts;
|
|
16731
|
+
if (unreadTs === undefined) {
|
|
16732
|
+
unknownBoundary = true;
|
|
16733
|
+
continue;
|
|
16734
|
+
}
|
|
16735
|
+
firstUnreadTs = Math.min(firstUnreadTs, unreadTs);
|
|
16736
|
+
const sessionId = sessionsToRead[index]?.sessionId;
|
|
16737
|
+
if (sessionId !== undefined && read.firstOmittedTs !== undefined && read.firstOmittedTs === oldestBySession?.get(sessionId)) {
|
|
16738
|
+
oversizedSessions.set(sessionId, read.firstOmittedTs);
|
|
16694
16739
|
}
|
|
16695
16740
|
}
|
|
16696
|
-
const
|
|
16741
|
+
const {
|
|
16742
|
+
kept: keptSince,
|
|
16743
|
+
budgetTruncated,
|
|
16744
|
+
oversized
|
|
16745
|
+
} = admitRetrospectiveCohorts(allSince, unknownBoundary ? scanSinceMs : firstUnreadTs, maxMessages, promptInputLimitTokens);
|
|
16746
|
+
const lastKept = keptSince.at(-1);
|
|
16697
16747
|
let maxScannedTs = scanSinceMs;
|
|
16698
|
-
if (
|
|
16699
|
-
|
|
16700
|
-
maxScannedTs =
|
|
16748
|
+
if (!unknownBoundary) {
|
|
16749
|
+
if (oversized) {
|
|
16750
|
+
maxScannedTs = oversized.ts;
|
|
16751
|
+
logSkippedRetrospectiveCohort(oversized.rows.map(({ sessionId }) => sessionId), maxScannedTs, oversized.rows.length, false);
|
|
16752
|
+
} else if (lastKept) {
|
|
16753
|
+
maxScannedTs = lastKept.ts;
|
|
16754
|
+
} else if (Number.isFinite(firstUnreadTs)) {
|
|
16755
|
+
const blockedSessions = sessions.filter(({ session }) => oldestBySession?.get(session.sessionId) === firstUnreadTs);
|
|
16756
|
+
const hitSessionReadCap = blockedSessions.some(({ session }) => oversizedSessions.get(session.sessionId) === firstUnreadTs);
|
|
16757
|
+
if (hitSessionReadCap || blockedSessions.length > sessionLimit) {
|
|
16758
|
+
maxScannedTs = firstUnreadTs;
|
|
16759
|
+
logSkippedRetrospectiveCohort(blockedSessions.map(({ session }) => session.sessionId), maxScannedTs, Math.max(blockedSessions.length, hitSessionReadCap ? capPerSession + 1 : 0), true);
|
|
16760
|
+
} else {
|
|
16761
|
+
maxScannedTs = Math.max(scanSinceMs, firstUnreadTs - 1);
|
|
16762
|
+
}
|
|
16763
|
+
} else if (oldestBySession && allSince.length === 0) {
|
|
16764
|
+
for (const { session } of eligibleSessions) {
|
|
16765
|
+
maxScannedTs = Math.max(maxScannedTs, session.updatedAt ?? scanSinceMs);
|
|
16766
|
+
}
|
|
16701
16767
|
}
|
|
16702
16768
|
}
|
|
16703
|
-
for (const row of keptSince) {
|
|
16704
|
-
if (row.ts > maxScannedTs)
|
|
16705
|
-
maxScannedTs = row.ts;
|
|
16706
|
-
}
|
|
16707
|
-
let frontier = saturatedFrontier;
|
|
16708
|
-
const firstDropped = droppedSince[0];
|
|
16709
|
-
if (firstDropped)
|
|
16710
|
-
frontier = Math.min(frontier, firstDropped.ts - 1);
|
|
16711
|
-
if (typeof firstExcludedPendingTs === "number") {
|
|
16712
|
-
frontier = Math.min(frontier, firstExcludedPendingTs - 1);
|
|
16713
|
-
} else if (typeof firstExcludedSession?.updatedAt === "number") {
|
|
16714
|
-
frontier = Math.min(frontier, firstExcludedSession.updatedAt - 1);
|
|
16715
|
-
}
|
|
16716
|
-
maxScannedTs = Math.max(scanSinceMs, Math.min(maxScannedTs, frontier));
|
|
16717
16769
|
const keptSessionIds = new Set(keptSince.map((message) => message.sessionId));
|
|
16718
16770
|
const overlapSessions = sessionsToRead.filter((session) => keptSessionIds.has(session.sessionId));
|
|
16719
16771
|
const overlapBatches = overlapUserCount > 0 && watermarkMs > 0 && watermarkMs >= recencyCutoffMs ? await Promise.all(overlapSessions.map((session) => provider.readUserMessagesBefore(session.sessionId, watermarkMs, overlapUserCount))) : [];
|
|
16720
16772
|
const seen = new Set;
|
|
16721
|
-
const merged = [];
|
|
16773
|
+
const merged = [...keptSince];
|
|
16722
16774
|
const appendUnique = (row) => {
|
|
16723
16775
|
const key = `${row.sessionId}\x00${row.ts}\x00${row.role}\x00${row.toolName ?? ""}`;
|
|
16724
16776
|
if (seen.has(key))
|
|
@@ -16727,9 +16779,7 @@ async function readRetrospectiveScanWindow(provider, projectIdentity, watermarkM
|
|
|
16727
16779
|
merged.push(row);
|
|
16728
16780
|
return true;
|
|
16729
16781
|
};
|
|
16730
|
-
|
|
16731
|
-
appendUnique(row);
|
|
16732
|
-
const overlapRows = overlapBatches.flat().filter((message) => message.ts >= recencyCutoffMs).map(clampRetrospectiveMessage).sort((a, b) => a.ts - b.ts || a.ordinal - b.ordinal);
|
|
16782
|
+
const overlapRows = overlapBatches.flat().filter((message) => message.ts >= recencyCutoffMs && message.ts <= watermarkMs).map(clampRetrospectiveMessage).sort((a, b) => a.ts - b.ts || a.ordinal - b.ordinal);
|
|
16733
16783
|
for (const row of overlapRows) {
|
|
16734
16784
|
const beforeLength = merged.length;
|
|
16735
16785
|
if (!appendUnique(row))
|
|
@@ -16749,7 +16799,7 @@ async function readRetrospectiveScanWindow(provider, projectIdentity, watermarkM
|
|
|
16749
16799
|
maxScannedTs,
|
|
16750
16800
|
promptTokens,
|
|
16751
16801
|
...promptInputLimitTokens === undefined ? {} : { promptInputLimitTokens },
|
|
16752
|
-
budgetTruncated
|
|
16802
|
+
budgetTruncated
|
|
16753
16803
|
};
|
|
16754
16804
|
} finally {
|
|
16755
16805
|
provider.dispose?.();
|
|
@@ -16782,7 +16832,12 @@ function readOpenCodeMessagesSince(db, sessionId, sinceMs, capPerSession) {
|
|
|
16782
16832
|
LIMIT ?`).all(sessionId, sinceMs, limit + 1);
|
|
16783
16833
|
const truncated = rows.length > limit;
|
|
16784
16834
|
const kept = truncated ? rows.slice(0, limit) : rows;
|
|
16785
|
-
|
|
16835
|
+
const firstOmitted = rows[limit];
|
|
16836
|
+
return {
|
|
16837
|
+
messages: normalizeOpenCodeRows(db, sessionId, kept),
|
|
16838
|
+
truncated,
|
|
16839
|
+
...firstOmitted ? { firstOmittedTs: firstOmitted.time_created } : {}
|
|
16840
|
+
};
|
|
16786
16841
|
}
|
|
16787
16842
|
function readOpenCodeOldestMessageTimesSince(db, sessionIds, sinceMs) {
|
|
16788
16843
|
const result = new Map;
|
|
@@ -17015,7 +17070,7 @@ function insertDreamRun(db, run) {
|
|
|
17015
17070
|
}
|
|
17016
17071
|
|
|
17017
17072
|
// ../plugin/src/features/magic-context/dreamer/verify.ts
|
|
17018
|
-
import { createHash as
|
|
17073
|
+
import { createHash as createHash11 } from "node:crypto";
|
|
17019
17074
|
|
|
17020
17075
|
// ../plugin/src/features/magic-context/dreamer/verify-diff.ts
|
|
17021
17076
|
import { execFile as execFile3 } from "node:child_process";
|
|
@@ -17139,7 +17194,7 @@ Read only these changed line ranges if they may affect the claim.`
|
|
|
17139
17194
|
import path12 from "node:path";
|
|
17140
17195
|
|
|
17141
17196
|
// ../plugin/src/features/magic-context/dreamer/verify-state.ts
|
|
17142
|
-
import { createHash as
|
|
17197
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
17143
17198
|
import { readFile, realpath as realpath2 } from "node:fs/promises";
|
|
17144
17199
|
import path11 from "node:path";
|
|
17145
17200
|
function verificationMetadata(memory) {
|
|
@@ -17152,7 +17207,7 @@ function verificationMetadata(memory) {
|
|
|
17152
17207
|
}
|
|
17153
17208
|
async function verificationFilesFingerprint(directory, files) {
|
|
17154
17209
|
const root = await resolveGitTopLevel(directory) ?? path11.resolve(directory);
|
|
17155
|
-
const hash =
|
|
17210
|
+
const hash = createHash10("sha256");
|
|
17156
17211
|
for (const file of [...new Set(files)].sort()) {
|
|
17157
17212
|
const absolute = path11.resolve(root, file);
|
|
17158
17213
|
const withinRoot = (candidate) => {
|
|
@@ -17165,7 +17220,7 @@ async function verificationFilesFingerprint(directory, files) {
|
|
|
17165
17220
|
try {
|
|
17166
17221
|
if (!withinRoot(await realpath2(absolute)))
|
|
17167
17222
|
return null;
|
|
17168
|
-
hash.update(
|
|
17223
|
+
hash.update(createHash10("sha256").update(await readFile(absolute)).digest("hex"));
|
|
17169
17224
|
} catch (error) {
|
|
17170
17225
|
if (error.code !== "ENOENT")
|
|
17171
17226
|
return null;
|
|
@@ -17970,7 +18025,7 @@ async function applyParsedVerifyManifest(args, batch, parsed, headAtPrompt, budg
|
|
|
17970
18025
|
name: "memory.set_verification",
|
|
17971
18026
|
arguments: {
|
|
17972
18027
|
memory_project: args.projectIdentity,
|
|
17973
|
-
command_id: `${args.moduleRoute.moduleCommandId}:${
|
|
18028
|
+
command_id: `${args.moduleRoute.moduleCommandId}:${createHash11("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
|
|
17974
18029
|
rows
|
|
17975
18030
|
}
|
|
17976
18031
|
}
|
|
@@ -18884,7 +18939,7 @@ function parseFrictionGateVerdict(verdict) {
|
|
|
18884
18939
|
}
|
|
18885
18940
|
function computeRetrospectiveWindowKey(flagged) {
|
|
18886
18941
|
const anchors = flagged.map((message) => `${message.sessionId}:${message.ts}`).sort().join("|");
|
|
18887
|
-
return
|
|
18942
|
+
return createHash12("sha256").update(anchors).digest("hex").slice(0, 32);
|
|
18888
18943
|
}
|
|
18889
18944
|
function renderFrictionWindow(messages, flaggedOrdinals, radius = 2) {
|
|
18890
18945
|
const flagged = new Set(flaggedOrdinals);
|
|
@@ -19003,6 +19058,13 @@ async function runRetrospectiveTask(config, ctx, helpers) {
|
|
|
19003
19058
|
const recencyDays = Math.max(1, Math.floor(config.retrospectiveRecencyDays ?? 30));
|
|
19004
19059
|
const recencyCutoffMs = helpers.invocationStartedAt - recencyDays * RETROSPECTIVE_DAY_MS;
|
|
19005
19060
|
const scan = await readRetrospectiveScanWindow(provider, projectIdentity, watermarkMs, RETROSPECTIVE_OVERLAP_USER_LINES, { usableInputTokens, recencyCutoffMs });
|
|
19061
|
+
ctx.onRetrospectiveScan?.({
|
|
19062
|
+
watermarkMs,
|
|
19063
|
+
maxScannedTs: scan.maxScannedTs,
|
|
19064
|
+
usableInputTokens,
|
|
19065
|
+
recencyCutoffMs,
|
|
19066
|
+
budgetTruncated: scan.budgetTruncated
|
|
19067
|
+
});
|
|
19006
19068
|
const clearedTaskStateJson = activeOverflow ? writeRetrospectiveOverflowState(taskState.root, null) : undefined;
|
|
19007
19069
|
const completedWindow = (retrospectiveWatermarkMs, noOpReason) => ({
|
|
19008
19070
|
retrospectiveWatermarkMs,
|
|
@@ -19790,6 +19852,7 @@ async function runDomainGroup(deps, group, cb) {
|
|
|
19790
19852
|
}
|
|
19791
19853
|
}
|
|
19792
19854
|
let outcome;
|
|
19855
|
+
const diagnostics = {};
|
|
19793
19856
|
const startedAt = Date.now();
|
|
19794
19857
|
try {
|
|
19795
19858
|
outcome = await executor(due.config, {
|
|
@@ -19797,7 +19860,12 @@ async function runDomainGroup(deps, group, cb) {
|
|
|
19797
19860
|
projectIdentity,
|
|
19798
19861
|
holderId,
|
|
19799
19862
|
leaseKey,
|
|
19800
|
-
leaseAcquisition: acquisition
|
|
19863
|
+
leaseAcquisition: acquisition,
|
|
19864
|
+
...due.config.task === "retrospective" ? {
|
|
19865
|
+
onRetrospectiveScan: (scan) => {
|
|
19866
|
+
diagnostics.retrospectiveScan = scan;
|
|
19867
|
+
}
|
|
19868
|
+
} : {}
|
|
19801
19869
|
});
|
|
19802
19870
|
} catch (error) {
|
|
19803
19871
|
outcome = { status: "failed", transient: true, error: String(error) };
|
|
@@ -19808,6 +19876,11 @@ async function runDomainGroup(deps, group, cb) {
|
|
|
19808
19876
|
cb?.onSkipped?.(due.config.task, outcome.detail);
|
|
19809
19877
|
} else if (outcome.status === "completed") {
|
|
19810
19878
|
advanceAfterRun(db, projectIdentity, due, finishedAt, "completed", null, outcome.schedulePatch, startedAt);
|
|
19879
|
+
const scan = diagnostics.retrospectiveScan;
|
|
19880
|
+
if (scan) {
|
|
19881
|
+
const stored = readRetrospectiveWatermark(db, projectIdentity, due.config.task);
|
|
19882
|
+
log2(`[dreamer] retrospective: watermark start=${scan.watermarkMs} maxScannedTs=${scan.maxScannedTs} patch=${outcome.schedulePatch?.retrospectiveWatermarkMs ?? "none"} stored=${stored ?? "none"} usableInputTokens=${scan.usableInputTokens} recencyCutoffMs=${scan.recencyCutoffMs} budgetTruncated=${scan.budgetTruncated}`, { projectIdentity });
|
|
19883
|
+
}
|
|
19811
19884
|
cb?.onRan?.(due.config.task, outcome.detail, outcome.backlog);
|
|
19812
19885
|
} else if (outcome.transient) {
|
|
19813
19886
|
recordTransientFailure(db, projectIdentity, due, finishedAt, outcome.error ?? null, outcome.schedulePatch);
|
|
@@ -23018,9 +23091,11 @@ class PiRetrospectiveRawProvider {
|
|
|
23018
23091
|
async readUserMessagesSince(sessionId, sinceMs, capPerSession) {
|
|
23019
23092
|
const limit = Math.max(1, Math.floor(capPerSession));
|
|
23020
23093
|
const messages = await this.selectUserEntries(sessionId, (ts) => ts > sinceMs, limit + 1, false, sinceMs);
|
|
23094
|
+
const firstOmitted = messages[limit];
|
|
23021
23095
|
return {
|
|
23022
23096
|
messages: messages.slice(0, limit),
|
|
23023
|
-
truncated: messages.length > limit
|
|
23097
|
+
truncated: messages.length > limit,
|
|
23098
|
+
...firstOmitted ? { firstOmittedTs: firstOmitted.ts } : {}
|
|
23024
23099
|
};
|
|
23025
23100
|
}
|
|
23026
23101
|
async readOldestMessageTimesSince(sessionIds, sinceMs) {
|
|
@@ -28932,7 +29007,7 @@ function recoveryReasoningPrefixes(messages, partsKey) {
|
|
|
28932
29007
|
}
|
|
28933
29008
|
|
|
28934
29009
|
// ../plugin/src/shared/tag-transcript.ts
|
|
28935
|
-
import { createHash as
|
|
29010
|
+
import { createHash as createHash13 } from "node:crypto";
|
|
28936
29011
|
function buildPersistedDropTargets(transcript, tags, options = {}) {
|
|
28937
29012
|
const targets = new Map;
|
|
28938
29013
|
const tools = new Map(tags.filter((tag) => tag.type === "tool").map((tag) => [makeToolCompositeKey(tag.toolOwnerMessageId ?? "", tag.messageId), tag]));
|
|
@@ -29015,7 +29090,7 @@ function buildPersistedDropTargets(transcript, tags, options = {}) {
|
|
|
29015
29090
|
return targets;
|
|
29016
29091
|
}
|
|
29017
29092
|
function textIdentityDigest(value) {
|
|
29018
|
-
return
|
|
29093
|
+
return createHash13("sha256").update(value).digest("hex");
|
|
29019
29094
|
}
|
|
29020
29095
|
function buildContentDerivedTextIds(messageId, parts) {
|
|
29021
29096
|
const sources = parts.filter((part) => part.kind === "text").map((part) => stripTagPrefix(part.getText() ?? ""));
|
|
@@ -32818,7 +32893,7 @@ function clearPiCtxReduceCallableSession(sessionId) {
|
|
|
32818
32893
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
32819
32894
|
|
|
32820
32895
|
// src/tail-hygiene-walk-pi.ts
|
|
32821
|
-
import { createHash as
|
|
32896
|
+
import { createHash as createHash14 } from "node:crypto";
|
|
32822
32897
|
|
|
32823
32898
|
// src/provider-visible-parts-pi.ts
|
|
32824
32899
|
function isRecord4(value) {
|
|
@@ -32947,7 +33022,7 @@ function memoizedContent(kind, content) {
|
|
|
32947
33022
|
function contentMemoKey(kind, content) {
|
|
32948
33023
|
if (content.length <= INLINE_CONTENT_KEY_CHARS)
|
|
32949
33024
|
return `${kind}\x00=${content}`;
|
|
32950
|
-
const digest =
|
|
33025
|
+
const digest = createHash14("sha256").update(content, "utf16le").digest("base64");
|
|
32951
33026
|
return `${kind}\x00#${content.length}\x00${digest}`;
|
|
32952
33027
|
}
|
|
32953
33028
|
function measuredContent(kind, content) {
|
|
@@ -37574,9 +37649,9 @@ function authorizePiToolRemoval(args) {
|
|
|
37574
37649
|
}
|
|
37575
37650
|
|
|
37576
37651
|
// src/native-replay-tag-provenance-pi.ts
|
|
37577
|
-
import { createHash as
|
|
37652
|
+
import { createHash as createHash15 } from "node:crypto";
|
|
37578
37653
|
function nativeResponseTagStripKey(id, phase, text) {
|
|
37579
|
-
return
|
|
37654
|
+
return createHash15("sha256").update(JSON.stringify([id, phase, text])).digest("hex");
|
|
37580
37655
|
}
|
|
37581
37656
|
|
|
37582
37657
|
// src/native-replay-tags-pi.ts
|
|
@@ -40882,7 +40957,7 @@ function piDispatchMismatchDiagnostic(payload, prepared, mismatch) {
|
|
|
40882
40957
|
}
|
|
40883
40958
|
|
|
40884
40959
|
// src/pi-foreign-session-index.ts
|
|
40885
|
-
import { createHash as
|
|
40960
|
+
import { createHash as createHash16 } from "node:crypto";
|
|
40886
40961
|
|
|
40887
40962
|
// src/pi-foreign-omp-kinds.ts
|
|
40888
40963
|
var PI_FOREIGN_RENDERED_CONTENT_KINDS = [
|
|
@@ -41715,7 +41790,7 @@ function fingerprint(text, index, wire = false) {
|
|
|
41715
41790
|
index.stats.wireHashes++;
|
|
41716
41791
|
else
|
|
41717
41792
|
index.stats.hashes++;
|
|
41718
|
-
return
|
|
41793
|
+
return createHash16("sha256").update(stableStringify([{ type: "text", text }])).digest("hex");
|
|
41719
41794
|
}
|
|
41720
41795
|
function protectSession(index, message, roleOverride, trackEntry = false) {
|
|
41721
41796
|
const rendering = texts(index, message, roleOverride, trackEntry);
|
|
@@ -42608,7 +42683,7 @@ function piExpandChainedRequest(payload, chained, anchor, prepared, pass) {
|
|
|
42608
42683
|
}
|
|
42609
42684
|
|
|
42610
42685
|
// src/pi-dispatch-cursor.ts
|
|
42611
|
-
import { createHash as
|
|
42686
|
+
import { createHash as createHash17 } from "node:crypto";
|
|
42612
42687
|
var MAX_BYTES = 32 * 1024 * 1024;
|
|
42613
42688
|
var MAX_ENTRIES = 1e5;
|
|
42614
42689
|
function object14(value) {
|
|
@@ -42735,7 +42810,7 @@ Today: ${day}; current working directory: '${cwd.replace(/\\/gu, "/")}'. Do not
|
|
|
42735
42810
|
const hash = (content) => {
|
|
42736
42811
|
const json = JSON.stringify({ role: "user", content });
|
|
42737
42812
|
if (json.length <= MAX_BYTES)
|
|
42738
|
-
roots.add(
|
|
42813
|
+
roots.add(createHash17("sha256").update(json).digest("hex"));
|
|
42739
42814
|
};
|
|
42740
42815
|
hash(parts);
|
|
42741
42816
|
if (reminder) {
|
|
@@ -45125,7 +45200,7 @@ function createPiFallbackIndex() {
|
|
|
45125
45200
|
}
|
|
45126
45201
|
|
|
45127
45202
|
// src/pi-fit-reclaim.ts
|
|
45128
|
-
import { createHash as
|
|
45203
|
+
import { createHash as createHash18, randomUUID as randomUUID4 } from "node:crypto";
|
|
45129
45204
|
var pendingInput = new Set;
|
|
45130
45205
|
var KEY3 = "piUpperEstimateReclaim";
|
|
45131
45206
|
function piFitOverflowPossible(args) {
|
|
@@ -45161,7 +45236,7 @@ function piUpperReclaimCursor(args) {
|
|
|
45161
45236
|
sessionId: args.sessionId,
|
|
45162
45237
|
modelKey: args.modelKey,
|
|
45163
45238
|
contextWindow: args.contextWindow ?? null,
|
|
45164
|
-
head: head ?
|
|
45239
|
+
head: head ? createHash18("sha256").update(JSON.stringify([
|
|
45165
45240
|
Buffer.from(head.cachedM0Bytes ?? []).toString("base64"),
|
|
45166
45241
|
Buffer.from(head.cachedM1Bytes ?? []).toString("base64"),
|
|
45167
45242
|
head.cachedM0MuralDataUrl ?? null
|
|
@@ -45248,7 +45323,7 @@ async function waitForPiHistorianInTurn(sessionId, remainingMs, wait) {
|
|
|
45248
45323
|
}
|
|
45249
45324
|
|
|
45250
45325
|
// src/pi-lkg-fit-envelope.ts
|
|
45251
|
-
import { createHash as
|
|
45326
|
+
import { createHash as createHash19 } from "node:crypto";
|
|
45252
45327
|
function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
|
|
45253
45328
|
try {
|
|
45254
45329
|
if (!modelKey || typeof pi.getAllTools !== "function")
|
|
@@ -45310,7 +45385,7 @@ function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
|
|
|
45310
45385
|
refusalToolDefinitionTokens,
|
|
45311
45386
|
toolDefinitionsMeasured: refusalToolDefinitionTokens !== undefined,
|
|
45312
45387
|
envelopeBytes: Buffer.byteLength(envelopeJson),
|
|
45313
|
-
envelopeSignature: activeNames ?
|
|
45388
|
+
envelopeSignature: activeNames ? createHash19("sha256").update(envelopeJson).update(JSON.stringify(activeNames)).digest("hex") : undefined,
|
|
45314
45389
|
calibration,
|
|
45315
45390
|
...piModelAcceptsImages(ctx.model) ? {} : { modelAcceptsImages: false }
|
|
45316
45391
|
};
|
|
@@ -45320,13 +45395,13 @@ function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
|
|
|
45320
45395
|
}
|
|
45321
45396
|
|
|
45322
45397
|
// src/pi-message-identity.ts
|
|
45323
|
-
import { createHash as
|
|
45398
|
+
import { createHash as createHash22 } from "node:crypto";
|
|
45324
45399
|
|
|
45325
45400
|
// src/pi-tool-identity.ts
|
|
45326
|
-
import { createHash as
|
|
45401
|
+
import { createHash as createHash21 } from "node:crypto";
|
|
45327
45402
|
|
|
45328
45403
|
// src/served-array-ledger.ts
|
|
45329
|
-
import { createHash as
|
|
45404
|
+
import { createHash as createHash20 } from "node:crypto";
|
|
45330
45405
|
import {
|
|
45331
45406
|
closeSync as closeSync2,
|
|
45332
45407
|
fstatSync,
|
|
@@ -45604,7 +45679,7 @@ function getPiLastServedArray(sessionId) {
|
|
|
45604
45679
|
return previous ? `[${previous.serializedMessages.join(",")}]` : undefined;
|
|
45605
45680
|
}
|
|
45606
45681
|
function sha256(value) {
|
|
45607
|
-
return
|
|
45682
|
+
return createHash20("sha256").update(value).digest("hex");
|
|
45608
45683
|
}
|
|
45609
45684
|
function safeSessionFileStem(sessionId) {
|
|
45610
45685
|
const readable = sessionId.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 96);
|
|
@@ -45939,7 +46014,7 @@ function readPiServedCachedArray(sessionId) {
|
|
|
45939
46014
|
const memory = getPiLastServedArray(sessionId);
|
|
45940
46015
|
const slot = memory === undefined ? getSlot(sessionId) : undefined;
|
|
45941
46016
|
const jsonPrefix = memory ?? slot?.jsonPrefix;
|
|
45942
|
-
if (jsonPrefix === undefined ||
|
|
46017
|
+
if (jsonPrefix === undefined || createHash21("sha256").update(jsonPrefix).digest("hex") !== getPiLastServedDigest(sessionId))
|
|
45943
46018
|
return;
|
|
45944
46019
|
let parsed;
|
|
45945
46020
|
try {
|
|
@@ -45963,7 +46038,7 @@ function piMessageEntryFingerprint(message) {
|
|
|
45963
46038
|
const m = message;
|
|
45964
46039
|
if (typeof m.role !== "string")
|
|
45965
46040
|
return null;
|
|
45966
|
-
const contentHash =
|
|
46041
|
+
const contentHash = createHash22("sha256").update(stableStringify(m.content)).digest("hex");
|
|
45967
46042
|
return JSON.stringify([
|
|
45968
46043
|
typeof m.responseId === "string" ? m.responseId : null,
|
|
45969
46044
|
typeof m.timestamp === "number" || typeof m.timestamp === "string" ? m.timestamp : null,
|
package/package.json
CHANGED