@cortexkit/pi-magic-context 0.42.4 → 0.42.5

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.
@@ -29308,16 +29308,27 @@ function startLockHeartbeat(lockPath) {
29308
29308
  timer.unref?.();
29309
29309
  return () => clearInterval(timer);
29310
29310
  }
29311
+ var ONNX_RUNTIME_WEB_SPECIFIER = "onnxruntime-web";
29311
29312
  var localEmbeddingRuntimeMode = "native";
29312
29313
  var localEmbeddingProcessFailure = null;
29313
29314
  var wasmRuntimeInjected = false;
29314
29315
  var localEmbeddingHostForRuntime = currentLocalEmbeddingHost;
29316
+ var resolveWasmOrtForRuntime = () => {
29317
+ try {
29318
+ return typeof import.meta.resolve === "function" ? import.meta.resolve(ONNX_RUNTIME_WEB_SPECIFIER) : undefined;
29319
+ } catch {
29320
+ return;
29321
+ }
29322
+ };
29323
+ var importWasmOrtModule = async (specifier) => await import(specifier);
29324
+ var importWasmOrtModuleForRuntime = importWasmOrtModule;
29315
29325
  var importWasmOrtForRuntime = async () => {
29316
29326
  const { createRequire: createRequireFn } = await import("node:module");
29317
29327
  const requireFn = createRequireFn(import.meta.url);
29318
- const ortEntry = requireFn.resolve("onnxruntime-web");
29328
+ const ortEntry = requireFn.resolve(ONNX_RUNTIME_WEB_SPECIFIER);
29329
+ const ortSpecifier = resolveWasmOrtForRuntime() ?? ONNX_RUNTIME_WEB_SPECIFIER;
29319
29330
  return {
29320
- module: await import("onnxruntime-web"),
29331
+ module: await importWasmOrtModuleForRuntime(ortSpecifier),
29321
29332
  entryPath: ortEntry
29322
29333
  };
29323
29334
  };
@@ -33760,6 +33771,174 @@ function createCtxExpandTool(deps) {
33760
33771
  };
33761
33772
  }
33762
33773
 
