@cortexkit/opencode-magic-context 0.49.87 → 0.49.90
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/{announcement-fnyxaahs.js → announcement-4ynkaf0d.js} +2 -2
- package/dist/auto-search-worker.js +3 -3
- package/dist/chunk-embedding-write-worker.js +5 -5
- package/dist/{context-gnk68pyy.js → context-cdds0gjj.js} +219 -41
- package/dist/{derive-budgets-90869322.js → derive-budgets-hzzq71rm.js} +2 -2
- package/dist/{embedding-backfill-9khxv6a9.js → embedding-backfill-qjkaee9s.js} +6 -6
- package/dist/embedding-worker.js +2 -2
- package/dist/features/magic-context/storage-db.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-partial-recomp.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-recomp-carry.d.ts +4 -0
- package/dist/hooks/magic-context/compartment-runner-recomp-carry.d.ts.map +1 -0
- package/dist/hooks/magic-context/compartment-runner-recomp.d.ts +8 -2
- package/dist/hooks/magic-context/compartment-runner-recomp.d.ts.map +1 -1
- package/dist/hooks/magic-context/history-boundary-repair.d.ts +2 -0
- package/dist/hooks/magic-context/history-boundary-repair.d.ts.map +1 -1
- package/dist/hooks/magic-context/recomp-orchestrator.d.ts +3 -5
- package/dist/hooks/magic-context/recomp-orchestrator.d.ts.map +1 -1
- package/dist/{index-watde7a1.js → index-2pdgy88n.js} +3 -3
- package/dist/{index-c1s40xmj.js → index-39rzef89.js} +7 -5
- package/dist/{index-c5tmzym6.js → index-5df2fw5b.js} +108 -13
- package/dist/{index-7svecf3m.js → index-5pgyqgmx.js} +1 -1
- package/dist/{index-k50xhjw1.js → index-60x5d68t.js} +1 -1
- package/dist/{index-jka4y6mv.js → index-61knrt52.js} +1 -1
- package/dist/{index-74sh122g.js → index-9d3qgwq0.js} +1 -1
- package/dist/{index-2kf73btc.js → index-cr483vx6.js} +1 -1
- package/dist/{index-5nmqgvz2.js → index-dk3hy2a2.js} +6 -6
- package/dist/{index-awyqqnd8.js → index-g0mb2kb4.js} +6 -6
- package/dist/{index-kmrv1fw3.js → index-h9hybzr5.js} +2 -2
- package/dist/{index-vyfrgwhk.js → index-jzfsnbmm.js} +2 -2
- package/dist/{index-rvf1726x.js → index-mrjat4eq.js} +75 -12
- package/dist/{index-b364vr04.js → index-n1ty0vd3.js} +22 -22
- package/dist/{index-csztadkj.js → index-q7msfgwz.js} +272 -101
- package/dist/{index-pmcvg3k1.js → index-qfcjrnpe.js} +6 -5
- package/dist/{index-3dtzyred.js → index-r4y0dczp.js} +1 -1
- package/dist/{index-bxrfq3mv.js → index-tt0vs4x5.js} +1 -1
- package/dist/{index-3x4qvp29.js → index-w51n3576.js} +1 -1
- package/dist/{index-3jgzd7nz.js → index-wmb2mcdw.js} +3 -3
- package/dist/{index-zmqx48vt.js → index-xsqw8kbd.js} +1 -1
- package/dist/{index-hdyfvdag.js → index-zxhev8ze.js} +1 -1
- package/dist/index.js +26 -26
- package/dist/migration-worker.js +4 -4
- package/dist/{project-embedding-registry-8t0gwf59.js → project-embedding-registry-m3fp1pa4.js} +5 -5
- package/dist/raw-ordinal-warmup-worker.js +2 -2
- package/dist/{recomp-orchestrator-2ztmtxt2.js → recomp-orchestrator-dgyb394j.js} +14 -14
- package/dist/{render-d6q6h9hy.js → render-d014e603.js} +6 -6
- package/dist/{search-d5aajhs3.js → search-9gceftb9.js} +11 -11
- package/dist/{search-archive-g96jn6p0.js → search-archive-gybn6q7s.js} +2 -2
- package/dist/shared/recomp-outcome.d.ts +4 -0
- package/dist/shared/recomp-outcome.d.ts.map +1 -0
- package/dist/shared/storage-permissions.d.ts +16 -2
- package/dist/shared/storage-permissions.d.ts.map +1 -1
- package/dist/shared/user-facing-codes.d.ts +4 -1
- package/dist/shared/user-facing-codes.d.ts.map +1 -1
- package/dist/{transform-postprocess-phase-b2yjw8by.js → transform-postprocess-phase-34k1zwsy.js} +15 -15
- package/dist/v2/auto-search-worker.js +3 -3
- package/dist/v2/chunk-embedding-write-worker.js +5 -5
- package/dist/v2/{context-s86114yy.js → context-satgm752.js} +218 -41
- package/dist/v2/{derive-budgets-ecjy1aqh.js → derive-budgets-hr4qqrnv.js} +3 -3
- package/dist/v2/{embedding-backfill-tazkbpyg.js → embedding-backfill-0ar1bm97.js} +6 -6
- package/dist/v2/embedding-worker.js +2 -2
- package/dist/v2/fold/native-replay.d.ts +11 -2
- package/dist/v2/fold/native-replay.d.ts.map +1 -1
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/revert-message-state.d.ts +19 -1
- package/dist/v2/hooks/revert-message-state.d.ts.map +1 -1
- package/dist/v2/migration-worker.js +4 -4
- package/dist/v2/{project-embedding-registry-ah3gsg48.js → project-embedding-registry-gx2waee8.js} +5 -5
- package/dist/v2/raw-ordinal-warmup-worker.js +2 -2
- package/dist/v2/{recomp-orchestrator-kc62xgb9.js → recomp-orchestrator-wq7gbkqa.js} +15 -15
- package/dist/v2/{render-j05per51.js → render-2dan17xc.js} +6 -6
- package/dist/v2/{search-archive-b4ptw02k.js → search-archive-89hdy0a2.js} +2 -2
- package/dist/v2/{search-kg31ad2s.js → search-nyqykx7q.js} +10 -10
- package/dist/v2/{server-ct0gs8fc.js → server-09h2vyvs.js} +2 -2
- package/dist/v2/{server-r2es6zt7.js → server-0tv6kytx.js} +108 -13
- package/dist/v2/{server-rz4snd3x.js → server-1rrmxhd1.js} +1 -1
- package/dist/v2/{server-xa8fefhw.js → server-96nm9vk4.js} +1 -1
- package/dist/v2/{server-2p0qayr1.js → server-a85j3kam.js} +1 -1
- package/dist/v2/{server-gwhj0362.js → server-add0j5n3.js} +7 -5
- package/dist/v2/{server-ff5wcfy4.js → server-b0a9h3ds.js} +2 -2
- package/dist/v2/{server-xn7zqs4j.js → server-dgjqvpgd.js} +3 -3
- package/dist/v2/{server-2r9btf0g.js → server-dtcwkdqj.js} +274 -103
- package/dist/v2/{server-axdmkvd5.js → server-f7tzvmzs.js} +1 -1
- package/dist/v2/{server-yh2z4gg2.js → server-fb5hvvfc.js} +75 -12
- package/dist/v2/{server-pbp58w5x.js → server-fn4ky6mn.js} +1 -1
- package/dist/v2/{server-3p6b0qya.js → server-gqkdfdvw.js} +1 -1
- package/dist/v2/{server-cwtehwbb.js → server-j4jjtdc5.js} +1 -1
- package/dist/v2/{server-b93f0bqh.js → server-pjk9spbf.js} +1 -1
- package/dist/v2/{server-gqrw0br5.js → server-ta4h0fch.js} +6 -6
- package/dist/v2/{server-e2k9mt86.js → server-tj65pgvg.js} +1 -1
- package/dist/v2/{server-6vnbz81n.js → server-vy0beygw.js} +1 -1
- package/dist/v2/server.js +5 -5
- package/dist/v2/{v2-archive-reader-2ayz16s4.js → v2-archive-reader-gh1jghf7.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-e20sjbdz.js → wrapup-orchestrator-2h7ayss9.js} +15 -15
- package/dist/{v2-archive-reader-x39mzvwn.js → v2-archive-reader-8158kyfd.js} +1 -1
- package/dist/{wrapup-orchestrator-h3s905vs.js → wrapup-orchestrator-ct59br0c.js} +15 -15
- package/package.json +1 -1
- package/src/shared/recomp-outcome.ts +8 -0
- package/src/shared/storage-permissions-startup.test.ts +296 -6
- package/src/shared/storage-permissions.ts +143 -18
- package/src/shared/user-facing-codes.ts +5 -2
- package/src/tui/dialogs/status-dialog.tsx +3 -0
- package/src/tui/slots/sidebar-content.tsx +6 -2
- package/src/tui-compiled/dialogs/status-dialog.tsx +12 -0
- package/src/tui-compiled/slots/sidebar-content.tsx +7 -2
|
@@ -64,7 +64,7 @@ import {
|
|
|
64
64
|
import {
|
|
65
65
|
ensureStorageDirectorySync,
|
|
66
66
|
writeStorageFileAtomicSync
|
|
67
|
-
} from "./index-
|
|
67
|
+
} from "./index-5df2fw5b.js";
|
|
68
68
|
import {
|
|
69
69
|
catalogOutputReserve,
|
|
70
70
|
setOutputReserveConfig,
|
|
@@ -74,7 +74,7 @@ import {
|
|
|
74
74
|
deriveTriggerBudget2,
|
|
75
75
|
resolveHistorianProducerLimits2,
|
|
76
76
|
producerSourceLocalBudget2
|
|
77
|
-
} from "./index-
|
|
77
|
+
} from "./index-xsqw8kbd.js";
|
|
78
78
|
import {
|
|
79
79
|
withContentLanguageDirective,
|
|
80
80
|
buildPrimaryLanguageDirective,
|
|
@@ -111,13 +111,13 @@ import {
|
|
|
111
111
|
import {
|
|
112
112
|
shouldSkipHomeProjectMemory,
|
|
113
113
|
resolveProjectIdentity
|
|
114
|
-
} from "./index-
|
|
114
|
+
} from "./index-5pgyqgmx.js";
|
|
115
115
|
import {
|
|
116
116
|
getSchemaFenceRejection,
|
|
117
117
|
LATEST_SUPPORTED_VERSION,
|
|
118
118
|
getPersistedSchemaVersion,
|
|
119
119
|
openDatabase
|
|
120
|
-
} from "./index-
|
|
120
|
+
} from "./index-mrjat4eq.js";
|
|
121
121
|
import {
|
|
122
122
|
areRustHistorianSyntheticParts2,
|
|
123
123
|
isStrictGapHealingMessage2,
|
|
@@ -134,7 +134,7 @@ import {
|
|
|
134
134
|
resolveStoredPathWorkspaceIdentity,
|
|
135
135
|
sourceNameForMemory,
|
|
136
136
|
computeWorkspaceEpochFingerprint
|
|
137
|
-
} from "./index-
|
|
137
|
+
} from "./index-tt0vs4x5.js";
|
|
138
138
|
import {
|
|
139
139
|
BoundedSessionMap
|
|
140
140
|
} from "./index-m6dnydf8.js";
|
|
@@ -206,7 +206,7 @@ import {
|
|
|
206
206
|
getProjectState,
|
|
207
207
|
recordSubagentInvocation,
|
|
208
208
|
getLatestHistorianInvocationId
|
|
209
|
-
} from "./index-
|
|
209
|
+
} from "./index-h9hybzr5.js";
|
|
210
210
|
import {
|
|
211
211
|
clearCompressionDepth,
|
|
212
212
|
clearCompressionDepthRange,
|
|
@@ -273,7 +273,7 @@ import {
|
|
|
273
273
|
getSessionNotes,
|
|
274
274
|
getReadySmartNotes,
|
|
275
275
|
insertPrimerCandidates
|
|
276
|
-
} from "./index-
|
|
276
|
+
} from "./index-61knrt52.js";
|
|
277
277
|
import {
|
|
278
278
|
pushNotification2
|
|
279
279
|
} from "./index-y14pawe1.js";
|
|
@@ -291,13 +291,13 @@ import {
|
|
|
291
291
|
getProjectChunkEmbeddingModelId2,
|
|
292
292
|
getProjectEmbeddingMaxInputTokens2,
|
|
293
293
|
embedItemsWindowBounded2
|
|
294
|
-
} from "./index-
|
|
294
|
+
} from "./index-2pdgy88n.js";
|
|
295
295
|
import {
|
|
296
296
|
renderUserFacingFailure,
|
|
297
297
|
userFacingFailureCode,
|
|
298
298
|
promoteSessionFactsDurable,
|
|
299
299
|
embedPromotedFacts
|
|
300
|
-
} from "./index-
|
|
300
|
+
} from "./index-39rzef89.js";
|
|
301
301
|
import {
|
|
302
302
|
isMarkerCandidateBasisCurrent2,
|
|
303
303
|
invalidateMarkerCandidateBasis2,
|
|
@@ -15425,6 +15425,16 @@ function sanitizeDumpName(value) {
|
|
|
15425
15425
|
return value.replace(/[^a-zA-Z0-9._-]/g, "-");
|
|
15426
15426
|
}
|
|
15427
15427
|
|
|
15428
|
+
// src/shared/recomp-outcome.ts
|
|
15429
|
+
var RECOMP_PAUSED_HEADING = "## Magic Recomp — Paused";
|
|
15430
|
+
function pausedRecompReason(message) {
|
|
15431
|
+
const prefix = `${RECOMP_PAUSED_HEADING}
|
|
15432
|
+
`;
|
|
15433
|
+
if (!message?.startsWith(prefix))
|
|
15434
|
+
return null;
|
|
15435
|
+
return message.slice(prefix.length).replace(/\s+/g, " ").trim();
|
|
15436
|
+
}
|
|
15437
|
+
|
|
15428
15438
|
// src/features/magic-context/compartment-embedding.ts
|
|
15429
15439
|
async function embedAndStoreCompartmentChunks(db, sessionId, projectPath, compartments) {
|
|
15430
15440
|
if (compartments.length === 0)
|
|
@@ -18546,15 +18556,44 @@ ${chunkText}`,
|
|
|
18546
18556
|
}
|
|
18547
18557
|
}
|
|
18548
18558
|
|
|
18559
|
+
// src/hooks/magic-context/compartment-runner-recomp-carry.ts
|
|
18560
|
+
function compartmentToInput(c, sequence) {
|
|
18561
|
+
return {
|
|
18562
|
+
sequence,
|
|
18563
|
+
startMessage: c.startMessage,
|
|
18564
|
+
endMessage: c.endMessage,
|
|
18565
|
+
startMessageId: c.startMessageId,
|
|
18566
|
+
endMessageId: c.endMessageId,
|
|
18567
|
+
startBlockIndex: c.startBlockIndex,
|
|
18568
|
+
endBlockIndex: c.endBlockIndex,
|
|
18569
|
+
title: c.title,
|
|
18570
|
+
content: c.content,
|
|
18571
|
+
p1: c.p1,
|
|
18572
|
+
p2: c.p2,
|
|
18573
|
+
p3: c.p3,
|
|
18574
|
+
p4: c.p4,
|
|
18575
|
+
importance: c.importance,
|
|
18576
|
+
episodeType: c.episodeType
|
|
18577
|
+
};
|
|
18578
|
+
}
|
|
18579
|
+
|
|
18549
18580
|
// src/hooks/magic-context/compartment-runner-recomp.ts
|
|
18550
|
-
function insertRecompCompartmentRows(db, sessionId, compartments, now) {
|
|
18551
|
-
const stmt = db.prepare(
|
|
18581
|
+
function insertRecompCompartmentRows(db, sessionId, compartments, now, carriedRows) {
|
|
18582
|
+
const stmt = db.prepare(`INSERT INTO compartments (session_id, sequence, start_message, end_message,
|
|
18583
|
+
start_message_id, end_message_id, title, content, p1, p2, p3, p4, importance,
|
|
18584
|
+
episode_type, legacy, created_at, harness, start_block_index, end_block_index, rebase_status)
|
|
18585
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
18552
18586
|
for (const c of compartments) {
|
|
18553
18587
|
const hasTiers = typeof c.p1 === "string" && c.p1.length > 0;
|
|
18554
|
-
|
|
18588
|
+
const carried = carriedRows?.get(c.sequence);
|
|
18589
|
+
stmt.run(sessionId, c.sequence, c.startMessage, c.endMessage, c.startMessageId, c.endMessageId, c.title, c.content, c.p1 ?? null, c.p2 ?? null, c.p3 ?? null, c.p4 ?? null, typeof c.importance === "number" ? c.importance : 50, c.episodeType ?? null, carried?.legacy ?? (hasTiers ? 0 : 1), now, getHarness2(), c.startBlockIndex ?? null, c.endBlockIndex ?? null, carried?.rebaseStatus ?? "ok");
|
|
18555
18590
|
}
|
|
18556
18591
|
}
|
|
18557
|
-
function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
|
|
18592
|
+
function promoteRecompStagingWithM0Mutation(db, sessionId, holderId, carriedRows) {
|
|
18593
|
+
const promoted = promoteRecompStaging(db, sessionId, holderId, undefined, carriedRows);
|
|
18594
|
+
return typeof promoted === "string" ? null : promoted;
|
|
18595
|
+
}
|
|
18596
|
+
function promoteRecompStaging(db, sessionId, holderId, stopped, carriedRows) {
|
|
18558
18597
|
const now = Date.now();
|
|
18559
18598
|
db.exec("BEGIN IMMEDIATE");
|
|
18560
18599
|
const transactionStartedAt = performance.now();
|
|
@@ -18563,18 +18602,40 @@ function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
|
|
|
18563
18602
|
if (!isCompartmentLeaseHeld(db, sessionId, holderId)) {
|
|
18564
18603
|
db.exec("ROLLBACK");
|
|
18565
18604
|
finished = true;
|
|
18566
|
-
return
|
|
18605
|
+
return "lease-lost";
|
|
18567
18606
|
}
|
|
18568
18607
|
const staging = getRecompStaging(db, sessionId);
|
|
18569
|
-
|
|
18608
|
+
const staged = staging?.compartments.at(-1);
|
|
18609
|
+
if (!staging || !staged) {
|
|
18570
18610
|
db.exec("ROLLBACK");
|
|
18571
18611
|
finished = true;
|
|
18572
|
-
return
|
|
18612
|
+
return "staging-removed";
|
|
18613
|
+
}
|
|
18614
|
+
let carried = null;
|
|
18615
|
+
if (stopped) {
|
|
18616
|
+
const live = readLiveRanges(db, sessionId);
|
|
18617
|
+
const stagedEnd = resolvedOrdinal(sessionId, staged.endMessageId) ?? staged.endMessage;
|
|
18618
|
+
if (live.some((row) => row.end > stagedEnd)) {
|
|
18619
|
+
if (stopped.allowCarry)
|
|
18620
|
+
carried = readAlignedLiveTail(db, sessionId, live, staging, stagedEnd);
|
|
18621
|
+
if (!carried) {
|
|
18622
|
+
if (stopped.discardIfShort) {
|
|
18623
|
+
clearRecompStaging(db, sessionId);
|
|
18624
|
+
db.exec("COMMIT");
|
|
18625
|
+
finished = true;
|
|
18626
|
+
return "discarded";
|
|
18627
|
+
}
|
|
18628
|
+
db.exec("ROLLBACK");
|
|
18629
|
+
finished = true;
|
|
18630
|
+
return "would-shrink";
|
|
18631
|
+
}
|
|
18632
|
+
}
|
|
18573
18633
|
}
|
|
18634
|
+
const compartments = carried ? [...staging.compartments, ...carried.compartments] : staging.compartments;
|
|
18574
18635
|
deleteChunkEmbedBackoffForSession2(db, sessionId);
|
|
18575
18636
|
db.prepare("DELETE FROM compartments WHERE session_id = ?").run(sessionId);
|
|
18576
18637
|
db.prepare("DELETE FROM session_facts WHERE session_id = ?").run(sessionId);
|
|
18577
|
-
insertRecompCompartmentRows(db, sessionId,
|
|
18638
|
+
insertRecompCompartmentRows(db, sessionId, compartments, now, carried?.rows ?? carriedRows);
|
|
18578
18639
|
queueM0Mutation(db, {
|
|
18579
18640
|
sessionId,
|
|
18580
18641
|
mutationType: "recomp_boundary_change",
|
|
@@ -18588,7 +18649,12 @@ function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
|
|
|
18588
18649
|
finished = true;
|
|
18589
18650
|
invalidateAutoEmbedSession(sessionId);
|
|
18590
18651
|
logSlowWriteTransaction("historian-publish:recomp", transactionStartedAt);
|
|
18591
|
-
return {
|
|
18652
|
+
return {
|
|
18653
|
+
compartments,
|
|
18654
|
+
facts: staging.facts,
|
|
18655
|
+
carriedCount: carried?.compartments.length ?? 0,
|
|
18656
|
+
carriedThrough: carried?.end ?? null
|
|
18657
|
+
};
|
|
18592
18658
|
} finally {
|
|
18593
18659
|
if (!finished) {
|
|
18594
18660
|
try {
|
|
@@ -18597,6 +18663,69 @@ function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
|
|
|
18597
18663
|
}
|
|
18598
18664
|
}
|
|
18599
18665
|
}
|
|
18666
|
+
function resolvedOrdinal(sessionId, id) {
|
|
18667
|
+
return id ? readRawSessionMessageOrdinalById2(sessionId, id) : null;
|
|
18668
|
+
}
|
|
18669
|
+
function readLiveRanges(db, sessionId) {
|
|
18670
|
+
const rows = db.prepare(`SELECT sequence, start_message, start_message_id, end_message, end_message_id FROM compartments
|
|
18671
|
+
WHERE session_id = ? ORDER BY sequence`).all(sessionId);
|
|
18672
|
+
return rows.map((row) => {
|
|
18673
|
+
const resolvedEnd = resolvedOrdinal(sessionId, row.end_message_id);
|
|
18674
|
+
return { ...row, end: resolvedEnd ?? row.end_message, resolvedEnd };
|
|
18675
|
+
});
|
|
18676
|
+
}
|
|
18677
|
+
function readAlignedLiveTail(db, sessionId, live, staging, stagedEnd) {
|
|
18678
|
+
let next = 1;
|
|
18679
|
+
let seam;
|
|
18680
|
+
for (const row of live) {
|
|
18681
|
+
const start = resolvedOrdinal(sessionId, row.start_message_id);
|
|
18682
|
+
if ((start ?? row.start_message) !== next || row.end < next)
|
|
18683
|
+
return null;
|
|
18684
|
+
if (seam !== undefined && (start === null || row.resolvedEnd === null))
|
|
18685
|
+
return null;
|
|
18686
|
+
if (row.end === stagedEnd)
|
|
18687
|
+
seam = row.sequence;
|
|
18688
|
+
next = row.end + 1;
|
|
18689
|
+
}
|
|
18690
|
+
if (seam === undefined)
|
|
18691
|
+
return null;
|
|
18692
|
+
const seamSequence = seam;
|
|
18693
|
+
const tail = getCompartments(db, sessionId).filter((row) => row.sequence > seamSequence);
|
|
18694
|
+
if (!tail.length || tail.length !== live.filter((row) => row.sequence > seamSequence).length)
|
|
18695
|
+
return null;
|
|
18696
|
+
return {
|
|
18697
|
+
compartments: tail.map((row, index) => compartmentToInput(row, staging.compartments.length + index)),
|
|
18698
|
+
rows: new Map(tail.map((row, index) => [staging.compartments.length + index, row])),
|
|
18699
|
+
end: next - 1
|
|
18700
|
+
};
|
|
18701
|
+
}
|
|
18702
|
+
function getResumableFullStaging(db, sessionId, rawMessageCount) {
|
|
18703
|
+
const staging = getRecompStaging(db, sessionId);
|
|
18704
|
+
let reason = null;
|
|
18705
|
+
if (getRecompPartialRange(db, sessionId)) {
|
|
18706
|
+
reason = "the staged passes were for a range rebuild";
|
|
18707
|
+
} else if (staging) {
|
|
18708
|
+
reason = validateStoredCompartments(staging.compartments);
|
|
18709
|
+
if (!reason) {
|
|
18710
|
+
const ordinals = readRawSessionMessageIdOrdinalsForRange2(sessionId, 1, Math.min(rawMessageCount, staging.lastEndMessage));
|
|
18711
|
+
if (staging.compartments.some(({ startMessage, endMessage, startMessageId, endMessageId }) => ordinals.get(startMessageId) !== startMessage || ordinals.get(endMessageId) !== endMessage)) {
|
|
18712
|
+
reason = "staged endpoints no longer match the raw history";
|
|
18713
|
+
}
|
|
18714
|
+
}
|
|
18715
|
+
}
|
|
18716
|
+
if (!reason)
|
|
18717
|
+
return staging;
|
|
18718
|
+
clearRecompStaging(db, sessionId);
|
|
18719
|
+
sessionLog2(sessionId, `recomp discarded staging: ${reason}`);
|
|
18720
|
+
return null;
|
|
18721
|
+
}
|
|
18722
|
+
var PUBLISH_LEASE_LOST = `## Magic Recomp — Skipped
|
|
18723
|
+
|
|
18724
|
+
Another process acquired the compartment-state lease before recomp could publish. No state was written.`;
|
|
18725
|
+
var STAGING_REMOVED = `## Magic Recomp — Failed
|
|
18726
|
+
|
|
18727
|
+
The unfinished rebuild was removed because the session's history changed. Nothing was published.
|
|
18728
|
+
Run /ctx-recomp again.`;
|
|
18600
18729
|
async function executeContextRecompInternal(deps) {
|
|
18601
18730
|
const {
|
|
18602
18731
|
client,
|
|
@@ -18639,6 +18768,12 @@ Session ordinals are warming in the background. Retry shortly; no history was re
|
|
|
18639
18768
|
updateSessionMeta(db, sessionId, { compartmentInProgress: true });
|
|
18640
18769
|
try {
|
|
18641
18770
|
const rawMessageCount = getRawSessionMessageCount2(sessionId);
|
|
18771
|
+
const existingStaging = getResumableFullStaging(db, sessionId, rawMessageCount);
|
|
18772
|
+
if (rawMessageCount <= 0) {
|
|
18773
|
+
return `## Magic Recomp
|
|
18774
|
+
|
|
18775
|
+
No raw history exists, so nothing was rebuilt.`;
|
|
18776
|
+
}
|
|
18642
18777
|
const boundarySnapshot = resolveOpenCodeProtectedTailBoundary({
|
|
18643
18778
|
db,
|
|
18644
18779
|
sessionId,
|
|
@@ -18649,21 +18784,21 @@ Session ordinals are warming in the background. Retry shortly; no history was re
|
|
|
18649
18784
|
usageSource: "provisional-zero"
|
|
18650
18785
|
});
|
|
18651
18786
|
const protectedTailStart = Math.min(boundarySnapshot.protectedTailStart, rawMessageCount + 1);
|
|
18652
|
-
if (
|
|
18653
|
-
return `## Magic Recomp
|
|
18787
|
+
if (!existingStaging && protectedTailStart === 1) {
|
|
18788
|
+
return `## Magic Recomp — Skipped
|
|
18654
18789
|
|
|
18655
|
-
|
|
18790
|
+
Nothing to rebuild yet: every message is still in the recent part that is kept raw.`;
|
|
18656
18791
|
}
|
|
18657
18792
|
const parentSessionResponse = await client?.session.get({ path: { id: sessionId } }).catch(() => null);
|
|
18658
18793
|
const parentSession = normalizeSDKResponse(parentSessionResponse, null, { preferResponseOnMissingData: true });
|
|
18659
18794
|
const sessionDirectory = parentSession?.directory ?? directory;
|
|
18660
|
-
const existingStaging = getRecompStaging(db, sessionId);
|
|
18661
18795
|
let candidateCompartments = existingStaging?.compartments ?? [];
|
|
18662
18796
|
let candidateFacts = existingStaging?.facts ?? [];
|
|
18663
18797
|
let offset = existingStaging ? existingStaging.lastEndMessage + 1 : 1;
|
|
18664
18798
|
let passCount = existingStaging?.passCount ?? 0;
|
|
18665
18799
|
let currentTokenBudget = historianChunkTokens;
|
|
18666
18800
|
let passAttempt = 1;
|
|
18801
|
+
let hadModelFailureOrBudgetReduction = false;
|
|
18667
18802
|
const resumed = existingStaging !== null;
|
|
18668
18803
|
if (resumed) {
|
|
18669
18804
|
await sendStatusNotification2(client, sessionId, `## Magic Recomp — Resumed
|
|
@@ -18688,19 +18823,53 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
|
|
|
18688
18823
|
} catch {}
|
|
18689
18824
|
};
|
|
18690
18825
|
emitProgress("Preparing…");
|
|
18691
|
-
async function promoteAndFinalize(reason) {
|
|
18826
|
+
async function promoteAndFinalize(reason, heading = "Partial", failure = "recomp_unavailable", sentence, deterministicStop = false) {
|
|
18692
18827
|
if (passCount === 0 || candidateCompartments.length === 0)
|
|
18693
18828
|
return null;
|
|
18694
18829
|
const mergedError = validateStoredCompartments(candidateCompartments);
|
|
18695
18830
|
if (mergedError)
|
|
18696
18831
|
return null;
|
|
18697
|
-
saveRecompStagingPass(db, sessionId, passCount, candidateCompartments, candidateFacts);
|
|
18698
18832
|
const lastCompartmentEnd = candidateCompartments[candidateCompartments.length - 1]?.endMessage ?? 0;
|
|
18699
18833
|
const compartmentTagKeys = lastCompartmentEnd > 0 ? await getRawSessionTagKeysThrough2(sessionId, lastCompartmentEnd, { db }) : null;
|
|
18700
|
-
const promoted =
|
|
18701
|
-
|
|
18702
|
-
|
|
18703
|
-
|
|
18834
|
+
const promoted = promoteRecompStaging(db, sessionId, leaseHolderId, {
|
|
18835
|
+
allowCarry: heading === "Complete",
|
|
18836
|
+
discardIfShort: deterministicStop && passAttempt === 1 && !hadModelFailureOrBudgetReduction && resumed && passCount === existingStaging.passCount
|
|
18837
|
+
});
|
|
18838
|
+
if (promoted === "would-shrink" || promoted === "discarded") {
|
|
18839
|
+
const detail = renderUserFacingFailure(failure, "markdown", {
|
|
18840
|
+
sentence,
|
|
18841
|
+
...failure !== "historian_window_too_small" ? { action: "" } : {}
|
|
18842
|
+
});
|
|
18843
|
+
if (promoted === "discarded") {
|
|
18844
|
+
return [
|
|
18845
|
+
"## Magic Recomp — Failed",
|
|
18846
|
+
"",
|
|
18847
|
+
`The rebuild could not get past message ${offset}. ${detail}`,
|
|
18848
|
+
"The unfinished rebuild was discarded.",
|
|
18849
|
+
"Your current history is unchanged."
|
|
18850
|
+
].join(`
|
|
18851
|
+
`);
|
|
18852
|
+
}
|
|
18853
|
+
const continueFrom = `Run /ctx-recomp again to continue from message ${lastCompartmentEnd + 1}.`;
|
|
18854
|
+
return [
|
|
18855
|
+
RECOMP_PAUSED_HEADING,
|
|
18856
|
+
"",
|
|
18857
|
+
resumed ? `Messages 1-${lastCompartmentEnd} of ${totalMessages} are rebuilt and kept for the next run. ${detail}` : `Rebuilt messages 1-${lastCompartmentEnd} of ${totalMessages}, then stopped. ${detail}`,
|
|
18858
|
+
"Your current history is unchanged.",
|
|
18859
|
+
deterministicStop ? `${continueFrom} If it stops at the same place again, the unfinished rebuild is discarded and your history stays as it is.` : continueFrom
|
|
18860
|
+
].join(`
|
|
18861
|
+
`);
|
|
18862
|
+
}
|
|
18863
|
+
if (promoted === "lease-lost")
|
|
18864
|
+
return PUBLISH_LEASE_LOST;
|
|
18865
|
+
if (promoted === "staging-removed")
|
|
18866
|
+
return STAGING_REMOVED;
|
|
18867
|
+
afterPublish("compression-depth", () => {
|
|
18868
|
+
if (promoted.carriedCount > 0)
|
|
18869
|
+
clearCompressionDepthRange(db, sessionId, 1, lastCompartmentEnd);
|
|
18870
|
+
else
|
|
18871
|
+
clearCompressionDepth(db, sessionId);
|
|
18872
|
+
});
|
|
18704
18873
|
if (deps.preserveInjectionCacheUntilConsumed !== true) {
|
|
18705
18874
|
clearInjectionCache(sessionId);
|
|
18706
18875
|
}
|
|
@@ -18720,9 +18889,10 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
|
|
|
18720
18889
|
afterPublish("drop-queue", () => queueDropsForCompartmentalizedMessages(db, sessionId, lastCompartmentEnd, compartmentTagKeys));
|
|
18721
18890
|
}
|
|
18722
18891
|
afterPublish("publication-signal", () => deps.onCompartmentStatePublished?.(sessionId));
|
|
18723
|
-
|
|
18892
|
+
const publishedEnd = promoted.carriedThrough ?? lastCompartmentEnd;
|
|
18893
|
+
if (publishedEnd > 0) {
|
|
18724
18894
|
afterPublish("compaction-marker", () => {
|
|
18725
|
-
const markerUpdated = (deps.compactionMarkerStrategy?.publish ?? updateCompactionMarkerAfterPublication)(db, sessionId,
|
|
18895
|
+
const markerUpdated = (deps.compactionMarkerStrategy?.publish ?? updateCompactionMarkerAfterPublication)(db, sessionId, publishedEnd, deps.directory);
|
|
18726
18896
|
if (markerUpdated) {
|
|
18727
18897
|
const stalePending = getPendingCompactionMarkerState(db, sessionId);
|
|
18728
18898
|
if (stalePending) {
|
|
@@ -18731,8 +18901,26 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
|
|
|
18731
18901
|
}
|
|
18732
18902
|
});
|
|
18733
18903
|
}
|
|
18904
|
+
const rebuilt = promoted.compartments.length - promoted.carriedCount;
|
|
18905
|
+
const rebuiltThrough = `Rebuilt ${rebuilt} history block${rebuilt === 1 ? "" : "s"} through message ${lastCompartmentEnd}.`;
|
|
18906
|
+
if (promoted.carriedCount > 0) {
|
|
18907
|
+
return [
|
|
18908
|
+
"## Magic Recomp — Complete",
|
|
18909
|
+
"",
|
|
18910
|
+
rebuiltThrough,
|
|
18911
|
+
`Kept ${promoted.carriedCount} existing history block${promoted.carriedCount === 1 ? "" : "s"} through message ${publishedEnd}.`
|
|
18912
|
+
].join(`
|
|
18913
|
+
`);
|
|
18914
|
+
}
|
|
18915
|
+
if (heading === "Complete") {
|
|
18916
|
+
return `## Magic Recomp — Complete
|
|
18917
|
+
|
|
18918
|
+
${rebuiltThrough} Messages ${offset} to ${protectedTailStart - 1} have nothing to summarize and stay as they are.`;
|
|
18919
|
+
}
|
|
18734
18920
|
sessionLog2(sessionId, `recomp partial code=${userFacingFailureCode("recomp_unavailable")} reason="${reason}"`);
|
|
18735
18921
|
return [
|
|
18922
|
+
`## Magic Recomp — ${heading}`,
|
|
18923
|
+
"",
|
|
18736
18924
|
`Rebuilt ${promoted.compartments.length} history block${promoted.compartments.length === 1 ? "" : "s"} across ${passCount} successful pass${passCount === 1 ? "" : "es"}.`,
|
|
18737
18925
|
renderUserFacingFailure("recomp_unavailable")
|
|
18738
18926
|
].join(`
|
|
@@ -18762,12 +18950,9 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
|
|
|
18762
18950
|
compartmentsProduced: 0
|
|
18763
18951
|
});
|
|
18764
18952
|
sessionLog2(sessionId, `recomp failed code=${userFacingFailureCode("historian_window_too_small")} reason="${promptFit.reason}"`);
|
|
18765
|
-
const partial = await promoteAndFinalize(`the history model's window cannot hold a historian prompt: ${promptFit.reason}
|
|
18766
|
-
if (partial)
|
|
18767
|
-
return
|
|
18768
|
-
|
|
18769
|
-
${partial}`;
|
|
18770
|
-
}
|
|
18953
|
+
const partial = await promoteAndFinalize(`the history model's window cannot hold a historian prompt: ${promptFit.reason}`, "Partial", "historian_window_too_small");
|
|
18954
|
+
if (partial)
|
|
18955
|
+
return partial;
|
|
18771
18956
|
return `## Magic Recomp — Failed
|
|
18772
18957
|
|
|
18773
18958
|
${renderUserFacingFailure("historian_window_too_small")}`;
|
|
@@ -18775,26 +18960,22 @@ ${renderUserFacingFailure("historian_window_too_small")}`;
|
|
|
18775
18960
|
if (promptFit.trimmed || promptFit.chunkTokens < currentTokenBudget) {
|
|
18776
18961
|
sessionLog2(sessionId, `recomp prompt fit: ${describeHistorianPromptTrim(promptFit)} requestedChunkTokens=${currentTokenBudget}`);
|
|
18777
18962
|
}
|
|
18963
|
+
if (promptFit.chunkTokens < currentTokenBudget)
|
|
18964
|
+
hadModelFailureOrBudgetReduction = true;
|
|
18778
18965
|
const chunk = readSessionChunk2(sessionId, promptFit.chunkTokens, offset, protectedTailStart, { expandTools: deps.historianExpandTools });
|
|
18779
18966
|
if (!chunk.text || chunk.messageCount === 0 || chunk.endIndex < offset) {
|
|
18780
|
-
const promoted = await promoteAndFinalize(`remaining messages ${offset}-${protectedTailStart - 1} were too few or all noise to form a historian chunk`);
|
|
18781
|
-
if (promoted)
|
|
18782
|
-
return
|
|
18783
|
-
|
|
18784
|
-
${promoted}`;
|
|
18785
|
-
}
|
|
18967
|
+
const promoted = await promoteAndFinalize(`remaining messages ${offset}-${protectedTailStart - 1} were too few or all noise to form a historian chunk`, "Complete", "recomp_unavailable", `Raw history ${offset}-${protectedTailStart - 1} could not be turned into a valid historian chunk.`, true);
|
|
18968
|
+
if (promoted)
|
|
18969
|
+
return promoted;
|
|
18786
18970
|
return `## Magic Recomp — Failed
|
|
18787
18971
|
|
|
18788
18972
|
Recomp stopped because raw history ${offset}-${protectedTailStart - 1} could not be turned into a valid historian chunk. Nothing was written.`;
|
|
18789
18973
|
}
|
|
18790
18974
|
const chunkCoverageError = validateChunkCoverage(chunk);
|
|
18791
18975
|
if (chunkCoverageError) {
|
|
18792
|
-
const partial = await promoteAndFinalize(`chunk could not be represented safely: ${chunkCoverageError}
|
|
18793
|
-
if (partial)
|
|
18794
|
-
return
|
|
18795
|
-
|
|
18796
|
-
${partial}`;
|
|
18797
|
-
}
|
|
18976
|
+
const partial = await promoteAndFinalize(`chunk could not be represented safely: ${chunkCoverageError}`, "Partial", "recomp_unavailable", "The next chunk could not be represented safely.", true);
|
|
18977
|
+
if (partial)
|
|
18978
|
+
return partial;
|
|
18798
18979
|
sessionLog2(sessionId, `recomp failed code=${userFacingFailureCode("recomp_unavailable")} reason="${chunkCoverageError}"`);
|
|
18799
18980
|
return `## Magic Recomp — Failed
|
|
18800
18981
|
|
|
@@ -18836,6 +19017,7 @@ Historian pass ${passCount + 1}, attempt ${passAttempt} started for messages ${c
|
|
|
18836
19017
|
language: deps.language,
|
|
18837
19018
|
callbacks: {
|
|
18838
19019
|
onRepairRetry: async (error) => {
|
|
19020
|
+
hadModelFailureOrBudgetReduction = true;
|
|
18839
19021
|
emitProgress(`Repair retry (pass ${passCount + 1})…`);
|
|
18840
19022
|
sessionLog2(sessionId, `recomp retry code=${userFacingFailureCode("recomp_unavailable")} reason="${error}"`);
|
|
18841
19023
|
await sendStatusNotification2(client, sessionId, `## Magic Recomp
|
|
@@ -18843,12 +19025,14 @@ Historian pass ${passCount + 1}, attempt ${passAttempt} started for messages ${c
|
|
|
18843
19025
|
History compression is retrying this pass. ${renderUserFacingFailure("recomp_unavailable")}`, notifParams());
|
|
18844
19026
|
},
|
|
18845
19027
|
onModelFallback: (modelId, index, total) => {
|
|
19028
|
+
hadModelFailureOrBudgetReduction = true;
|
|
18846
19029
|
const short = modelId.includes("/") ? modelId.split("/").pop() : modelId;
|
|
18847
19030
|
emitProgress(`Trying fallback ${short} (${index}/${total})…`);
|
|
18848
19031
|
}
|
|
18849
19032
|
}
|
|
18850
19033
|
});
|
|
18851
19034
|
if (!validatedPass.ok) {
|
|
19035
|
+
hadModelFailureOrBudgetReduction = true;
|
|
18852
19036
|
const reducedBudget = getReducedRecompTokenBudget(promptFit.chunkTokens);
|
|
18853
19037
|
if (reducedBudget !== null) {
|
|
18854
19038
|
const smallerChunk = readSessionChunk2(sessionId, reducedBudget, offset, protectedTailStart, { expandTools: deps.historianExpandTools });
|
|
@@ -18874,11 +19058,8 @@ History compression is retrying with a smaller set of messages. ${renderUserFaci
|
|
|
18874
19058
|
});
|
|
18875
19059
|
sessionLog2(sessionId, `recomp failed code=${userFacingFailureCode("recomp_unavailable")} reason="${validatedPass.error}" messageRange=${chunk.startIndex}-${chunk.endIndex}`);
|
|
18876
19060
|
const partial = await promoteAndFinalize(`history model response did not validate for messages ${chunk.startIndex}-${chunk.endIndex}`);
|
|
18877
|
-
if (partial)
|
|
18878
|
-
return
|
|
18879
|
-
|
|
18880
|
-
${partial}`;
|
|
18881
|
-
}
|
|
19061
|
+
if (partial)
|
|
19062
|
+
return partial;
|
|
18882
19063
|
return `## Magic Recomp — Failed
|
|
18883
19064
|
|
|
18884
19065
|
${renderUserFacingFailure("recomp_unavailable")}`;
|
|
@@ -18905,6 +19086,17 @@ ${renderUserFacingFailure("recomp_unavailable")}`;
|
|
|
18905
19086
|
importanceAvg: imp.avg
|
|
18906
19087
|
});
|
|
18907
19088
|
}
|
|
19089
|
+
const nextOffset = (validatedPass.compartments?.[validatedPass.compartments.length - 1]?.endMessage ?? chunk.endIndex) + 1;
|
|
19090
|
+
if (nextOffset <= offset) {
|
|
19091
|
+
const reason = `Recomp made no forward progress after messages ${chunk.startIndex}-${chunk.endIndex}.`;
|
|
19092
|
+
const partial = await promoteAndFinalize(reason, "Partial", "recomp_unavailable", reason, true);
|
|
19093
|
+
if (partial)
|
|
19094
|
+
return partial;
|
|
19095
|
+
return `## Magic Recomp — Failed
|
|
19096
|
+
|
|
19097
|
+
${reason} Nothing was written.`;
|
|
19098
|
+
}
|
|
19099
|
+
const hadStagedPrefix = candidateCompartments.length > 0;
|
|
18908
19100
|
candidateCompartments = [
|
|
18909
19101
|
...candidateCompartments,
|
|
18910
19102
|
...validatedPass.compartments ?? []
|
|
@@ -18913,19 +19105,14 @@ ${renderUserFacingFailure("recomp_unavailable")}`;
|
|
|
18913
19105
|
passCount += 1;
|
|
18914
19106
|
currentTokenBudget = historianChunkTokens;
|
|
18915
19107
|
passAttempt = 1;
|
|
18916
|
-
|
|
18917
|
-
|
|
18918
|
-
|
|
18919
|
-
|
|
18920
|
-
|
|
18921
|
-
|
|
18922
|
-
|
|
18923
|
-
|
|
18924
|
-
}
|
|
18925
|
-
return `## Magic Recomp — Failed
|
|
18926
|
-
|
|
18927
|
-
Recomp made no forward progress after messages ${chunk.startIndex}-${chunk.endIndex}. Nothing was written.`;
|
|
18928
|
-
}
|
|
19108
|
+
const saved = db.transaction(() => {
|
|
19109
|
+
if (hadStagedPrefix && !db.prepare("SELECT 1 FROM recomp_compartments WHERE session_id = ? LIMIT 1").get(sessionId))
|
|
19110
|
+
return false;
|
|
19111
|
+
saveRecompStagingPass(db, sessionId, passCount, candidateCompartments, candidateFacts);
|
|
19112
|
+
return true;
|
|
19113
|
+
}).immediate();
|
|
19114
|
+
if (!saved)
|
|
19115
|
+
return STAGING_REMOVED;
|
|
18929
19116
|
offset = nextOffset;
|
|
18930
19117
|
emitProgress();
|
|
18931
19118
|
}
|
|
@@ -18937,15 +19124,15 @@ Recomp made no forward progress after messages ${chunk.startIndex}-${chunk.endIn
|
|
|
18937
19124
|
|
|
18938
19125
|
${renderUserFacingFailure("recomp_unavailable")}`;
|
|
18939
19126
|
}
|
|
18940
|
-
saveRecompStagingPass(db, sessionId, passCount, candidateCompartments, candidateFacts);
|
|
18941
19127
|
const lastCompartmentEnd = candidateCompartments[candidateCompartments.length - 1]?.endMessage ?? 0;
|
|
18942
19128
|
const compartmentTagKeys = lastCompartmentEnd > 0 ? await getRawSessionTagKeysThrough2(sessionId, lastCompartmentEnd, { db }) : null;
|
|
18943
|
-
const promoted =
|
|
18944
|
-
if (
|
|
19129
|
+
const promoted = promoteRecompStaging(db, sessionId, leaseHolderId);
|
|
19130
|
+
if (promoted === "staging-removed") {
|
|
19131
|
+
return candidateCompartments.length > 0 ? STAGING_REMOVED : PUBLISH_LEASE_LOST;
|
|
19132
|
+
}
|
|
19133
|
+
if (typeof promoted === "string") {
|
|
18945
19134
|
sessionLog2(sessionId, "recomp publish skipped: compartment lease no longer held");
|
|
18946
|
-
return
|
|
18947
|
-
|
|
18948
|
-
Another process acquired the compartment-state lease before recomp could publish. No state was written.`;
|
|
19135
|
+
return PUBLISH_LEASE_LOST;
|
|
18949
19136
|
}
|
|
18950
19137
|
afterPublish("compression-depth", () => clearCompressionDepth(db, sessionId));
|
|
18951
19138
|
if (deps.preserveInjectionCacheUntilConsumed !== true) {
|
|
@@ -19038,25 +19225,6 @@ function snapRangeToCompartments(compartments, range) {
|
|
|
19038
19225
|
tailCompartments: sorted.slice(lastEnclosingIdx + 1)
|
|
19039
19226
|
};
|
|
19040
19227
|
}
|
|
19041
|
-
function compartmentToInput(c, newSequence) {
|
|
19042
|
-
return {
|
|
19043
|
-
sequence: newSequence,
|
|
19044
|
-
startMessage: c.startMessage,
|
|
19045
|
-
endMessage: c.endMessage,
|
|
19046
|
-
startMessageId: c.startMessageId,
|
|
19047
|
-
endMessageId: c.endMessageId,
|
|
19048
|
-
startBlockIndex: c.startBlockIndex,
|
|
19049
|
-
endBlockIndex: c.endBlockIndex,
|
|
19050
|
-
title: c.title,
|
|
19051
|
-
content: c.content,
|
|
19052
|
-
p1: c.p1,
|
|
19053
|
-
p2: c.p2,
|
|
19054
|
-
p3: c.p3,
|
|
19055
|
-
p4: c.p4,
|
|
19056
|
-
importance: c.importance,
|
|
19057
|
-
episodeType: c.episodeType
|
|
19058
|
-
};
|
|
19059
|
-
}
|
|
19060
19228
|
async function executePartialRecompInternal(deps, range) {
|
|
19061
19229
|
const {
|
|
19062
19230
|
client,
|
|
@@ -19076,6 +19244,7 @@ Could not acquire the compartment-state lease for this session.`;
|
|
|
19076
19244
|
}
|
|
19077
19245
|
const leaseHolderId = holderId;
|
|
19078
19246
|
updateSessionMeta(db, sessionId, { compartmentInProgress: true });
|
|
19247
|
+
let wroteStaging = false;
|
|
19079
19248
|
try {
|
|
19080
19249
|
let promoteFinal = function() {
|
|
19081
19250
|
const newBuilt = candidateCompartments.slice(priorCompartments.length);
|
|
@@ -19111,7 +19280,12 @@ Could not acquire the compartment-state lease for this session.`;
|
|
|
19111
19280
|
return null;
|
|
19112
19281
|
}
|
|
19113
19282
|
saveRecompStagingPass(db, sessionId, passCount + 1, merged, stagedFacts);
|
|
19114
|
-
|
|
19283
|
+
wroteStaging = true;
|
|
19284
|
+
const carriedRows = new Map([
|
|
19285
|
+
...priorCompartments.map((c, idx) => [idx, c]),
|
|
19286
|
+
...tailCompartments.map((c, idx) => [candidateCompartments.length + idx, c])
|
|
19287
|
+
]);
|
|
19288
|
+
const promoted = promoteRecompStagingWithM0Mutation(db, sessionId, leaseHolderId, carriedRows);
|
|
19115
19289
|
if (!promoted) {
|
|
19116
19290
|
log2("[magic-context] partial recomp promote returned null");
|
|
19117
19291
|
return null;
|
|
@@ -19160,8 +19334,7 @@ ${snapResult.error}`;
|
|
|
19160
19334
|
"",
|
|
19161
19335
|
`An unfinished partial recomp is already staged for range ${storedRange.start}-${storedRange.end}, which does not match the requested range ${snapStart}-${snapEnd}.`,
|
|
19162
19336
|
"",
|
|
19163
|
-
"
|
|
19164
|
-
"or cancel it by running `/ctx-flush` before starting a new partial recomp."
|
|
19337
|
+
"Finish that range by running `/ctx-recomp` with the same original arguments, or run `/ctx-recomp` without arguments to start a full rebuild."
|
|
19165
19338
|
].join(`
|
|
19166
19339
|
`);
|
|
19167
19340
|
}
|
|
@@ -19169,9 +19342,7 @@ ${snapResult.error}`;
|
|
|
19169
19342
|
return [
|
|
19170
19343
|
"## Magic Recomp — Failed",
|
|
19171
19344
|
"",
|
|
19172
|
-
|
|
19173
|
-
"Resume it by running `/ctx-recomp` without arguments,",
|
|
19174
|
-
"or cancel it before starting a partial recomp."
|
|
19345
|
+
`A full rebuild is paused at message ${existingStaging.lastEndMessage}. Run \`/ctx-recomp\` without arguments to continue it. A partial recomp can start when it completes or is discarded.`
|
|
19175
19346
|
].join(`
|
|
19176
19347
|
`);
|
|
19177
19348
|
}
|
|
@@ -19193,6 +19364,7 @@ ${snapResult.error}`;
|
|
|
19193
19364
|
passCount = 0;
|
|
19194
19365
|
offset = snapStart;
|
|
19195
19366
|
saveRecompStagingPass(db, sessionId, 0, candidateCompartments, stagedFacts);
|
|
19367
|
+
wroteStaging = true;
|
|
19196
19368
|
setRecompPartialRange(db, sessionId, { start: snapStart, end: snapEnd });
|
|
19197
19369
|
}
|
|
19198
19370
|
let currentTokenBudget = historianChunkTokens;
|
|
@@ -19302,6 +19474,7 @@ ${renderUserFacingFailure("recomp_unavailable")}`;
|
|
|
19302
19474
|
currentTokenBudget = historianChunkTokens;
|
|
19303
19475
|
passAttempt = 1;
|
|
19304
19476
|
saveRecompStagingPass(db, sessionId, passCount, candidateCompartments, stagedFacts);
|
|
19477
|
+
wroteStaging = true;
|
|
19305
19478
|
const nextOffset = (validatedPass.compartments?.[validatedPass.compartments.length - 1]?.endMessage ?? chunk.endIndex) + 1;
|
|
19306
19479
|
if (nextOffset <= offset) {
|
|
19307
19480
|
return `## Magic Recomp — Failed
|
|
@@ -19333,9 +19506,7 @@ Partial recomp completed historian passes but the final compartment set failed v
|
|
|
19333
19506
|
${renderUserFacingFailure("recomp_unavailable")}`;
|
|
19334
19507
|
} finally {
|
|
19335
19508
|
updateSessionMeta(db, sessionId, { compartmentInProgress: false });
|
|
19336
|
-
|
|
19337
|
-
const leftoverRange = getRecompPartialRange(db, sessionId);
|
|
19338
|
-
if (leftoverStaging && leftoverRange) {} else if (leftoverStaging && !leftoverRange) {
|
|
19509
|
+
if (wroteStaging && getRecompStaging(db, sessionId) && !getRecompPartialRange(db, sessionId)) {
|
|
19339
19510
|
log2(`[magic-context] partial recomp cleanup: clearing orphaned staging without range marker for session ${sessionId}`);
|
|
19340
19511
|
clearRecompStaging(db, sessionId);
|
|
19341
19512
|
}
|
|
@@ -19535,4 +19706,4 @@ async function executeContextRecomp(deps, options = {}) {
|
|
|
19535
19706
|
return (await executeContextRecompWithResult(deps, options)).message;
|
|
19536
19707
|
}
|
|
19537
19708
|
|
|
19538
|
-
export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, isCommitRetentionPaused, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, supportsQuietHiddenChildren, matchesHiddenRunLocation, hiddenRunPlacement, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, isLatestAssistantLengthCapped, parseProviderModel, modelBodyField, toModelEntry, hiddenModelCooldowns, ModelProducedNoOutputError, noteModelActivityMonitored, noteModelOutputReceived, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, annotateSubagentInvocationError, failedInvocationStatus, emptyTokenTotals, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, validateStoredCompartments, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, stripMemoryMuralBlock, servedHeadTexts, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, headMessagesForSizing, rawTailAfterNewestCompartment, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, readHistorianFailureStreak, describeHistorianJoinRefusal, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, nonNarrativeStoredGapRanges, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };
|
|
19709
|
+
export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, isCommitRetentionPaused, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, supportsQuietHiddenChildren, matchesHiddenRunLocation, hiddenRunPlacement, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, isLatestAssistantLengthCapped, parseProviderModel, modelBodyField, toModelEntry, hiddenModelCooldowns, ModelProducedNoOutputError, noteModelActivityMonitored, noteModelOutputReceived, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, annotateSubagentInvocationError, failedInvocationStatus, emptyTokenTotals, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, validateStoredCompartments, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, stripMemoryMuralBlock, servedHeadTexts, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, headMessagesForSizing, rawTailAfterNewestCompartment, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, pausedRecompReason, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, readHistorianFailureStreak, describeHistorianJoinRefusal, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, nonNarrativeStoredGapRanges, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };
|