Skip to content
This repository was archived by the owner on Jul 13, 2026. It is now read-only.

Commit c47a45b

Browse files
committed
fix(plugin): 8 audit fixes — JSON safety, dream scheduling, smart notes, dedup
- cortexkit#1: try-catch JSON.parse in smart note eval, greedy regex, mark-as-checked on failure - cortexkit#5: check drop() return value in dedup — skip updateTagStatus on incomplete - cortexkit#6: try-catch JSON.parse in read-session-raw — skip corrupt rows - cortexkit#9: include pending smart_notes in findProjectsNeedingDream - cortexkit#10: thread projectPath to peekNoteNudgeText so ready smart notes surface - cortexkit#11: raise dream queue stale threshold from 10min to 2h - cortexkit#12: restrict ctx-memory schema enum to allowedActions - #19: move dream schedule debounce after successful execution
1 parent bdc1b14 commit c47a45b

9 files changed

Lines changed: 61 additions & 26 deletions

File tree

‎packages/plugin/src/features/magic-context/dreamer/queue.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ export function enqueueDream(
3535
const now = Date.now();
3636
return db.transaction(() => {
3737
// Clean stale started entries before checking — prevents post-crash permanent "already queued"
38-
const staleThresholdMs = 10 * 60 * 1000; // 10 minutes
38+
// Use 2h threshold to avoid deleting entries for long-running dreams (max runtime is configurable, up to 120min)
39+
const staleThresholdMs = 120 * 60 * 1000; // 2 hours
3940
db.run(
4041
"DELETE FROM dream_queue WHERE project_path = ? AND started_at IS NOT NULL AND started_at < ?",
4142
[projectIdentity, now - staleThresholdMs],

‎packages/plugin/src/features/magic-context/dreamer/runner.ts‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -391,20 +391,24 @@ Only include notes whose conditions you could definitively evaluate. Skip notes
391391
const output = extractLatestAssistantText(messages);
392392
if (!output) throw new Error("Smart note evaluation returned no output.");
393393

394-
// Parse the JSON results from the LLM response
395-
const jsonMatch = output.match(/\[[\s\S]*?\]/);
394+
// Parse the JSON results from the LLM response — use greedy match to handle
395+
// `]` chars inside JSON string values (e.g., reasons containing brackets).
396+
const jsonMatch = output.match(/\[[\s\S]*\]/);
396397
if (!jsonMatch) {
397398
log("[dreamer] smart notes: no JSON array found in output, skipping");
398399
// Still mark all as checked
399400
for (const note of pendingNotes) markSmartNoteChecked(args.db, note.id);
400401
return;
401402
}
402403

403-
const evaluations = JSON.parse(jsonMatch[0]) as Array<{
404-
id: number;
405-
met: boolean;
406-
reason?: string;
407-
}>;
404+
let evaluations: Array<{ id: number; met: boolean; reason?: string }>;
405+
try {
406+
evaluations = JSON.parse(jsonMatch[0]);
407+
} catch {
408+
log(`[dreamer] smart notes: failed to parse JSON from LLM output, marking all checked`);
409+
for (const note of pendingNotes) markSmartNoteChecked(args.db, note.id);
410+
return;
411+
}
408412
let surfaced = 0;
409413
let checked = 0;
410414
for (const evaluation of evaluations) {

‎packages/plugin/src/features/magic-context/dreamer/scheduler.ts‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,15 @@ export function isInScheduleWindow(schedule: string, now: Date = new Date()): bo
4646
return currentMinutes >= window.startMinutes || currentMinutes < window.endMinutes;
4747
}
4848

49-
/** Find projects that have memory updates since their per-project last dream time. */
49+
/** Find projects that have memory updates or pending smart notes since their per-project last dream time. */
5050
export function findProjectsNeedingDream(db: Database): string[] {
51-
// Get all active project paths
51+
// Get all active project paths from memories and smart notes
5252
const projectRows = db
5353
.query<{ project_path: string }, []>(
54-
`SELECT DISTINCT project_path FROM memories WHERE status = 'active' ORDER BY project_path`,
54+
`SELECT DISTINCT project_path FROM memories WHERE status = 'active'
55+
UNION
56+
SELECT DISTINCT project_path FROM smart_notes WHERE status = 'pending'
57+
ORDER BY project_path`,
5558
)
5659
.all();
5760

@@ -62,14 +65,24 @@ export function findProjectsNeedingDream(db: Database): string[] {
6265
const fallbackStr = !lastDreamAtStr ? getDreamState(db, "last_dream_at") : null;
6366
const lastDreamAt = Number(lastDreamAtStr ?? fallbackStr ?? "0") || 0;
6467

65-
const updated = db
68+
const updatedMemories = db
6669
.query<{ cnt: number }, [string, number]>(
6770
`SELECT COUNT(*) as cnt FROM memories
6871
WHERE project_path = ? AND status = 'active' AND updated_at > ?`,
6972
)
7073
.get(row.project_path, lastDreamAt);
7174

72-
if (updated && updated.cnt > 0) {
75+
const pendingSmartNotes = db
76+
.query<{ cnt: number }, [string]>(
77+
`SELECT COUNT(*) as cnt FROM smart_notes
78+
WHERE project_path = ? AND status = 'pending'`,
79+
)
80+
.get(row.project_path);
81+
82+
if (
83+
(updatedMemories && updatedMemories.cnt > 0) ||
84+
(pendingSmartNotes && pendingSmartNotes.cnt > 0)
85+
) {
7386
projects.push(row.project_path);
7487
}
7588
}

‎packages/plugin/src/hooks/magic-context/heuristic-cleanup.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,8 @@ export function applyHeuristicCleanup(
128128
for (let i = 0; i < group.length - 1; i++) {
129129
const tag = group[i];
130130
const target = targets.get(tag.tagNumber);
131-
target?.drop?.();
131+
const dropResult = target?.drop?.() ?? "absent";
132+
if (dropResult === "incomplete") continue;
132133
updateTagStatus(db, sessionId, tag.tagNumber, "dropped");
133134
deduplicatedTools++;
134135
}

‎packages/plugin/src/hooks/magic-context/hook.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ export function createMagicContextHook(deps: MagicContextDeps) {
191191
const model = liveModelBySession.get(sessionId);
192192
return resolveModelKey(model?.providerID, model?.modelID);
193193
},
194+
projectPath,
194195
});
195196
const eventHandler = createEventHandler({
196197
contextUsageMap,
@@ -216,9 +217,9 @@ export function createMagicContextHook(deps: MagicContextDeps) {
216217
return;
217218
}
218219

219-
lastScheduleCheckMs = now;
220220
try {
221221
checkScheduleAndEnqueue(db, dreaming.schedule);
222+
lastScheduleCheckMs = now;
222223
} catch (error) {
223224
log("[dreamer] scheduled enqueue check failed:", error);
224225
return;

‎packages/plugin/src/hooks/magic-context/read-session-raw.ts‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,24 @@ function isRawPartRow(row: unknown): row is RawPartRow {
2929
return typeof candidate.message_id === "string" && typeof candidate.data === "string";
3030
}
3131

32-
function parseJsonRecord(value: string): Record<string, unknown> {
33-
const parsed = JSON.parse(value);
34-
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
35-
throw new Error("Expected JSON object");
32+
function parseJsonRecord(value: string): Record<string, unknown> | null {
33+
try {
34+
const parsed = JSON.parse(value);
35+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
36+
return null;
37+
}
38+
return parsed as Record<string, unknown>;
39+
} catch {
40+
return null;
3641
}
37-
return parsed as Record<string, unknown>;
3842
}
3943

4044
function parseJsonUnknown(value: string): unknown {
41-
return JSON.parse(value);
45+
try {
46+
return JSON.parse(value);
47+
} catch {
48+
return null;
49+
}
4250
}
4351

4452
export function readRawSessionMessagesFromDb(db: Database, sessionId: string): RawMessage[] {
@@ -63,8 +71,9 @@ export function readRawSessionMessagesFromDb(db: Database, sessionId: string): R
6371
partsByMessageId.set(part.message_id, list);
6472
}
6573

66-
return messageRows.map((row, index) => {
74+
return messageRows.flatMap((row, index) => {
6775
const info = parseJsonRecord(row.data);
76+
if (!info) return [];
6877
const role = typeof info.role === "string" ? info.role : "unknown";
6978
return {
7079
ordinal: index + 1,

‎packages/plugin/src/hooks/magic-context/transform-postprocess-phase.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ interface RunPostTransformPhaseArgs {
8181
watermark: number;
8282
forceMaterializationPercentage: number;
8383
hasRecentReduceCall: boolean;
84+
projectPath?: string;
8485
}
8586

8687
export function runPostTransformPhase(args: RunPostTransformPhaseArgs): void {
@@ -473,7 +474,12 @@ export function runPostTransformPhase(args: RunPostTransformPhaseArgs): void {
473474
}
474475
}
475476

476-
const deferredNoteText = peekNoteNudgeText(args.db, args.sessionId, args.currentTurnId);
477+
const deferredNoteText = peekNoteNudgeText(
478+
args.db,
479+
args.sessionId,
480+
args.currentTurnId,
481+
args.projectPath,
482+
);
477483
if (deferredNoteText) {
478484
const noteInstruction = `\n\n<instruction name="deferred_notes">${deferredNoteText}</instruction>`;
479485
const anchoredMessageId = appendReminderToLatestUserMessage(args.messages, noteInstruction);

‎packages/plugin/src/hooks/magic-context/transform.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ export interface TransformDeps {
7373
sessionId: string,
7474
) => import("./send-session-notification").NotificationParams;
7575
getModelKey?: (sessionId: string) => string | undefined;
76+
projectPath?: string;
7677
}
7778

7879
export function createTransform(deps: TransformDeps) {
@@ -313,6 +314,7 @@ export function createTransform(deps: TransformDeps) {
313314
watermark,
314315
forceMaterializationPercentage: FORCE_MATERIALIZE_PERCENTAGE,
315316
hasRecentReduceCall,
317+
projectPath: deps.projectPath,
316318
});
317319

318320
const elapsed = (performance.now() - startTime).toFixed(1);

‎packages/plugin/src/tools/ctx-memory/tools.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -158,9 +158,7 @@ function createCtxMemoryTool(deps: CtxMemoryToolDeps): ToolDefinition {
158158
return tool({
159159
description: CTX_MEMORY_DESCRIPTION,
160160
args: {
161-
action: tool.schema
162-
.enum(CTX_MEMORY_DREAMER_ACTIONS)
163-
.describe("Action to perform on memories"),
161+
action: tool.schema.enum(allowedActions).describe("Action to perform on memories"),
164162
content: tool.schema
165163
.string()
166164
.optional()

0 commit comments

Comments
 (0)