@cortexkit/opencode-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/{context-00f1hdz2.js → context-xmyke353.js} +8 -3
- package/dist/features/magic-context/dreamer/map-memories-retry.d.ts +18 -0
- package/dist/features/magic-context/dreamer/map-memories-retry.d.ts.map +1 -0
- package/dist/features/magic-context/dreamer/map-memories.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/retrospective-raw-provider.d.ts +2 -0
- package/dist/features/magic-context/dreamer/retrospective-raw-provider.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-gates.d.ts +1 -1
- package/dist/features/magic-context/dreamer/task-gates.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-registry.d.ts +7 -0
- package/dist/features/magic-context/dreamer/task-registry.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-scheduler.d.ts +9 -0
- package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
- package/dist/{index-jvr9ba9y.js → index-eyk7msgw.js} +193 -122
- package/dist/{index-nda0zgna.js → index-kknjvmpx.js} +2 -1
- package/dist/index.js +4 -4
- package/dist/{task-config-t6bpyka7.js → task-config-qt6n4bxm.js} +1 -1
- package/dist/v2/{context-gwkgh0wd.js → context-zn18k0yk.js} +280 -202
- package/dist/v2/retrospective-raw-provider.d.ts.map +1 -1
- package/dist/v2/{server-92g7d776.js → server-2kswss3d.js} +2 -1
- package/dist/v2/server.js +2 -2
- package/dist/v2/{task-config-7md27rx8.js → task-config-ex2vajr2.js} +1 -1
- package/package.json +1 -1
- package/src/features/magic-context/dreamer/task-registry.ts +8 -0
|
@@ -63,6 +63,7 @@ import {
|
|
|
63
63
|
} from "./server-rz6g5xne.js";
|
|
64
64
|
import {
|
|
65
65
|
CANONICAL_DREAM_TASKS,
|
|
66
|
+
MIN_POOL_TO_CLASSIFY,
|
|
66
67
|
DREAM_TASK_CAPABILITIES,
|
|
67
68
|
toolLoopDreamTasks,
|
|
68
69
|
formatUnsupportedDreamTasks,
|
|
@@ -78,7 +79,7 @@ import {
|
|
|
78
79
|
userMemoryCollectionEnabled2,
|
|
79
80
|
userObservationCollectionEnabled2,
|
|
80
81
|
userObservationsRequested2
|
|
81
|
-
} from "./server-
|
|
82
|
+
} from "./server-2kswss3d.js";
|
|
82
83
|
import {
|
|
83
84
|
historianRunConfig,
|
|
84
85
|
dreamerRunConfig,
|
|
@@ -5536,6 +5537,91 @@ function getCurateCategoryScopeRefusal(args) {
|
|
|
5536
5537
|
return null;
|
|
5537
5538
|
}
|
|
5538
5539
|
|
|
5540
|
+
// src/features/magic-context/dreamer/map-memories-retry.ts
|
|
5541
|
+
import { createHash } from "node:crypto";
|
|
5542
|
+
|
|
5543
|
+
// src/features/magic-context/dreamer/storage-dream-state.ts
|
|
5544
|
+
var getDreamStateStatements = new WeakMap;
|
|
5545
|
+
var setDreamStateStatements = new WeakMap;
|
|
5546
|
+
var deleteDreamStateStatements = new WeakMap;
|
|
5547
|
+
function getGetDreamStateStatement(db) {
|
|
5548
|
+
let stmt = getDreamStateStatements.get(db);
|
|
5549
|
+
if (!stmt) {
|
|
5550
|
+
stmt = db.prepare("SELECT value FROM dream_state WHERE key = ?");
|
|
5551
|
+
getDreamStateStatements.set(db, stmt);
|
|
5552
|
+
}
|
|
5553
|
+
return stmt;
|
|
5554
|
+
}
|
|
5555
|
+
function getSetDreamStateStatement(db) {
|
|
5556
|
+
let stmt = setDreamStateStatements.get(db);
|
|
5557
|
+
if (!stmt) {
|
|
5558
|
+
stmt = db.prepare("INSERT INTO dream_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value");
|
|
5559
|
+
setDreamStateStatements.set(db, stmt);
|
|
5560
|
+
}
|
|
5561
|
+
return stmt;
|
|
5562
|
+
}
|
|
5563
|
+
function getDeleteDreamStateStatement(db) {
|
|
5564
|
+
let stmt = deleteDreamStateStatements.get(db);
|
|
5565
|
+
if (!stmt) {
|
|
5566
|
+
stmt = db.prepare("DELETE FROM dream_state WHERE key = ?");
|
|
5567
|
+
deleteDreamStateStatements.set(db, stmt);
|
|
5568
|
+
}
|
|
5569
|
+
return stmt;
|
|
5570
|
+
}
|
|
5571
|
+
function getDreamState(db, key) {
|
|
5572
|
+
const row = getGetDreamStateStatement(db).get(key);
|
|
5573
|
+
return typeof row?.value === "string" ? row.value : null;
|
|
5574
|
+
}
|
|
5575
|
+
function setDreamState(db, key, value) {
|
|
5576
|
+
getSetDreamStateStatement(db).run(key, value);
|
|
5577
|
+
}
|
|
5578
|
+
function deleteDreamState(db, key) {
|
|
5579
|
+
getDeleteDreamStateStatement(db).run(key);
|
|
5580
|
+
}
|
|
5581
|
+
|
|
5582
|
+
// src/features/magic-context/dreamer/map-memories-retry.ts
|
|
5583
|
+
function mapMemoryRetryKey(project) {
|
|
5584
|
+
return `map-memories:retry:${project}`;
|
|
5585
|
+
}
|
|
5586
|
+
function readMapMemoryRetries(db, project) {
|
|
5587
|
+
try {
|
|
5588
|
+
const parsed = JSON.parse(getDreamState(db, mapMemoryRetryKey(project)) ?? "{}");
|
|
5589
|
+
if (!isRecord(parsed))
|
|
5590
|
+
return {};
|
|
5591
|
+
const retries = {};
|
|
5592
|
+
for (const [id, value] of Object.entries(parsed)) {
|
|
5593
|
+
if (isRecord(value) && typeof value.content === "string" && typeof value.failures === "number" && typeof value.deferUntil === "number") {
|
|
5594
|
+
retries[id] = {
|
|
5595
|
+
content: value.content,
|
|
5596
|
+
failures: value.failures,
|
|
5597
|
+
deferUntil: value.deferUntil
|
|
5598
|
+
};
|
|
5599
|
+
}
|
|
5600
|
+
}
|
|
5601
|
+
return retries;
|
|
5602
|
+
} catch {
|
|
5603
|
+
return {};
|
|
5604
|
+
}
|
|
5605
|
+
}
|
|
5606
|
+
function contentKey(memory) {
|
|
5607
|
+
return createHash("sha256").update(`${memory.category}
|
|
5608
|
+
${memory.content}`).digest("hex");
|
|
5609
|
+
}
|
|
5610
|
+
function isMapMemoryDeferred(memory, retries, now = Date.now()) {
|
|
5611
|
+
const retry = retries[memory.id];
|
|
5612
|
+
return !!retry && retry.deferUntil > now && retry.content === contentKey(memory);
|
|
5613
|
+
}
|
|
5614
|
+
function nextMapMemoryRetry(memory, prior) {
|
|
5615
|
+
const content = contentKey(memory);
|
|
5616
|
+
const failures = (prior?.content === content ? prior.failures : 0) + 1;
|
|
5617
|
+
const maxWaitHours = 7 * 24;
|
|
5618
|
+
return {
|
|
5619
|
+
content,
|
|
5620
|
+
failures,
|
|
5621
|
+
deferUntil: failures < 2 ? 0 : Date.now() + Math.min(maxWaitHours, 2 ** (failures - 2)) * 3600000
|
|
5622
|
+
};
|
|
5623
|
+
}
|
|
5624
|
+
|
|
5539
5625
|
// src/features/magic-context/dreamer/task-gates.ts
|
|
5540
5626
|
function countActiveMemories(db, projectPath) {
|
|
5541
5627
|
const row = db.prepare("SELECT COUNT(*) AS cnt FROM memories WHERE project_path = ? AND status IN ('active','permanent')").get(projectPath);
|
|
@@ -5552,16 +5638,24 @@ function countLiveMemories(db, projectPath, options = {}) {
|
|
|
5552
5638
|
const row = options.category ? db.prepare(`${sql} AND category = ?`).get(projectPath, Date.now(), options.category) : db.prepare(sql).get(projectPath, Date.now());
|
|
5553
5639
|
return row?.cnt ?? 0;
|
|
5554
5640
|
}
|
|
5641
|
+
var UNMAPPED_LIVE_MEMORIES_SQL = `FROM memories m
|
|
5642
|
+
WHERE m.project_path = ?
|
|
5643
|
+
AND m.status IN ('active','permanent')
|
|
5644
|
+
AND (m.expires_at IS NULL OR m.expires_at > ?)
|
|
5645
|
+
AND NOT EXISTS (SELECT 1 FROM memory_verifications v WHERE v.memory_id = m.id)`;
|
|
5555
5646
|
function countUnmappedActiveMemories(db, projectPath) {
|
|
5556
|
-
const
|
|
5557
|
-
|
|
5558
|
-
|
|
5559
|
-
|
|
5560
|
-
|
|
5561
|
-
|
|
5562
|
-
|
|
5563
|
-
|
|
5564
|
-
|
|
5647
|
+
const now = Date.now();
|
|
5648
|
+
const row = db.prepare(`SELECT COUNT(*) AS cnt ${UNMAPPED_LIVE_MEMORIES_SQL}`).get(projectPath, now);
|
|
5649
|
+
const total = row?.cnt ?? 0;
|
|
5650
|
+
if (total === 0)
|
|
5651
|
+
return 0;
|
|
5652
|
+
const retries = readMapMemoryRetries(db, projectPath);
|
|
5653
|
+
const waitingIds = Object.entries(retries).filter(([, retry]) => retry.deferUntil > now).map(([id]) => id);
|
|
5654
|
+
if (waitingIds.length === 0)
|
|
5655
|
+
return total;
|
|
5656
|
+
const waiting = db.prepare(`SELECT m.id, m.category, m.content ${UNMAPPED_LIVE_MEMORIES_SQL}
|
|
5657
|
+
AND m.id IN (SELECT CAST(value AS INTEGER) FROM json_each(?))`).all(projectPath, now, JSON.stringify(waitingIds));
|
|
5658
|
+
return total - waiting.filter((memory) => isMapMemoryDeferred(memory, retries, now)).length;
|
|
5565
5659
|
}
|
|
5566
5660
|
function countCompartmentsSince(db, projectPath, since) {
|
|
5567
5661
|
const row = db.prepare(`SELECT COUNT(*) AS cnt
|
|
@@ -5744,7 +5838,7 @@ function getDreamTaskBacklog(db, projectPath, task, options = {}) {
|
|
|
5744
5838
|
case "classify-memories": {
|
|
5745
5839
|
const total = countLiveMemories(db, projectPath);
|
|
5746
5840
|
return {
|
|
5747
|
-
pending: countLiveMemories(db, projectPath, { unclassifiedOnly: true }),
|
|
5841
|
+
pending: total >= MIN_POOL_TO_CLASSIFY ? countLiveMemories(db, projectPath, { unclassifiedOnly: true }) : 0,
|
|
5748
5842
|
total
|
|
5749
5843
|
};
|
|
5750
5844
|
}
|
|
@@ -5850,6 +5944,9 @@ function getDreamTaskBacklogs(db, projectPath, tasks = CANONICAL_DREAM_TASKS, op
|
|
|
5850
5944
|
cache.eligibleProjects.clear();
|
|
5851
5945
|
cache.eligibleProjects.set(projectPath, eligible);
|
|
5852
5946
|
}
|
|
5947
|
+
if (eligible && tasks.includes("map-memories")) {
|
|
5948
|
+
eligible = !Object.values(readMapMemoryRetries(db, projectPath)).some(({ deferUntil }) => deferUntil > 0);
|
|
5949
|
+
}
|
|
5853
5950
|
const optionKey = (value) => value === undefined ? "omitted" : value === null ? "null" : `number:${value}`;
|
|
5854
5951
|
const key = JSON.stringify([
|
|
5855
5952
|
getHarness2(),
|
|
@@ -5885,7 +5982,7 @@ function evaluateTaskGate(task, ctx) {
|
|
|
5885
5982
|
case "compress-cues":
|
|
5886
5983
|
return countLiveMemories(db, project) > 0;
|
|
5887
5984
|
case "classify-memories":
|
|
5888
|
-
return countLiveMemories(db, project)
|
|
5985
|
+
return countLiveMemories(db, project) >= MIN_POOL_TO_CLASSIFY;
|
|
5889
5986
|
case "retrospective":
|
|
5890
5987
|
return countProjectSessionsSince(db, project, ctx.retrospectiveWatermarkMs ?? null) > 0;
|
|
5891
5988
|
case "maintain-docs":
|
|
@@ -7047,7 +7144,7 @@ function createToolExecuteAfterHook(args) {
|
|
|
7047
7144
|
}
|
|
7048
7145
|
|
|
7049
7146
|
// src/hooks/magic-context/host-checkpoint-ride.ts
|
|
7050
|
-
import { createHash } from "node:crypto";
|
|
7147
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
7051
7148
|
var SESSIONS_MAX = 100;
|
|
7052
7149
|
var servedHeads = new BoundedSessionMap(SESSIONS_MAX);
|
|
7053
7150
|
var commits = new BoundedSessionMap(SESSIONS_MAX);
|
|
@@ -7057,7 +7154,7 @@ function servedHeadDigest(head) {
|
|
|
7057
7154
|
return null;
|
|
7058
7155
|
const mural = head.muralDataUrl ?? null;
|
|
7059
7156
|
const m0 = mural ? head.m0Text : stripMemoryMuralBlock(head.m0Text);
|
|
7060
|
-
return
|
|
7157
|
+
return createHash2("sha256").update(JSON.stringify([m0, head.m1Text, mural])).digest("hex");
|
|
7061
7158
|
}
|
|
7062
7159
|
function servedHeadChanged(before, after) {
|
|
7063
7160
|
const a = servedHeadDigest(before);
|
|
@@ -13041,12 +13138,12 @@ function systemPromptDates(prompt, sticky) {
|
|
|
13041
13138
|
}
|
|
13042
13139
|
|
|
13043
13140
|
// src/hooks/magic-context/system-prompt-diagnostics.ts
|
|
13044
|
-
import { createHash as
|
|
13141
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
13045
13142
|
function snapshotSystemPrompt(system, preset) {
|
|
13046
13143
|
return { elements: system.map((element) => Buffer.from(element)), preset };
|
|
13047
13144
|
}
|
|
13048
13145
|
function describeSystemPromptChange(previous, current) {
|
|
13049
|
-
const metadata = (element) => element === undefined ? "absent" : `bytes=${element.length},md5=${
|
|
13146
|
+
const metadata = (element) => element === undefined ? "absent" : `bytes=${element.length},md5=${createHash3("md5").update(element).digest("hex")}`;
|
|
13050
13147
|
const elements = [];
|
|
13051
13148
|
for (let index = 0;index < Math.max(previous?.elements.length ?? 0, current.elements.length); index++) {
|
|
13052
13149
|
const before = previous?.elements[index];
|
|
@@ -14270,7 +14367,7 @@ function evaluateRequestToolsRelease(args) {
|
|
|
14270
14367
|
}
|
|
14271
14368
|
|
|
14272
14369
|
// src/hooks/magic-context/rust-mode-transform.ts
|
|
14273
|
-
import { createHash as
|
|
14370
|
+
import { createHash as createHash7, randomUUID as randomUUID2 } from "node:crypto";
|
|
14274
14371
|
|
|
14275
14372
|
// src/features/magic-context/memory/single-store-embedding-drain.ts
|
|
14276
14373
|
function isWatermarkRow(row) {
|
|
@@ -14334,7 +14431,7 @@ function advanceEmbeddedWatermark(db, projectPath, upTo) {
|
|
|
14334
14431
|
}
|
|
14335
14432
|
|
|
14336
14433
|
// src/features/magic-context/mural/source-revision.ts
|
|
14337
|
-
import { createHash as
|
|
14434
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
14338
14435
|
var statements = new WeakMap;
|
|
14339
14436
|
function muralSourceRevision(db, projectPath) {
|
|
14340
14437
|
let statement = statements.get(db);
|
|
@@ -14351,7 +14448,7 @@ function muralSourceRevision(db, projectPath) {
|
|
|
14351
14448
|
statements.set(db, statement);
|
|
14352
14449
|
}
|
|
14353
14450
|
const row = statement.get(projectPath, Date.now());
|
|
14354
|
-
return
|
|
14451
|
+
return createHash4("sha256").update(row.revision).digest("hex");
|
|
14355
14452
|
}
|
|
14356
14453
|
|
|
14357
14454
|
// src/features/magic-context/install-instance-id.ts
|
|
@@ -16726,7 +16823,7 @@ function noteExternalLkgReplay(participant, sessionId, inputMessages, servedMess
|
|
|
16726
16823
|
}
|
|
16727
16824
|
|
|
16728
16825
|
// src/hooks/magic-context/rust-served-raw.ts
|
|
16729
|
-
import { createHash as
|
|
16826
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
16730
16827
|
class RustServedRawConflict extends EmergencyFailClosedError {
|
|
16731
16828
|
reason;
|
|
16732
16829
|
messageIds;
|
|
@@ -16740,7 +16837,7 @@ class RustServedRawConflict extends EmergencyFailClosedError {
|
|
|
16740
16837
|
}
|
|
16741
16838
|
function partDigest(part) {
|
|
16742
16839
|
const serialized = JSON.stringify(part);
|
|
16743
|
-
return
|
|
16840
|
+
return createHash6("sha256").update(stableStringify(serialized === undefined ? undefined : JSON.parse(serialized))).digest("hex");
|
|
16744
16841
|
}
|
|
16745
16842
|
function records(doc) {
|
|
16746
16843
|
if (doc.rustServedRaw === undefined)
|
|
@@ -17292,10 +17389,10 @@ function messageCacheSignature(message) {
|
|
|
17292
17389
|
const parts = Array.isArray(message.parts) ? message.parts : [];
|
|
17293
17390
|
const serializedParts = JSON.stringify(parts) ?? "null";
|
|
17294
17391
|
const serializedMessage = JSON.stringify(message) ?? "null";
|
|
17295
|
-
return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${
|
|
17392
|
+
return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash7("sha256").update(serializedMessage).digest("hex")}`;
|
|
17296
17393
|
}
|
|
17297
17394
|
function advanceWireFingerprint(previous, encoded) {
|
|
17298
|
-
return
|
|
17395
|
+
return createHash7("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
|
|
17299
17396
|
}
|
|
17300
17397
|
function buildWireFingerprint(encoded) {
|
|
17301
17398
|
let fingerprint = "rust-wire-v1";
|
|
@@ -19084,7 +19181,7 @@ ${notice}`, {}));
|
|
|
19084
19181
|
const id = messageIdOf(message) ?? `index:${todoStart + offset}`;
|
|
19085
19182
|
const parts = message.parts?.filter((part) => isRecord4(part) && part.type === "tool" && part.tool === "todowrite");
|
|
19086
19183
|
if (parts?.length) {
|
|
19087
|
-
todoCalls.set(id,
|
|
19184
|
+
todoCalls.set(id, createHash7("sha256").update(JSON.stringify(parts)).digest("hex"));
|
|
19088
19185
|
} else {
|
|
19089
19186
|
todoCalls.delete(id);
|
|
19090
19187
|
}
|
|
@@ -24723,7 +24820,7 @@ function setSessionWorkMetricsCarry(db, sessionId, source, carry, metrics) {
|
|
|
24723
24820
|
import { readFileSync, statSync } from "node:fs";
|
|
24724
24821
|
|
|
24725
24822
|
// src/plugin/embedding-bootstrap-helpers.ts
|
|
24726
|
-
import { createHash as
|
|
24823
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
24727
24824
|
var EMBEDDING_AFFECTING_KEYS = new Set([
|
|
24728
24825
|
"embedding.api_key",
|
|
24729
24826
|
"embedding.endpoint",
|
|
@@ -24772,7 +24869,7 @@ var EMBEDDING_WARNING_TERMS = [
|
|
|
24772
24869
|
];
|
|
24773
24870
|
var loggedFailureSignatures = new Map;
|
|
24774
24871
|
function sha256Prefix(value, length = 16) {
|
|
24775
|
-
return
|
|
24872
|
+
return createHash8("sha256").update(value).digest("hex").slice(0, length);
|
|
24776
24873
|
}
|
|
24777
24874
|
function warningLooksEmbeddingRelated(message) {
|
|
24778
24875
|
const lower = message.toLowerCase();
|
|
@@ -26257,7 +26354,7 @@ function registerRpcHandlers(rpcServer, args) {
|
|
|
26257
26354
|
const buildManagedCtx = async (db) => {
|
|
26258
26355
|
const { deriveHistorianChunkTokens, resolveHistorianContextLimit } = await importPluginModule(() => import("./derive-budgets-2eam671q.js"));
|
|
26259
26356
|
const { resolveHistorianModel } = await importPluginModule(() => import("./model-resolution-280gmqvd.js"));
|
|
26260
|
-
const { userObservationCollectionEnabled, userObservationsRequested } = await importPluginModule(() => import("./task-config-
|
|
26357
|
+
const { userObservationCollectionEnabled, userObservationsRequested } = await importPluginModule(() => import("./task-config-ex2vajr2.js"));
|
|
26261
26358
|
const DEFAULT_HISTORIAN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
26262
26359
|
const runConfig = historianRunConfig(config, currentPluginConfigReader(directory)?.poll().effective ?? config);
|
|
26263
26360
|
const historianModel = resolveHistorianModel(runConfig, "opencode");
|
|
@@ -27721,7 +27818,7 @@ function stageManualBaseline(db, sessionID, render) {
|
|
|
27721
27818
|
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
27722
27819
|
|
|
27723
27820
|
// src/v2/fold/owner.ts
|
|
27724
|
-
import { createHash as
|
|
27821
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
27725
27822
|
|
|
27726
27823
|
// src/v2/fold/summary.ts
|
|
27727
27824
|
var RAW_HISTORY_ACCOUNT = "Magic Context retains the conversation as raw messages; no summarized history is available yet.";
|
|
@@ -27751,7 +27848,7 @@ ${head}
|
|
|
27751
27848
|
}
|
|
27752
27849
|
|
|
27753
27850
|
// src/v2/fold/owner.ts
|
|
27754
|
-
var foldDigest = (value) =>
|
|
27851
|
+
var foldDigest = (value) => createHash9("sha256").update(value).digest("hex");
|
|
27755
27852
|
var boundToCheckpoint = (record) => record.cutSeq !== undefined || record.rendered !== undefined || record.answered !== undefined;
|
|
27756
27853
|
|
|
27757
27854
|
class FoldOwner {
|
|
@@ -28252,7 +28349,7 @@ function instanceBytes(value, seen) {
|
|
|
28252
28349
|
bytes += 16 + instanceBytes(entry, seen);
|
|
28253
28350
|
return bytes;
|
|
28254
28351
|
}
|
|
28255
|
-
function
|
|
28352
|
+
function contentKey2(value) {
|
|
28256
28353
|
const plain = (entry) => {
|
|
28257
28354
|
if (ArrayBuffer.isView(entry)) {
|
|
28258
28355
|
return {
|
|
@@ -28316,7 +28413,7 @@ function adaptPayload(draft, syntheticIDs = new Set, messageTimes = new Map, hid
|
|
|
28316
28413
|
for (const message of source) {
|
|
28317
28414
|
for (const part of message.content) {
|
|
28318
28415
|
if (part.type !== "tool-call" && part.type !== "tool-result" && part.type !== "tool" && containsHostInstance(part)) {
|
|
28319
|
-
const key =
|
|
28416
|
+
const key = contentKey2(part);
|
|
28320
28417
|
if (!hostParts.has(key))
|
|
28321
28418
|
hostParts.set(key, part);
|
|
28322
28419
|
hostPartTypes.add(part.type);
|
|
@@ -28521,7 +28618,7 @@ function adaptPayload(draft, syntheticIDs = new Set, messageTimes = new Map, hid
|
|
|
28521
28618
|
continue;
|
|
28522
28619
|
}
|
|
28523
28620
|
const { synthetic: _synthetic, ...clean } = part;
|
|
28524
|
-
const original = hostPartTypes.has(clean.type) && !containsHostInstance(clean) ? hostParts.get(
|
|
28621
|
+
const original = hostPartTypes.has(clean.type) && !containsHostInstance(clean) ? hostParts.get(contentKey2(clean)) : undefined;
|
|
28525
28622
|
const projected = original ?? clean;
|
|
28526
28623
|
if (projected.type === "media" && !isHostInstance(projected.media)) {
|
|
28527
28624
|
content.push(repairMediaPart(message, partIndex, projected));
|
|
@@ -32064,50 +32161,11 @@ class DeletedSessionTombstones {
|
|
|
32064
32161
|
}
|
|
32065
32162
|
|
|
32066
32163
|
// src/features/magic-context/dreamer/task-executor.ts
|
|
32067
|
-
import { createHash as
|
|
32164
|
+
import { createHash as createHash17 } from "node:crypto";
|
|
32068
32165
|
import { existsSync as existsSync7, readFileSync as readFileSync8 } from "node:fs";
|
|
32069
32166
|
|
|
32070
32167
|
// src/features/magic-context/mural/compress-cues.ts
|
|
32071
|
-
import { createHash as
|
|
32072
|
-
|
|
32073
|
-
// src/features/magic-context/dreamer/storage-dream-state.ts
|
|
32074
|
-
var getDreamStateStatements = new WeakMap;
|
|
32075
|
-
var setDreamStateStatements = new WeakMap;
|
|
32076
|
-
var deleteDreamStateStatements = new WeakMap;
|
|
32077
|
-
function getGetDreamStateStatement(db) {
|
|
32078
|
-
let stmt = getDreamStateStatements.get(db);
|
|
32079
|
-
if (!stmt) {
|
|
32080
|
-
stmt = db.prepare("SELECT value FROM dream_state WHERE key = ?");
|
|
32081
|
-
getDreamStateStatements.set(db, stmt);
|
|
32082
|
-
}
|
|
32083
|
-
return stmt;
|
|
32084
|
-
}
|
|
32085
|
-
function getSetDreamStateStatement(db) {
|
|
32086
|
-
let stmt = setDreamStateStatements.get(db);
|
|
32087
|
-
if (!stmt) {
|
|
32088
|
-
stmt = db.prepare("INSERT INTO dream_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value");
|
|
32089
|
-
setDreamStateStatements.set(db, stmt);
|
|
32090
|
-
}
|
|
32091
|
-
return stmt;
|
|
32092
|
-
}
|
|
32093
|
-
function getDeleteDreamStateStatement(db) {
|
|
32094
|
-
let stmt = deleteDreamStateStatements.get(db);
|
|
32095
|
-
if (!stmt) {
|
|
32096
|
-
stmt = db.prepare("DELETE FROM dream_state WHERE key = ?");
|
|
32097
|
-
deleteDreamStateStatements.set(db, stmt);
|
|
32098
|
-
}
|
|
32099
|
-
return stmt;
|
|
32100
|
-
}
|
|
32101
|
-
function getDreamState(db, key) {
|
|
32102
|
-
const row = getGetDreamStateStatement(db).get(key);
|
|
32103
|
-
return typeof row?.value === "string" ? row.value : null;
|
|
32104
|
-
}
|
|
32105
|
-
function setDreamState(db, key, value) {
|
|
32106
|
-
getSetDreamStateStatement(db).run(key, value);
|
|
32107
|
-
}
|
|
32108
|
-
function deleteDreamState(db, key) {
|
|
32109
|
-
getDeleteDreamStateStatement(db).run(key);
|
|
32110
|
-
}
|
|
32168
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
32111
32169
|
|
|
32112
32170
|
// src/features/magic-context/dreamer/lease.ts
|
|
32113
32171
|
var LEASE_DURATION_MS = 2 * 60 * 1000;
|
|
@@ -32813,7 +32871,7 @@ async function applyCuesThroughModule(args, chunk, manifestText, signal) {
|
|
|
32813
32871
|
log2(`[dreamer] compress-cues: skipped cue for memory ${entry.id} (${failure.reason}; rejection ${rejectionCount}/${CUE_REJECTION_LATCH_THRESHOLD})`);
|
|
32814
32872
|
}
|
|
32815
32873
|
}
|
|
32816
|
-
const commandId = `mural-cues:${route.moduleCommandId}:${
|
|
32874
|
+
const commandId = `mural-cues:${route.moduleCommandId}:${createHash10("sha256").update(chunk.map((candidate) => candidate.memory.id).join(",")).digest("hex").slice(0, 24)}`;
|
|
32817
32875
|
let response;
|
|
32818
32876
|
try {
|
|
32819
32877
|
response = await route.moduleClient.call({
|
|
@@ -33430,7 +33488,7 @@ function applyReviewVerdict(args, leaseKey, parsed, result) {
|
|
|
33430
33488
|
}
|
|
33431
33489
|
|
|
33432
33490
|
// src/features/magic-context/dreamer/classify.ts
|
|
33433
|
-
import { createHash as
|
|
33491
|
+
import { createHash as createHash11 } from "node:crypto";
|
|
33434
33492
|
|
|
33435
33493
|
// src/plugin/rust-tool-backends.ts
|
|
33436
33494
|
function isRustAuthorityDrainingError(error) {
|
|
@@ -33603,7 +33661,6 @@ async function readFailedChildMessages(client, sessionId, directory) {
|
|
|
33603
33661
|
}
|
|
33604
33662
|
|
|
33605
33663
|
// src/features/magic-context/dreamer/classify.ts
|
|
33606
|
-
var MIN_POOL_TO_CLASSIFY = 10;
|
|
33607
33664
|
var FULL_POOL_CEILING = 100;
|
|
33608
33665
|
var STAGE3_ANCHOR_COUNT = 30;
|
|
33609
33666
|
var CLASSIFY_CHUNK_SIZE = 100;
|
|
@@ -33868,7 +33925,7 @@ async function runClassifyThroughModule(args, chunk, anchors, signal, runOnHost)
|
|
|
33868
33925
|
if (entry.qualifier)
|
|
33869
33926
|
modelVariants[entry.model] = entry.qualifier;
|
|
33870
33927
|
}
|
|
33871
|
-
const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${
|
|
33928
|
+
const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${createHash11("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`;
|
|
33872
33929
|
const runTask = (hostCompletion) => args.moduleClient?.call({
|
|
33873
33930
|
sessionId: args.moduleSessionId,
|
|
33874
33931
|
projectRoot: args.moduleProjectRoot,
|
|
@@ -34161,7 +34218,7 @@ function takeCurateSafetyRefusalCount(sessionId) {
|
|
|
34161
34218
|
|
|
34162
34219
|
// src/features/magic-context/dreamer/docs-proposals.ts
|
|
34163
34220
|
import { execFileSync } from "node:child_process";
|
|
34164
|
-
import { createHash as
|
|
34221
|
+
import { createHash as createHash12 } from "node:crypto";
|
|
34165
34222
|
import {
|
|
34166
34223
|
existsSync as existsSync4,
|
|
34167
34224
|
mkdirSync,
|
|
@@ -34176,7 +34233,7 @@ import {
|
|
|
34176
34233
|
import { tmpdir } from "node:os";
|
|
34177
34234
|
import { join as join8 } from "node:path";
|
|
34178
34235
|
var FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
|
|
34179
|
-
var hash = (text) =>
|
|
34236
|
+
var hash = (text) => createHash12("sha256").update(text).digest("hex");
|
|
34180
34237
|
var proposalDir = (projectDir) => join8(projectDir, ".cortexkit/magic-context/docs-update-proposals");
|
|
34181
34238
|
function docsBaseHashes(projectDir) {
|
|
34182
34239
|
return Object.fromEntries(FILES.map((name) => [
|
|
@@ -34796,7 +34853,7 @@ function throwIfAborted2(signal) {
|
|
|
34796
34853
|
}
|
|
34797
34854
|
|
|
34798
34855
|
// src/features/magic-context/smart-notes/compiler.ts
|
|
34799
|
-
import { createHash as
|
|
34856
|
+
import { createHash as createHash13 } from "node:crypto";
|
|
34800
34857
|
|
|
34801
34858
|
// src/features/magic-context/smart-notes/compiler-prompt.ts
|
|
34802
34859
|
var SMART_NOTE_COMPILER_SYSTEM_PROMPT = `You are the Magic Context smart-note compiler for the magic-context system.
|
|
@@ -35143,7 +35200,7 @@ function manifestAdvisoryWarnings(code, manifest) {
|
|
|
35143
35200
|
return warnings;
|
|
35144
35201
|
}
|
|
35145
35202
|
function hashCheck(surfaceCondition, compiledCheck, manifest, checkCron) {
|
|
35146
|
-
return
|
|
35203
|
+
return createHash13("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
|
|
35147
35204
|
}
|
|
35148
35205
|
function extractJsonObject(output) {
|
|
35149
35206
|
const fenced = output.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
@@ -35916,7 +35973,7 @@ function snapshotMaintainDocsFiles(docsDir) {
|
|
|
35916
35973
|
}
|
|
35917
35974
|
|
|
35918
35975
|
// src/features/magic-context/dreamer/map-memories.ts
|
|
35919
|
-
import { createHash as
|
|
35976
|
+
import { createHash as createHash14 } from "node:crypto";
|
|
35920
35977
|
|
|
35921
35978
|
// src/features/magic-context/dreamer/map-memories-prompt.ts
|
|
35922
35979
|
import { execFile as execFile2 } from "node:child_process";
|
|
@@ -36126,37 +36183,6 @@ var MAP_BATCH_SIZE = 5;
|
|
|
36126
36183
|
var MAP_BATCH_FLOOR_MS = 240000;
|
|
36127
36184
|
var CONSECUTIVE_TIMEOUT_LIMIT2 = 2;
|
|
36128
36185
|
var MAX_INDEPENDENT_REQUEUE_PER_RUN = MAP_BATCH_SIZE;
|
|
36129
|
-
function retryKey(project) {
|
|
36130
|
-
return `map-memories:retry:${project}`;
|
|
36131
|
-
}
|
|
36132
|
-
function readRetries(db, project) {
|
|
36133
|
-
try {
|
|
36134
|
-
const parsed = JSON.parse(getDreamState(db, retryKey(project)) ?? "{}");
|
|
36135
|
-
if (!isRecord(parsed))
|
|
36136
|
-
return {};
|
|
36137
|
-
const retries = {};
|
|
36138
|
-
for (const [id, value] of Object.entries(parsed)) {
|
|
36139
|
-
if (isRecord(value) && typeof value.content === "string" && typeof value.failures === "number" && typeof value.deferUntil === "number") {
|
|
36140
|
-
retries[id] = {
|
|
36141
|
-
content: value.content,
|
|
36142
|
-
failures: value.failures,
|
|
36143
|
-
deferUntil: value.deferUntil
|
|
36144
|
-
};
|
|
36145
|
-
}
|
|
36146
|
-
}
|
|
36147
|
-
return retries;
|
|
36148
|
-
} catch {
|
|
36149
|
-
return {};
|
|
36150
|
-
}
|
|
36151
|
-
}
|
|
36152
|
-
function contentKey2(memory) {
|
|
36153
|
-
return createHash13("sha256").update(`${memory.category}
|
|
36154
|
-
${memory.content}`).digest("hex");
|
|
36155
|
-
}
|
|
36156
|
-
function isDeferred(memory, retries) {
|
|
36157
|
-
const retry = retries[memory.id];
|
|
36158
|
-
return !!retry && retry.content === contentKey2(memory) && retry.deferUntil > Date.now();
|
|
36159
|
-
}
|
|
36160
36186
|
function assistantText2(messages) {
|
|
36161
36187
|
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(`
|
|
36162
36188
|
`) : "")).join(`
|
|
@@ -36225,8 +36251,8 @@ function selectMapMemoryInputs(db, projectIdentity, repoDir, includeDeferred = f
|
|
|
36225
36251
|
if (requeue.length >= MAX_INDEPENDENT_REQUEUE_PER_RUN)
|
|
36226
36252
|
break;
|
|
36227
36253
|
}
|
|
36228
|
-
const retries =
|
|
36229
|
-
return [...unmappedInputs, ...requeue].filter((memory) => includeDeferred || !
|
|
36254
|
+
const retries = readMapMemoryRetries(db, projectIdentity);
|
|
36255
|
+
return [...unmappedInputs, ...requeue].filter((memory) => includeDeferred || !isMapMemoryDeferred(memory, retries));
|
|
36230
36256
|
}
|
|
36231
36257
|
async function mapMemories(args) {
|
|
36232
36258
|
const result = {
|
|
@@ -36237,12 +36263,12 @@ async function mapMemories(args) {
|
|
|
36237
36263
|
complete: true
|
|
36238
36264
|
};
|
|
36239
36265
|
const allInputs = selectMapMemoryInputs(args.db, args.projectIdentity, args.sessionDirectory, true);
|
|
36240
|
-
const retries =
|
|
36266
|
+
const retries = readMapMemoryRetries(args.db, args.projectIdentity);
|
|
36241
36267
|
const activeIds = new Set(allInputs.map((memory) => String(memory.id)));
|
|
36242
36268
|
for (const id of Object.keys(retries))
|
|
36243
36269
|
if (!activeIds.has(id))
|
|
36244
36270
|
delete retries[id];
|
|
36245
|
-
const inputs = allInputs.filter((memory) => !
|
|
36271
|
+
const inputs = allInputs.filter((memory) => !isMapMemoryDeferred(memory, retries));
|
|
36246
36272
|
result.remaining = allInputs.length;
|
|
36247
36273
|
result.complete = result.remaining === 0;
|
|
36248
36274
|
if (inputs.length === 0) {
|
|
@@ -36259,6 +36285,7 @@ async function mapMemories(args) {
|
|
|
36259
36285
|
try {
|
|
36260
36286
|
let consecutiveTimeouts = 0;
|
|
36261
36287
|
let timeoutStreakElapsedMs = [];
|
|
36288
|
+
const countedMisses = new Set;
|
|
36262
36289
|
for (let i = 0;i < batches.length; i += 1) {
|
|
36263
36290
|
const remainingMs = Math.max(0, args.deadline - Date.now());
|
|
36264
36291
|
if (remainingMs <= 0) {
|
|
@@ -36281,22 +36308,19 @@ async function mapMemories(args) {
|
|
|
36281
36308
|
}
|
|
36282
36309
|
const committed = outcome.mapped + outcome.independent;
|
|
36283
36310
|
const committedIds = new Set(outcome.committedIds);
|
|
36311
|
+
const missedIds = new Set(outcome.missedIds);
|
|
36284
36312
|
runLeaseGuardedWrite(args.db, args.holderId, args.leaseKey, () => {
|
|
36285
36313
|
for (const memory of batch.inputs) {
|
|
36286
36314
|
if (committedIds.has(memory.id)) {
|
|
36287
36315
|
delete retries[memory.id];
|
|
36288
36316
|
continue;
|
|
36289
36317
|
}
|
|
36290
|
-
|
|
36291
|
-
|
|
36292
|
-
|
|
36293
|
-
|
|
36294
|
-
content,
|
|
36295
|
-
failures,
|
|
36296
|
-
deferUntil: failures < 2 ? 0 : Date.now() + Math.min(24, 2 ** (failures - 2)) * 3600000
|
|
36297
|
-
};
|
|
36318
|
+
if (missedIds.has(memory.id) && !countedMisses.has(memory.id)) {
|
|
36319
|
+
countedMisses.add(memory.id);
|
|
36320
|
+
retries[memory.id] = nextMapMemoryRetry(memory, retries[memory.id]);
|
|
36321
|
+
}
|
|
36298
36322
|
}
|
|
36299
|
-
setDreamState(args.db,
|
|
36323
|
+
setDreamState(args.db, mapMemoryRetryKey(args.projectIdentity), JSON.stringify(retries));
|
|
36300
36324
|
});
|
|
36301
36325
|
result.mapped += outcome.mapped;
|
|
36302
36326
|
result.independent += outcome.independent;
|
|
@@ -36308,7 +36332,7 @@ async function mapMemories(args) {
|
|
|
36308
36332
|
if (outcome.requeue?.length) {
|
|
36309
36333
|
if (!batch.isOmissionRetry) {
|
|
36310
36334
|
batches.push({
|
|
36311
|
-
inputs: outcome.requeue.filter((memory) => !
|
|
36335
|
+
inputs: outcome.requeue.filter((memory) => !isMapMemoryDeferred(memory, retries)),
|
|
36312
36336
|
isOmissionRetry: true
|
|
36313
36337
|
});
|
|
36314
36338
|
log2(`[dreamer] map-memories: committed ${committed}/${batch.inputs.length} mapping(s); requeueing ${outcome.requeue.length} omitted id(s) in a targeted retry`);
|
|
@@ -36396,11 +36420,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
|
|
|
36396
36420
|
stage = "apply";
|
|
36397
36421
|
const outcome = await applyParsedBatchMappings(args, batch, run.validated, budgetFinalized, true);
|
|
36398
36422
|
logBatchUsage(run.completion.messages ?? [], outcome.mapped + outcome.independent, startedAt);
|
|
36399
|
-
|
|
36400
|
-
return {
|
|
36401
|
-
...outcome,
|
|
36402
|
-
requeue: budgetFinalized ? [] : batch.filter((memory) => !returnedIds.has(memory.id))
|
|
36403
|
-
};
|
|
36423
|
+
return completedMapBatch(outcome, batch, run.validated, budgetFinalized);
|
|
36404
36424
|
}
|
|
36405
36425
|
const client = args.client;
|
|
36406
36426
|
if (!client)
|
|
@@ -36454,11 +36474,7 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
|
|
|
36454
36474
|
stage = "apply";
|
|
36455
36475
|
const outcome = await applyParsedBatchMappings(args, batch, run.validated, budgetFinalized, true);
|
|
36456
36476
|
logBatchUsage(run.output, outcome.mapped + outcome.independent, startedAt);
|
|
36457
|
-
|
|
36458
|
-
return {
|
|
36459
|
-
...outcome,
|
|
36460
|
-
requeue: budgetFinalized ? [] : batch.filter((memory) => !returnedIds.has(memory.id))
|
|
36461
|
-
};
|
|
36477
|
+
return completedMapBatch(outcome, batch, run.validated, budgetFinalized);
|
|
36462
36478
|
} catch (error) {
|
|
36463
36479
|
const desc = describeError(error);
|
|
36464
36480
|
log2(`[dreamer] map-memories batch failed: ${desc.brief}`, desc.stackHead ? { stackHead: desc.stackHead } : undefined);
|
|
@@ -36500,6 +36516,17 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
|
|
|
36500
36516
|
});
|
|
36501
36517
|
}
|
|
36502
36518
|
}
|
|
36519
|
+
function completedMapBatch(outcome, batch, parsed, budgetFinalized) {
|
|
36520
|
+
if (budgetFinalized)
|
|
36521
|
+
return outcome;
|
|
36522
|
+
const decided = new Set(parsed.map(({ id }) => id));
|
|
36523
|
+
const committed = new Set(outcome.committedIds);
|
|
36524
|
+
return {
|
|
36525
|
+
...outcome,
|
|
36526
|
+
missedIds: batch.filter(({ id }) => !decided.has(id)).map(({ id }) => id),
|
|
36527
|
+
requeue: batch.filter(({ id }) => !committed.has(id))
|
|
36528
|
+
};
|
|
36529
|
+
}
|
|
36503
36530
|
async function applyParsedBatchMappings(args, batch, parsed, budgetFinalized = false, allowPartial = false) {
|
|
36504
36531
|
const batchIds = new Set(batch.map((memory) => memory.id));
|
|
36505
36532
|
const valid = parsed.filter((entry) => batchIds.has(entry.id));
|
|
@@ -36591,7 +36618,7 @@ async function applyParsedBatchMappings(args, batch, parsed, budgetFinalized = f
|
|
|
36591
36618
|
name: "memory.set_mapping",
|
|
36592
36619
|
arguments: {
|
|
36593
36620
|
memory_project: args.projectIdentity,
|
|
36594
|
-
command_id: `${args.moduleRoute.moduleCommandId}:${
|
|
36621
|
+
command_id: `${args.moduleRoute.moduleCommandId}:${createHash14("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
|
|
36595
36622
|
rows
|
|
36596
36623
|
}
|
|
36597
36624
|
}
|
|
@@ -37527,6 +37554,33 @@ ${buildFrictionGatePrompt({ userLines })}`;
|
|
|
37527
37554
|
function retrospectiveGatePromptTokens(messages) {
|
|
37528
37555
|
return estimateTokens(retrospectiveGatePrompt(messages));
|
|
37529
37556
|
}
|
|
37557
|
+
function admitRetrospectiveCohorts(rows, firstUnreadTs, maxMessages, promptInputLimitTokens) {
|
|
37558
|
+
const kept = [];
|
|
37559
|
+
let start = 0;
|
|
37560
|
+
for (let first = rows[start];first && first.ts < firstUnreadTs; first = rows[start]) {
|
|
37561
|
+
const ts = first.ts;
|
|
37562
|
+
let end = start + 1;
|
|
37563
|
+
while (end < rows.length && rows[end]?.ts === ts)
|
|
37564
|
+
end += 1;
|
|
37565
|
+
const cohort = rows.slice(start, end);
|
|
37566
|
+
const tooManyRows = end > maxMessages;
|
|
37567
|
+
const tooManyTokens = !tooManyRows && promptInputLimitTokens !== undefined && retrospectiveGatePromptTokens([...kept, ...cohort]) > promptInputLimitTokens;
|
|
37568
|
+
if (tooManyRows || tooManyTokens) {
|
|
37569
|
+
return {
|
|
37570
|
+
kept,
|
|
37571
|
+
budgetTruncated: tooManyTokens,
|
|
37572
|
+
...kept.length === 0 ? { oversized: { ts, rows: cohort } } : {}
|
|
37573
|
+
};
|
|
37574
|
+
}
|
|
37575
|
+
kept.push(...cohort);
|
|
37576
|
+
start = end;
|
|
37577
|
+
}
|
|
37578
|
+
return { kept, budgetTruncated: false };
|
|
37579
|
+
}
|
|
37580
|
+
function logSkippedRetrospectiveCohort(sessionIds, ts, count, lowerBound) {
|
|
37581
|
+
const sessions = [...new Set(sessionIds)].join(",");
|
|
37582
|
+
log2(`[dreamer] retrospective: oversized timestamp cohort sessionIds=${sessions} timestamp=${ts} ${lowerBound ? "skippedAtLeast" : "skipped"}=${count}`);
|
|
37583
|
+
}
|
|
37530
37584
|
async function readRetrospectiveScanWindow(provider, projectIdentity, watermarkMs, overlapUserCount, options) {
|
|
37531
37585
|
const maxMessages = options?.maxMessagesPerRun ?? RETROSPECTIVE_MAX_MESSAGES_PER_RUN;
|
|
37532
37586
|
const capPerSession = options?.capPerSession ?? RETROSPECTIVE_MAX_MESSAGES_PER_SESSION;
|
|
@@ -37556,59 +37610,57 @@ async function readRetrospectiveScanWindow(provider, projectIdentity, watermarkM
|
|
|
37556
37610
|
if (sessionsToRead.length > 0) {
|
|
37557
37611
|
sinceReads.push(...await Promise.all(sessionsToRead.map((session) => provider.readUserMessagesSince(session.sessionId, scanSinceMs, capPerSession))));
|
|
37558
37612
|
}
|
|
37559
|
-
|
|
37560
|
-
|
|
37561
|
-
|
|
37562
|
-
|
|
37563
|
-
|
|
37564
|
-
|
|
37565
|
-
|
|
37566
|
-
|
|
37567
|
-
|
|
37568
|
-
|
|
37569
|
-
|
|
37570
|
-
|
|
37571
|
-
|
|
37572
|
-
|
|
37573
|
-
|
|
37574
|
-
|
|
37575
|
-
if (!row)
|
|
37576
|
-
continue;
|
|
37577
|
-
const candidate = [...keptSince, row];
|
|
37578
|
-
if (retrospectiveGatePromptTokens(candidate) <= promptInputLimitTokens) {
|
|
37579
|
-
keptSince.push(row);
|
|
37580
|
-
continue;
|
|
37581
|
-
}
|
|
37582
|
-
budgetDropped = countCandidates.slice(index);
|
|
37583
|
-
break;
|
|
37613
|
+
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);
|
|
37614
|
+
let unknownBoundary = !!firstExcludedSession && firstExcludedPendingTs === undefined;
|
|
37615
|
+
let firstUnreadTs = firstExcludedPendingTs ?? Number.POSITIVE_INFINITY;
|
|
37616
|
+
const oversizedSessions = new Map;
|
|
37617
|
+
for (const [index, read] of sinceReads.entries()) {
|
|
37618
|
+
if (!read.truncated)
|
|
37619
|
+
continue;
|
|
37620
|
+
const unreadTs = read.firstOmittedTs ?? read.messages.at(-1)?.ts;
|
|
37621
|
+
if (unreadTs === undefined) {
|
|
37622
|
+
unknownBoundary = true;
|
|
37623
|
+
continue;
|
|
37624
|
+
}
|
|
37625
|
+
firstUnreadTs = Math.min(firstUnreadTs, unreadTs);
|
|
37626
|
+
const sessionId = sessionsToRead[index]?.sessionId;
|
|
37627
|
+
if (sessionId !== undefined && read.firstOmittedTs !== undefined && read.firstOmittedTs === oldestBySession?.get(sessionId)) {
|
|
37628
|
+
oversizedSessions.set(sessionId, read.firstOmittedTs);
|
|
37584
37629
|
}
|
|
37585
37630
|
}
|
|
37586
|
-
const
|
|
37631
|
+
const {
|
|
37632
|
+
kept: keptSince,
|
|
37633
|
+
budgetTruncated,
|
|
37634
|
+
oversized
|
|
37635
|
+
} = admitRetrospectiveCohorts(allSince, unknownBoundary ? scanSinceMs : firstUnreadTs, maxMessages, promptInputLimitTokens);
|
|
37636
|
+
const lastKept = keptSince.at(-1);
|
|
37587
37637
|
let maxScannedTs = scanSinceMs;
|
|
37588
|
-
if (
|
|
37589
|
-
|
|
37590
|
-
maxScannedTs =
|
|
37638
|
+
if (!unknownBoundary) {
|
|
37639
|
+
if (oversized) {
|
|
37640
|
+
maxScannedTs = oversized.ts;
|
|
37641
|
+
logSkippedRetrospectiveCohort(oversized.rows.map(({ sessionId }) => sessionId), maxScannedTs, oversized.rows.length, false);
|
|
37642
|
+
} else if (lastKept) {
|
|
37643
|
+
maxScannedTs = lastKept.ts;
|
|
37644
|
+
} else if (Number.isFinite(firstUnreadTs)) {
|
|
37645
|
+
const blockedSessions = sessions.filter(({ session }) => oldestBySession?.get(session.sessionId) === firstUnreadTs);
|
|
37646
|
+
const hitSessionReadCap = blockedSessions.some(({ session }) => oversizedSessions.get(session.sessionId) === firstUnreadTs);
|
|
37647
|
+
if (hitSessionReadCap || blockedSessions.length > sessionLimit) {
|
|
37648
|
+
maxScannedTs = firstUnreadTs;
|
|
37649
|
+
logSkippedRetrospectiveCohort(blockedSessions.map(({ session }) => session.sessionId), maxScannedTs, Math.max(blockedSessions.length, hitSessionReadCap ? capPerSession + 1 : 0), true);
|
|
37650
|
+
} else {
|
|
37651
|
+
maxScannedTs = Math.max(scanSinceMs, firstUnreadTs - 1);
|
|
37652
|
+
}
|
|
37653
|
+
} else if (oldestBySession && allSince.length === 0) {
|
|
37654
|
+
for (const { session } of eligibleSessions) {
|
|
37655
|
+
maxScannedTs = Math.max(maxScannedTs, session.updatedAt ?? scanSinceMs);
|
|
37656
|
+
}
|
|
37591
37657
|
}
|
|
37592
37658
|
}
|
|
37593
|
-
for (const row of keptSince) {
|
|
37594
|
-
if (row.ts > maxScannedTs)
|
|
37595
|
-
maxScannedTs = row.ts;
|
|
37596
|
-
}
|
|
37597
|
-
let frontier = saturatedFrontier;
|
|
37598
|
-
const firstDropped = droppedSince[0];
|
|
37599
|
-
if (firstDropped)
|
|
37600
|
-
frontier = Math.min(frontier, firstDropped.ts - 1);
|
|
37601
|
-
if (typeof firstExcludedPendingTs === "number") {
|
|
37602
|
-
frontier = Math.min(frontier, firstExcludedPendingTs - 1);
|
|
37603
|
-
} else if (typeof firstExcludedSession?.updatedAt === "number") {
|
|
37604
|
-
frontier = Math.min(frontier, firstExcludedSession.updatedAt - 1);
|
|
37605
|
-
}
|
|
37606
|
-
maxScannedTs = Math.max(scanSinceMs, Math.min(maxScannedTs, frontier));
|
|
37607
37659
|
const keptSessionIds = new Set(keptSince.map((message) => message.sessionId));
|
|
37608
37660
|
const overlapSessions = sessionsToRead.filter((session) => keptSessionIds.has(session.sessionId));
|
|
37609
37661
|
const overlapBatches = overlapUserCount > 0 && watermarkMs > 0 && watermarkMs >= recencyCutoffMs ? await Promise.all(overlapSessions.map((session) => provider.readUserMessagesBefore(session.sessionId, watermarkMs, overlapUserCount))) : [];
|
|
37610
37662
|
const seen = new Set;
|
|
37611
|
-
const merged = [];
|
|
37663
|
+
const merged = [...keptSince];
|
|
37612
37664
|
const appendUnique = (row) => {
|
|
37613
37665
|
const key = `${row.sessionId}\x00${row.ts}\x00${row.role}\x00${row.toolName ?? ""}`;
|
|
37614
37666
|
if (seen.has(key))
|
|
@@ -37617,9 +37669,7 @@ async function readRetrospectiveScanWindow(provider, projectIdentity, watermarkM
|
|
|
37617
37669
|
merged.push(row);
|
|
37618
37670
|
return true;
|
|
37619
37671
|
};
|
|
37620
|
-
|
|
37621
|
-
appendUnique(row);
|
|
37622
|
-
const overlapRows = overlapBatches.flat().filter((message) => message.ts >= recencyCutoffMs).map(clampRetrospectiveMessage).sort((a, b) => a.ts - b.ts || a.ordinal - b.ordinal);
|
|
37672
|
+
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);
|
|
37623
37673
|
for (const row of overlapRows) {
|
|
37624
37674
|
const beforeLength = merged.length;
|
|
37625
37675
|
if (!appendUnique(row))
|
|
@@ -37639,7 +37689,7 @@ async function readRetrospectiveScanWindow(provider, projectIdentity, watermarkM
|
|
|
37639
37689
|
maxScannedTs,
|
|
37640
37690
|
promptTokens,
|
|
37641
37691
|
...promptInputLimitTokens === undefined ? {} : { promptInputLimitTokens },
|
|
37642
|
-
budgetTruncated
|
|
37692
|
+
budgetTruncated
|
|
37643
37693
|
};
|
|
37644
37694
|
} finally {
|
|
37645
37695
|
provider.dispose?.();
|
|
@@ -37672,7 +37722,12 @@ function readOpenCodeMessagesSince(db, sessionId, sinceMs, capPerSession) {
|
|
|
37672
37722
|
LIMIT ?`).all(sessionId, sinceMs, limit + 1);
|
|
37673
37723
|
const truncated = rows.length > limit;
|
|
37674
37724
|
const kept = truncated ? rows.slice(0, limit) : rows;
|
|
37675
|
-
|
|
37725
|
+
const firstOmitted = rows[limit];
|
|
37726
|
+
return {
|
|
37727
|
+
messages: normalizeOpenCodeRows(db, sessionId, kept),
|
|
37728
|
+
truncated,
|
|
37729
|
+
...firstOmitted ? { firstOmittedTs: firstOmitted.time_created } : {}
|
|
37730
|
+
};
|
|
37676
37731
|
}
|
|
37677
37732
|
function readOpenCodeOldestMessageTimesSince(db, sessionIds, sinceMs) {
|
|
37678
37733
|
const result = new Map;
|
|
@@ -37900,7 +37955,7 @@ function insertDreamRun(db, run) {
|
|
|
37900
37955
|
}
|
|
37901
37956
|
|
|
37902
37957
|
// src/features/magic-context/dreamer/verify.ts
|
|
37903
|
-
import { createHash as
|
|
37958
|
+
import { createHash as createHash16 } from "node:crypto";
|
|
37904
37959
|
|
|
37905
37960
|
// src/features/magic-context/dreamer/verify-diff.ts
|
|
37906
37961
|
import { execFile as execFile3 } from "node:child_process";
|
|
@@ -38024,7 +38079,7 @@ Read only these changed line ranges if they may affect the claim.`
|
|
|
38024
38079
|
import path6 from "node:path";
|
|
38025
38080
|
|
|
38026
38081
|
// src/features/magic-context/dreamer/verify-state.ts
|
|
38027
|
-
import { createHash as
|
|
38082
|
+
import { createHash as createHash15 } from "node:crypto";
|
|
38028
38083
|
import { readFile, realpath as realpath2 } from "node:fs/promises";
|
|
38029
38084
|
import path5 from "node:path";
|
|
38030
38085
|
function verificationMetadata(memory) {
|
|
@@ -38037,7 +38092,7 @@ function verificationMetadata(memory) {
|
|
|
38037
38092
|
}
|
|
38038
38093
|
async function verificationFilesFingerprint(directory, files) {
|
|
38039
38094
|
const root = await resolveGitTopLevel(directory) ?? path5.resolve(directory);
|
|
38040
|
-
const hash =
|
|
38095
|
+
const hash = createHash15("sha256");
|
|
38041
38096
|
for (const file of [...new Set(files)].sort()) {
|
|
38042
38097
|
const absolute = path5.resolve(root, file);
|
|
38043
38098
|
const withinRoot = (candidate) => {
|
|
@@ -38050,7 +38105,7 @@ async function verificationFilesFingerprint(directory, files) {
|
|
|
38050
38105
|
try {
|
|
38051
38106
|
if (!withinRoot(await realpath2(absolute)))
|
|
38052
38107
|
return null;
|
|
38053
|
-
hash.update(
|
|
38108
|
+
hash.update(createHash15("sha256").update(await readFile(absolute)).digest("hex"));
|
|
38054
38109
|
} catch (error) {
|
|
38055
38110
|
if (error.code !== "ENOENT")
|
|
38056
38111
|
return null;
|
|
@@ -38855,7 +38910,7 @@ async function applyParsedVerifyManifest(args, batch, parsed, headAtPrompt, budg
|
|
|
38855
38910
|
name: "memory.set_verification",
|
|
38856
38911
|
arguments: {
|
|
38857
38912
|
memory_project: args.projectIdentity,
|
|
38858
|
-
command_id: `${args.moduleRoute.moduleCommandId}:${
|
|
38913
|
+
command_id: `${args.moduleRoute.moduleCommandId}:${createHash16("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
|
|
38859
38914
|
rows
|
|
38860
38915
|
}
|
|
38861
38916
|
}
|
|
@@ -39769,7 +39824,7 @@ function parseFrictionGateVerdict(verdict) {
|
|
|
39769
39824
|
}
|
|
39770
39825
|
function computeRetrospectiveWindowKey(flagged) {
|
|
39771
39826
|
const anchors = flagged.map((message) => `${message.sessionId}:${message.ts}`).sort().join("|");
|
|
39772
|
-
return
|
|
39827
|
+
return createHash17("sha256").update(anchors).digest("hex").slice(0, 32);
|
|
39773
39828
|
}
|
|
39774
39829
|
function renderFrictionWindow(messages, flaggedOrdinals, radius = 2) {
|
|
39775
39830
|
const flagged = new Set(flaggedOrdinals);
|
|
@@ -39888,6 +39943,13 @@ async function runRetrospectiveTask(config, ctx, helpers) {
|
|
|
39888
39943
|
const recencyDays = Math.max(1, Math.floor(config.retrospectiveRecencyDays ?? 30));
|
|
39889
39944
|
const recencyCutoffMs = helpers.invocationStartedAt - recencyDays * RETROSPECTIVE_DAY_MS;
|
|
39890
39945
|
const scan = await readRetrospectiveScanWindow(provider, projectIdentity, watermarkMs, RETROSPECTIVE_OVERLAP_USER_LINES, { usableInputTokens, recencyCutoffMs });
|
|
39946
|
+
ctx.onRetrospectiveScan?.({
|
|
39947
|
+
watermarkMs,
|
|
39948
|
+
maxScannedTs: scan.maxScannedTs,
|
|
39949
|
+
usableInputTokens,
|
|
39950
|
+
recencyCutoffMs,
|
|
39951
|
+
budgetTruncated: scan.budgetTruncated
|
|
39952
|
+
});
|
|
39891
39953
|
const clearedTaskStateJson = activeOverflow ? writeRetrospectiveOverflowState(taskState.root, null) : undefined;
|
|
39892
39954
|
const completedWindow = (retrospectiveWatermarkMs, noOpReason) => ({
|
|
39893
39955
|
retrospectiveWatermarkMs,
|
|
@@ -40675,6 +40737,7 @@ async function runDomainGroup(deps, group, cb) {
|
|
|
40675
40737
|
}
|
|
40676
40738
|
}
|
|
40677
40739
|
let outcome;
|
|
40740
|
+
const diagnostics = {};
|
|
40678
40741
|
const startedAt = Date.now();
|
|
40679
40742
|
try {
|
|
40680
40743
|
outcome = await executor(due.config, {
|
|
@@ -40682,7 +40745,12 @@ async function runDomainGroup(deps, group, cb) {
|
|
|
40682
40745
|
projectIdentity,
|
|
40683
40746
|
holderId,
|
|
40684
40747
|
leaseKey,
|
|
40685
|
-
leaseAcquisition: acquisition
|
|
40748
|
+
leaseAcquisition: acquisition,
|
|
40749
|
+
...due.config.task === "retrospective" ? {
|
|
40750
|
+
onRetrospectiveScan: (scan) => {
|
|
40751
|
+
diagnostics.retrospectiveScan = scan;
|
|
40752
|
+
}
|
|
40753
|
+
} : {}
|
|
40686
40754
|
});
|
|
40687
40755
|
} catch (error) {
|
|
40688
40756
|
outcome = { status: "failed", transient: true, error: String(error) };
|
|
@@ -40693,6 +40761,11 @@ async function runDomainGroup(deps, group, cb) {
|
|
|
40693
40761
|
cb?.onSkipped?.(due.config.task, outcome.detail);
|
|
40694
40762
|
} else if (outcome.status === "completed") {
|
|
40695
40763
|
advanceAfterRun(db, projectIdentity, due, finishedAt, "completed", null, outcome.schedulePatch, startedAt);
|
|
40764
|
+
const scan = diagnostics.retrospectiveScan;
|
|
40765
|
+
if (scan) {
|
|
40766
|
+
const stored = readRetrospectiveWatermark(db, projectIdentity, due.config.task);
|
|
40767
|
+
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 });
|
|
40768
|
+
}
|
|
40696
40769
|
cb?.onRan?.(due.config.task, outcome.detail, outcome.backlog);
|
|
40697
40770
|
} else if (outcome.transient) {
|
|
40698
40771
|
recordTransientFailure(db, projectIdentity, due, finishedAt, outcome.error ?? null, outcome.schedulePatch);
|
|
@@ -40876,7 +40949,12 @@ class V2RetrospectiveRawProvider {
|
|
|
40876
40949
|
readUserMessagesSince(sessionId, sinceMs, capPerSession) {
|
|
40877
40950
|
const cap = Math.max(1, Math.min(9999, Math.floor(capPerSession)));
|
|
40878
40951
|
const rows = this.read(sessionId, sinceMs, cap + 1);
|
|
40879
|
-
|
|
40952
|
+
const firstOmitted = rows[cap];
|
|
40953
|
+
return {
|
|
40954
|
+
messages: rows.slice(0, cap),
|
|
40955
|
+
truncated: rows.length > cap,
|
|
40956
|
+
...firstOmitted ? { firstOmittedTs: firstOmitted.ts } : {}
|
|
40957
|
+
};
|
|
40880
40958
|
}
|
|
40881
40959
|
readUserMessagesBefore(sessionId, beforeMs, count) {
|
|
40882
40960
|
return this.read(sessionId, beforeMs, Math.max(1, Math.min(1e4, Math.floor(count))), true).reverse().filter((row) => hasMeaningfulUserText2([{ type: "text", text: row.text }]));
|
|
@@ -41779,10 +41857,10 @@ function readForkHistoryGap(db, openReader, sessionID) {
|
|
|
41779
41857
|
}
|
|
41780
41858
|
|
|
41781
41859
|
// src/v2/hooks/generate.ts
|
|
41782
|
-
import { createHash as
|
|
41860
|
+
import { createHash as createHash18 } from "node:crypto";
|
|
41783
41861
|
var typedArrayName = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get;
|
|
41784
41862
|
function hostPrefixDigest(messages, end) {
|
|
41785
|
-
const hash =
|
|
41863
|
+
const hash = createHash18("sha256");
|
|
41786
41864
|
const chunks = [];
|
|
41787
41865
|
let pendingCodeUnits = 0;
|
|
41788
41866
|
const batchCodeUnits = 16 * 1024 * 1024;
|
|
@@ -41981,9 +42059,9 @@ function hiddenTerminalError(event) {
|
|
|
41981
42059
|
}
|
|
41982
42060
|
|
|
41983
42061
|
// src/v2/hooks/lkg-system.ts
|
|
41984
|
-
import { createHash as
|
|
42062
|
+
import { createHash as createHash19 } from "node:crypto";
|
|
41985
42063
|
function identity2(slot) {
|
|
41986
|
-
return
|
|
42064
|
+
return createHash19("sha256").update(JSON.stringify({
|
|
41987
42065
|
capturedAt: slot.capturedAt,
|
|
41988
42066
|
captureSequence: slot.captureSequence,
|
|
41989
42067
|
rowVersion: slot.rowVersion,
|
|
@@ -56270,7 +56348,7 @@ function formatCtxReduceReply(stampedCount, selfStampCount = 0) {
|
|
|
56270
56348
|
return parts.join(" ");
|
|
56271
56349
|
}
|
|
56272
56350
|
// src/tools/ctx-reduce/tools.ts
|
|
56273
|
-
import { createHash as
|
|
56351
|
+
import { createHash as createHash20 } from "node:crypto";
|
|
56274
56352
|
|
|
56275
56353
|
// src/features/magic-context/range-parser.ts
|
|
56276
56354
|
function parseRangeString(input) {
|
|
@@ -56333,11 +56411,11 @@ function createCtxReduceTool(deps) {
|
|
|
56333
56411
|
const stableId = `oc-${sessionId}-${callId}`;
|
|
56334
56412
|
if (Buffer.byteLength(stableId) <= 128)
|
|
56335
56413
|
return stableId;
|
|
56336
|
-
return `oc-${
|
|
56414
|
+
return `oc-${createHash20("sha256").update(stableId).digest("hex")}`;
|
|
56337
56415
|
}
|
|
56338
56416
|
fallbackCommandSequence += 1;
|
|
56339
56417
|
const monotonicId = `oc-${sessionId}-${fallbackCommandSequence}`;
|
|
56340
|
-
return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${
|
|
56418
|
+
return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash20("sha256").update(monotonicId).digest("hex")}`;
|
|
56341
56419
|
};
|
|
56342
56420
|
return tool({
|
|
56343
56421
|
description: CTX_REDUCE_DESCRIPTION,
|