@cortexkit/opencode-magic-context 0.49.55 → 0.49.57
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-vx5gw5h2.js → context-a617pcqe.js} +210 -57
- package/dist/features/magic-context/mural/render-mural.d.ts +17 -0
- package/dist/features/magic-context/mural/render-mural.d.ts.map +1 -1
- package/dist/features/magic-context/mural/render-trigger.d.ts +2 -1
- package/dist/features/magic-context/mural/render-trigger.d.ts.map +1 -1
- package/dist/features/magic-context/mural/resolve-mural.d.ts +8 -2
- package/dist/features/magic-context/mural/resolve-mural.d.ts.map +1 -1
- package/dist/features/magic-context/pi-identity-fold-guards.d.ts +38 -0
- package/dist/features/magic-context/pi-identity-fold-guards.d.ts.map +1 -0
- package/dist/features/magic-context/storage-historian-runs.d.ts +7 -0
- package/dist/features/magic-context/storage-historian-runs.d.ts.map +1 -1
- package/dist/features/magic-context/storage-session-tables.d.ts.map +1 -1
- package/dist/hooks/magic-context/command-handler.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-types.d.ts +9 -0
- package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner.d.ts +7 -1
- package/dist/hooks/magic-context/compartment-runner.d.ts.map +1 -1
- package/dist/hooks/magic-context/historian-failure-report.d.ts +112 -0
- package/dist/hooks/magic-context/historian-failure-report.d.ts.map +1 -0
- package/dist/hooks/magic-context/hook-handlers.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts +11 -1
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/{index-eyr425dx.js → index-0r2jk2na.js} +2 -2
- package/dist/{index-a3n2dczz.js → index-1wsb0e8h.js} +1 -1
- package/dist/{index-xj5bap1r.js → index-3600gm9z.js} +268 -21
- package/dist/{index-tx8nfw85.js → index-bev3zks1.js} +25 -1
- package/dist/{index-567xsm72.js → index-pdnan1e3.js} +3 -3
- package/dist/{index-9n6mdfqy.js → index-wpcjxzrm.js} +53 -27
- package/dist/{index-yamsmkmh.js → index-x8e50d8f.js} +2 -2
- package/dist/{index-xvtjwhm6.js → index-zyanqxtc.js} +2 -2
- package/dist/index.js +11 -11
- package/dist/raw-ordinal-warmup-worker.js +2 -2
- package/dist/{recomp-orchestrator-wbm4kpq9.js → recomp-orchestrator-xwsjrqcs.js} +3 -3
- package/dist/{render-73vrt30h.js → render-22ebrmep.js} +1 -1
- package/dist/{search-archive-ew4c3bsw.js → search-archive-bqqf5p7f.js} +2 -2
- package/dist/{transform-postprocess-phase-mt4dcbhd.js → transform-postprocess-phase-nejydt3q.js} +3 -3
- package/dist/v2/{context-13er940g.js → context-4gxr2xd4.js} +240 -67
- package/dist/v2/hidden-child-native.d.ts +10 -13
- package/dist/v2/hidden-child-native.d.ts.map +1 -1
- package/dist/v2/hidden-child-record.d.ts +2 -0
- package/dist/v2/hidden-child-record.d.ts.map +1 -1
- package/dist/v2/hidden-child-sweep.d.ts +39 -0
- package/dist/v2/hidden-child-sweep.d.ts.map +1 -0
- package/dist/v2/hidden-completion.d.ts.map +1 -1
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/usage-persist.d.ts +7 -1
- package/dist/v2/hooks/usage-persist.d.ts.map +1 -1
- package/dist/v2/raw-ordinal-warmup-worker.js +2 -2
- package/dist/v2/{recomp-orchestrator-cdkfynz4.js → recomp-orchestrator-1de5c0zr.js} +2 -2
- package/dist/v2/{render-a7j6fqbd.js → render-g44ksejs.js} +1 -1
- package/dist/v2/{search-archive-3a36887a.js → search-archive-5ycchnyp.js} +2 -2
- package/dist/v2/{server-96g41nad.js → server-dqwx9pdh.js} +268 -21
- package/dist/v2/{server-79tbtk5w.js → server-r7nj8ga0.js} +1 -1
- package/dist/v2/{server-578pc4tf.js → server-t5c8awdm.js} +2 -2
- package/dist/v2/{server-7rmf6a57.js → server-v57wr0r9.js} +25 -1
- package/dist/v2/server.js +2 -2
- package/dist/v2/{v2-archive-reader-jm3d7ccj.js → v2-archive-reader-tgydjgfy.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-xnqq81c4.js → wrapup-orchestrator-3871zj7c.js} +2 -2
- package/dist/{v2-archive-reader-9bbfh131.js → v2-archive-reader-2czwvyc9.js} +1 -1
- package/dist/{wrapup-orchestrator-svhee0fn.js → wrapup-orchestrator-m1yzmgq4.js} +4 -4
- package/package.json +1 -1
|
@@ -188,6 +188,7 @@ import {
|
|
|
188
188
|
readProjectDocsCanonical,
|
|
189
189
|
updateSessionMeta,
|
|
190
190
|
externalHistorianFailureReason,
|
|
191
|
+
getRecentFailedHistorianRunTimes,
|
|
191
192
|
recordHistorianRun,
|
|
192
193
|
summarizeImportance,
|
|
193
194
|
tallyFactsByCategory,
|
|
@@ -200,7 +201,7 @@ import {
|
|
|
200
201
|
getProjectState,
|
|
201
202
|
recordSubagentInvocation,
|
|
202
203
|
getLatestHistorianInvocationId
|
|
203
|
-
} from "./index-
|
|
204
|
+
} from "./index-bev3zks1.js";
|
|
204
205
|
import {
|
|
205
206
|
clearCompressionDepth,
|
|
206
207
|
clearCompressionDepthRange,
|
|
@@ -218,6 +219,7 @@ import {
|
|
|
218
219
|
persistCachedM0,
|
|
219
220
|
clearCachedM0M1,
|
|
220
221
|
describeProtectedTailDrainBudgetSkip,
|
|
222
|
+
loadPersistedUsage,
|
|
221
223
|
loadProtectedTailMeta,
|
|
222
224
|
markProtectedTailPolicyV3Seeded,
|
|
223
225
|
recordProtectedTailPublicationFloor,
|
|
@@ -7306,6 +7308,60 @@ function codepoints(value) {
|
|
|
7306
7308
|
function escapeText(value) {
|
|
7307
7309
|
return value.replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim();
|
|
7308
7310
|
}
|
|
7311
|
+
var PUNCTUATION_FALLBACKS = {
|
|
7312
|
+
"‘": "'",
|
|
7313
|
+
"’": "'",
|
|
7314
|
+
"‚": "'",
|
|
7315
|
+
"‛": "'",
|
|
7316
|
+
"“": '"',
|
|
7317
|
+
"”": '"',
|
|
7318
|
+
"„": '"',
|
|
7319
|
+
"‟": '"',
|
|
7320
|
+
"–": "-",
|
|
7321
|
+
"—": "-",
|
|
7322
|
+
"…": "...",
|
|
7323
|
+
" ": " ",
|
|
7324
|
+
" ": " ",
|
|
7325
|
+
" ": " "
|
|
7326
|
+
};
|
|
7327
|
+
var REMOVABLE_COMBINING_MARK = /(?![\u0334-\u0338])\p{M}/gu;
|
|
7328
|
+
function hasGlyph(character) {
|
|
7329
|
+
return MURAL_FONT_GLYPHS[character] !== undefined;
|
|
7330
|
+
}
|
|
7331
|
+
function drawableMuralCue(cue) {
|
|
7332
|
+
const text = escapeText(cue);
|
|
7333
|
+
let normalized = "";
|
|
7334
|
+
let changed = false;
|
|
7335
|
+
for (const character of text) {
|
|
7336
|
+
if (hasGlyph(character)) {
|
|
7337
|
+
normalized += character;
|
|
7338
|
+
continue;
|
|
7339
|
+
}
|
|
7340
|
+
changed = true;
|
|
7341
|
+
const replacement = PUNCTUATION_FALLBACKS[character] ?? character.normalize("NFKD").replace(REMOVABLE_COMBINING_MARK, "");
|
|
7342
|
+
for (const part of replacement) {
|
|
7343
|
+
if (!hasGlyph(part))
|
|
7344
|
+
return null;
|
|
7345
|
+
}
|
|
7346
|
+
normalized += replacement;
|
|
7347
|
+
}
|
|
7348
|
+
if (!changed)
|
|
7349
|
+
return cue;
|
|
7350
|
+
const result = escapeText(normalized);
|
|
7351
|
+
return result.length > 0 ? result : null;
|
|
7352
|
+
}
|
|
7353
|
+
function partitionDrawableEntries(entries) {
|
|
7354
|
+
const drawable = [];
|
|
7355
|
+
const undrawableIds = [];
|
|
7356
|
+
for (const entry of entries) {
|
|
7357
|
+
const cue = drawableMuralCue(entry.cue);
|
|
7358
|
+
if (cue === null)
|
|
7359
|
+
undrawableIds.push(entry.id);
|
|
7360
|
+
else
|
|
7361
|
+
drawable.push(cue === entry.cue ? entry : { ...entry, cue });
|
|
7362
|
+
}
|
|
7363
|
+
return { drawable, undrawableIds };
|
|
7364
|
+
}
|
|
7309
7365
|
function banner(category, roomWidth) {
|
|
7310
7366
|
const label = ` <${category}> `;
|
|
7311
7367
|
if (codepoints(label) > roomWidth) {
|
|
@@ -7611,11 +7667,12 @@ function snapDimensionToVisionTile(contentPixels, maximum) {
|
|
|
7611
7667
|
return Math.min(maximum, Math.max(MURAL_VISION_TILE, Math.ceil(contentPixels / MURAL_VISION_TILE) * MURAL_VISION_TILE));
|
|
7612
7668
|
}
|
|
7613
7669
|
function planMuralRender(entries) {
|
|
7614
|
-
const
|
|
7615
|
-
const
|
|
7670
|
+
const { drawable, undrawableIds } = partitionDrawableEntries(entries);
|
|
7671
|
+
const roomWidth = chooseRoomWidth(drawable);
|
|
7672
|
+
const plan = planLines(drawable, roomWidth);
|
|
7616
7673
|
const candidates = Array.from({ length: MURAL_COLUMNS }, (_, index) => {
|
|
7617
7674
|
const requestedColumnCount = index + 1;
|
|
7618
|
-
const layout = renderLayout(
|
|
7675
|
+
const layout = renderLayout(drawable, plan, roomWidth, requestedColumnCount);
|
|
7619
7676
|
const contentWidth = layout.columnCount === 0 ? 0 : layout.columnCount * roomWidth * MURAL_CELL_WIDTH + MURAL_COLUMN_GAP * (layout.columnCount - 1) * MURAL_CELL_WIDTH;
|
|
7620
7677
|
const contentHeight = layout.rowCount * MURAL_LINE_PITCH;
|
|
7621
7678
|
const width = snapDimensionToVisionTile(contentWidth, MURAL_WIDTH);
|
|
@@ -7644,7 +7701,13 @@ function planMuralRender(entries) {
|
|
|
7644
7701
|
}
|
|
7645
7702
|
return candidate.requestedColumnCount < best.requestedColumnCount ? candidate : best;
|
|
7646
7703
|
}, firstCandidate);
|
|
7647
|
-
return {
|
|
7704
|
+
return {
|
|
7705
|
+
roomWidth,
|
|
7706
|
+
layout: selected.layout,
|
|
7707
|
+
width: selected.width,
|
|
7708
|
+
height: selected.height,
|
|
7709
|
+
undrawableIds
|
|
7710
|
+
};
|
|
7648
7711
|
}
|
|
7649
7712
|
function rasterMural(plan) {
|
|
7650
7713
|
const { roomWidth, layout, width, height } = plan;
|
|
@@ -7680,6 +7743,7 @@ function renderPlannedMural(plan) {
|
|
|
7680
7743
|
layoutItems: layout.layoutItems,
|
|
7681
7744
|
renderedIds: layout.renderedIds,
|
|
7682
7745
|
droppedIds: layout.droppedIds,
|
|
7746
|
+
undrawableIds: plan.undrawableIds,
|
|
7683
7747
|
categoryLineUsage: layout.usage,
|
|
7684
7748
|
filledLineCount: layout.filledLineCount,
|
|
7685
7749
|
width,
|
|
@@ -7711,13 +7775,17 @@ function poolContentHash(pool, memory) {
|
|
|
7711
7775
|
function getMuralCoverage(db, projectIdentity, pool) {
|
|
7712
7776
|
const { memories, cueState } = pool ?? readMuralPool(db, projectIdentity);
|
|
7713
7777
|
let cuedMemoryCount = 0;
|
|
7778
|
+
let undrawableCueCount = 0;
|
|
7714
7779
|
for (const memory of memories) {
|
|
7715
7780
|
const state = cueState.get(memory.id);
|
|
7716
7781
|
if (state && typeof state.cue === "string" && state.cue.trim() !== "" && state.hash !== null && state.hash === poolContentHash(pool, memory)) {
|
|
7717
|
-
|
|
7782
|
+
if (drawableMuralCue(state.cue) === null)
|
|
7783
|
+
undrawableCueCount += 1;
|
|
7784
|
+
else
|
|
7785
|
+
cuedMemoryCount += 1;
|
|
7718
7786
|
}
|
|
7719
7787
|
}
|
|
7720
|
-
return { activeMemoryCount: memories.length, cuedMemoryCount };
|
|
7788
|
+
return { activeMemoryCount: memories.length, cuedMemoryCount, undrawableCueCount };
|
|
7721
7789
|
}
|
|
7722
7790
|
function resolveMural(db, projectIdentity, budgetTokens = DEFAULT_MURAL_MEMORY_BUDGET, pool) {
|
|
7723
7791
|
const memories = pool?.memories ?? getMemoriesByProject2(db, projectIdentity, ["active", "permanent"]);
|
|
@@ -7835,7 +7903,8 @@ function ensureMuralRendered(db, projectIdentity, budgetTokens = DEFAULT_MURAL_M
|
|
|
7835
7903
|
const pool = readMuralPool(db, projectIdentity);
|
|
7836
7904
|
const coverage = getMuralCoverage(db, projectIdentity, pool);
|
|
7837
7905
|
if (coverage.activeMemoryCount === 0 || !muralCoverageGate(coverage.cuedMemoryCount, coverage.activeMemoryCount)) {
|
|
7838
|
-
const
|
|
7906
|
+
const undrawable = coverage.undrawableCueCount > 0 ? ` the mural font can draw (${coverage.undrawableCueCount} more use characters it has no glyph for)` : "";
|
|
7907
|
+
const skipReason = coverage.activeMemoryCount === 0 ? "no active memories" : `only ${coverage.cuedMemoryCount}/${coverage.activeMemoryCount} active memories have current cues${undrawable} (requires ${MIN_MURAL_CUED_MEMORIES} cues or ${MIN_MURAL_COVERAGE * 100}% coverage)`;
|
|
7839
7908
|
log2(`[mural] skipped for ${projectIdentity}: ${skipReason}`);
|
|
7840
7909
|
return { hasMural: false, rerendered: false, skipReason };
|
|
7841
7910
|
}
|
|
@@ -7850,6 +7919,11 @@ function ensureMuralRendered(db, projectIdentity, budgetTokens = DEFAULT_MURAL_M
|
|
|
7850
7919
|
return { ...cached.result };
|
|
7851
7920
|
}
|
|
7852
7921
|
const plan = planMuralRender(entries);
|
|
7922
|
+
if (plan.layout.renderedIds.length === 0) {
|
|
7923
|
+
const skipReason = `none of the ${entries.length} overflow cues can be drawn (${plan.undrawableIds.length} use characters the mural font has no glyph for)`;
|
|
7924
|
+
log2(`[mural] skipped for ${projectIdentity}: ${skipReason}`);
|
|
7925
|
+
return { hasMural: false, rerendered: false, skipReason };
|
|
7926
|
+
}
|
|
7853
7927
|
const textHash = createHash5("sha256").update(plan.layout.text).digest("hex");
|
|
7854
7928
|
if (existing && existing.contentHash === textHash && existing.width === plan.width && existing.height === plan.height) {
|
|
7855
7929
|
return rememberRender(db, projectIdentity, key, existing.image, {
|
|
@@ -7862,6 +7936,8 @@ function ensureMuralRendered(db, projectIdentity, budgetTokens = DEFAULT_MURAL_M
|
|
|
7862
7936
|
});
|
|
7863
7937
|
}
|
|
7864
7938
|
const rendered = renderPlannedMural(plan);
|
|
7939
|
+
if (rendered.undrawableIds.length > 0)
|
|
7940
|
+
log2(`[mural] rendered for ${projectIdentity}: ${rendered.renderedIds.length} cues drawn, ${rendered.droppedIds.length} left out for space, ${rendered.undrawableIds.length} left out because the mural font has no glyph for their characters`);
|
|
7865
7941
|
if (mode === "persist")
|
|
7866
7942
|
upsertMural(db, {
|
|
7867
7943
|
projectPath: projectIdentity,
|
|
@@ -15965,6 +16041,140 @@ function queueDropsForCompartmentalizedMessages(db, sessionId, upToMessageIndex,
|
|
|
15965
16041
|
queuePreparedCompartmentDrops(db, prepareCompartmentDrops(db, sessionId, upToMessageIndex, observedKeys, fromMessageIndex));
|
|
15966
16042
|
}
|
|
15967
16043
|
|
|
16044
|
+
// src/hooks/magic-context/historian-failure-report.ts
|
|
16045
|
+
var REPEATED_HISTORIAN_FAILURE_WARNING_STEP = 3;
|
|
16046
|
+
var REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS = 30 * 60 * 1000;
|
|
16047
|
+
var ACTIONS = "What to do: run /ctx-status for detail; change the historian model or its fallback models in magic-context.jsonc (user or project config); or run /ctx-recomp to rebuild the history.";
|
|
16048
|
+
var REFUSAL_ERROR_MAX_CHARS = 500;
|
|
16049
|
+
var WARNING_ERROR_MAX_CHARS = 200;
|
|
16050
|
+
function readHistorianFailureStreak(db, sessionId, options = {}) {
|
|
16051
|
+
const state = getHistorianFailureState(db, sessionId);
|
|
16052
|
+
const count = state.failureCount;
|
|
16053
|
+
let since = null;
|
|
16054
|
+
if (count > 0) {
|
|
16055
|
+
const recorded = count - Math.max(0, options.unrecordedFailures ?? 0);
|
|
16056
|
+
if (recorded <= 0) {
|
|
16057
|
+
since = state.lastFailureAt;
|
|
16058
|
+
} else {
|
|
16059
|
+
const times = getRecentFailedHistorianRunTimes(db, sessionId, recorded);
|
|
16060
|
+
since = times.length === recorded ? times[recorded - 1] ?? null : null;
|
|
16061
|
+
}
|
|
16062
|
+
}
|
|
16063
|
+
return { count, lastError: state.lastError, lastFailureAt: state.lastFailureAt, since };
|
|
16064
|
+
}
|
|
16065
|
+
function formatHistorianClockTime(at, now = Date.now()) {
|
|
16066
|
+
const date = new Date(at);
|
|
16067
|
+
const pad = (value) => String(value).padStart(2, "0");
|
|
16068
|
+
const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
16069
|
+
const today = new Date(now);
|
|
16070
|
+
const sameDay = date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
|
|
16071
|
+
return sameDay ? clock : `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock}`;
|
|
16072
|
+
}
|
|
16073
|
+
function formatHistorianSeconds(ms) {
|
|
16074
|
+
const seconds = Math.max(0, ms) / 1000;
|
|
16075
|
+
return String(Number(seconds.toFixed(seconds >= 10 ? 0 : 3)));
|
|
16076
|
+
}
|
|
16077
|
+
function singleLine(text) {
|
|
16078
|
+
return text.replace(/\s+/g, " ").trim();
|
|
16079
|
+
}
|
|
16080
|
+
function quoteError(error, maxChars) {
|
|
16081
|
+
const text = sanitizeDiagnosticText(singleLine(error));
|
|
16082
|
+
return text.length > maxChars ? `${text.slice(0, maxChars - 1).trimEnd()}…` : text;
|
|
16083
|
+
}
|
|
16084
|
+
function endSentence(text) {
|
|
16085
|
+
return /[.!?]$/.test(text) ? text : `${text}.`;
|
|
16086
|
+
}
|
|
16087
|
+
function usageClause(usagePercentage) {
|
|
16088
|
+
return typeof usagePercentage === "number" && Number.isFinite(usagePercentage) ? `context is at ${Math.round(usagePercentage)}% of the window` : "context is nearly full";
|
|
16089
|
+
}
|
|
16090
|
+
function capitalize(text) {
|
|
16091
|
+
return text.charAt(0).toUpperCase() + text.slice(1);
|
|
16092
|
+
}
|
|
16093
|
+
function chunkLabel(chunk) {
|
|
16094
|
+
return chunk ? `messages ${chunk.start}-${chunk.end}` : "";
|
|
16095
|
+
}
|
|
16096
|
+
function streakSentence(failures, now) {
|
|
16097
|
+
if (failures.count <= 0)
|
|
16098
|
+
return null;
|
|
16099
|
+
const since = failures.since !== null ? `, since ${formatHistorianClockTime(failures.since, now)}` : "";
|
|
16100
|
+
return `Summary runs failed in a row: ${failures.count}${since}.`;
|
|
16101
|
+
}
|
|
16102
|
+
function failureBelongsToRun(failures, run) {
|
|
16103
|
+
return failures.count > 0 && failures.lastFailureAt !== null && run?.startedAt !== undefined && failures.lastFailureAt >= run.startedAt;
|
|
16104
|
+
}
|
|
16105
|
+
function describeHistorianJoinRefusal(input) {
|
|
16106
|
+
const now = input.now ?? Date.now();
|
|
16107
|
+
const { run, failures } = input;
|
|
16108
|
+
const sentences = [
|
|
16109
|
+
`This turn was not sent: ${usageClause(input.usagePercentage)}, and Magic Context waited ${formatHistorianSeconds(input.waitedMs)} s for a history summary that did not finish in time.`
|
|
16110
|
+
];
|
|
16111
|
+
const subject = run?.chunk ? `The summary of ${chunkLabel(run.chunk)}` : "The summary run";
|
|
16112
|
+
const ownFailure = failureBelongsToRun(failures, run);
|
|
16113
|
+
const lastError = failures.lastError ? quoteError(failures.lastError, REFUSAL_ERROR_MAX_CHARS) : "";
|
|
16114
|
+
if (ownFailure) {
|
|
16115
|
+
sentences.push(endSentence(`${subject} failed: ${lastError || "no reason recorded"}`));
|
|
16116
|
+
} else if (run && run.endedAt === undefined) {
|
|
16117
|
+
sentences.push(run.startedAt !== undefined ? `${subject} is still running after ${formatHistorianSeconds(now - run.startedAt)} s.` : `${subject} is still running.`);
|
|
16118
|
+
} else if (run) {
|
|
16119
|
+
sentences.push(`${subject} finished after the wait ended.`);
|
|
16120
|
+
}
|
|
16121
|
+
if (!ownFailure && failures.count > 0 && lastError && failures.lastFailureAt !== null) {
|
|
16122
|
+
sentences.push(endSentence(`The previous run failed at ${formatHistorianClockTime(failures.lastFailureAt, now)}: ${lastError}`));
|
|
16123
|
+
}
|
|
16124
|
+
const streak = streakSentence(failures, now);
|
|
16125
|
+
if (streak)
|
|
16126
|
+
sentences.push(streak);
|
|
16127
|
+
sentences.push(ACTIONS);
|
|
16128
|
+
return sentences.join(" ");
|
|
16129
|
+
}
|
|
16130
|
+
function describeRepeatedHistorianFailures(input) {
|
|
16131
|
+
const now = input.now ?? Date.now();
|
|
16132
|
+
const { failures } = input;
|
|
16133
|
+
const facts = [
|
|
16134
|
+
streakSentence(failures, now) ?? "Summary runs are failing.",
|
|
16135
|
+
...input.chunk ? [`Last chunk: ${chunkLabel(input.chunk)}.`] : [],
|
|
16136
|
+
...failures.lastError ? [
|
|
16137
|
+
endSentence(`Last error: ${quoteError(failures.lastError, WARNING_ERROR_MAX_CHARS)}`)
|
|
16138
|
+
] : [],
|
|
16139
|
+
`${capitalize(usageClause(input.usagePercentage))}; at 95% a turn can be refused if no summary finishes in time.`
|
|
16140
|
+
];
|
|
16141
|
+
return [
|
|
16142
|
+
"## Magic Context — History summaries keep failing",
|
|
16143
|
+
"",
|
|
16144
|
+
facts.join(" "),
|
|
16145
|
+
"",
|
|
16146
|
+
ACTIONS
|
|
16147
|
+
].join(`
|
|
16148
|
+
`);
|
|
16149
|
+
}
|
|
16150
|
+
var repeatedFailureWarnings = new Map;
|
|
16151
|
+
function shouldWarnRepeatedHistorianFailures(sessionId, failureCount, now = Date.now()) {
|
|
16152
|
+
const step = REPEATED_HISTORIAN_FAILURE_WARNING_STEP;
|
|
16153
|
+
if (failureCount < step || failureCount % step !== 0)
|
|
16154
|
+
return false;
|
|
16155
|
+
const last = repeatedFailureWarnings.get(sessionId);
|
|
16156
|
+
if (last && failureCount > last.count && now - last.at < REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS) {
|
|
16157
|
+
return false;
|
|
16158
|
+
}
|
|
16159
|
+
repeatedFailureWarnings.set(sessionId, { count: failureCount, at: now });
|
|
16160
|
+
return true;
|
|
16161
|
+
}
|
|
16162
|
+
function takeRepeatedHistorianFailureWarning(input) {
|
|
16163
|
+
const now = input.now ?? Date.now();
|
|
16164
|
+
if (!shouldWarnRepeatedHistorianFailures(input.sessionId, input.failureCount, now)) {
|
|
16165
|
+
return null;
|
|
16166
|
+
}
|
|
16167
|
+
const failures = readHistorianFailureStreak(input.db, input.sessionId, {
|
|
16168
|
+
unrecordedFailures: input.unrecordedFailures
|
|
16169
|
+
});
|
|
16170
|
+
return describeRepeatedHistorianFailures({
|
|
16171
|
+
chunk: input.chunk,
|
|
16172
|
+
failures: { ...failures, count: input.failureCount },
|
|
16173
|
+
usagePercentage: loadPersistedUsage(input.db, input.sessionId)?.usage.percentage,
|
|
16174
|
+
now
|
|
16175
|
+
});
|
|
16176
|
+
}
|
|
16177
|
+
|
|
15968
16178
|
// src/hooks/magic-context/historian-history-wait.ts
|
|
15969
16179
|
var historyWaits = new Map;
|
|
15970
16180
|
function newestMessageId(snapshot) {
|
|
@@ -17393,6 +17603,28 @@ async function runCompartmentAgent(deps) {
|
|
|
17393
17603
|
}
|
|
17394
17604
|
await sendStatusNotification2(client, sessionId, message, getNotificationParams?.() ?? {});
|
|
17395
17605
|
};
|
|
17606
|
+
const notifyCountedFailure = async (failureCount, notice) => {
|
|
17607
|
+
let warning = null;
|
|
17608
|
+
try {
|
|
17609
|
+
warning = takeRepeatedHistorianFailureWarning({
|
|
17610
|
+
db,
|
|
17611
|
+
sessionId,
|
|
17612
|
+
failureCount,
|
|
17613
|
+
chunk: telemetry.chunkStartOrdinal != null && telemetry.chunkEndOrdinal != null ? { start: telemetry.chunkStartOrdinal, end: telemetry.chunkEndOrdinal } : undefined,
|
|
17614
|
+
unrecordedFailures: 1
|
|
17615
|
+
});
|
|
17616
|
+
} catch (error) {
|
|
17617
|
+
sessionLog2(sessionId, "historian repeated-failure warning failed:", error);
|
|
17618
|
+
}
|
|
17619
|
+
if (!warning) {
|
|
17620
|
+
await notifyHistorianIssue(notice);
|
|
17621
|
+
return;
|
|
17622
|
+
}
|
|
17623
|
+
issueNotified = true;
|
|
17624
|
+
lastHistorianAlertBySession.set(sessionId, Date.now());
|
|
17625
|
+
sessionLog2(sessionId, `historian repeated-failure warning sent: count=${failureCount}`);
|
|
17626
|
+
await sendStatusNotification2(client, sessionId, warning, getNotificationParams?.() ?? {});
|
|
17627
|
+
};
|
|
17396
17628
|
const truncateHistorianInputIfNeeded = (text, budget) => {
|
|
17397
17629
|
if (estimateTokens(text) <= budget)
|
|
17398
17630
|
return text;
|
|
@@ -17473,9 +17705,9 @@ async function runCompartmentAgent(deps) {
|
|
|
17473
17705
|
telemetry.failureReason = `existing-validation: ${existingValidationError}`;
|
|
17474
17706
|
retainDrainReservationForRetryThrottle = true;
|
|
17475
17707
|
if (unresolvedInvolved) {
|
|
17476
|
-
await
|
|
17708
|
+
await notifyCountedFailure(failCount, buildStoredCompartmentsInvalidNotice());
|
|
17477
17709
|
} else {
|
|
17478
|
-
await
|
|
17710
|
+
await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, existingValidationError));
|
|
17479
17711
|
}
|
|
17480
17712
|
return;
|
|
17481
17713
|
}
|
|
@@ -17606,9 +17838,9 @@ async function runCompartmentAgent(deps) {
|
|
|
17606
17838
|
return;
|
|
17607
17839
|
}
|
|
17608
17840
|
sessionLog2(sessionId, `historian failure: source=prompt-fit reason="${promptFit.reason}"`);
|
|
17609
|
-
incrementHistorianFailure(db, sessionId, promptFit.reason);
|
|
17841
|
+
const failCount = incrementHistorianFailure(db, sessionId, promptFit.reason);
|
|
17610
17842
|
retainDrainReservationForRetryThrottle = true;
|
|
17611
|
-
await
|
|
17843
|
+
await notifyCountedFailure(failCount, buildHistorianWindowTooSmallNotice());
|
|
17612
17844
|
return;
|
|
17613
17845
|
}
|
|
17614
17846
|
const chunkTokens = promptFit.chunkTokens;
|
|
@@ -17648,6 +17880,7 @@ async function runCompartmentAgent(deps) {
|
|
|
17648
17880
|
const forceKeepLastCompartmentForChunk = deps.forceKeepLastCompartment === true && !chunk.hasMore;
|
|
17649
17881
|
telemetry.chunkStartOrdinal = chunk.startIndex;
|
|
17650
17882
|
telemetry.chunkEndOrdinal = chunk.endIndex;
|
|
17883
|
+
deps.onChunkSelected?.({ start: chunk.startIndex, end: chunk.endIndex });
|
|
17651
17884
|
if (!chunk.text || chunk.messageCount === 0) {
|
|
17652
17885
|
if (persistFilteredNoise(db, sessionId, chunk, eligibleEndOrdinal)) {
|
|
17653
17886
|
telemetry.status = "noop";
|
|
@@ -17708,7 +17941,7 @@ async function runCompartmentAgent(deps) {
|
|
|
17708
17941
|
telemetry.failureReason = `chunk-coverage: ${chunkCoverageError}`;
|
|
17709
17942
|
sessionLog2(sessionId, `historian failure: source=chunk-coverage reason="${chunkCoverageError}" chunkRange=${chunk.startIndex}-${chunk.endIndex}`);
|
|
17710
17943
|
const failCount = incrementHistorianFailure(db, sessionId, chunkCoverageError);
|
|
17711
|
-
await
|
|
17944
|
+
await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, chunkCoverageError));
|
|
17712
17945
|
rollbackDrainReservation();
|
|
17713
17946
|
return;
|
|
17714
17947
|
}
|
|
@@ -17759,7 +17992,7 @@ ${chunkText}`,
|
|
|
17759
17992
|
sessionLog2(sessionId, `historian failure: source=validation reason="${validatedPass.error}" chunkRange=${chunk.startIndex}-${chunk.endIndex} fallbackModel=${deps.fallbackModelId ?? "<none>"} twoPass=${deps.historianTwoPass ? "true" : "false"}`);
|
|
17760
17993
|
const failCount = incrementHistorianFailure(db, sessionId, validatedPass.error);
|
|
17761
17994
|
telemetry.failureReason = validatedPass.failureReason ?? validatedPass.error;
|
|
17762
|
-
await
|
|
17995
|
+
await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, validatedPass.error));
|
|
17763
17996
|
return;
|
|
17764
17997
|
}
|
|
17765
17998
|
retainDrainReservationForRetryThrottle = false;
|
|
@@ -17788,7 +18021,7 @@ ${chunkText}`,
|
|
|
17788
18021
|
sessionLog2(sessionId, "historian output discarded: reason=no_forward_progress");
|
|
17789
18022
|
const failCount = incrementHistorianFailure(db, sessionId, `no forward progress beyond raw message ${offset - 1}`);
|
|
17790
18023
|
try {
|
|
17791
|
-
await
|
|
18024
|
+
await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, `historian made no forward progress beyond raw message ${offset - 1}`));
|
|
17792
18025
|
} finally {
|
|
17793
18026
|
recordHistorianNoProgress(boundarySnapshot, inEmergency);
|
|
17794
18027
|
}
|
|
@@ -17839,7 +18072,7 @@ ${chunkText}`,
|
|
|
17839
18072
|
sessionLog2(sessionId, `historian publish refused: sequence=${danglingBoundary.sequence} side=${danglingBoundary.side} missing_id=${danglingBoundary.messageId}; raw snapshot changed during the historian run`);
|
|
17840
18073
|
sessionLog2(sessionId, "historian output discarded: reason=dangling_boundary");
|
|
17841
18074
|
const failCount = incrementHistorianFailure(db, sessionId, reason);
|
|
17842
|
-
await
|
|
18075
|
+
await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, reason));
|
|
17843
18076
|
rollbackDrainReservation();
|
|
17844
18077
|
return;
|
|
17845
18078
|
}
|
|
@@ -18047,7 +18280,7 @@ ${chunkText}`,
|
|
|
18047
18280
|
sessionLog2(sessionId, `historian failure: source=exception ${desc.brief}${desc.stackHead ? ` stackHead="${desc.stackHead}"` : ""}`);
|
|
18048
18281
|
if (!issueNotified) {
|
|
18049
18282
|
const failCount = incrementHistorianFailure(db, sessionId, desc.brief);
|
|
18050
|
-
await
|
|
18283
|
+
await notifyCountedFailure(failCount, buildHistorianFailureNotice(failCount, desc.brief));
|
|
18051
18284
|
}
|
|
18052
18285
|
} finally {
|
|
18053
18286
|
if (!completedSuccessfully) {
|
|
@@ -18871,10 +19104,12 @@ function registerActiveCompartmentRun(sessionId, promise, kind = "other") {
|
|
|
18871
19104
|
const activeRun = {
|
|
18872
19105
|
promise: Promise.resolve(),
|
|
18873
19106
|
published: false,
|
|
18874
|
-
kind
|
|
19107
|
+
kind,
|
|
19108
|
+
startedAt: Date.now()
|
|
18875
19109
|
};
|
|
18876
19110
|
const wrapped = promise.finally(() => {
|
|
18877
19111
|
activeRun.settled = true;
|
|
19112
|
+
activeRun.endedAt = Date.now();
|
|
18878
19113
|
if (activeRuns.get(sessionId)?.promise === wrapped) {
|
|
18879
19114
|
activeRuns.delete(sessionId);
|
|
18880
19115
|
}
|
|
@@ -18931,9 +19166,19 @@ function startBackgroundCompartmentAgent(deps, runAgent, prepareBoundary) {
|
|
|
18931
19166
|
return;
|
|
18932
19167
|
}
|
|
18933
19168
|
const renewal = startLeaseRenewal(deps, holderId);
|
|
19169
|
+
const activeRun = {
|
|
19170
|
+
promise: Promise.resolve(),
|
|
19171
|
+
published: false,
|
|
19172
|
+
kind: "incremental",
|
|
19173
|
+
startedAt: Date.now()
|
|
19174
|
+
};
|
|
18934
19175
|
const runnerDeps = withPublishedCallback({
|
|
18935
19176
|
...deps,
|
|
18936
|
-
compartmentLeaseHolderId: holderId
|
|
19177
|
+
compartmentLeaseHolderId: holderId,
|
|
19178
|
+
onChunkSelected: (chunk) => {
|
|
19179
|
+
activeRun.chunk = chunk;
|
|
19180
|
+
deps.onChunkSelected?.(chunk);
|
|
19181
|
+
}
|
|
18937
19182
|
});
|
|
18938
19183
|
const promise = new Promise((resolve) => setTimeout(resolve, 0)).then(() => withRawSessionMessageCache2(() => {
|
|
18939
19184
|
const snapshot = deps.boundarySnapshot;
|
|
@@ -18963,6 +19208,7 @@ function startBackgroundCompartmentAgent(deps, runAgent, prepareBoundary) {
|
|
|
18963
19208
|
updateSessionMeta(deps.db, deps.sessionId, { compartmentInProgress: false });
|
|
18964
19209
|
} catch {}
|
|
18965
19210
|
}).finally(() => {
|
|
19211
|
+
activeRun.endedAt = Date.now();
|
|
18966
19212
|
try {
|
|
18967
19213
|
clearInterval(renewal);
|
|
18968
19214
|
releaseCompartmentLeaseBestEffort(deps.db, deps.sessionId, holderId, sessionLog2);
|
|
@@ -18973,7 +19219,8 @@ function startBackgroundCompartmentAgent(deps, runAgent, prepareBoundary) {
|
|
|
18973
19219
|
sessionLog2(deps.sessionId, "compartment agent: finalizer failed:", err);
|
|
18974
19220
|
}
|
|
18975
19221
|
});
|
|
18976
|
-
|
|
19222
|
+
activeRun.promise = promise;
|
|
19223
|
+
activeRuns.set(deps.sessionId, activeRun);
|
|
18977
19224
|
}
|
|
18978
19225
|
async function executeContextRecompWithResult(deps, options = {}) {
|
|
18979
19226
|
const { sessionId } = deps;
|
|
@@ -19037,4 +19284,4 @@ async function executeContextRecomp(deps, options = {}) {
|
|
|
19037
19284
|
return (await executeContextRecompWithResult(deps, options)).message;
|
|
19038
19285
|
}
|
|
19039
19286
|
|
|
19040
|
-
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, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, 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, 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, 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, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };
|
|
19287
|
+
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, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, 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, 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, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };
|
|
@@ -1231,6 +1231,12 @@ function resolveIsSubagentFromOpenCode2Db(sessionId) {
|
|
|
1231
1231
|
}
|
|
1232
1232
|
}
|
|
1233
1233
|
|
|
1234
|
+
// src/features/magic-context/pi-identity-fold-guards.ts
|
|
1235
|
+
var PI_IDENTITY_FOLD_GUARD_PREFIX = "pi_identity_fold_guards:";
|
|
1236
|
+
function piIdentityFoldGuardKey(sessionId) {
|
|
1237
|
+
return `${PI_IDENTITY_FOLD_GUARD_PREFIX}${sessionId}`;
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1234
1240
|
// src/features/magic-context/storage-session-tables.ts
|
|
1235
1241
|
var SESSION_SCOPED_TABLES = [
|
|
1236
1242
|
{ table: "pending_ops", harnessScoped: true },
|
|
@@ -1347,6 +1353,9 @@ function deleteSessionScopedRows(db, sessionIds, harness, options = {}) {
|
|
|
1347
1353
|
statement.run(...deletableSessionIds);
|
|
1348
1354
|
}
|
|
1349
1355
|
deleteSessionActivity(db, deletableSessionIds);
|
|
1356
|
+
const deleteFoldGuards = cleanupStatement(db, "DELETE FROM schema_migrations_meta WHERE key = ? AND NOT EXISTS (SELECT 1 FROM session_meta WHERE session_id = ?)");
|
|
1357
|
+
for (const id of deletableSessionIds)
|
|
1358
|
+
deleteFoldGuards.run(piIdentityFoldGuardKey(id), id);
|
|
1350
1359
|
if (!options.preserveTagRevisionTombstones) {
|
|
1351
1360
|
const retireOwner = cleanupStatement(db, harness === undefined ? "DELETE FROM schema_migrations_meta WHERE key >= ? AND key < ?" : "DELETE FROM schema_migrations_meta WHERE key = ?");
|
|
1352
1361
|
const survivingRows = harnessTables.map((definition) => `EXISTS (SELECT 1 FROM ${definition.table} WHERE session_id = ?${definition.extraPredicate ? ` AND ${definition.extraPredicate}` : ""})`).join(" OR ");
|
|
@@ -4850,6 +4859,21 @@ function externalHistorianFailureReason(error, prefix = "provider_error") {
|
|
|
4850
4859
|
}
|
|
4851
4860
|
|
|
4852
4861
|
// src/features/magic-context/storage-historian-runs.ts
|
|
4862
|
+
function getRecentFailedHistorianRunTimes(db, sessionId, limit) {
|
|
4863
|
+
if (!Number.isInteger(limit) || limit <= 0)
|
|
4864
|
+
return [];
|
|
4865
|
+
try {
|
|
4866
|
+
return db.prepare(`SELECT created_at FROM historian_runs
|
|
4867
|
+
WHERE session_id = ? AND run_kind = 'incremental' AND status = 'failed'
|
|
4868
|
+
AND id > (
|
|
4869
|
+
SELECT COALESCE(MAX(id), 0) FROM historian_runs
|
|
4870
|
+
WHERE session_id = ? AND run_kind = 'incremental' AND status = 'success'
|
|
4871
|
+
)
|
|
4872
|
+
ORDER BY id DESC LIMIT ?`).all(sessionId, sessionId, limit).map((row) => row.created_at);
|
|
4873
|
+
} catch {
|
|
4874
|
+
return [];
|
|
4875
|
+
}
|
|
4876
|
+
}
|
|
4853
4877
|
function recordHistorianRun(db, input) {
|
|
4854
4878
|
try {
|
|
4855
4879
|
const failureReason = input.failureReason == null ? input.status === "failed" ? "provider_error" : null : capHistorianFailureReason(input.failureReason, input.status === "failed" ? "provider_error" : "");
|
|
@@ -5154,4 +5178,4 @@ var ERROR_CLASSES = new Set([
|
|
|
5154
5178
|
"permission_denied",
|
|
5155
5179
|
"unknown"
|
|
5156
5180
|
]);
|
|
5157
|
-
export { advanceSessionActivity, observeSessionActivity, backfillSessionActivity, COMPARTMENT_LEASE_RENEWAL_MS, getCompartmentLeaseBlocker, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, buildCompartmentBlock, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndsThrough, isPartialCompartmentEnd, readProjectDocsCanonical, readServerFallbackUsage, providerResponseFailed, isSuccessfulProviderCompletion, LkgRecoveryFenceError, lkgServedArrayDigest, hasCleanLkgRecoveryFence, dirtyLkgRecoveryRevision, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, prepareLkgCaptureFence, certifyCommittedLkgCapture, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, clearPendingMaterializationOrigin, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, isHeldHeadForRequest, deferDeliveredSystemRefresh, retirePendingSystemPromptDelivery, lkgProviderInputTotal, beginV2LkgRequest, claimLkgRequestIdentity, currentLkgRequestIdentity, noteCapturedLkgRequest, noteLkgProviderResponse, measuredLkgPrefix, clearLkgMeasuredRequest, saveLkgSlotToDb, clearPersistedLkgSlotStrict, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, resolveLkgModelKeys, createLkgEntryProjector, captureLkgSlot, validateAnthropicReasoningRuns, validateLkgSeam, replayLkg, coldStartRawServedIndex, coldStartUncapturedReplay, noteUncertifiedNormalLkg, hasProcessLocalLkgProof, lkgDirtyRevision, rememberLkgDirtyRevision, readPersistedLkgUntaggedInputIds, persistLkgUntaggedInputIds, noteLkgRecoveryPrefix, readLkgRecoveryPrefix, noteLkgHealthyPrefix, lkgRecoveryReplayUnproven, lkgRecoveryEntryUnproven, beginServedRequest, noteServedPassPermission, noteServedModel, noteServedReplay, noteServedHostInput, noteServedRefusal, countServedRefusal, dropServedRecord, forgetServedRecord, commitServedRequest, lkgInputIdentity, registerLkgPersistence, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgContentDigest, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, forgetInMemorySlot, dropSlot, noteEntry, getLkgSlotHeapStats, TOOL_SWEEP_SCOPED_MARKER, useScopedToolSweep, createPreAdoptionToolSweepResolver, copySessionStateForClone, externalHistorianFailureReason, recordHistorianRun, summarizeImportance, tallyFactsByCategory, MEMORY_VISIBILITY_MUTATION_CATEGORY, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId };
|
|
5181
|
+
export { advanceSessionActivity, observeSessionActivity, backfillSessionActivity, COMPARTMENT_LEASE_RENEWAL_MS, getCompartmentLeaseBlocker, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, buildCompartmentBlock, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndsThrough, isPartialCompartmentEnd, readProjectDocsCanonical, readServerFallbackUsage, providerResponseFailed, isSuccessfulProviderCompletion, LkgRecoveryFenceError, lkgServedArrayDigest, hasCleanLkgRecoveryFence, dirtyLkgRecoveryRevision, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, prepareLkgCaptureFence, certifyCommittedLkgCapture, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, clearPendingMaterializationOrigin, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, isHeldHeadForRequest, deferDeliveredSystemRefresh, retirePendingSystemPromptDelivery, lkgProviderInputTotal, beginV2LkgRequest, claimLkgRequestIdentity, currentLkgRequestIdentity, noteCapturedLkgRequest, noteLkgProviderResponse, measuredLkgPrefix, clearLkgMeasuredRequest, saveLkgSlotToDb, clearPersistedLkgSlotStrict, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, resolveLkgModelKeys, createLkgEntryProjector, captureLkgSlot, validateAnthropicReasoningRuns, validateLkgSeam, replayLkg, coldStartRawServedIndex, coldStartUncapturedReplay, noteUncertifiedNormalLkg, hasProcessLocalLkgProof, lkgDirtyRevision, rememberLkgDirtyRevision, readPersistedLkgUntaggedInputIds, persistLkgUntaggedInputIds, noteLkgRecoveryPrefix, readLkgRecoveryPrefix, noteLkgHealthyPrefix, lkgRecoveryReplayUnproven, lkgRecoveryEntryUnproven, beginServedRequest, noteServedPassPermission, noteServedModel, noteServedReplay, noteServedHostInput, noteServedRefusal, countServedRefusal, dropServedRecord, forgetServedRecord, commitServedRequest, lkgInputIdentity, registerLkgPersistence, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgContentDigest, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, forgetInMemorySlot, dropSlot, noteEntry, getLkgSlotHeapStats, TOOL_SWEEP_SCOPED_MARKER, useScopedToolSweep, createPreAdoptionToolSweepResolver, copySessionStateForClone, externalHistorianFailureReason, getRecentFailedHistorianRunTimes, recordHistorianRun, summarizeImportance, tallyFactsByCategory, MEMORY_VISIBILITY_MUTATION_CATEGORY, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId };
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
releaseCompartmentLeaseBestEffort,
|
|
9
9
|
getCompartments,
|
|
10
10
|
getLastCompartmentEndMessage
|
|
11
|
-
} from "./index-
|
|
11
|
+
} from "./index-bev3zks1.js";
|
|
12
12
|
import {
|
|
13
13
|
inRootAsyncContext2
|
|
14
14
|
} from "./index-gzy5w8ya.js";
|
|
@@ -34,14 +34,14 @@ import {
|
|
|
34
34
|
getActiveCompartmentRun,
|
|
35
35
|
markActiveCompartmentRunPublished,
|
|
36
36
|
registerActiveCompartmentRun
|
|
37
|
-
} from "./index-
|
|
37
|
+
} from "./index-3600gm9z.js";
|
|
38
38
|
import {
|
|
39
39
|
sendStatusNotification2
|
|
40
40
|
} from "./index-r9agn061.js";
|
|
41
41
|
import {
|
|
42
42
|
setRecompStarting2,
|
|
43
43
|
setRecompTerminal2
|
|
44
|
-
} from "./index-
|
|
44
|
+
} from "./index-x8e50d8f.js";
|
|
45
45
|
|
|
46
46
|
// src/hooks/magic-context/wrapup-orchestrator.ts
|
|
47
47
|
import * as crypto from "node:crypto";
|