33774
+ // ../plugin/src/features/magic-context/dreamer/storage-task-schedule.ts
33775
+ function toRow(r) {
33776
+ return {
33777
+ projectPath: r.project_path,
33778
+ task: r.task,
33779
+ lastRunAt: r.last_run_at,
33780
+ nextDueAt: r.next_due_at,
33781
+ schedule: r.schedule ?? null,
33782
+ lastStatus: r.last_status ?? null,
33783
+ lastError: r.last_error,
33784
+ retryCount: r.retry_count ?? 0,
33785
+ taskStateJson: r.last_checked_commit ?? null,
33786
+ lastCheckedCommit: r.last_checked_commit ?? null,
33787
+ lastBroadRunAt: r.last_broad_run_at ?? null,
33788
+ retrospectiveWatermarkMs: r.retrospective_watermark_ms ?? null
33789
+ };
33790
+ }
33791
+ var SELECT_COLUMNS = "project_path, task, last_run_at, next_due_at, schedule, last_status, last_error, retry_count, last_checked_commit, last_broad_run_at, retrospective_watermark_ms";
33792
+ function getTaskScheduleState(db, projectPath, task) {
33793
+ const row = db.prepare(`SELECT ${SELECT_COLUMNS} FROM task_schedule_state WHERE project_path = ? AND task = ?`).get(projectPath, task);
33794
+ return row ? toRow(row) : null;
33795
+ }
33796
+ function getMostRecentTaskRunAt(db, projectPath) {
33797
+ const row = db.prepare("SELECT MAX(last_run_at) AS max_at FROM task_schedule_state WHERE project_path = ?").get(projectPath);
33798
+ const value = row?.max_at ?? null;
33799
+ return typeof value === "number" && value > 0 ? value : null;
33800
+ }
33801
+ function pruneNonCanonicalTaskRows(db, projectPath, canonicalTasks) {
33802
+ if (canonicalTasks.length === 0)
33803
+ return 0;
33804
+ const placeholders = canonicalTasks.map(() => "?").join(", ");
33805
+ const result = db.prepare(`DELETE FROM task_schedule_state WHERE project_path = ? AND task NOT IN (${placeholders})`).run(projectPath, ...canonicalTasks);
33806
+ return Number(result.changes ?? 0);
33807
+ }
33808
+ function deleteTaskScheduleRowsForProject(db, projectPath) {
33809
+ const result = db.prepare("DELETE FROM task_schedule_state WHERE project_path = ?").run(projectPath);
33810
+ return Number(result.changes ?? 0);
33811
+ }
33812
+ function seedTaskScheduleState(db, projectPath, task, nextDueAt, lastRunAt, schedule) {
33813
+ db.prepare("INSERT INTO task_schedule_state (project_path, task, last_run_at, next_due_at, schedule, last_status, last_error, retry_count) VALUES (?, ?, ?, ?, ?, NULL, NULL, 0) ON CONFLICT(project_path, task) DO NOTHING").run(projectPath, task, lastRunAt, nextDueAt, schedule);
33814
+ }
33815
+ function writeTaskScheduleState(db, row) {
33816
+ const broadCycleUpdate = row.lastBroadRunAt === undefined ? "last_broad_run_at = task_schedule_state.last_broad_run_at" : "last_broad_run_at = excluded.last_broad_run_at";
33817
+ db.prepare(`INSERT INTO task_schedule_state
33818
+ (project_path, task, last_run_at, next_due_at, schedule, last_status, last_error, retry_count, last_checked_commit, last_broad_run_at, retrospective_watermark_ms)
33819
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
33820
+ ON CONFLICT(project_path, task) DO UPDATE SET
33821
+ last_run_at = excluded.last_run_at,
33822
+ next_due_at = excluded.next_due_at,
33823
+ schedule = excluded.schedule,
33824
+ last_status = excluded.last_status,
33825
+ last_error = excluded.last_error,
33826
+ retry_count = excluded.retry_count,
33827
+ last_checked_commit = COALESCE(excluded.last_checked_commit, task_schedule_state.last_checked_commit),
33828
+ ${broadCycleUpdate},
33829
+ retrospective_watermark_ms = COALESCE(excluded.retrospective_watermark_ms, task_schedule_state.retrospective_watermark_ms)`).run(row.projectPath, row.task, row.lastRunAt, row.nextDueAt, row.schedule, row.lastStatus, row.lastError, row.retryCount, row.taskStateJson ?? row.lastCheckedCommit ?? null, row.lastBroadRunAt ?? null, row.retrospectiveWatermarkMs ?? null);
33830
+ }
33831
+ function writeTaskStateJson(db, projectPath, task, taskStateJson) {
33832
+ db.prepare(`INSERT INTO task_schedule_state (project_path, task, last_checked_commit)
33833
+ VALUES (?, ?, ?)
33834
+ ON CONFLICT(project_path, task) DO UPDATE SET last_checked_commit = excluded.last_checked_commit`).run(projectPath, task, taskStateJson);
33835
+ }
33836
+ function isRetrospectiveWindowProcessed(db, projectPath, windowKey) {
33837
+ const row = db.prepare("SELECT 1 AS one FROM retrospective_processed_windows WHERE project_path = ? AND window_key = ?").get(projectPath, windowKey);
33838
+ return row != null;
33839
+ }
33840
+ function recordRetrospectiveWindowProcessed(db, projectPath, windowKey) {
33841
+ db.prepare("INSERT INTO retrospective_processed_windows (project_path, window_key, processed_at) VALUES (?, ?, ?) ON CONFLICT(project_path, window_key) DO NOTHING").run(projectPath, windowKey, Date.now());
33842
+ }
33843
+
33844
+ // ../plugin/src/features/magic-context/dreamer/curate-category-rotation.ts
33845
+ var CURATE_MEMORY_CATEGORIES = [
33846
+ "PROJECT_RULES",
33847
+ "ARCHITECTURE",
33848
+ "CONSTRAINTS",
33849
+ "CONFIG_VALUES",
33850
+ "NAMING"
33851
+ ];
33852
+ var LEGACY_CURATE_CATEGORY_BUCKETS = {
33853
+ ARCHITECTURE_DECISIONS: "ARCHITECTURE",
33854
+ CONFIG_DEFAULTS: "CONFIG_VALUES",
33855
+ ENVIRONMENT: "CONFIG_VALUES",
33856
+ KNOWN_ISSUES: "CONSTRAINTS",
33857
+ USER_DIRECTIVES: "PROJECT_RULES",
33858
+ USER_PREFERENCES: "PROJECT_RULES",
33859
+ WORKFLOW_RULES: "PROJECT_RULES"
33860
+ };
33861
+ function curateCategoryForMemoryCategory(category) {
33862
+ return isCurateMemoryCategory(category) ? category : LEGACY_CURATE_CATEGORY_BUCKETS[category] ?? null;
33863
+ }
33864
+ function isCurateMemoryCategory(value) {
33865
+ return CURATE_MEMORY_CATEGORIES.includes(value);
33866
+ }
33867
+ function parseTaskState(raw) {
33868
+ if (!raw)
33869
+ return {};
33870
+ try {
33871
+ const parsed = JSON.parse(raw);
33872
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
33873
+ } catch {
33874
+ return {};
33875
+ }
33876
+ }
33877
+ function normalizedCursor(value) {
33878
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value % CURATE_MEMORY_CATEGORIES.length : 0;
33879
+ }
33880
+ function readState(db, projectIdentity) {
33881
+ return parseTaskState(getTaskScheduleState(db, projectIdentity, "curate")?.taskStateJson);
33882
+ }
33883
+ function categoryStartIndex(state, populated) {
33884
+ const active = state.curate?.activeCategory;
33885
+ if (isCurateMemoryCategory(active)) {
33886
+ const activeIndex = CURATE_MEMORY_CATEGORIES.indexOf(active);
33887
+ return populated.has(active) ? activeIndex : (activeIndex + 1) % CURATE_MEMORY_CATEGORIES.length;
33888
+ }
33889
+ return normalizedCursor(state.curate?.cursor);
33890
+ }
33891
+ function peekCurateCategoryScope(db, projectIdentity, memories) {
33892
+ const populated = new Set(memories.map((memory) => curateCategoryForMemoryCategory(memory.category)).filter((category) => category !== null));
33893
+ const start = categoryStartIndex(readState(db, projectIdentity), populated);
33894
+ for (let offset = 0;offset < CURATE_MEMORY_CATEGORIES.length; offset += 1) {
33895
+ const category = CURATE_MEMORY_CATEGORIES[(start + offset) % CURATE_MEMORY_CATEGORIES.length];
33896
+ const scoped = memories.filter((memory) => curateCategoryForMemoryCategory(memory.category) === category);
33897
+ if (scoped.length > 0)
33898
+ return { category, memories: scoped };
33899
+ }
33900
+ return null;
33901
+ }
33902
+ function beginCurateCategoryRun(db, projectIdentity, memories) {
33903
+ const scope = peekCurateCategoryScope(db, projectIdentity, memories);
33904
+ if (!scope)
33905
+ return null;
33906
+ const state = readState(db, projectIdentity);
33907
+ writeTaskStateJson(db, projectIdentity, "curate", JSON.stringify({
33908
+ ...state,
33909
+ curate: {
33910
+ cursor: normalizedCursor(state.curate?.cursor),
33911
+ activeCategory: scope.category
33912
+ }
33913
+ }));
33914
+ return scope;
33915
+ }
33916
+ function curateTaskStateAfterSuccess(db, projectIdentity, category) {
33917
+ const state = readState(db, projectIdentity);
33918
+ return JSON.stringify({
33919
+ ...state,
33920
+ curate: {
33921
+ cursor: (CURATE_MEMORY_CATEGORIES.indexOf(category) + 1) % CURATE_MEMORY_CATEGORIES.length
33922
+ }
33923
+ });
33924
+ }
33925
+ function getActiveCurateCategory(db, projectIdentity) {
33926
+ const active = readState(db, projectIdentity).curate?.activeCategory;
33927
+ return isCurateMemoryCategory(active) ? active : null;
33928
+ }
33929
+ function getCurateCategoryScopeRefusal(args) {
33930
+ if (args.requestedCategory && args.requestedCategory !== args.scope) {
33931
+ return `Error: Curate scope is ${args.scope}; ${args.action} cannot target category ${args.requestedCategory}.`;
33932
+ }
33933
+ for (const id of args.ids ?? []) {
33934
+ const category = args.categoryForId(id);
33935
+ if (category && category !== args.scope) {
33936
+ return `Error: Curate scope is ${args.scope}; memory ID ${id} is outside the scoped category.`;
33937
+ }
33938
+ }
33939
+ return null;
33940
+ }
33941
+
33763
33942
  // ../plugin/src/features/magic-context/dreamer/memory-claim-safety.ts
