@cortexkit/pi-magic-context 0.33.0 → 0.33.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{index-f3jfb2ed.js → index-e3kftg52.js} +682 -94
- package/dist/index.js +92 -544
- package/dist/subagent-entry.js +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import {
|
|
2
2
|
AGE_RECLAIM_MIN_TOKENS,
|
|
3
|
-
CANONICAL_DREAM_TASKS,
|
|
4
3
|
COMPARTMENT_LEASE_RENEWAL_MS,
|
|
5
4
|
COMPARTMENT_RENDER_EPOCH,
|
|
6
5
|
DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE,
|
|
@@ -63,7 +62,6 @@ import {
|
|
|
63
62
|
clearPersistedTodoSyntheticAnchor,
|
|
64
63
|
clearRecompStaging,
|
|
65
64
|
closeQuietly,
|
|
66
|
-
compareTaskOrder,
|
|
67
65
|
computeCueContentHash,
|
|
68
66
|
computeNormalizedHash,
|
|
69
67
|
computeWorkspaceEpochFingerprint,
|
|
@@ -150,13 +148,13 @@ import {
|
|
|
150
148
|
getNotes,
|
|
151
149
|
getNullOwnerToolTag,
|
|
152
150
|
getOldestActiveUnprotectedToolTags,
|
|
151
|
+
getOpenCodeDbPath,
|
|
153
152
|
getOrCreateSessionMeta,
|
|
154
153
|
getOverflowState,
|
|
155
154
|
getPendingCompactionMarkerState,
|
|
156
155
|
getPendingOps,
|
|
157
156
|
getPendingPiCompactionMarkerState,
|
|
158
157
|
getPendingSmartNotes,
|
|
159
|
-
getPersistedCompactionMarkerState,
|
|
160
158
|
getPersistedNoteNudge,
|
|
161
159
|
getPersistedTodoSyntheticAnchor,
|
|
162
160
|
getPersistedToolTagAccounting,
|
|
@@ -205,7 +203,6 @@ import {
|
|
|
205
203
|
insertUserMemory,
|
|
206
204
|
insertUserMemoryCandidates,
|
|
207
205
|
invalidateMemory,
|
|
208
|
-
isCanonicalDreamTask,
|
|
209
206
|
isCompartmentLeaseHeld,
|
|
210
207
|
isDreamerRunnable,
|
|
211
208
|
isEditTool,
|
|
@@ -215,8 +212,6 @@ import {
|
|
|
215
212
|
isRecord,
|
|
216
213
|
isSaneLimit,
|
|
217
214
|
isWrapupInProgress,
|
|
218
|
-
leaseKeyFor,
|
|
219
|
-
leaseKindFor,
|
|
220
215
|
loadPiConfig,
|
|
221
216
|
loadProtectedTailMeta,
|
|
222
217
|
markGitSweepSuccessAndRelease,
|
|
@@ -233,6 +228,7 @@ import {
|
|
|
233
228
|
openDatabase,
|
|
234
229
|
openDatabaseAsync,
|
|
235
230
|
parkGitSweepNonIndexable,
|
|
231
|
+
parseCompartmentOutput,
|
|
236
232
|
parseCron,
|
|
237
233
|
parseTodos,
|
|
238
234
|
peekDeferredExecutePending,
|
|
@@ -309,7 +305,6 @@ import {
|
|
|
309
305
|
setMemoryClassification,
|
|
310
306
|
setMuralCue,
|
|
311
307
|
setPendingPiCompactionMarkerState,
|
|
312
|
-
setPersistedCompactionMarkerState,
|
|
313
308
|
setPersistedNoteNudgeTrigger,
|
|
314
309
|
setPersistedNoteNudgeTriggerMessageId,
|
|
315
310
|
setPersistedTodoSyntheticAnchor,
|
|
@@ -333,6 +328,7 @@ import {
|
|
|
333
328
|
trimWorkspaceMemoriesToBudgetV2,
|
|
334
329
|
unifiedSearch,
|
|
335
330
|
updateCavemanDepth,
|
|
331
|
+
updateCompactionMarkerAfterPublication,
|
|
336
332
|
updatePrimerAnswer,
|
|
337
333
|
updatePrimerCandidateEmbedding,
|
|
338
334
|
updatePrimerSupport,
|
|
@@ -350,10 +346,9 @@ import {
|
|
|
350
346
|
withMigrationLanguageDirective,
|
|
351
347
|
withRawMessageProvider,
|
|
352
348
|
withRawSessionMessageCache
|
|
353
|
-
} from "./index-
|
|
349
|
+
} from "./index-e3kftg52.js";
|
|
354
350
|
import {
|
|
355
351
|
ensureCortexKitArtifactGitignore,
|
|
356
|
-
getDataDir,
|
|
357
352
|
getHarness,
|
|
358
353
|
getMagicContextStorageDir,
|
|
359
354
|
getProjectMagicContextHistorianDir,
|
|
@@ -368,7 +363,7 @@ import {
|
|
|
368
363
|
|
|
369
364
|
// src/index.ts
|
|
370
365
|
import { createRequire as createRequire3 } from "node:module";
|
|
371
|
-
import { join as
|
|
366
|
+
import { join as join5, resolve as resolve2 } from "node:path";
|
|
372
367
|
|
|
373
368
|
// ../plugin/src/shared/resolve-fallbacks.ts
|
|
374
369
|
function resolveFallbackChain(userFallbacks) {
|
|
@@ -415,6 +410,61 @@ function modelBodyField(spec) {
|
|
|
415
410
|
return parsed ? { model: parsed } : {};
|
|
416
411
|
}
|
|
417
412
|
|
|
413
|
+
// ../plugin/src/features/magic-context/dreamer/task-registry.ts
|
|
414
|
+
var CANONICAL_DREAM_TASKS = [
|
|
415
|
+
"map-memories",
|
|
416
|
+
"verify",
|
|
417
|
+
"verify-broad",
|
|
418
|
+
"curate",
|
|
419
|
+
"compress-cues",
|
|
420
|
+
"classify-memories",
|
|
421
|
+
"retrospective",
|
|
422
|
+
"maintain-docs",
|
|
423
|
+
"evaluate-smart-notes",
|
|
424
|
+
"review-user-memories",
|
|
425
|
+
"promote-primers",
|
|
426
|
+
"refresh-primers"
|
|
427
|
+
];
|
|
428
|
+
var MEMORY_DOMAIN_TASKS = [
|
|
429
|
+
"map-memories",
|
|
430
|
+
"verify",
|
|
431
|
+
"verify-broad",
|
|
432
|
+
"curate",
|
|
433
|
+
"compress-cues",
|
|
434
|
+
"classify-memories",
|
|
435
|
+
"retrospective",
|
|
436
|
+
"promote-primers",
|
|
437
|
+
"refresh-primers"
|
|
438
|
+
];
|
|
439
|
+
var MEMORY_DOMAIN_SET = new Set(MEMORY_DOMAIN_TASKS);
|
|
440
|
+
function leaseKindFor(task) {
|
|
441
|
+
if (MEMORY_DOMAIN_SET.has(task))
|
|
442
|
+
return "memory";
|
|
443
|
+
switch (task) {
|
|
444
|
+
case "review-user-memories":
|
|
445
|
+
return "user-memories";
|
|
446
|
+
case "promote-primers":
|
|
447
|
+
case "refresh-primers":
|
|
448
|
+
return "memory";
|
|
449
|
+
case "maintain-docs":
|
|
450
|
+
return "maintain-docs";
|
|
451
|
+
case "evaluate-smart-notes":
|
|
452
|
+
return "evaluate-smart-notes";
|
|
453
|
+
default:
|
|
454
|
+
return "memory";
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
function leaseKeyFor(task, projectIdentity) {
|
|
458
|
+
const kind = leaseKindFor(task);
|
|
459
|
+
return kind === "user-memories" ? "user-memories" : `${kind}:${projectIdentity}`;
|
|
460
|
+
}
|
|
461
|
+
function isCanonicalDreamTask(value) {
|
|
462
|
+
return CANONICAL_DREAM_TASKS.includes(value);
|
|
463
|
+
}
|
|
464
|
+
function compareTaskOrder(a, b) {
|
|
465
|
+
return CANONICAL_DREAM_TASKS.indexOf(a) - CANONICAL_DREAM_TASKS.indexOf(b);
|
|
466
|
+
}
|
|
467
|
+
|
|
418
468
|
// ../plugin/src/features/magic-context/dreamer/task-config.ts
|
|
419
469
|
function buildDreamTaskRuntimeConfigs(dreamer, language) {
|
|
420
470
|
const tasks = dreamer.tasks ?? {};
|
|
@@ -2903,264 +2953,10 @@ ${sidekickText}
|
|
|
2903
2953
|
}
|
|
2904
2954
|
|
|
2905
2955
|
// ../plugin/src/features/magic-context/dreamer/open-opencode-db.ts
|
|
2906
|
-
import { existsSync as existsSync5 } from "node:fs";
|
|
2907
|
-
|
|
2908
|
-
// ../plugin/src/features/magic-context/compaction-marker.ts
|
|
2909
|
-
import { createHash as createHash2 } from "node:crypto";
|
|
2910
2956
|
import { existsSync as existsSync4 } from "node:fs";
|
|
2911
|
-
import { join as join3 } from "node:path";
|
|
2912
|
-
var BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
2913
|
-
var ID_PREFIX_HEX_LENGTH = 12;
|
|
2914
|
-
var ID_SUFFIX_LENGTH = 14;
|
|
2915
|
-
var ID_PREFIX_MASK = (1n << BigInt(ID_PREFIX_HEX_LENGTH * 4)) - 1n;
|
|
2916
|
-
function deterministicBase62(seed, length) {
|
|
2917
|
-
let value = BigInt(`0x${createHash2("sha256").update(seed).digest("hex")}`);
|
|
2918
|
-
const chars = Array(length);
|
|
2919
|
-
for (let index = length - 1;index >= 0; index -= 1) {
|
|
2920
|
-
chars[index] = BASE62_CHARS[Number(value % 62n)];
|
|
2921
|
-
value /= 62n;
|
|
2922
|
-
}
|
|
2923
|
-
return chars.join("");
|
|
2924
|
-
}
|
|
2925
|
-
function generateId(prefix, timestampMs, counter, identity) {
|
|
2926
|
-
const encoded = BigInt(Math.max(0, Math.floor(timestampMs))) * 0x1000n + counter & ID_PREFIX_MASK;
|
|
2927
|
-
const hex = encoded.toString(16).padStart(ID_PREFIX_HEX_LENGTH, "0");
|
|
2928
|
-
return `${prefix}_${hex}${deterministicBase62(`${prefix}\x00${identity}`, ID_SUFFIX_LENGTH)}`;
|
|
2929
|
-
}
|
|
2930
|
-
function generateMessageId(timestampMs, counter = 0n, identity = "") {
|
|
2931
|
-
return generateId("msg", timestampMs, counter, identity);
|
|
2932
|
-
}
|
|
2933
|
-
function generatePartId(timestampMs, counter = 0n, identity = "") {
|
|
2934
|
-
return generateId("prt", timestampMs, counter, identity);
|
|
2935
|
-
}
|
|
2936
|
-
function getOpenCodeDbPath() {
|
|
2937
|
-
return join3(getDataDir(), "opencode", "opencode.db");
|
|
2938
|
-
}
|
|
2939
|
-
var cachedWriteDb = null;
|
|
2940
|
-
var REQUIRED_MESSAGE_COLUMNS = ["id", "session_id", "time_created", "time_updated", "data"];
|
|
2941
|
-
var REQUIRED_PART_COLUMNS = [
|
|
2942
|
-
"id",
|
|
2943
|
-
"message_id",
|
|
2944
|
-
"session_id",
|
|
2945
|
-
"time_created",
|
|
2946
|
-
"time_updated",
|
|
2947
|
-
"data"
|
|
2948
|
-
];
|
|
2949
|
-
var cachedSchemaCompatible = null;
|
|
2950
|
-
function isOpenCodeSchemaCompatible(db, dbPath) {
|
|
2951
|
-
if (cachedSchemaCompatible?.path === dbPath) {
|
|
2952
|
-
return cachedSchemaCompatible.compatible;
|
|
2953
|
-
}
|
|
2954
|
-
try {
|
|
2955
|
-
const messageCols = new Set(db.prepare("PRAGMA table_info(message)").all().map((r) => r.name ?? "").filter((n) => n.length > 0));
|
|
2956
|
-
const partCols = new Set(db.prepare("PRAGMA table_info(part)").all().map((r) => r.name ?? "").filter((n) => n.length > 0));
|
|
2957
|
-
const missingMessage = REQUIRED_MESSAGE_COLUMNS.filter((c) => !messageCols.has(c));
|
|
2958
|
-
const missingPart = REQUIRED_PART_COLUMNS.filter((c) => !partCols.has(c));
|
|
2959
|
-
if (missingMessage.length > 0 || missingPart.length > 0) {
|
|
2960
|
-
log(`[magic-context] compaction-marker: OpenCode DB schema missing required columns ` + `(message: [${missingMessage.join(", ")}], part: [${missingPart.join(", ")}]). ` + `Marker injection disabled for this process. ` + `This usually means OpenCode was updated and magic-context is out of date.`);
|
|
2961
|
-
cachedSchemaCompatible = { path: dbPath, compatible: false };
|
|
2962
|
-
return false;
|
|
2963
|
-
}
|
|
2964
|
-
cachedSchemaCompatible = { path: dbPath, compatible: true };
|
|
2965
|
-
return true;
|
|
2966
|
-
} catch (error) {
|
|
2967
|
-
log(`[magic-context] compaction-marker: schema probe failed: ${error instanceof Error ? error.message : String(error)}. ` + `Marker injection disabled until next process restart.`);
|
|
2968
|
-
cachedSchemaCompatible = { path: dbPath, compatible: false };
|
|
2969
|
-
return false;
|
|
2970
|
-
}
|
|
2971
|
-
}
|
|
2972
|
-
function getWritableOpenCodeDb() {
|
|
2973
|
-
const dbPath = getOpenCodeDbPath();
|
|
2974
|
-
if (cachedWriteDb?.path === dbPath) {
|
|
2975
|
-
return cachedWriteDb.db;
|
|
2976
|
-
}
|
|
2977
|
-
if (cachedWriteDb) {
|
|
2978
|
-
try {
|
|
2979
|
-
closeQuietly(cachedWriteDb.db);
|
|
2980
|
-
} catch {}
|
|
2981
|
-
}
|
|
2982
|
-
if (!existsSync4(dbPath)) {
|
|
2983
|
-
throw new Error(`OpenCode database not found at ${dbPath} (is OpenCode installed?)`);
|
|
2984
|
-
}
|
|
2985
|
-
const db = new Database(dbPath);
|
|
2986
|
-
db.exec("PRAGMA busy_timeout=5000");
|
|
2987
|
-
db.exec("PRAGMA journal_mode=WAL");
|
|
2988
|
-
cachedWriteDb = { path: dbPath, db };
|
|
2989
|
-
return db;
|
|
2990
|
-
}
|
|
2991
|
-
function getNonSummaryMessageSortKey(sessionId, messageId) {
|
|
2992
|
-
const db = getWritableOpenCodeDb();
|
|
2993
|
-
const row = db.prepare(`SELECT time_created, id
|
|
2994
|
-
FROM message
|
|
2995
|
-
WHERE session_id = ?
|
|
2996
|
-
AND id = ?
|
|
2997
|
-
AND NOT (COALESCE(json_extract(data, '$.summary'), 0) = 1
|
|
2998
|
-
AND COALESCE(json_extract(data, '$.finish'), '') = 'stop')
|
|
2999
|
-
LIMIT 1`).get(sessionId, messageId);
|
|
3000
|
-
if (typeof row?.time_created !== "number" || typeof row.id !== "string") {
|
|
3001
|
-
return null;
|
|
3002
|
-
}
|
|
3003
|
-
return { id: row.id, timeCreated: row.time_created };
|
|
3004
|
-
}
|
|
3005
|
-
function findBoundaryUserMessage(sessionId, endMessageId) {
|
|
3006
|
-
const db = getWritableOpenCodeDb();
|
|
3007
|
-
const target = getNonSummaryMessageSortKey(sessionId, endMessageId);
|
|
3008
|
-
if (!target)
|
|
3009
|
-
return null;
|
|
3010
|
-
const boundary = db.prepare(`SELECT id, time_created, data
|
|
3011
|
-
FROM message
|
|
3012
|
-
WHERE session_id = ?
|
|
3013
|
-
AND NOT (COALESCE(json_extract(data, '$.summary'), 0) = 1
|
|
3014
|
-
AND COALESCE(json_extract(data, '$.finish'), '') = 'stop')
|
|
3015
|
-
AND COALESCE(json_extract(data, '$.role'), '') = 'user'
|
|
3016
|
-
AND (time_created < ? OR (time_created = ? AND id <= ?))
|
|
3017
|
-
ORDER BY time_created DESC, id DESC
|
|
3018
|
-
LIMIT 1`).get(sessionId, target.timeCreated, target.timeCreated, target.id);
|
|
3019
|
-
if (typeof boundary?.id !== "string" || typeof boundary.time_created !== "number") {
|
|
3020
|
-
return null;
|
|
3021
|
-
}
|
|
3022
|
-
return { id: boundary.id, timeCreated: boundary.time_created };
|
|
3023
|
-
}
|
|
3024
|
-
function compareOpenCodeMessagesByCanonicalOrder(sessionId, leftMessageId, rightMessageId) {
|
|
3025
|
-
const left = getNonSummaryMessageSortKey(sessionId, leftMessageId);
|
|
3026
|
-
const right = getNonSummaryMessageSortKey(sessionId, rightMessageId);
|
|
3027
|
-
if (!left || !right)
|
|
3028
|
-
return null;
|
|
3029
|
-
if (left.timeCreated < right.timeCreated)
|
|
3030
|
-
return -1;
|
|
3031
|
-
if (left.timeCreated > right.timeCreated)
|
|
3032
|
-
return 1;
|
|
3033
|
-
if (left.id < right.id)
|
|
3034
|
-
return -1;
|
|
3035
|
-
if (left.id > right.id)
|
|
3036
|
-
return 1;
|
|
3037
|
-
return 0;
|
|
3038
|
-
}
|
|
3039
|
-
function removeLegacyMarkerLineageRows(db, args) {
|
|
3040
|
-
const legacySummaries = db.prepare(`SELECT m.id
|
|
3041
|
-
FROM message m
|
|
3042
|
-
WHERE m.session_id = ?
|
|
3043
|
-
AND m.id <> ?
|
|
3044
|
-
AND COALESCE(json_extract(m.data, '$.summary'), 0) = 1
|
|
3045
|
-
AND COALESCE(json_extract(m.data, '$.finish'), '') = 'stop'
|
|
3046
|
-
AND COALESCE(json_extract(m.data, '$.parentID'), '') = ?
|
|
3047
|
-
AND EXISTS (
|
|
3048
|
-
SELECT 1
|
|
3049
|
-
FROM part p
|
|
3050
|
-
WHERE p.session_id = m.session_id
|
|
3051
|
-
AND p.message_id = m.id
|
|
3052
|
-
AND COALESCE(json_extract(p.data, '$.type'), '') = 'text'
|
|
3053
|
-
AND COALESCE(json_extract(p.data, '$.text'), '') = ?
|
|
3054
|
-
)`).all(args.sessionId, args.summaryMessageId, args.boundaryMessageId, args.summaryText);
|
|
3055
|
-
const legacySummaryIds = legacySummaries.flatMap((row) => typeof row.id === "string" ? [row.id] : []);
|
|
3056
|
-
if (legacySummaryIds.length === 0)
|
|
3057
|
-
return;
|
|
3058
|
-
const deleteSummaryParts = db.prepare("DELETE FROM part WHERE session_id = ? AND message_id = ?");
|
|
3059
|
-
const deleteSummary = db.prepare("DELETE FROM message WHERE session_id = ? AND id = ?");
|
|
3060
|
-
for (const summaryMessageId of legacySummaryIds) {
|
|
3061
|
-
deleteSummaryParts.run(args.sessionId, summaryMessageId);
|
|
3062
|
-
deleteSummary.run(args.sessionId, summaryMessageId);
|
|
3063
|
-
}
|
|
3064
|
-
db.prepare(`DELETE FROM part
|
|
3065
|
-
WHERE session_id = ?
|
|
3066
|
-
AND message_id = ?
|
|
3067
|
-
AND id <> ?
|
|
3068
|
-
AND COALESCE(json_extract(data, '$.type'), '') = 'compaction'
|
|
3069
|
-
AND COALESCE(json_extract(data, '$.auto'), 0) = 1`).run(args.sessionId, args.boundaryMessageId, args.compactionPartId);
|
|
3070
|
-
}
|
|
3071
|
-
function injectCompactionMarker(args) {
|
|
3072
|
-
const db = getWritableOpenCodeDb();
|
|
3073
|
-
if (!isOpenCodeSchemaCompatible(db, getOpenCodeDbPath())) {
|
|
3074
|
-
return null;
|
|
3075
|
-
}
|
|
3076
|
-
const boundary = args.resolvedBoundary ?? findBoundaryUserMessage(args.sessionId, args.endMessageId);
|
|
3077
|
-
if (!boundary) {
|
|
3078
|
-
log(`[magic-context] compaction-marker: no user message found at or before endMessageId ${args.endMessageId} (ordinal ${args.endOrdinal})`);
|
|
3079
|
-
return null;
|
|
3080
|
-
}
|
|
3081
|
-
const boundaryTime = boundary.timeCreated;
|
|
3082
|
-
const markerIdentity = `${args.sessionId}\x00${args.endMessageId}`;
|
|
3083
|
-
const summaryMsgId = generateMessageId(boundaryTime + 1, 1n, `${markerIdentity}\x00summary-message`);
|
|
3084
|
-
const compactionPartId = generatePartId(boundaryTime, 1n, `${markerIdentity}\x00compaction-part`);
|
|
3085
|
-
const summaryPartId = generatePartId(boundaryTime + 1, 2n, `${markerIdentity}\x00summary-part`);
|
|
3086
|
-
const summaryMsgData = JSON.stringify({
|
|
3087
|
-
role: "assistant",
|
|
3088
|
-
parentID: boundary.id,
|
|
3089
|
-
summary: true,
|
|
3090
|
-
finish: "stop",
|
|
3091
|
-
mode: "compaction",
|
|
3092
|
-
agent: "compaction",
|
|
3093
|
-
path: { cwd: args.directory, root: args.directory },
|
|
3094
|
-
cost: 0,
|
|
3095
|
-
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
|
3096
|
-
modelID: "magic-context",
|
|
3097
|
-
providerID: "magic-context",
|
|
3098
|
-
time: { created: boundaryTime + 1 }
|
|
3099
|
-
});
|
|
3100
|
-
try {
|
|
3101
|
-
db.transaction(() => {
|
|
3102
|
-
removeLegacyMarkerLineageRows(db, {
|
|
3103
|
-
sessionId: args.sessionId,
|
|
3104
|
-
boundaryMessageId: boundary.id,
|
|
3105
|
-
summaryText: args.summaryText,
|
|
3106
|
-
summaryMessageId: summaryMsgId,
|
|
3107
|
-
compactionPartId
|
|
3108
|
-
});
|
|
3109
|
-
db.prepare(`INSERT INTO part (id, message_id, session_id, time_created, time_updated, data)
|
|
3110
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
3111
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
3112
|
-
message_id = excluded.message_id,
|
|
3113
|
-
session_id = excluded.session_id,
|
|
3114
|
-
time_created = excluded.time_created,
|
|
3115
|
-
time_updated = excluded.time_updated,
|
|
3116
|
-
data = excluded.data`).run(compactionPartId, boundary.id, args.sessionId, boundaryTime, boundaryTime, '{"type":"compaction","auto":true}');
|
|
3117
|
-
db.prepare(`INSERT INTO message (id, session_id, time_created, time_updated, data)
|
|
3118
|
-
VALUES (?, ?, ?, ?, ?)
|
|
3119
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
3120
|
-
session_id = excluded.session_id,
|
|
3121
|
-
time_created = excluded.time_created,
|
|
3122
|
-
time_updated = excluded.time_updated,
|
|
3123
|
-
data = excluded.data`).run(summaryMsgId, args.sessionId, boundaryTime + 1, boundaryTime + 1, summaryMsgData);
|
|
3124
|
-
db.prepare(`INSERT INTO part (id, message_id, session_id, time_created, time_updated, data)
|
|
3125
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
3126
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
3127
|
-
message_id = excluded.message_id,
|
|
3128
|
-
session_id = excluded.session_id,
|
|
3129
|
-
time_created = excluded.time_created,
|
|
3130
|
-
time_updated = excluded.time_updated,
|
|
3131
|
-
data = excluded.data`).run(summaryPartId, summaryMsgId, args.sessionId, boundaryTime + 1, boundaryTime + 1, JSON.stringify({ type: "text", text: args.summaryText }));
|
|
3132
|
-
})();
|
|
3133
|
-
log(`[magic-context] compaction-marker: injected boundary at user msg ${boundary.id} (ordinal ~${args.endOrdinal}), summary msg ${summaryMsgId}`);
|
|
3134
|
-
return {
|
|
3135
|
-
boundaryMessageId: boundary.id,
|
|
3136
|
-
summaryMessageId: summaryMsgId,
|
|
3137
|
-
compactionPartId,
|
|
3138
|
-
summaryPartId
|
|
3139
|
-
};
|
|
3140
|
-
} catch (error) {
|
|
3141
|
-
log(`[magic-context] compaction-marker: injection failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
3142
|
-
return null;
|
|
3143
|
-
}
|
|
3144
|
-
}
|
|
3145
|
-
function removeCompactionMarker(state) {
|
|
3146
|
-
try {
|
|
3147
|
-
const db = getWritableOpenCodeDb();
|
|
3148
|
-
db.transaction(() => {
|
|
3149
|
-
db.prepare("DELETE FROM part WHERE id = ?").run(state.summaryPartId);
|
|
3150
|
-
db.prepare("DELETE FROM message WHERE id = ?").run(state.summaryMessageId);
|
|
3151
|
-
db.prepare("DELETE FROM part WHERE id = ?").run(state.compactionPartId);
|
|
3152
|
-
})();
|
|
3153
|
-
return true;
|
|
3154
|
-
} catch (error) {
|
|
3155
|
-
log(`[magic-context] compaction-marker: removal failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
3156
|
-
return false;
|
|
3157
|
-
}
|
|
3158
|
-
}
|
|
3159
|
-
|
|
3160
|
-
// ../plugin/src/features/magic-context/dreamer/open-opencode-db.ts
|
|
3161
2957
|
function openOpenCodeDb() {
|
|
3162
2958
|
const dbPath = getOpenCodeDbPath();
|
|
3163
|
-
if (!
|
|
2959
|
+
if (!existsSync4(dbPath)) {
|
|
3164
2960
|
log(`[dreamer] OpenCode DB not found at ${dbPath} — skipping OpenCode history scan`);
|
|
3165
2961
|
return null;
|
|
3166
2962
|
}
|
|
@@ -3175,8 +2971,8 @@ function openOpenCodeDb() {
|
|
|
3175
2971
|
}
|
|
3176
2972
|
|
|
3177
2973
|
// ../plugin/src/features/magic-context/dreamer/task-executor.ts
|
|
3178
|
-
import { createHash as
|
|
3179
|
-
import { existsSync as
|
|
2974
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
2975
|
+
import { existsSync as existsSync7 } from "node:fs";
|
|
3180
2976
|
|
|
3181
2977
|
// ../plugin/src/agents/dreamer.ts
|
|
3182
2978
|
var DREAMER_AGENT = "dreamer";
|
|
@@ -4585,7 +4381,7 @@ If no promotions are warranted, return empty arrays. Always consume reviewed can
|
|
|
4585
4381
|
}
|
|
4586
4382
|
|
|
4587
4383
|
// ../plugin/src/features/magic-context/dreamer/classify.ts
|
|
4588
|
-
import { createHash as
|
|
4384
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
4589
4385
|
|
|
4590
4386
|
// ../plugin/src/plugin/rust-tool-backends.ts
|
|
4591
4387
|
function isRustAuthorityDrainingError(error) {
|
|
@@ -5146,7 +4942,7 @@ async function runClassifyThroughModule(args, chunk, anchors, signal) {
|
|
|
5146
4942
|
v: 1,
|
|
5147
4943
|
session_id: args.moduleSessionId,
|
|
5148
4944
|
task: "classify",
|
|
5149
|
-
command_id: `classify:${args.moduleCommandId ?? Date.now()}:${
|
|
4945
|
+
command_id: `classify:${args.moduleCommandId ?? Date.now()}:${createHash2("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`,
|
|
5150
4946
|
authority_generation: args.moduleAuthorityGeneration,
|
|
5151
4947
|
payload: {
|
|
5152
4948
|
prompt_body: prompt,
|
|
@@ -5842,7 +5638,7 @@ function throwIfAborted2(signal) {
|
|
|
5842
5638
|
}
|
|
5843
5639
|
|
|
5844
5640
|
// ../plugin/src/features/magic-context/smart-notes/compiler.ts
|
|
5845
|
-
import { createHash as
|
|
5641
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
5846
5642
|
|
|
5847
5643
|
// ../plugin/src/features/magic-context/smart-notes/compiler-prompt.ts
|
|
5848
5644
|
var SMART_NOTE_COMPILER_SYSTEM_PROMPT = `You are the Magic Context smart-note compiler for the magic-context system.
|
|
@@ -6266,7 +6062,7 @@ function manifestAdvisoryWarnings(code, manifest) {
|
|
|
6266
6062
|
return warnings;
|
|
6267
6063
|
}
|
|
6268
6064
|
function hashCheck(surfaceCondition, compiledCheck, manifest, checkCron) {
|
|
6269
|
-
return
|
|
6065
|
+
return createHash3("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
|
|
6270
6066
|
}
|
|
6271
6067
|
function extractJsonObject(output) {
|
|
6272
6068
|
const fenced = output.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
@@ -6964,8 +6760,8 @@ Output exactly JSON: {"met": false}`;
|
|
|
6964
6760
|
}
|
|
6965
6761
|
|
|
6966
6762
|
// ../plugin/src/features/magic-context/dreamer/maintain-docs-protected-enforcement.ts
|
|
6967
|
-
import { existsSync as
|
|
6968
|
-
import { join as
|
|
6763
|
+
import { existsSync as existsSync5, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "node:fs";
|
|
6764
|
+
import { join as join3 } from "node:path";
|
|
6969
6765
|
|
|
6970
6766
|
// ../plugin/src/features/magic-context/dreamer/protected-regions.ts
|
|
6971
6767
|
var PROTECTED_START_TOKEN = "mc:protected START";
|
|
@@ -7066,9 +6862,9 @@ var MAINTAIN_DOCS_SNAPSHOT_FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
|
|
|
7066
6862
|
function snapshotMaintainDocsFiles(docsDir) {
|
|
7067
6863
|
const snapshot = new Map;
|
|
7068
6864
|
for (const name of MAINTAIN_DOCS_SNAPSHOT_FILES) {
|
|
7069
|
-
const path4 =
|
|
6865
|
+
const path4 = join3(docsDir, name);
|
|
7070
6866
|
try {
|
|
7071
|
-
if (
|
|
6867
|
+
if (existsSync5(path4)) {
|
|
7072
6868
|
snapshot.set(name, readFileSync2(path4, "utf8"));
|
|
7073
6869
|
}
|
|
7074
6870
|
} catch {}
|
|
@@ -7077,7 +6873,7 @@ function snapshotMaintainDocsFiles(docsDir) {
|
|
|
7077
6873
|
}
|
|
7078
6874
|
function enforceMaintainDocsProtectedRegions(args) {
|
|
7079
6875
|
for (const [fileName, original] of args.snapshot) {
|
|
7080
|
-
const path4 =
|
|
6876
|
+
const path4 = join3(args.docsDir, fileName);
|
|
7081
6877
|
try {
|
|
7082
6878
|
const current = readFileSync2(path4, "utf8");
|
|
7083
6879
|
const { text, violated } = enforceProtectedRegions(original, current);
|
|
@@ -7093,10 +6889,10 @@ function enforceMaintainDocsProtectedRegions(args) {
|
|
|
7093
6889
|
}
|
|
7094
6890
|
|
|
7095
6891
|
// ../plugin/src/features/magic-context/dreamer/map-memories.ts
|
|
7096
|
-
import { createHash as
|
|
6892
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
7097
6893
|
|
|
7098
6894
|
// ../plugin/src/features/magic-context/dreamer/map-memories-prompt.ts
|
|
7099
|
-
import { existsSync as
|
|
6895
|
+
import { existsSync as existsSync6, statSync } from "node:fs";
|
|
7100
6896
|
import path4 from "node:path";
|
|
7101
6897
|
var MAP_MEMORIES_SYSTEM_PROMPT = `You are a memory mapper for the magic-context system. You map project memories to the repository files that back them.
|
|
7102
6898
|
|
|
@@ -7134,7 +6930,7 @@ function extractMemoryCandidatePaths(content, repoDir) {
|
|
|
7134
6930
|
if (!abs.startsWith(`${root}/`))
|
|
7135
6931
|
continue;
|
|
7136
6932
|
try {
|
|
7137
|
-
if (
|
|
6933
|
+
if (existsSync6(abs) && statSync(abs).isFile())
|
|
7138
6934
|
found.add(rel);
|
|
7139
6935
|
} catch {}
|
|
7140
6936
|
if (found.size >= MAX_SEED_PATHS_PER_MEMORY)
|
|
@@ -7353,7 +7149,7 @@ async function applyBatchMappings(args, batch, manifestText) {
|
|
|
7353
7149
|
memory_project: args.projectIdentity,
|
|
7354
7150
|
context_store_uuid: args.moduleRoute.moduleContextStoreUuid,
|
|
7355
7151
|
authority_generation: args.moduleRoute.moduleAuthorityGeneration,
|
|
7356
|
-
command_id: `${args.moduleRoute.moduleCommandId}:${
|
|
7152
|
+
command_id: `${args.moduleRoute.moduleCommandId}:${createHash4("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
|
|
7357
7153
|
rows
|
|
7358
7154
|
}
|
|
7359
7155
|
}
|
|
@@ -8473,7 +8269,7 @@ function recordRetrospectiveWindowProcessed(db, projectPath, windowKey) {
|
|
|
8473
8269
|
}
|
|
8474
8270
|
|
|
8475
8271
|
// ../plugin/src/features/magic-context/dreamer/verify.ts
|
|
8476
|
-
import { createHash as
|
|
8272
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
8477
8273
|
|
|
8478
8274
|
// ../plugin/src/features/magic-context/dreamer/verify-gate.ts
|
|
8479
8275
|
import path5 from "node:path";
|
|
@@ -8811,7 +8607,7 @@ async function applyVerifyManifest(args, batch, manifestText) {
|
|
|
8811
8607
|
memory_project: args.projectIdentity,
|
|
8812
8608
|
context_store_uuid: args.moduleRoute.moduleContextStoreUuid,
|
|
8813
8609
|
authority_generation: args.moduleRoute.moduleAuthorityGeneration,
|
|
8814
|
-
command_id: `${args.moduleRoute.moduleCommandId}:${
|
|
8610
|
+
command_id: `${args.moduleRoute.moduleCommandId}:${createHash5("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
|
|
8815
8611
|
rows
|
|
8816
8612
|
}
|
|
8817
8613
|
}
|
|
@@ -9308,7 +9104,7 @@ function parseFrictionGateVerdict(verdict) {
|
|
|
9308
9104
|
}
|
|
9309
9105
|
function computeRetrospectiveWindowKey(flagged) {
|
|
9310
9106
|
const anchors = flagged.map((message) => `${message.sessionId}:${message.ts}`).sort().join("|");
|
|
9311
|
-
return
|
|
9107
|
+
return createHash6("sha256").update(anchors).digest("hex").slice(0, 32);
|
|
9312
9108
|
}
|
|
9313
9109
|
function renderFrictionWindow(messages, flaggedOrdinals, radius = 2) {
|
|
9314
9110
|
const flagged = new Set(flaggedOrdinals);
|
|
@@ -9541,8 +9337,8 @@ async function runAgenticTask(config, ctx, helpers) {
|
|
|
9541
9337
|
const lastRunAt = getTaskScheduleState(db, projectIdentity, config.task)?.lastRunAt ?? null;
|
|
9542
9338
|
const maintainDocsSnapshot = task === "maintain-docs" ? snapshotMaintainDocsFiles(docsDir) : undefined;
|
|
9543
9339
|
const existingDocs = task === "maintain-docs" ? {
|
|
9544
|
-
architecture:
|
|
9545
|
-
structure:
|
|
9340
|
+
architecture: existsSync7(`${docsDir}/ARCHITECTURE.md`),
|
|
9341
|
+
structure: existsSync7(`${docsDir}/STRUCTURE.md`)
|
|
9546
9342
|
} : undefined;
|
|
9547
9343
|
const userMemories = task === "curate" ? getActiveUserMemories(db).map((um) => ({ id: um.id, content: um.content })) : undefined;
|
|
9548
9344
|
let curateMemories;
|
|
@@ -13977,7 +13773,7 @@ function advanceToolReclaimWatermarkToCurrentMax(db, sessionId) {
|
|
|
13977
13773
|
}
|
|
13978
13774
|
|
|
13979
13775
|
// ../plugin/src/shared/tag-transcript.ts
|
|
13980
|
-
import { createHash as
|
|
13776
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
13981
13777
|
|
|
13982
13778
|
// ../plugin/src/hooks/magic-context/image-token-estimate.ts
|
|
13983
13779
|
var IMAGE_TOKEN_DIVISOR = 750;
|
|
@@ -14132,7 +13928,7 @@ function readUint32BE(b, offset) {
|
|
|
14132
13928
|
// ../plugin/src/shared/tag-transcript.ts
|
|
14133
13929
|
var TEXT_TAG_IDENTITY_MARKER = ":mc-text-v1:";
|
|
14134
13930
|
function textIdentityDigest(value) {
|
|
14135
|
-
return
|
|
13931
|
+
return createHash7("sha256").update(value).digest("hex");
|
|
14136
13932
|
}
|
|
14137
13933
|
function buildContentDerivedTextIds(messageId, parts) {
|
|
14138
13934
|
const sources = parts.filter((part) => part.kind === "text").map((part) => stripTagPrefix(part.getText() ?? ""));
|
|
@@ -17745,6 +17541,8 @@ If no candidates, omit the \`<primer_candidates>\` section entirely.
|
|
|
17745
17541
|
|
|
17746
17542
|
Output valid XML only in this shape:
|
|
17747
17543
|
|
|
17544
|
+
Closing tags must match their opening tier tag (e.g. \`<p1>...</p1>\`, never \`<p1>...</p2>\`).
|
|
17545
|
+
|
|
17748
17546
|
\`\`\`xml
|
|
17749
17547
|
<output>
|
|
17750
17548
|
<compartments>
|
|
@@ -17961,161 +17759,6 @@ function queueDropsForCompartmentalizedMessages(db, sessionId, upToMessageIndex)
|
|
|
17961
17759
|
sessionLog(sessionId, `compartment agent: queued ${dropsQueued} drops for messages 0-${upToMessageIndex}`);
|
|
17962
17760
|
}
|
|
17963
17761
|
|
|
17964
|
-
// ../plugin/src/hooks/magic-context/compartment-parser.ts
|
|
17965
|
-
var COMPARTMENT_REGEX = /<compartment\s+([^>]*?)\s*>(.*?)<\/compartment>/gs;
|
|
17966
|
-
var ATTR_START_REGEX = /\bstart="(\d+)"/;
|
|
17967
|
-
var ATTR_END_REGEX = /\bend="(\d+)"/;
|
|
17968
|
-
var ATTR_TITLE_REGEX = /\btitle="([^"]*)"/;
|
|
17969
|
-
var ATTR_EPISODE_REGEX = /\bepisode_type="([^"]*)"/;
|
|
17970
|
-
var ATTR_IMPORTANCE_REGEX = /\bimportance="(\d+)"/;
|
|
17971
|
-
function makeTierRegex(n) {
|
|
17972
|
-
return new RegExp(`<p${n}\\s*/>|<p${n}\\s*>(.*?)</p${n}>`, "s");
|
|
17973
|
-
}
|
|
17974
|
-
var TIER_REGEXES = [makeTierRegex(1), makeTierRegex(2), makeTierRegex(3), makeTierRegex(4)];
|
|
17975
|
-
var CATEGORY_BLOCK_REGEX = /<(PROJECT_RULES|ARCHITECTURE|CONSTRAINTS|CONFIG_VALUES|NAMING)>(.*?)<\/\1>/gs;
|
|
17976
|
-
var FACT_ITEM_REGEX = /^\s*\*\s*(.+)$/gm;
|
|
17977
|
-
var UNPROCESSED_REGEX = /<unprocessed_from>(\d+)<\/unprocessed_from>/;
|
|
17978
|
-
var USER_OBSERVATIONS_REGEX = /<user_observations>(.*?)<\/user_observations>/s;
|
|
17979
|
-
var USER_OBS_ITEM_REGEX = /^\s*\*\s*(.+)$/gm;
|
|
17980
|
-
var PRIMER_CANDIDATES_REGEX = /<primer_candidates>(.*?)<\/primer_candidates>/s;
|
|
17981
|
-
var PRIMER_ELEMENT_REGEX = /<primer\s+at_compartment="(\d+)"\s*>(.*?)<\/primer>/gs;
|
|
17982
|
-
var PRIMER_ITEM_REGEX = /^\s*(?:\*|-|\d+\.)\s*(.+)$/gm;
|
|
17983
|
-
var FACTS_BLOCK_REGEX = /<facts>(.*?)<\/facts>/s;
|
|
17984
|
-
var EVENTS_BLOCK_REGEX = /<events>(.*?)<\/events>/s;
|
|
17985
|
-
var EVENT_ELEMENT_REGEX = /<([a-z_]+)\s+at_compartment="(\d+)"\s*>(.*?)<\/\1>/gs;
|
|
17986
|
-
var EVENT_FIELD_REGEX = /<([a-z_]+)\s*>(.*?)<\/\1>/gs;
|
|
17987
|
-
function extractTier(inner, index) {
|
|
17988
|
-
const m = inner.match(TIER_REGEXES[index]);
|
|
17989
|
-
if (!m)
|
|
17990
|
-
return;
|
|
17991
|
-
return unescapeXml3((m[1] ?? "").trim());
|
|
17992
|
-
}
|
|
17993
|
-
function parseCompartmentOutput(text) {
|
|
17994
|
-
const compartments = [];
|
|
17995
|
-
const facts = [];
|
|
17996
|
-
for (const match of text.matchAll(COMPARTMENT_REGEX)) {
|
|
17997
|
-
const attrs = match[1];
|
|
17998
|
-
const inner = match[2];
|
|
17999
|
-
const startMatch = attrs.match(ATTR_START_REGEX);
|
|
18000
|
-
const endMatch = attrs.match(ATTR_END_REGEX);
|
|
18001
|
-
const titleMatch = attrs.match(ATTR_TITLE_REGEX);
|
|
18002
|
-
if (!startMatch || !endMatch || !titleMatch)
|
|
18003
|
-
continue;
|
|
18004
|
-
const startMessage = parseInt(startMatch[1], 10);
|
|
18005
|
-
const endMessage = parseInt(endMatch[1], 10);
|
|
18006
|
-
const title = unescapeXml3(titleMatch[1]);
|
|
18007
|
-
if (Number.isNaN(startMessage) || Number.isNaN(endMessage) || !title)
|
|
18008
|
-
continue;
|
|
18009
|
-
const episodeMatch = attrs.match(ATTR_EPISODE_REGEX);
|
|
18010
|
-
const importanceMatch = attrs.match(ATTR_IMPORTANCE_REGEX);
|
|
18011
|
-
const episodeType = episodeMatch ? unescapeXml3(episodeMatch[1]) : undefined;
|
|
18012
|
-
const importance = importanceMatch ? parseInt(importanceMatch[1], 10) : undefined;
|
|
18013
|
-
const p1 = extractTier(inner, 0);
|
|
18014
|
-
if (typeof p1 === "string" && p1.length > 0) {
|
|
18015
|
-
const p2 = extractTier(inner, 1);
|
|
18016
|
-
const p3 = extractTier(inner, 2);
|
|
18017
|
-
const p4 = extractTier(inner, 3);
|
|
18018
|
-
compartments.push({
|
|
18019
|
-
startMessage,
|
|
18020
|
-
endMessage,
|
|
18021
|
-
title,
|
|
18022
|
-
content: p1,
|
|
18023
|
-
p1,
|
|
18024
|
-
p2: typeof p2 === "string" ? p2 : p1,
|
|
18025
|
-
p3: typeof p3 === "string" ? p3 : typeof p2 === "string" ? p2 : p1,
|
|
18026
|
-
p4: typeof p4 === "string" ? p4 : "",
|
|
18027
|
-
importance,
|
|
18028
|
-
episodeType
|
|
18029
|
-
});
|
|
18030
|
-
continue;
|
|
18031
|
-
}
|
|
18032
|
-
const content = unescapeXml3(inner.trim());
|
|
18033
|
-
if (content) {
|
|
18034
|
-
compartments.push({
|
|
18035
|
-
startMessage,
|
|
18036
|
-
endMessage,
|
|
18037
|
-
title,
|
|
18038
|
-
content,
|
|
18039
|
-
importance,
|
|
18040
|
-
episodeType
|
|
18041
|
-
});
|
|
18042
|
-
}
|
|
18043
|
-
}
|
|
18044
|
-
const factsBlockMatch = text.match(FACTS_BLOCK_REGEX);
|
|
18045
|
-
const factsScope = factsBlockMatch ? factsBlockMatch[1] : text.replace(EVENTS_BLOCK_REGEX, "").replace(/<compartment\s+[^>]*?\s*>.*?<\/compartment>/gs, "");
|
|
18046
|
-
for (const categoryMatch of factsScope.matchAll(CATEGORY_BLOCK_REGEX)) {
|
|
18047
|
-
const category = categoryMatch[1];
|
|
18048
|
-
const blockContent = categoryMatch[2];
|
|
18049
|
-
for (const itemMatch of blockContent.matchAll(FACT_ITEM_REGEX)) {
|
|
18050
|
-
const content = unescapeXml3(itemMatch[1].trim());
|
|
18051
|
-
if (content) {
|
|
18052
|
-
facts.push({ category, content });
|
|
18053
|
-
}
|
|
18054
|
-
}
|
|
18055
|
-
}
|
|
18056
|
-
const unprocessedMatch = text.match(UNPROCESSED_REGEX);
|
|
18057
|
-
const unprocessedFrom = unprocessedMatch ? parseInt(unprocessedMatch[1], 10) : null;
|
|
18058
|
-
const userObservations = [];
|
|
18059
|
-
const userObsMatch = text.match(USER_OBSERVATIONS_REGEX);
|
|
18060
|
-
if (userObsMatch) {
|
|
18061
|
-
for (const itemMatch of userObsMatch[1].matchAll(USER_OBS_ITEM_REGEX)) {
|
|
18062
|
-
const obs = unescapeXml3(itemMatch[1].trim());
|
|
18063
|
-
if (obs)
|
|
18064
|
-
userObservations.push(obs);
|
|
18065
|
-
}
|
|
18066
|
-
}
|
|
18067
|
-
const primerCandidates = [];
|
|
18068
|
-
const primerMatch = text.match(PRIMER_CANDIDATES_REGEX);
|
|
18069
|
-
if (primerMatch) {
|
|
18070
|
-
const block = primerMatch[1];
|
|
18071
|
-
let sawElement = false;
|
|
18072
|
-
for (const el of block.matchAll(PRIMER_ELEMENT_REGEX)) {
|
|
18073
|
-
sawElement = true;
|
|
18074
|
-
const question = unescapeXml3(el[2].trim());
|
|
18075
|
-
if (question) {
|
|
18076
|
-
primerCandidates.push({
|
|
18077
|
-
question,
|
|
18078
|
-
originCompartmentIndex: Number.parseInt(el[1], 10)
|
|
18079
|
-
});
|
|
18080
|
-
}
|
|
18081
|
-
}
|
|
18082
|
-
if (!sawElement) {
|
|
18083
|
-
for (const itemMatch of block.matchAll(PRIMER_ITEM_REGEX)) {
|
|
18084
|
-
const question = unescapeXml3(itemMatch[1].trim());
|
|
18085
|
-
if (question)
|
|
18086
|
-
primerCandidates.push({ question });
|
|
18087
|
-
}
|
|
18088
|
-
}
|
|
18089
|
-
}
|
|
18090
|
-
const events = parseEvents(text);
|
|
18091
|
-
compartments.sort((a, b) => a.startMessage - b.startMessage);
|
|
18092
|
-
return { compartments, facts, events, unprocessedFrom, userObservations, primerCandidates };
|
|
18093
|
-
}
|
|
18094
|
-
function parseEvents(text) {
|
|
18095
|
-
const blockMatch = text.match(EVENTS_BLOCK_REGEX);
|
|
18096
|
-
if (!blockMatch)
|
|
18097
|
-
return [];
|
|
18098
|
-
const block = blockMatch[1];
|
|
18099
|
-
const events = [];
|
|
18100
|
-
for (const elMatch of block.matchAll(EVENT_ELEMENT_REGEX)) {
|
|
18101
|
-
const kind = elMatch[1];
|
|
18102
|
-
const atRaw = parseInt(elMatch[2], 10);
|
|
18103
|
-
const atCompartment = Number.isNaN(atRaw) ? null : atRaw;
|
|
18104
|
-
const fields = {};
|
|
18105
|
-
for (const fieldMatch of elMatch[3].matchAll(EVENT_FIELD_REGEX)) {
|
|
18106
|
-
const name = fieldMatch[1];
|
|
18107
|
-
const value = unescapeXml3(fieldMatch[2].trim());
|
|
18108
|
-
if (value)
|
|
18109
|
-
fields[name] = value;
|
|
18110
|
-
}
|
|
18111
|
-
events.push({ kind, atCompartment, fields });
|
|
18112
|
-
}
|
|
18113
|
-
return events;
|
|
18114
|
-
}
|
|
18115
|
-
function unescapeXml3(s) {
|
|
18116
|
-
return s.replace(/&/g, "&").replace(/'/g, "'").replace(/"/g, '"').replace(/</g, "<").replace(/>/g, ">");
|
|
18117
|
-
}
|
|
18118
|
-
|
|
18119
17762
|
// ../plugin/src/hooks/magic-context/compartment-runner-mapping.ts
|
|
18120
17763
|
function tierFieldsOf(c) {
|
|
18121
17764
|
return {
|
|
@@ -21427,7 +21070,7 @@ function stripPiProcessedImages(args) {
|
|
|
21427
21070
|
}
|
|
21428
21071
|
|
|
21429
21072
|
// src/system-prompt.ts
|
|
21430
|
-
import { createHash as
|
|
21073
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
21431
21074
|
|
|
21432
21075
|
// ../plugin/src/agents/magic-context-prompt.ts
|
|
21433
21076
|
var LONG_TERM_PARTNER_FRAME = `### You are the user's long-term partner on this project — not a one-off hire
|
|
@@ -21580,7 +21223,7 @@ function processSystemPromptForCache(args) {
|
|
|
21580
21223
|
sessionLog(sessionId, `system prompt date frozen: real=${liveDate}, using=${stickyDate} (cache-stable pass)`);
|
|
21581
21224
|
}
|
|
21582
21225
|
}
|
|
21583
|
-
const currentHash =
|
|
21226
|
+
const currentHash = createHash8("md5").update(frozenPrompt).digest("hex");
|
|
21584
21227
|
const hashChanged = !isFirstHash && currentHash !== previousHash;
|
|
21585
21228
|
if (hashChanged) {
|
|
21586
21229
|
sessionLog(sessionId, `system prompt hash changed: ${previousHash} → ${currentHash} (len=${frozenPrompt.length})`);
|
|
@@ -24798,104 +24441,9 @@ function cleanupHistorianStateFile(path6) {
|
|
|
24798
24441
|
unlinkSync(path6);
|
|
24799
24442
|
} catch {}
|
|
24800
24443
|
}
|
|
24801
|
-
// ../plugin/src/hooks/magic-context/compaction-marker-manager.ts
|
|
24802
|
-
var MARKER_SUMMARY_TEXT = "[Compacted by magic-context — session history is managed by the plugin]";
|
|
24803
|
-
function dropMarkerSummaryTag(db, sessionId, summaryMessageId) {
|
|
24804
|
-
const tagNumber = getTagNumberByMessageId(db, sessionId, `${summaryMessageId}:p0`);
|
|
24805
|
-
if (tagNumber !== null)
|
|
24806
|
-
updateTagStatus(db, sessionId, tagNumber, "dropped");
|
|
24807
|
-
}
|
|
24808
|
-
function persistMarkerStateAndDropReplacedTag(db, sessionId, state, replacedSummaryMessageId) {
|
|
24809
|
-
db.transaction(() => {
|
|
24810
|
-
setPersistedCompactionMarkerState(db, sessionId, state);
|
|
24811
|
-
if (replacedSummaryMessageId !== null) {
|
|
24812
|
-
dropMarkerSummaryTag(db, sessionId, replacedSummaryMessageId);
|
|
24813
|
-
}
|
|
24814
|
-
})();
|
|
24815
|
-
}
|
|
24816
|
-
function getCompartmentEndMessageIdForOrdinal(db, sessionId, endOrdinal) {
|
|
24817
|
-
const row = db.prepare(`SELECT end_message_id
|
|
24818
|
-
FROM compartments
|
|
24819
|
-
WHERE session_id = ? AND end_message = ?
|
|
24820
|
-
ORDER BY sequence DESC
|
|
24821
|
-
LIMIT 1`).get(sessionId, endOrdinal);
|
|
24822
|
-
return typeof row?.end_message_id === "string" && row.end_message_id.length > 0 ? row.end_message_id : null;
|
|
24823
|
-
}
|
|
24824
|
-
function existingMarkerAlreadyCoversTarget(sessionId, existing, targetOrdinal, targetEndMessageId) {
|
|
24825
|
-
if (existing.boundaryOrdinal < targetOrdinal) {
|
|
24826
|
-
return false;
|
|
24827
|
-
}
|
|
24828
|
-
if (existing.boundaryOrdinal === targetOrdinal) {
|
|
24829
|
-
const boundaryCompare = compareOpenCodeMessagesByCanonicalOrder(sessionId, existing.boundaryMessageId, targetEndMessageId);
|
|
24830
|
-
if (boundaryCompare === null || boundaryCompare > 0) {
|
|
24831
|
-
return false;
|
|
24832
|
-
}
|
|
24833
|
-
if (existing.targetEndMessageId !== null && existing.targetEndMessageId !== targetEndMessageId) {
|
|
24834
|
-
return false;
|
|
24835
|
-
}
|
|
24836
|
-
return true;
|
|
24837
|
-
}
|
|
24838
|
-
if (existing.targetEndMessageId !== null) {
|
|
24839
|
-
const targetCompare = compareOpenCodeMessagesByCanonicalOrder(sessionId, existing.targetEndMessageId, targetEndMessageId);
|
|
24840
|
-
if (targetCompare !== null && targetCompare <= 0) {
|
|
24841
|
-
return false;
|
|
24842
|
-
}
|
|
24843
|
-
}
|
|
24844
|
-
return true;
|
|
24845
|
-
}
|
|
24846
|
-
function updateCompactionMarkerAfterPublication(db, sessionId, lastCompartmentEnd, directory) {
|
|
24847
|
-
if (getHarness() !== "opencode") {
|
|
24848
|
-
return true;
|
|
24849
|
-
}
|
|
24850
|
-
const targetEndMessageId = getCompartmentEndMessageIdForOrdinal(db, sessionId, lastCompartmentEnd);
|
|
24851
|
-
if (!targetEndMessageId) {
|
|
24852
|
-
sessionLog(sessionId, `compaction-marker: no compartment endMessageId for ordinal ${lastCompartmentEnd}; preserving existing marker`);
|
|
24853
|
-
return false;
|
|
24854
|
-
}
|
|
24855
|
-
const existing = getPersistedCompactionMarkerState(db, sessionId);
|
|
24856
|
-
const removedSummaryMessageId = existing?.summaryMessageId ?? null;
|
|
24857
|
-
if (existing) {
|
|
24858
|
-
if (existingMarkerAlreadyCoversTarget(sessionId, existing, lastCompartmentEnd, targetEndMessageId)) {
|
|
24859
|
-
return true;
|
|
24860
|
-
}
|
|
24861
|
-
}
|
|
24862
|
-
const boundary = findBoundaryUserMessage(sessionId, targetEndMessageId);
|
|
24863
|
-
if (!boundary) {
|
|
24864
|
-
sessionLog(sessionId, `compaction-marker: no user boundary found at or before endMessageId ${targetEndMessageId} (ordinal ${lastCompartmentEnd}); preserving existing marker`);
|
|
24865
|
-
return false;
|
|
24866
|
-
}
|
|
24867
|
-
if (existing) {
|
|
24868
|
-
const removed = removeCompactionMarker(existing);
|
|
24869
|
-
if (!removed) {
|
|
24870
|
-
sessionLog(sessionId, `compaction-marker: failed to remove old boundary at ordinal ${existing.boundaryOrdinal}; preserving persisted state for retry (not injecting new marker this pass)`);
|
|
24871
|
-
return false;
|
|
24872
|
-
}
|
|
24873
|
-
persistMarkerStateAndDropReplacedTag(db, sessionId, null, removedSummaryMessageId);
|
|
24874
|
-
sessionLog(sessionId, `compaction-marker: removed old boundary at ordinal ${existing.boundaryOrdinal}, moving to ${lastCompartmentEnd}`);
|
|
24875
|
-
}
|
|
24876
|
-
const result = injectCompactionMarker({
|
|
24877
|
-
sessionId,
|
|
24878
|
-
endOrdinal: lastCompartmentEnd,
|
|
24879
|
-
endMessageId: targetEndMessageId,
|
|
24880
|
-
summaryText: MARKER_SUMMARY_TEXT,
|
|
24881
|
-
directory: directory ?? process.cwd(),
|
|
24882
|
-
resolvedBoundary: boundary
|
|
24883
|
-
});
|
|
24884
|
-
if (result) {
|
|
24885
|
-
persistMarkerStateAndDropReplacedTag(db, sessionId, {
|
|
24886
|
-
...result,
|
|
24887
|
-
boundaryOrdinal: lastCompartmentEnd,
|
|
24888
|
-
targetEndMessageId
|
|
24889
|
-
}, removedSummaryMessageId);
|
|
24890
|
-
sessionLog(sessionId, `compaction-marker: injected at ordinal ${lastCompartmentEnd}, boundary user msg ${result.boundaryMessageId}`);
|
|
24891
|
-
return true;
|
|
24892
|
-
}
|
|
24893
|
-
return false;
|
|
24894
|
-
}
|
|
24895
|
-
|
|
24896
24444
|
// ../plugin/src/hooks/magic-context/compartment-runner-historian.ts
|
|
24897
24445
|
import { mkdirSync as mkdirSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync5 } from "node:fs";
|
|
24898
|
-
import { join as
|
|
24446
|
+
import { join as join4 } from "node:path";
|
|
24899
24447
|
|
|
24900
24448
|
// ../plugin/src/agents/historian.ts
|
|
24901
24449
|
var HISTORIAN_AGENT = "historian";
|
|
@@ -25212,7 +24760,7 @@ function dumpHistorianResponse(sessionId, directory, label, text) {
|
|
|
25212
24760
|
ensureCortexKitArtifactGitignore(directory);
|
|
25213
24761
|
const safeSessionId = sanitizeDumpName(sessionId);
|
|
25214
24762
|
const safeLabel = sanitizeDumpName(label);
|
|
25215
|
-
const dumpPath =
|
|
24763
|
+
const dumpPath = join4(dumpDir, `${safeSessionId}-${safeLabel}-${Date.now()}.xml`);
|
|
25216
24764
|
writeFileSync5(dumpPath, text, "utf8");
|
|
25217
24765
|
sessionLog(sessionId, "compartment agent: historian response dumped", {
|
|
25218
24766
|
label,
|
|
@@ -27286,7 +26834,7 @@ ${c.content}
|
|
|
27286
26834
|
// package.json
|
|
27287
26835
|
var package_default = {
|
|
27288
26836
|
name: "@cortexkit/pi-magic-context",
|
|
27289
|
-
version: "0.33.
|
|
26837
|
+
version: "0.33.1",
|
|
27290
26838
|
type: "module",
|
|
27291
26839
|
description: "Pi coding agent extension for Magic Context — cross-session memory and context management",
|
|
27292
26840
|
main: "dist/index.js",
|
|
@@ -27312,7 +26860,7 @@ var package_default = {
|
|
|
27312
26860
|
"README.md"
|
|
27313
26861
|
],
|
|
27314
26862
|
scripts: {
|
|
27315
|
-
build: "bun build src/index.ts src/subagent-entry.ts --outdir dist --target node --format esm --splitting --external @earendil-works/pi-coding-agent --external @earendil-works/pi-tui --external @huggingface/transformers --external node:sqlite",
|
|
26863
|
+
build: "rm -f dist/index.js dist/subagent-entry.js dist/*-*.js && bun build src/index.ts src/subagent-entry.ts --outdir dist --target node --format esm --splitting --external @earendil-works/pi-coding-agent --external @earendil-works/pi-tui --external @huggingface/transformers --external node:sqlite",
|
|
27316
26864
|
typecheck: "tsc --noEmit",
|
|
27317
26865
|
test: "bun test",
|
|
27318
26866
|
lint: "biome check src",
|
|
@@ -28579,7 +28127,7 @@ async function src_default(pi) {
|
|
|
28579
28127
|
}
|
|
28580
28128
|
beginBootQuietPeriod();
|
|
28581
28129
|
const storageDir = getMagicContextStorageDir();
|
|
28582
|
-
const dbPath =
|
|
28130
|
+
const dbPath = join5(storageDir, "context.db");
|
|
28583
28131
|
let db;
|
|
28584
28132
|
let openFailureCause = null;
|
|
28585
28133
|
try {
|