33764
33943
  var POLICY_SENTENCE_START = /(?:^|[.!?]\s+|\n\s*)(?:[-*]\s+|\d+[.)]\s+)?(?:you\s+|we\s+)?(?:must(?:\s+not)?|never|always|do\s+not|don't|shall\s+not)\b/i;
33765
33944
  var ACTOR_POLICY = /\b(?:you|we|agents?|masons?|workers?|operators?|users?|maintainers?)\s+(?:must(?:\s+not)?|should(?:\s+not)?|need\s+to|shall(?:\s+not)?|cannot|can't|may\s+not)\b/i;
@@ -35332,6 +35511,24 @@ function createCtxMemoryTool(deps) {
35332
35511
  return err2("Error: Could not resolve project identity for memory action.");
35333
35512
  }
35334
35513
  await deps.ensureProjectRegistered?.(ctx.cwd, deps.db);
35514
+ const activeCurateCategory = dreamerAllowed ? getActiveCurateCategory(deps.db, projectIdentity) : null;
35515
+ if (activeCurateCategory) {
35516
+ const scopeRefusal = getCurateCategoryScopeRefusal({
35517
+ scope: activeCurateCategory,
35518
+ action: params.action,
35519
+ requestedCategory: params.category,
35520
+ ids: [
35521
+ ...params.ids ?? [],
35522
+ ...Number.isInteger(params.superseded_by) ? [params.superseded_by] : []
35523
+ ],
35524
+ categoryForId: (id) => {
35525
+ const category = getMemoryById(deps.db, id)?.category;
35526
+ return category ? curateCategoryForMemoryCategory(category) : null;
35527
+ }
35528
+ });
35529
+ if (scopeRefusal)
35530
+ return err2(scopeRefusal);
35531
+ }
35335
35532
  const workspaceIdentitySet = resolveWorkspaceIdentitySet(deps.db, projectIdentity);
35336
35533
  const expandedWorkspace = expandWorkspaceIdentitySetWithAliases(deps.db, workspaceIdentitySet.identities);
35337
35534
  const workspaceVisibleIdentities = workspaceIdentitySet.identities.length > 1 ? expandedWorkspace.expandedIdentities : workspaceIdentitySet.identities;
@@ -35420,7 +35617,7 @@ function createCtxMemoryTool(deps) {
35420
35617
  const limit = normalizeLimit(params.limit);
35421
35618
  const filtered = getMemoriesByProject(deps.db, projectIdentity);
35422
35619
  const category = params.category;
35423
- const filtered2 = category ? filtered.filter((m) => m.category === category) : filtered;
35620
+ const filtered2 = activeCurateCategory ? filtered.filter((memory) => curateCategoryForMemoryCategory(memory.category) === activeCurateCategory) : category ? filtered.filter((memory) => memory.category === category) : filtered;
35424
35621
  return ok2(formatMemoryList(filtered2.slice(0, limit)));
35425
35622
  }
35426
35623
  if (params.action === "get") {
@@ -40463,4 +40660,4 @@ function registerMagicContextTools(pi, opts) {
40463
40660
  }
40464
40661
  }
40465
40662
 
40466
- export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, parseCron, nextOccurrence, nextDueAtMs, canonicalModelIdentity, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, resolveModelConfigValue, resolveModelConfigOrDefault, DEFAULT_HISTORIAN_TIMEOUT_MS, getProtectedTokensTierOverrides, sanitizeDiagnosticText, hasShareabilitySensitiveText, FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, setHarness, getHarness, ensureCortexKitArtifactGitignore, getProjectMagicContextHistorianDir, getMagicContextStorageResolution, getMagicContextStorageDir, log, sessionLog, flushLogger, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, CTX_REDUCE_KEEP, newestCtxReduceTagNumbers, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isRecord, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, updateTagByteSize, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getAssignableTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, resolveOpenCodeDbPath, openCodeDbPathExists, recordOpenCodeDbReadFailure, clearOpenCodeDbReadFailure, claimOpenCodeDbDiagnosticOnce, Database, closeQuietly, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, DROPPED_INPUT_MESSAGE, droppedInputMarker, containsDroppedInputPlaceholder, isEditTool, applyEditMarkerToInput, setRawMessageProvider, withRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, getCachedAbsoluteMessageCount, primeInMemoryTailRawMessageCache, getRawSessionMessageCount, getRawSessionTagKeysThrough, getLegacyProtectedTailStartOrdinal, readSessionChunk, logSlowWriteTransaction, clearCompressionDepth, clearCompressionDepthRange, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordSessionProjectIdentity, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, drainMirrorPages, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, encodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, getErrorMessage, describeError, piHarnessKindFromExecutable, setStoragePrivatePermissionEnforcement, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, computeProtectionWindow, readEpochFloorSnapshot, getProtectionWindowForSession, isProviderOverflowFailClosedProven, describeProtectedTailDrainBudgetSkip, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, NEWEST_REASONING_BEARING_ASSISTANT, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, setSessionWorkMetrics, getSessionWorkMetrics, resolveEpochFloorForPass, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, BoundedSessionMap, MIN_PLAUSIBLE_CONTEXT_LIMIT, reloadWindowOverlay, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, isSaneLimit, resolveOutputReserve, getSdkContextLimit, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findLastModelKeyFromBranch, convertEntriesToRawMessages, convertEntriesToRawMessagePage, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, formatSynapseLaneDescriptor, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, describeShadowBackfillWriteRefusal, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, ensureProjectRegisteredFromPiDirectory, resolvePiHarnessDetection, resolvePiHarnessKind, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
40663
+ export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, migrateMagicContextConfigLocations, withContentLanguageDirective, withMigrationLanguageDirective, buildPrimaryLanguageDirective, parseCron, nextOccurrence, nextDueAtMs, canonicalModelIdentity, piModelRefToCanonical, resolveModelRefForPi, modelRefLookupOrder, ompModelRefToCanonical, resolveModelRefForOmp, resolveModelConfigValue, resolveModelConfigOrDefault, DEFAULT_HISTORIAN_TIMEOUT_MS, getProtectedTokensTierOverrides, sanitizeDiagnosticText, hasShareabilitySensitiveText, FAIL_CLOSED_DOCTOR_COMMAND, formatFailClosedBlockingMessage, createFailClosedBlockingError, isFailClosedBlockingError, shouldBypassFailClosedBlock, createFailClosedController, setHarness, getHarness, ensureCortexKitArtifactGitignore, getProjectMagicContextHistorianDir, getMagicContextStorageResolution, getMagicContextStorageDir, log, sessionLog, flushLogger, ProjectIdentityError, resolveProjectIdentityStrict, resolveProjectIdentity, resolveProjectIdentityForSession, beginBootQuietPeriod, scheduleAfterBootQuiet, CTX_REDUCE_KEEP, newestCtxReduceTagNumbers, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, stripWellFormedLeadingTagPrefix, stripPersistedAssistantText, byteSize, stripTagPrefix, peelLeadingMcTagNotation, prependTag, isRecord, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, stripChannel1ReminderSpans, effectiveTailHygiene, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, decideChannel1, evaluateChannel2, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, planEmergencyDrop, updateTagByteSize, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, updateTagInputByteSize, updateTagTokenCount, getPersistedToolTagAccounting, getAllStatusTagTokenTotalsFlat, updateTagInputTokenCount, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, hasPiFallbackMessageTags, findAdoptableFallbackTags, hasPiFallbackToolOwnerTags, findPiFallbackToolOwnerTags, adoptPiFallbackToolOwnerTag, adoptPiFallbackMessageTag, getMaxTagNumberBySession, getAssignableTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTagsForPendingOperations, getTagsByNumbers, getDroppedTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, resolveOpenCodeDbPath, openCodeDbPathExists, recordOpenCodeDbReadFailure, clearOpenCodeDbReadFailure, claimOpenCodeDbDiagnosticOnce, Database, closeQuietly, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, DROPPED_INPUT_MESSAGE, droppedInputMarker, containsDroppedInputPlaceholder, isEditTool, applyEditMarkerToInput, setRawMessageProvider, withRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, getCachedAbsoluteMessageCount, primeInMemoryTailRawMessageCache, getRawSessionMessageCount, getRawSessionTagKeysThrough, getLegacyProtectedTailStartOrdinal, readSessionChunk, logSlowWriteTransaction, clearCompressionDepth, clearCompressionDepthRange, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordSessionProjectIdentity, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, persistCachedM0, clearCachedM0M1, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getModuleNoteEvaluationBridge, getContextStoreUuid, drainMirrorPages, parseCompartmentOutput, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, sourceNameForMemory, computeWorkspaceEpochFingerprint, bumpEpochsForWorkspaceMembers, readProjectDocsCanonical, encodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, getErrorMessage, describeError, piHarnessKindFromExecutable, setStoragePrivatePermissionEnforcement, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, applySqliteTuningPragmas, runSqliteOptimize, openDatabase, openDatabaseAsync, queueM0Mutation, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, computeProtectionWindow, readEpochFloorSnapshot, getProtectionWindowForSession, isProviderOverflowFailClosedProven, describeProtectedTailDrainBudgetSkip, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, NEWEST_REASONING_BEARING_ASSISTANT, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, thinkingBindingRecoveryFrozenId, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, getSessionsWithPendingPiMarker, setSessionWorkMetrics, getSessionWorkMetrics, resolveEpochFloorForPass, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, getNotes, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, getPendingOpsCount, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, insertPrimerCandidates, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, BoundedSessionMap, MIN_PLAUSIBLE_CONTEXT_LIMIT, reloadWindowOverlay, getWindowOverlay, resolveWindowOverlayFacts, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, isSaneLimit, resolveOutputReserve, getSdkContextLimit, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findLastModelKeyFromBranch, convertEntriesToRawMessages, convertEntriesToRawMessagePage, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, invalidateMemory, computeNormalizedHash, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, insertMemory, getMemoryByHash, getMemoriesByProject, getMemoriesByProjects, getMaxMemoryIdForProjects, getAllActiveMemoriesForMigration, getMemoryById, setMemoryClassification, archiveMemory, deleteMemory, getMemoryCount, getMemoryCountsByStatus, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, formatSynapseLaneDescriptor, buildCanonicalChunkTextFromFts, buildCompartmentSummaryFallbackText, canonicalizeInMemoryChunkTextForEmbedding, chunkCanonicalText, chunkEmbeddingWindowsAreCurrent, replaceCompartmentChunkEmbeddings, cosineSimilarity, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, describeShadowBackfillWriteRefusal, contentSha256, sweepStaleEmbeddingIdentitiesForProject, enqueueShadowEmbeddingItems, getProjectEmbeddingSnapshot, getProjectChunkEmbeddingModelId, getProjectEmbeddingMaxInputTokens, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, promoteSessionFactsDurable, embedPromotedFacts, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, indexCommitsForProject, embedUnembeddedCommits, loadPiConfig, ensureProjectRegisteredFromPiDirectory, resolvePiHarnessDetection, resolvePiHarnessKind, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, temporalMarkerPrefix, clearInjectionCache, getVisibleMemoryIds, renderMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, unifiedSearch, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
package/dist/index.js CHANGED
@@ -385,6 +385,18 @@ import {
385
385
  getActiveUserMemories,
386
386
  updateUserMemoryContent,
387
387
  dismissUserMemory,
388
+ getTaskScheduleState,
389
+ getMostRecentTaskRunAt,
390
+ pruneNonCanonicalTaskRows,
391
+ deleteTaskScheduleRowsForProject,
392
+ seedTaskScheduleState,
393
+ writeTaskScheduleState,
394
+ isRetrospectiveWindowProcessed,
395
+ recordRetrospectiveWindowProcessed,
396
+ curateCategoryForMemoryCategory,
397
+ peekCurateCategoryScope,
398
+ beginCurateCategoryRun,
399
+ curateTaskStateAfterSuccess,
388
400
  formatSynapseLaneDescriptor,
389
401
  buildCanonicalChunkTextFromFts,
390
402
  buildCompartmentSummaryFallbackText,
@@ -464,7 +476,7 @@ import {
464
476
  registerTodoStateLifecycle,
465
477
  syncCtxMemoryToolEnabled,
466
478
  registerMagicContextTools
467
- } from "./index-pbkqtaac.js";
479
+ } from "./index-a0960w4w.js";
468
480
  import {
469
481
  pushNotification2
470
482
  } from "./index-b3eqj1g6.js";
@@ -613,6 +625,9 @@ var DREAM_TASK_CAPABILITIES = {
613
625
  function formatDreamTaskBacklogs(backlogs, tasks = CANONICAL_DREAM_TASKS) {
614
626
  return tasks.filter((task) => backlogs[task] !== undefined).map((task) => {
615
627
  const backlog = backlogs[task];
628
+ if (task === "curate" && backlog?.category) {
629
+ return `- curate: ${backlog.category} (${backlog.pending})`;
630
+ }
616
631
  return `- ${task}: ${backlog?.pending ?? 0} pending / ${backlog?.total ?? 0} total`;
617
632
  }).join(`
618
633
  `);
@@ -2360,70 +2375,6 @@ function backoffMs(failureCount) {
2360
2375
  return minutes * 60 * 1000;
2361
2376
  }
2362
2377
 
2363
- // ../plugin/src/features/magic-context/dreamer/storage-task-schedule.ts
2364
- function toRow(r) {
2365
- return {
2366
- projectPath: r.project_path,
2367
- task: r.task,
2368
- lastRunAt: r.last_run_at,
2369
- nextDueAt: r.next_due_at,
2370
- schedule: r.schedule ?? null,
2371
- lastStatus: r.last_status ?? null,
2372
- lastError: r.last_error,
2373
- retryCount: r.retry_count ?? 0,
2374
- lastCheckedCommit: r.last_checked_commit ?? null,
2375
- lastBroadRunAt: r.last_broad_run_at ?? null,
2376
- retrospectiveWatermarkMs: r.retrospective_watermark_ms ?? null
2377
- };
2378
- }
2379
- var SELECT_COLUMNS = "project_path, task, last_run_at, next_due_at, schedule, last_status, last_error, retry_count, last_checked_commit, last_broad_run_at, retrospective_watermark_ms";
2380
- function getTaskScheduleState(db, projectPath, task) {
2381
- const row = db.prepare(`SELECT ${SELECT_COLUMNS} FROM task_schedule_state WHERE project_path = ? AND task = ?`).get(projectPath, task);
2382
- return row ? toRow(row) : null;
2383
- }
2384
- function getMostRecentTaskRunAt(db, projectPath) {
2385
- const row = db.prepare("SELECT MAX(last_run_at) AS max_at FROM task_schedule_state WHERE project_path = ?").get(projectPath);
2386
- const value = row?.max_at ?? null;
2387
- return typeof value === "number" && value > 0 ? value : null;
2388
- }
2389
- function pruneNonCanonicalTaskRows(db, projectPath, canonicalTasks) {
2390
- if (canonicalTasks.length === 0)
2391
- return 0;
2392
- const placeholders = canonicalTasks.map(() => "?").join(", ");
2393
- const result = db.prepare(`DELETE FROM task_schedule_state WHERE project_path = ? AND task NOT IN (${placeholders})`).run(projectPath, ...canonicalTasks);
2394
- return Number(result.changes ?? 0);
2395
- }
2396
- function deleteTaskScheduleRowsForProject(db, projectPath) {
2397
- const result = db.prepare("DELETE FROM task_schedule_state WHERE project_path = ?").run(projectPath);
2398
- return Number(result.changes ?? 0);
2399
- }
2400
- function seedTaskScheduleState(db, projectPath, task, nextDueAt, lastRunAt, schedule) {
2401
- db.prepare("INSERT INTO task_schedule_state (project_path, task, last_run_at, next_due_at, schedule, last_status, last_error, retry_count) VALUES (?, ?, ?, ?, ?, NULL, NULL, 0) ON CONFLICT(project_path, task) DO NOTHING").run(projectPath, task, lastRunAt, nextDueAt, schedule);
2402
- }
2403
- function writeTaskScheduleState(db, row) {
2404
- const broadCycleUpdate = row.lastBroadRunAt === undefined ? "last_broad_run_at = task_schedule_state.last_broad_run_at" : "last_broad_run_at = excluded.last_broad_run_at";
2405
- db.prepare(`INSERT INTO task_schedule_state
2406
- (project_path, task, last_run_at, next_due_at, schedule, last_status, last_error, retry_count, last_checked_commit, last_broad_run_at, retrospective_watermark_ms)
2407
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2408
- ON CONFLICT(project_path, task) DO UPDATE SET
2409
- last_run_at = excluded.last_run_at,
2410
- next_due_at = excluded.next_due_at,
2411
- schedule = excluded.schedule,
2412
- last_status = excluded.last_status,
2413
- last_error = excluded.last_error,
2414
- retry_count = excluded.retry_count,
2415
- last_checked_commit = COALESCE(excluded.last_checked_commit, task_schedule_state.last_checked_commit),
2416
- ${broadCycleUpdate},
2417
- retrospective_watermark_ms = COALESCE(excluded.retrospective_watermark_ms, task_schedule_state.retrospective_watermark_ms)`).run(row.projectPath, row.task, row.lastRunAt, row.nextDueAt, row.schedule, row.lastStatus, row.lastError, row.retryCount, row.lastCheckedCommit ?? null, row.lastBroadRunAt ?? null, row.retrospectiveWatermarkMs ?? null);
2418
- }
2419
- function isRetrospectiveWindowProcessed(db, projectPath, windowKey) {
2420
- const row = db.prepare("SELECT 1 AS one FROM retrospective_processed_windows WHERE project_path = ? AND window_key = ?").get(projectPath, windowKey);
2421
- return row != null;
2422
- }
2423
- function recordRetrospectiveWindowProcessed(db, projectPath, windowKey) {
2424
- db.prepare("INSERT INTO retrospective_processed_windows (project_path, window_key, processed_at) VALUES (?, ?, ?) ON CONFLICT(project_path, window_key) DO NOTHING").run(projectPath, windowKey, Date.now());
2425
- }
2426
-
2427
2378
  // ../plugin/src/features/magic-context/dreamer/task-gates.ts
2428
2379
  function countActiveMemories(db, projectPath) {
2429
2380
  const row = db.prepare("SELECT COUNT(*) AS cnt FROM memories WHERE project_path = ? AND status IN ('active','permanent')").get(projectPath);
@@ -2431,12 +2382,13 @@ function countActiveMemories(db, projectPath) {
2431
2382
  }
2432
2383
  function countLiveMemories(db, projectPath, options = {}) {
2433
2384
  const unclassified = options.unclassifiedOnly && hasMemoryClassifiedAtColumn(db);
2434
- const row = db.prepare(`SELECT COUNT(*) AS cnt
2435
- FROM memories
2436
- WHERE project_path = ?
2437
- AND status IN ('active','permanent')
2438
- AND (expires_at IS NULL OR expires_at > ?)
2439
- ${unclassified ? "AND classified_at IS NULL" : ""}`).get(projectPath, Date.now());
2385
+ const sql = `SELECT COUNT(*) AS cnt
2386
+ FROM memories
2387
+ WHERE project_path = ?
2388
+ AND status IN ('active','permanent')
2389
+ AND (expires_at IS NULL OR expires_at > ?)
2390
+ ${unclassified ? "AND classified_at IS NULL" : ""}`;
2391
+ const row = options.category ? db.prepare(`${sql} AND category = ?`).get(projectPath, Date.now(), options.category) : db.prepare(sql).get(projectPath, Date.now());
2440
2392
  return row?.cnt ?? 0;
2441
2393
  }
2442
2394
  function countUnmappedActiveMemories(db, projectPath) {
@@ -2547,8 +2499,13 @@ function getDreamTaskBacklog(db, projectPath, task, options = {}) {
2547
2499
  return { pending, total };
2548
2500
  }
2549
2501
  case "curate": {
2550
- const total = countLiveMemories(db, projectPath);
2551
- return { pending: total, total };
2502
+ const categories = db.prepare(`SELECT category FROM memories
2503
+ WHERE project_path = ?
2504
+ AND status IN ('active','permanent')
2505
+ AND (expires_at IS NULL OR expires_at > ?)`).all(projectPath, Date.now());
2506
+ const scope = peekCurateCategoryScope(db, projectPath, categories);
2507
+ const total = scope?.memories.length ?? 0;
2508
+ return scope ? { pending: total, total, category: scope.category } : { pending: 0, total: 0 };
2552
2509
  }
2553
2510
  case "compress-cues": {
2554
2511
  const total = countLiveMemories(db, projectPath);
@@ -6186,9 +6143,11 @@ function buildCuratePrompt(args) {
6186
6143
 
6187
6144
  **Project:** ${args.projectPath}
6188
6145
 
6146
+ This run covers the whole of the \`${args.category}\` category (the other categories run in later windows).
6147
+
6189
6148
  The memories below are assumed ACCURATE (a separate verify task keeps them true). Your job is pool QUALITY: remove duplicates, tighten wording, and consolidate redundant entries that waste the ~6000-token injection budget. Explain each action in one line first. Do NOT mint new facts (that is the historian's job).
6190
6149
 
6191
- Work ALL THREE phases below in order (A → B → C) over the whole pool. Do NOT stop after consolidating — a run that only merges and never improves or archives is incomplete.
6150
+ Work ALL THREE phases below in order (A → B → C) over this category. Do NOT stop after consolidating — a run that only merges and never improves or archives is incomplete.
6192
6151
 
6193
6152
  ### Phase A — Consolidate duplicates
6194
6153
  Group by category, then merge near-identical / superset-subset / same-fact-different-angle clusters into one canonical memory with \`ctx_memory(action="merge", ids=[...], content="...", category="...")\`. Preserve every unique detail; terse present tense; paths/keys verbatim. Every id in a merge MUST share the same category — the system rejects cross-category merges. If two similar memories sit in different categories they are NOT duplicates; do not archive either as a consolidation. One fact per memory.
@@ -6408,6 +6367,7 @@ function buildDreamTaskPrompt(task, args) {
6408
6367
  case "curate":
6409
6368
  return buildCuratePrompt({
6410
6369
  projectPath: args.projectPath,
6370
+ category: args.curate?.category ?? "PROJECT_RULES",
6411
6371
  memories: args.curate?.memories ?? []
6412
6372
  });
6413
6373
  case "maintain-docs":
@@ -11210,6 +11170,7 @@ function createDreamTaskExecutor(deps) {
11210
11170
  processed: Math.max(0, processed),
11211
11171
  total: backlogAtStart.pending,
11212
11172
  startedAt,
11173
+ ...backlogAtStart.category ? { category: backlogAtStart.category } : {},
11213
11174
  ...refused === undefined ? {} : { refused: Math.max(0, refused) }
11214
11175
  });
11215
11176
  };
@@ -11262,7 +11223,8 @@ function createDreamTaskExecutor(deps) {
11262
11223
  totalAtStart: backlogAtStart.total,
11263
11224
  pendingAtEnd: end.pending,
11264
11225
  totalAtEnd: end.total,
11265
- processed
11226
+ processed,
11227
+ ...backlogAtStart.category ? { category: backlogAtStart.category } : {}
11266
11228
  };
11267
11229
  return value;
11268
11230
  })()
@@ -11868,6 +11830,7 @@ async function runAgenticTask(config, ctx, helpers) {
11868
11830
  let expiredArchived = 0;
11869
11831
  try {
11870
11832
  let curateMemories;
11833
+ let curateCategory;
11871
11834
  if (task === "curate") {
11872
11835
  expiredArchived = await archiveExpiredMemories({
11873
11836
  db,
@@ -11879,10 +11842,12 @@ async function runAgenticTask(config, ctx, helpers) {
11879
11842
  });
11880
11843
  if (leaseLost)
11881
11844
  throw new Error("Dream lease lost during expired-memory archive");
11882
- curateMemories = loadActiveMemoryPromptMemories(db, projectIdentity);
11883
- log(`[dreamer] curate pool: in_scope=${curateMemories.length} expired_archived=${expiredArchived}`);
11884
- if (curateMemories.length === 0 && expiredArchived > 0) {
11885
- const progress = formatExpiredArchiveProgress(expiredArchived);
11845
+ const scope = beginCurateCategoryRun(db, projectIdentity, loadActiveMemoryPromptMemories(db, projectIdentity));
11846
+ curateMemories = scope?.memories ?? [];
11847
+ curateCategory = scope?.category;
11848
+ log(`[dreamer] curate pool: category=${curateCategory ?? "none"} in_scope=${curateMemories.length} expired_archived=${expiredArchived}`);
11849
+ if (curateMemories.length === 0) {
11850
+ const progress = expiredArchived > 0 ? formatExpiredArchiveProgress(expiredArchived) : "curate: no populated project-memory category";
11886
11851
  helpers.recordRun("completed", null, {
11887
11852
  memoryChanges: helpers.computeMemoryDelta(memoryBefore),
11888
11853
  progress
@@ -11894,7 +11859,7 @@ async function runAgenticTask(config, ctx, helpers) {
11894
11859
  projectPath: projectIdentity,
11895
11860
  lastDreamAt: lastRunAt ? String(lastRunAt) : null,
11896
11861
  existingDocs,
11897
- curate: curateMemories ? { memories: curateMemories } : undefined
11862
+ curate: curateMemories && curateCategory ? { category: curateCategory, memories: curateMemories } : undefined
11898
11863
  });
11899
11864
  const createResponse = await createChildSessionWithFence({
11900
11865
  client: requireDreamClient(deps.client),
@@ -11986,16 +11951,34 @@ async function runAgenticTask(config, ctx, helpers) {
11986
11951
  }
11987
11952
  }
11988
11953
  const curateOutput = task === "curate" ? run.validated : undefined;
11954
+ const curateScopeProgress = task === "curate" && curateCategory && curateMemories ? `curate: ${curateCategory} (${curateMemories.length})` : null;
11989
11955
  const progress = [
11956
+ curateScopeProgress,
11990
11957
  expiredArchived > 0 ? formatExpiredArchiveProgress(expiredArchived) : null,
11991
11958
  curateOutput && curateOutput.memoryOperations.completedActions.length > 0 ? formatCurateMemoryOperations(curateOutput.memoryOperations.completedActions) : null,
11992
11959
  curateRefused > 0 ? `curate: refused ${curateRefused} unsafe mutation(s)` : null
11993
11960
  ].filter((value) => Boolean(value)).join("; ");
11961
+ const curateCount = task === "curate" && curateCategory ? loadActiveMemoryPromptMemories(db, projectIdentity).filter((memory) => curateCategoryForMemoryCategory(memory.category) === curateCategory).length : undefined;
11962
+ const curateBacklog = curateCount !== undefined && curateCategory ? {
11963
+ pending: curateCount,
11964
+ total: curateCount,
11965
+ category: curateCategory
11966
+ } : undefined;
11994
11967
  helpers.recordRun("completed", null, {
11995
11968
  memoryChanges: helpers.computeMemoryDelta(memoryBefore),
11996
- progress: progress || null
11969
+ progress: progress || null,
11970
+ backlogAfter: curateBacklog
11997
11971
  });
11998
- return { status: "completed", ...progress ? { detail: progress } : {} };
11972
+ return {
11973
+ status: "completed",
11974
+ ...progress ? { detail: progress } : {},
11975
+ ...curateBacklog ? { backlog: curateBacklog } : {},
11976
+ ...curateCategory ? {
11977
+ schedulePatch: {
11978
+ taskStateJson: curateTaskStateAfterSuccess(db, projectIdentity, curateCategory)
11979
+ }
11980
+ } : {}
11981
+ };
11999
11982
  } finally {
12000
11983
  heartbeat.stop();
12001
11984
  if (childSessionId)
@@ -12070,6 +12053,7 @@ function advanceAfterRun(db, projectIdentity, due, finishedAt, status, error, sc
12070
12053
  lastStatus: status,
12071
12054
  lastError: error,
12072
12055
  retryCount: 0,
12056
+ taskStateJson: schedulePatch?.taskStateJson,
12073
12057
  retrospectiveWatermarkMs: schedulePatch?.retrospectiveWatermarkMs
12074
12058
  });
12075
12059
  }
@@ -12162,7 +12146,7 @@ async function runDomainGroup(deps, group, cb) {
12162
12146
  const finishedAt = Date.now();
12163
12147
  if (outcome.status === "completed") {
12164
12148
  advanceAfterRun(db, projectIdentity, due, finishedAt, "completed", null, outcome.schedulePatch);
12165
- cb?.onRan?.(due.config.task, outcome.detail);
12149
+ cb?.onRan?.(due.config.task, outcome.detail, outcome.backlog);
12166
12150
  } else if (outcome.transient) {
12167
12151
  recordTransientFailure(db, projectIdentity, due, finishedAt, outcome.error ?? null);
12168
12152
  cb?.onFailed?.(due.config.task, outcome.failureDetail ?? outcome.error);
@@ -12229,6 +12213,7 @@ async function runManualDream(deps) {
12229
12213
  return result;
12230
12214
  }
12231
12215
  const groups = new Map;
12216
+ const runLocalBacklogs = {};
12232
12217
  for (const d of gated) {
12233
12218
  const kind = leaseKindFor(d.config.task);
12234
12219
  const arr = groups.get(kind) ?? [];
@@ -12238,10 +12223,12 @@ async function runManualDream(deps) {
12238
12223
  await Promise.all([...groups.values()].map((group) => runDomainGroup({ ...deps, executor: deps.executor }, group, {
12239
12224
  forceGate,
12240
12225
  leaseWaitMs: MANUAL_RUN_LEASE_WAIT_MS,
12241
- onRan: (t, detail) => {
12226
+ onRan: (t, detail, backlog) => {
12242
12227
  result.ran.push(t);
12243
12228
  if (detail)
12244
12229
  result.details?.push(detail);
12230
+ if (backlog)
12231
+ runLocalBacklogs[t] = backlog;
12245
12232
  },
12246
12233
  onFailed: (task, error) => {
12247
12234
  result.failed.push(task);
@@ -12250,7 +12237,10 @@ async function runManualDream(deps) {
12250
12237
  },
12251
12238
  onBusy: (t) => result.deferredBusy.push(t)
12252
12239
  })));
12253
- result.backlogAfter = getDreamTaskBacklogs(deps.db, deps.projectIdentity, selectedTaskNames);
12240
+ result.backlogAfter = {
12241
+ ...getDreamTaskBacklogs(deps.db, deps.projectIdentity, selectedTaskNames),
12242
+ ...runLocalBacklogs
12243
+ };
12254
12244
  return result;
12255
12245
  }
12256
12246
  async function runDueTasksForProject(deps) {
@@ -22023,7 +22013,7 @@ function memoizedContent(kind, content) {
22023
22013
  return cached;
22024
22014
  const measured = {
22025
22015
  hash: fnv1a32(key),
22026
- tokens: kind === "excluded" ? 0 : estimateTokens(content),
22016
+ tokens: kind === "excluded" ? 0 : undefined,
22027
22017
  keyBytes: key.length * 2 + 32
22028
22018
  };
22029
22019
  contentMemo.set(key, measured);
@@ -22040,7 +22030,11 @@ function memoizedContent(kind, content) {
22040
22030
  return measured;
22041
22031
  }
22042
22032
  function memoizedTokens(kind, content) {
22043
- return memoizedContent(kind, content).tokens;
22033
+ const measured = memoizedContent(kind, content);
22034
+ if (measured.tokens === undefined) {
22035
+ measured.tokens = estimateTokens(content);
22036
+ }
22037
+ return measured.tokens;
22044
22038
  }
22045
22039
  function partHash(kind, content) {
22046
22040
  return memoizedContent(kind, content).hash;
@@ -32811,7 +32805,7 @@ function formatTailHygiene(status) {
32811
32805
  // package.json
32812
32806
  var package_default = {
32813
32807
  name: "@cortexkit/pi-magic-context",
32814
- version: "0.42.4",
32808
+ version: "0.42.5",
32815
32809
  type: "module",
32816
32810
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
32817
32811
  main: "dist/index.js",
@@ -8,7 +8,7 @@ import {
8
8
  ensureProjectRegisteredFromPiDirectory,
9
9
  resolvePiHarnessKind,
10
10
  registerMagicContextTools
11
- } from "./index-pbkqtaac.js";
11
+ } from "./index-a0960w4w.js";
12
12
 
13
13
  // src/subagent-entry.ts
14
14
  var SUBAGENT_DREAMER_ACTIONS_FLAG = "magic-context-dreamer-actions";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.42.4",
3
+ "version": "0.42.5",
4
4
  "type": "module",
5
5
  "description": "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",