@cortexkit/opencode-magic-context 0.40.0 → 0.41.0
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/README.md +1 -1
- package/dist/agents/permissions.d.ts +5 -3
- package/dist/agents/permissions.d.ts.map +1 -1
- package/dist/{announcement-5eg4t64s.js → announcement-3g9xg433.js} +2 -2
- package/dist/{conflict-warning-hook-f406ggbw.js → conflict-warning-hook-xj1r88a7.js} +4 -4
- package/dist/{derive-budgets-xk8cy5e6.js → derive-budgets-3xfyphvk.js} +3 -3
- package/dist/features/builtin-commands/commands.d.ts +35 -2
- package/dist/features/builtin-commands/commands.d.ts.map +1 -1
- package/dist/features/magic-context/context-authority.d.ts +10 -0
- package/dist/features/magic-context/context-authority.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/classify.d.ts +1 -0
- package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/lease.d.ts +12 -27
- package/dist/features/magic-context/dreamer/lease.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/map-memories-prompt.d.ts +1 -1
- package/dist/features/magic-context/dreamer/map-memories-prompt.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/map-memories.d.ts +2 -0
- package/dist/features/magic-context/dreamer/map-memories.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/memory-claim-safety.d.ts +9 -0
- package/dist/features/magic-context/dreamer/memory-claim-safety.d.ts.map +1 -0
- package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-registry.d.ts +2 -0
- package/dist/features/magic-context/dreamer/task-registry.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/verify-prompt.d.ts +7 -2
- package/dist/features/magic-context/dreamer/verify-prompt.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/verify.d.ts +13 -10
- package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-local.d.ts +19 -0
- package/dist/features/magic-context/memory/embedding-local.d.ts.map +1 -1
- package/dist/features/magic-context/memory/storage-memory-verifications.d.ts +5 -1
- package/dist/features/magic-context/memory/storage-memory-verifications.d.ts.map +1 -1
- package/dist/features/magic-context/memory/storage-memory.d.ts.map +1 -1
- package/dist/features/magic-context/migrations.d.ts.map +1 -1
- package/dist/features/magic-context/project-embedding-registry.d.ts +3 -0
- package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
- package/dist/features/magic-context/storage-db.d.ts +1 -1
- package/dist/features/magic-context/storage-db.d.ts.map +1 -1
- package/dist/features/magic-context/storage-identity-merge.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta-persisted.d.ts +29 -3
- package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta.d.ts +1 -1
- package/dist/features/magic-context/storage-meta.d.ts.map +1 -1
- package/dist/features/magic-context/storage-tags.d.ts +7 -0
- package/dist/features/magic-context/storage-tags.d.ts.map +1 -1
- package/dist/features/magic-context/storage.d.ts +1 -1
- package/dist/features/magic-context/storage.d.ts.map +1 -1
- package/dist/hooks/magic-context/channel2-delivery.d.ts +2 -4
- package/dist/hooks/magic-context/channel2-delivery.d.ts.map +1 -1
- package/dist/hooks/magic-context/command-handler.d.ts +7 -0
- package/dist/hooks/magic-context/command-handler.d.ts.map +1 -1
- package/dist/hooks/magic-context/compaction-marker-manager.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-recomp.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-trigger.d.ts +1 -0
- package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
- package/dist/hooks/magic-context/ctx-reduce-nudge.d.ts +15 -14
- package/dist/hooks/magic-context/ctx-reduce-nudge.d.ts.map +1 -1
- package/dist/hooks/magic-context/emergency-drop.d.ts +6 -8
- package/dist/hooks/magic-context/emergency-drop.d.ts.map +1 -1
- package/dist/hooks/magic-context/event-resolvers.d.ts +2 -2
- package/dist/hooks/magic-context/execute-status.d.ts +4 -1
- package/dist/hooks/magic-context/execute-status.d.ts.map +1 -1
- package/dist/hooks/magic-context/heuristic-cleanup.d.ts +6 -0
- package/dist/hooks/magic-context/heuristic-cleanup.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook-handlers.d.ts +21 -8
- package/dist/hooks/magic-context/hook-handlers.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook.d.ts +16 -1
- package/dist/hooks/magic-context/hook.d.ts.map +1 -1
- package/dist/hooks/magic-context/inject-compartments.d.ts +6 -16
- package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
- package/dist/hooks/magic-context/maintenance-authority.d.ts +3 -0
- package/dist/hooks/magic-context/maintenance-authority.d.ts.map +1 -0
- package/dist/hooks/magic-context/module-transport.d.ts.map +1 -1
- package/dist/hooks/magic-context/module-wire.d.ts.map +1 -1
- package/dist/hooks/magic-context/protected-tail-boundary.d.ts.map +1 -1
- package/dist/hooks/magic-context/read-session-true-raw-tokens.d.ts +1 -0
- package/dist/hooks/magic-context/read-session-true-raw-tokens.d.ts.map +1 -1
- package/dist/hooks/magic-context/rust-mode-transform.d.ts +9 -0
- package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
- package/dist/hooks/magic-context/strip-content.d.ts +8 -0
- package/dist/hooks/magic-context/strip-content.d.ts.map +1 -1
- package/dist/hooks/magic-context/stripped-command.d.ts +19 -0
- package/dist/hooks/magic-context/stripped-command.d.ts.map +1 -0
- package/dist/hooks/magic-context/supersession-reclaim.d.ts +11 -0
- package/dist/hooks/magic-context/supersession-reclaim.d.ts.map +1 -1
- package/dist/hooks/magic-context/tag-messages.d.ts +6 -0
- package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
- package/dist/hooks/magic-context/tail-hygiene-walk.d.ts +11 -0
- package/dist/hooks/magic-context/tail-hygiene-walk.d.ts.map +1 -1
- package/dist/hooks/magic-context/temporal-awareness.d.ts +1 -1
- package/dist/hooks/magic-context/temporal-awareness.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-operations.d.ts +1 -1
- package/dist/hooks/magic-context/transform-operations.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +5 -1
- package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/{index-pck9vadr.js → index-26ds03jd.js} +1 -1
- package/dist/{index-mg1yx1ph.js → index-2bykz3bx.js} +2 -2
- package/dist/{index-mmrhhk9a.js → index-37yzyeca.js} +36 -8
- package/dist/{index-btj2qhmc.js → index-88za3sz8.js} +3 -3
- package/dist/index-b4gv9f7g.js +284 -0
- package/dist/{index-ehpzdy0v.js → index-bf799gbq.js} +8 -1
- package/dist/{index-1h9t9xb5.js → index-dmgbar7r.js} +2 -2
- package/dist/{index-qf20mv7e.js → index-dmvy29z0.js} +1 -1
- package/dist/{index-sw8gnq34.js → index-jmwq2wxr.js} +2 -2
- package/dist/{index-3dkzzh0t.js → index-knna83k0.js} +1 -1
- package/dist/{index-axpym70t.js → index-w8rkbhn6.js} +617 -324
- package/dist/{index-rw0qrkvq.js → index-x9dmzyp5.js} +17 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2901 -2305
- package/dist/{model-resolution-r9jbcz86.js → model-resolution-jgrkt0z2.js} +3 -1
- package/dist/plugin/dream-timer.d.ts.map +1 -1
- package/dist/plugin/hooks/create-session-hooks.d.ts +14 -0
- package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
- package/dist/plugin/rpc-handlers.d.ts +10 -0
- package/dist/plugin/rpc-handlers.d.ts.map +1 -1
- package/dist/{recomp-orchestrator-dmyvqekw.js → recomp-orchestrator-1w4xj6jt.js} +7 -7
- package/dist/{safe-notification-target-tepzc2xa.js → safe-notification-target-p0c0csxw.js} +3 -3
- package/dist/{send-session-notification-6v5b72b4.js → send-session-notification-kn34g7mx.js} +4 -4
- package/dist/shared/data-path.d.ts +12 -3
- package/dist/shared/data-path.d.ts.map +1 -1
- package/dist/shared/logger.d.ts.map +1 -1
- package/dist/shared/model-resolution.d.ts +1 -0
- package/dist/shared/model-resolution.d.ts.map +1 -1
- package/dist/shared/rpc-types.d.ts +5 -0
- package/dist/shared/rpc-types.d.ts.map +1 -1
- package/dist/shared/rust-mode-status.d.ts +3 -0
- package/dist/shared/rust-mode-status.d.ts.map +1 -0
- package/dist/shared/status-detail-text.d.ts.map +1 -1
- package/dist/shared/subagent-runner.d.ts +4 -0
- package/dist/shared/subagent-runner.d.ts.map +1 -1
- package/dist/shared/write-transaction-timing.d.ts +11 -0
- package/dist/shared/write-transaction-timing.d.ts.map +1 -0
- package/dist/{storage-meta-session-yvtbaw7c.js → storage-meta-session-snbzd26z.js} +4 -4
- package/dist/{task-config-a1qmj9bx.js → task-config-ty08ptc2.js} +2 -2
- package/dist/tools/ctx-expand/tools.d.ts.map +1 -1
- package/dist/tools/ctx-memory/tools.d.ts.map +1 -1
- package/dist/tui/data/context-db.d.ts +10 -3
- package/dist/tui/data/context-db.d.ts.map +1 -1
- package/dist/tui-compiled/data/context-db.d.ts +10 -3
- package/dist/tui-compiled/data/context-db.d.ts.map +1 -1
- package/package.json +2 -1
- package/src/agents/permissions.ts +14 -4
- package/src/config/index.test.ts +38 -0
- package/src/features/magic-context/dreamer/task-registry.ts +2 -0
- package/src/shared/data-path.test.ts +44 -4
- package/src/shared/data-path.ts +54 -11
- package/src/shared/logger.test.ts +15 -0
- package/src/shared/logger.ts +9 -4
- package/src/shared/model-resolution.test.ts +39 -0
- package/src/shared/model-resolution.ts +8 -0
- package/src/shared/redaction.ts +2 -2
- package/src/shared/rpc-types.ts +5 -0
- package/src/shared/rust-mode-status.ts +3 -0
- package/src/shared/status-detail-text.test.ts +13 -0
- package/src/shared/status-detail-text.ts +2 -0
- package/src/shared/subagent-runner.ts +4 -0
- package/src/shared/write-transaction-timing.ts +25 -0
- package/src/tui/data/context-db.test.ts +31 -1
- package/src/tui/data/context-db.ts +17 -61
- package/src/tui/index.tsx +36 -5
- package/src/tui-compiled/data/context-db.ts +17 -61
- package/src/tui-compiled/index.tsx +229 -191
- package/dist/index-8pqfcghm.js +0 -81
|
@@ -2,19 +2,20 @@ import {
|
|
|
2
2
|
deriveTriggerBudget,
|
|
3
3
|
modelSupportsVision,
|
|
4
4
|
shouldEnforcePrivateStoragePermissions
|
|
5
|
-
} from "./index-
|
|
5
|
+
} from "./index-2bykz3bx.js";
|
|
6
6
|
import {
|
|
7
7
|
describeError,
|
|
8
8
|
getErrorMessage,
|
|
9
9
|
sendIgnoredMessage
|
|
10
|
-
} from "./index-
|
|
10
|
+
} from "./index-88za3sz8.js";
|
|
11
11
|
import {
|
|
12
12
|
clearCachedM0M1,
|
|
13
13
|
deleteSessionScopedRows,
|
|
14
14
|
ensureSessionMetaRow,
|
|
15
|
+
logSlowWriteTransaction,
|
|
15
16
|
persistCachedM0,
|
|
16
17
|
updateSessionMeta
|
|
17
|
-
} from "./index-
|
|
18
|
+
} from "./index-x9dmzyp5.js";
|
|
18
19
|
import {
|
|
19
20
|
modelRefLookupOrder,
|
|
20
21
|
piModelRefToCanonical
|
|
@@ -27,7 +28,7 @@ import {
|
|
|
27
28
|
openCodeDbExists,
|
|
28
29
|
withPrivilegedWriter,
|
|
29
30
|
withReadOnlySessionDb
|
|
30
|
-
} from "./index-
|
|
31
|
+
} from "./index-jmwq2wxr.js";
|
|
31
32
|
import {
|
|
32
33
|
detectConfigFile
|
|
33
34
|
} from "./index-8mtsfhyg.js";
|
|
@@ -36,8 +37,9 @@ import {
|
|
|
36
37
|
} from "./index-d62ypazr.js";
|
|
37
38
|
import {
|
|
38
39
|
log,
|
|
40
|
+
sanitizeDiagnosticText,
|
|
39
41
|
sessionLog
|
|
40
|
-
} from "./index-
|
|
42
|
+
} from "./index-b4gv9f7g.js";
|
|
41
43
|
import {
|
|
42
44
|
ensureCortexKitArtifactGitignore,
|
|
43
45
|
getDataDir,
|
|
@@ -45,7 +47,7 @@ import {
|
|
|
45
47
|
getLegacyOpenCodeMagicContextStorageDir,
|
|
46
48
|
getMagicContextStorageDir,
|
|
47
49
|
getProjectMagicContextHistorianDir
|
|
48
|
-
} from "./index-
|
|
50
|
+
} from "./index-37yzyeca.js";
|
|
49
51
|
import {
|
|
50
52
|
__export,
|
|
51
53
|
__require
|
|
@@ -398,153 +400,6 @@ function buildPrimaryLanguageDirective(language) {
|
|
|
398
400
|
return `Use ${target} for your natural-language replies to the user unless the user explicitly asks for another language. Keep code, identifiers, file paths, commands, logs, and quoted text verbatim.`;
|
|
399
401
|
}
|
|
400
402
|
|
|
401
|
-
// src/shared/redaction.ts
|
|
402
|
-
import { homedir, userInfo } from "node:os";
|
|
403
|
-
function escapeRegex(value) {
|
|
404
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
405
|
-
}
|
|
406
|
-
var SECRET_WORDS = [
|
|
407
|
-
"key",
|
|
408
|
-
"token",
|
|
409
|
-
"secret",
|
|
410
|
-
"password",
|
|
411
|
-
"auth",
|
|
412
|
-
"authorization",
|
|
413
|
-
"bearer",
|
|
414
|
-
"credential"
|
|
415
|
-
];
|
|
416
|
-
var SECRET_SEGMENT_PATTERN = new RegExp(`^(?:${SECRET_WORDS.map((w) => `${w}s?`).join("|")})$`, "i");
|
|
417
|
-
var TRAILING_DESCRIPTORS = new Set(["id", "ids", "value", "values", "header", "headers"]);
|
|
418
|
-
function redactionTypeForKey(key) {
|
|
419
|
-
const normalized = key.trim().toLowerCase().replace(/[^a-z0-9_.-]+/g, "_");
|
|
420
|
-
const suffix = normalized.split(".").filter(Boolean).at(-1) ?? normalized;
|
|
421
|
-
return suffix || "secret";
|
|
422
|
-
}
|
|
423
|
-
function isNonSecretScalarValue(value) {
|
|
424
|
-
const v = value.trim();
|
|
425
|
-
if (v === "true" || v === "false" || v === "null" || v === "undefined")
|
|
426
|
-
return true;
|
|
427
|
-
return /^[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(v);
|
|
428
|
-
}
|
|
429
|
-
var SECRET_QUALIFIERS = new Set([
|
|
430
|
-
"api",
|
|
431
|
-
"access",
|
|
432
|
-
"private",
|
|
433
|
-
"client",
|
|
434
|
-
"auth",
|
|
435
|
-
"authorization",
|
|
436
|
-
"secret",
|
|
437
|
-
"bearer",
|
|
438
|
-
"session",
|
|
439
|
-
"refresh",
|
|
440
|
-
"service",
|
|
441
|
-
"x",
|
|
442
|
-
"openai",
|
|
443
|
-
"anthropic",
|
|
444
|
-
"google",
|
|
445
|
-
"github",
|
|
446
|
-
"huggingface",
|
|
447
|
-
"aws",
|
|
448
|
-
"azure"
|
|
449
|
-
]);
|
|
450
|
-
function sanitizePathString(value) {
|
|
451
|
-
const home = homedir();
|
|
452
|
-
const username = userInfo().username;
|
|
453
|
-
let sanitized = value;
|
|
454
|
-
if (home) {
|
|
455
|
-
sanitized = sanitized.replace(new RegExp(escapeRegex(home), "g"), "~");
|
|
456
|
-
}
|
|
457
|
-
sanitized = sanitized.replace(/\/Users\/[^/]+\//g, "/Users/<USER>/");
|
|
458
|
-
sanitized = sanitized.replace(/\/home\/[^/]+\//g, "/home/<USER>/");
|
|
459
|
-
sanitized = sanitized.replace(/C:\\Users\\[^\\]+\\/g, "C:\\Users\\<USER>\\");
|
|
460
|
-
if (username) {
|
|
461
|
-
sanitized = sanitized.replace(new RegExp(escapeRegex(username), "g"), "<USER>");
|
|
462
|
-
}
|
|
463
|
-
return sanitized;
|
|
464
|
-
}
|
|
465
|
-
var SECRET_TEXT_PATTERNS = [
|
|
466
|
-
{
|
|
467
|
-
pattern: /\bsk-ant-(?:api03-)?[A-Za-z0-9_-]{32,}/g,
|
|
468
|
-
replacement: "<ANTHROPIC_API_KEY_REDACTED>"
|
|
469
|
-
},
|
|
470
|
-
{
|
|
471
|
-
pattern: /\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}/g,
|
|
472
|
-
replacement: "<OPENAI_API_KEY_REDACTED>"
|
|
473
|
-
},
|
|
474
|
-
{
|
|
475
|
-
pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
|
|
476
|
-
replacement: "<GITHUB_PAT_REDACTED>"
|
|
477
|
-
},
|
|
478
|
-
{
|
|
479
|
-
pattern: /\b(?:gh[opsu]|ghr)_[A-Za-z0-9]{30,}/g,
|
|
480
|
-
replacement: "<GITHUB_TOKEN_REDACTED>"
|
|
481
|
-
},
|
|
482
|
-
{
|
|
483
|
-
pattern: /\bhf_[A-Za-z0-9]{30,}/g,
|
|
484
|
-
replacement: "<HUGGINGFACE_TOKEN_REDACTED>"
|
|
485
|
-
},
|
|
486
|
-
{
|
|
487
|
-
pattern: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
|
|
488
|
-
replacement: "<AWS_ACCESS_KEY_ID_REDACTED>"
|
|
489
|
-
},
|
|
490
|
-
{
|
|
491
|
-
pattern: /\bxox[abprsuvc]-[A-Za-z0-9-]{10,}/g,
|
|
492
|
-
replacement: "<SLACK_TOKEN_REDACTED>"
|
|
493
|
-
},
|
|
494
|
-
{
|
|
495
|
-
pattern: /\bAIza[A-Za-z0-9_-]{35}\b/g,
|
|
496
|
-
replacement: "<GOOGLE_API_KEY_REDACTED>"
|
|
497
|
-
},
|
|
498
|
-
{
|
|
499
|
-
pattern: /\b(Authorization\s*:\s*Bearer\s+)([A-Za-z0-9._~+/=-]{8,})/gi,
|
|
500
|
-
replacement: (_full, prefix) => `${prefix}<REDACTED:bearer>`
|
|
501
|
-
},
|
|
502
|
-
{
|
|
503
|
-
pattern: /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,
|
|
504
|
-
replacement: "<JWT_REDACTED>"
|
|
505
|
-
},
|
|
506
|
-
{
|
|
507
|
-
pattern: /(["'])([^"']*(?:key|token|secret|password|auth|bearer|credential)[^"']*)\1(\s*:\s*)(["'])([^"']*)\4/gi,
|
|
508
|
-
replacement: (full, quote, key, separator, valueQuote, value) => isNonSecretScalarValue(value) ? full : `${quote}${key}${quote}${separator}${valueQuote}<REDACTED:${redactionTypeForKey(key)}>${valueQuote}`
|
|
509
|
-
},
|
|
510
|
-
{
|
|
511
|
-
pattern: /\b([A-Za-z0-9_.-]*(?:key|token|secret|password|auth|bearer|credential)[A-Za-z0-9_.-]*)\s*=\s*([^\s'"`]+)/gi,
|
|
512
|
-
replacement: (full, key, value) => isNonSecretScalarValue(value) ? full : `${key}=<REDACTED:${redactionTypeForKey(key)}>`
|
|
513
|
-
}
|
|
514
|
-
];
|
|
515
|
-
function redactSecretText(value) {
|
|
516
|
-
let redacted = value;
|
|
517
|
-
for (const { pattern, replacement } of SECRET_TEXT_PATTERNS) {
|
|
518
|
-
if (typeof replacement === "string") {
|
|
519
|
-
redacted = redacted.replace(pattern, replacement);
|
|
520
|
-
} else {
|
|
521
|
-
redacted = redacted.replace(pattern, replacement);
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
return redacted;
|
|
525
|
-
}
|
|
526
|
-
function sanitizeDiagnosticText(value) {
|
|
527
|
-
return redactSecretText(sanitizePathString(value));
|
|
528
|
-
}
|
|
529
|
-
var SHAREABILITY_SENSITIVE_PATTERNS = [
|
|
530
|
-
/\bC:\/Users\/[^/\s]+/i,
|
|
531
|
-
/(?:^|\s)~\/[^\s]+/,
|
|
532
|
-
/\b(?:api[_-]?key|secret|token|password|passwd|pwd|client[_-]?secret|access[_-]?key)\b\s*[:=]\s*\S+/i,
|
|
533
|
-
/\b(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d+)?\b/i,
|
|
534
|
-
/\b(?:10|127)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,
|
|
535
|
-
/\b192\.168\.\d{1,3}\.\d{1,3}\b/,
|
|
536
|
-
/\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b/
|
|
537
|
-
];
|
|
538
|
-
function hasShareabilitySensitiveText(text) {
|
|
539
|
-
try {
|
|
540
|
-
if (sanitizeDiagnosticText(text) !== text)
|
|
541
|
-
return true;
|
|
542
|
-
return SHAREABILITY_SENSITIVE_PATTERNS.some((pattern) => pattern.test(text));
|
|
543
|
-
} catch {
|
|
544
|
-
return true;
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
|
|
548
403
|
// src/features/magic-context/fail-closed-block.ts
|
|
549
404
|
var FAIL_CLOSED_DOCTOR_COMMAND = "npx @cortexkit/magic-context@latest doctor";
|
|
550
405
|
var FAIL_CLOSED_REPROBE_EVERY_N = 5;
|
|
@@ -1145,6 +1000,18 @@ function isValidPort(port) {
|
|
|
1145
1000
|
// src/features/magic-context/context-authority.ts
|
|
1146
1001
|
import { createHash as createHash2, randomUUID } from "node:crypto";
|
|
1147
1002
|
var AUTHORITY_DOMAINS = ["memories", "notes"];
|
|
1003
|
+
var observedAuthorityRoutingByProject = new Map;
|
|
1004
|
+
function observeAuthorityRouting(projectPath, location) {
|
|
1005
|
+
const previous = observedAuthorityRoutingByProject.get(projectPath);
|
|
1006
|
+
if (previous === location)
|
|
1007
|
+
return;
|
|
1008
|
+
observedAuthorityRoutingByProject.set(projectPath, location);
|
|
1009
|
+
if (location === "MODULE") {
|
|
1010
|
+
log(`[magic-context] project ${projectPath} authority → MODULE: host backends → MODULE: ctx_memory, ctx_note; historian: module-side`);
|
|
1011
|
+
} else if (previous === "MODULE") {
|
|
1012
|
+
log(`[magic-context] project ${projectPath} authority → TS: host backends → TypeScript: ctx_memory, ctx_note; historian: host-side`);
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1148
1015
|
var moduleNoteEvaluationBridges = new Map;
|
|
1149
1016
|
function registerModuleNoteEvaluationBridge(projectPath, bridge) {
|
|
1150
1017
|
moduleNoteEvaluationBridges.set(projectPath, bridge);
|
|
@@ -1512,6 +1379,9 @@ async function drainAuthority(args) {
|
|
|
1512
1379
|
if (next === cursor)
|
|
1513
1380
|
break;
|
|
1514
1381
|
}
|
|
1382
|
+
if (args.domain === "memories") {
|
|
1383
|
+
resolvePendingMemoryReferencesForDrain(args.db);
|
|
1384
|
+
}
|
|
1515
1385
|
for (const step of [
|
|
1516
1386
|
"seed",
|
|
1517
1387
|
"memories",
|
|
@@ -1684,6 +1554,83 @@ var MEMORY_SNAPSHOT_COLUMNS = [
|
|
|
1684
1554
|
"mural_cue_at",
|
|
1685
1555
|
"mural_cue_rejection_count"
|
|
1686
1556
|
];
|
|
1557
|
+
var IMMUTABLE_MEMORY_SNAPSHOT_COLUMNS = ["project_path", "first_seen_at", "created_at"];
|
|
1558
|
+
var CLASSIFICATION_MEMORY_SNAPSHOT_COLUMNS = [
|
|
1559
|
+
"importance",
|
|
1560
|
+
"scope",
|
|
1561
|
+
"shareable",
|
|
1562
|
+
"source_type",
|
|
1563
|
+
"classified_at"
|
|
1564
|
+
];
|
|
1565
|
+
var VERIFICATION_MEMORY_SNAPSHOT_COLUMNS = [
|
|
1566
|
+
"verification_status",
|
|
1567
|
+
"verified_at",
|
|
1568
|
+
"mapping",
|
|
1569
|
+
"mapping_origin"
|
|
1570
|
+
];
|
|
1571
|
+
var MURAL_MEMORY_SNAPSHOT_COLUMNS = [
|
|
1572
|
+
"mural_cue",
|
|
1573
|
+
"mural_cue_hash",
|
|
1574
|
+
"mural_cue_at",
|
|
1575
|
+
"mural_cue_rejection_count"
|
|
1576
|
+
];
|
|
1577
|
+
var UPDATED_MEMORY_SNAPSHOT_COLUMNS = [
|
|
1578
|
+
"category",
|
|
1579
|
+
"content",
|
|
1580
|
+
"normalized_hash",
|
|
1581
|
+
"source_session_id",
|
|
1582
|
+
"seen_count",
|
|
1583
|
+
"retrieval_count",
|
|
1584
|
+
"updated_at",
|
|
1585
|
+
"last_seen_at",
|
|
1586
|
+
"last_retrieved_at",
|
|
1587
|
+
"status",
|
|
1588
|
+
"expires_at",
|
|
1589
|
+
"superseded_by_memory_id",
|
|
1590
|
+
"merged_from",
|
|
1591
|
+
"metadata_json"
|
|
1592
|
+
];
|
|
1593
|
+
function memorySnapshotTimestamp(row, key) {
|
|
1594
|
+
const value = row[key];
|
|
1595
|
+
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
1596
|
+
}
|
|
1597
|
+
function parsedMemorySnapshot(snapshotJson, fallback) {
|
|
1598
|
+
try {
|
|
1599
|
+
const parsed = JSON.parse(snapshotJson);
|
|
1600
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : fallback;
|
|
1601
|
+
} catch {
|
|
1602
|
+
return fallback;
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
function guardMemorySnapshotByRecency(args) {
|
|
1606
|
+
const effectiveRow = { ...args.row };
|
|
1607
|
+
if (!args.existing) {
|
|
1608
|
+
return { effectiveRow, hostUpdatedNewer: false, hostVerificationNewer: false };
|
|
1609
|
+
}
|
|
1610
|
+
const existing = args.existing;
|
|
1611
|
+
const preserve = (columns) => {
|
|
1612
|
+
for (const column of columns) {
|
|
1613
|
+
if (Object.hasOwn(existing, column)) {
|
|
1614
|
+
effectiveRow[column] = existing[column];
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
};
|
|
1618
|
+
preserve(IMMUTABLE_MEMORY_SNAPSHOT_COLUMNS);
|
|
1619
|
+
const hostUpdatedNewer = memorySnapshotTimestamp(existing, "updated_at") > memorySnapshotTimestamp(args.snapshot, "updated_at");
|
|
1620
|
+
const hostClassificationNewer = hostUpdatedNewer || memorySnapshotTimestamp(existing, "classified_at") > memorySnapshotTimestamp(args.snapshot, "classified_at");
|
|
1621
|
+
const snapshotCarriesUpdatedAt = hasSnapshotField(args.snapshot, "updated_at");
|
|
1622
|
+
const hostVerificationNewer = hostUpdatedNewer && snapshotCarriesUpdatedAt;
|
|
1623
|
+
const hostMuralNewer = hostUpdatedNewer && snapshotCarriesUpdatedAt;
|
|
1624
|
+
if (hostUpdatedNewer)
|
|
1625
|
+
preserve(UPDATED_MEMORY_SNAPSHOT_COLUMNS);
|
|
1626
|
+
if (hostClassificationNewer)
|
|
1627
|
+
preserve(CLASSIFICATION_MEMORY_SNAPSHOT_COLUMNS);
|
|
1628
|
+
if (hostVerificationNewer)
|
|
1629
|
+
preserve(VERIFICATION_MEMORY_SNAPSHOT_COLUMNS);
|
|
1630
|
+
if (hostMuralNewer)
|
|
1631
|
+
preserve(MURAL_MEMORY_SNAPSHOT_COLUMNS);
|
|
1632
|
+
return { effectiveRow, hostUpdatedNewer, hostVerificationNewer };
|
|
1633
|
+
}
|
|
1687
1634
|
function hasSnapshotField(row, key) {
|
|
1688
1635
|
return Object.prototype.hasOwnProperty.call(row, key);
|
|
1689
1636
|
}
|
|
@@ -1828,11 +1775,11 @@ function prepareMirrorPageStatements(db) {
|
|
|
1828
1775
|
verification_status = ?, verified_at = ?, classified_at = ?, superseded_by_memory_id = ?,
|
|
1829
1776
|
merged_from = ?, metadata_json = ?, mural_cue = ?, mural_cue_hash = ?, mural_cue_at = ?,
|
|
1830
1777
|
mural_cue_rejection_count = ? WHERE id = ?`),
|
|
1831
|
-
updateSuperseded: db.prepare("UPDATE memories SET superseded_by_memory_id = ? WHERE id = ?"),
|
|
1778
|
+
updateSuperseded: db.prepare("UPDATE memories SET superseded_by_memory_id = ?, updated_at = ? WHERE id = ?"),
|
|
1832
1779
|
deletePendingReference: db.prepare("DELETE FROM mirror_pending_references WHERE domain = 'memories' AND module_project = ? AND module_row_id = ?"),
|
|
1833
1780
|
upsertPendingReference: db.prepare("INSERT INTO mirror_pending_references(domain, module_project, module_row_id, target_module_row_id) VALUES ('memories', ?, ?, ?) ON CONFLICT(domain, module_project, module_row_id) DO UPDATE SET target_module_row_id = excluded.target_module_row_id"),
|
|
1834
1781
|
deleteMemoryVerifications: db.prepare("DELETE FROM memory_verifications WHERE memory_id = ?"),
|
|
1835
|
-
insertMemoryVerification: db.prepare("INSERT INTO memory_verifications(memory_id, file_path, verified_at, mapped_at) VALUES (?, ?, ?, ?)"),
|
|
1782
|
+
insertMemoryVerification: db.prepare("INSERT INTO memory_verifications(memory_id, file_path, verified_at, mapped_at, mapping_origin) VALUES (?, ?, ?, ?, ?)"),
|
|
1836
1783
|
noteById: db.prepare("SELECT * FROM notes WHERE id = ?"),
|
|
1837
1784
|
noteIdByStoreId: db.prepare("SELECT id FROM notes WHERE id = ? AND type = 'smart' AND project_path = ?"),
|
|
1838
1785
|
insertNote: db.prepare("INSERT INTO notes (type, status, content, project_path, session_id, created_at, updated_at) VALUES ('smart', 'active', '', ?, ?, 0, 0)"),
|
|
@@ -1860,7 +1807,8 @@ function prepareMirrorPageStatements(db) {
|
|
|
1860
1807
|
AND target.module_row_id = pending.target_module_row_id
|
|
1861
1808
|
WHERE pending.domain = 'memories'
|
|
1862
1809
|
AND source.context_row_id = memories.id
|
|
1863
|
-
)
|
|
1810
|
+
),
|
|
1811
|
+
updated_at = ?
|
|
1864
1812
|
WHERE id IN (
|
|
1865
1813
|
SELECT source.context_row_id
|
|
1866
1814
|
FROM mirror_pending_references pending
|
|
@@ -1890,7 +1838,7 @@ function prepareMirrorPageStatements(db) {
|
|
|
1890
1838
|
repairPending: db.prepare("SELECT dirty FROM mirror_memory_repair_state WHERE id = 1"),
|
|
1891
1839
|
markRepairPending: db.prepare("UPDATE mirror_memory_repair_state SET dirty = 1, updated_at = ? WHERE id = 1"),
|
|
1892
1840
|
clearRepairPending: db.prepare("UPDATE mirror_memory_repair_state SET dirty = 0, updated_at = ? WHERE id = 1"),
|
|
1893
|
-
repairCandidates: db.prepare(`SELECT memory.id, live.full_row_snapshot
|
|
1841
|
+
repairCandidates: db.prepare(`SELECT memory.id, memory.updated_at, memory.classified_at, live.full_row_snapshot
|
|
1894
1842
|
FROM memories memory
|
|
1895
1843
|
JOIN mirror_identity identity
|
|
1896
1844
|
ON identity.domain = 'memories'
|
|
@@ -1904,9 +1852,14 @@ function prepareMirrorPageStatements(db) {
|
|
|
1904
1852
|
WHERE (memory.source_type IS NULL OR memory.importance IS NULL)
|
|
1905
1853
|
AND live.full_row_snapshot IS NOT NULL`),
|
|
1906
1854
|
repairMemory: db.prepare(`UPDATE memories
|
|
1907
|
-
SET source_type = COALESCE(
|
|
1908
|
-
importance = COALESCE(
|
|
1909
|
-
|
|
1855
|
+
SET source_type = COALESCE(source_type, ?),
|
|
1856
|
+
importance = COALESCE(importance, ?),
|
|
1857
|
+
updated_at = ?
|
|
1858
|
+
WHERE id = ?
|
|
1859
|
+
AND COALESCE(updated_at, 0) <= ?
|
|
1860
|
+
AND COALESCE(classified_at, 0) <= ?
|
|
1861
|
+
AND ((source_type IS NULL AND ? IS NOT NULL)
|
|
1862
|
+
OR (importance IS NULL AND ? IS NOT NULL))`),
|
|
1910
1863
|
updateCursor: db.prepare("INSERT INTO mirror_cursors(domain, cursor, updated_at) VALUES (?, ?, ?) ON CONFLICT(domain) DO UPDATE SET cursor = excluded.cursor, updated_at = excluded.updated_at"),
|
|
1911
1864
|
contextStoreUuid: getContextStoreUuid(db)
|
|
1912
1865
|
};
|
|
@@ -1917,12 +1870,13 @@ function mirrorIdentity(db, domain, moduleProject, moduleRowId, statements) {
|
|
|
1917
1870
|
function applyMirroredNoteCompileFields(args) {
|
|
1918
1871
|
return withPrivilegedWriter(args.db, () => {
|
|
1919
1872
|
const result = args.db.prepare(`UPDATE notes
|
|
1920
|
-
SET compiled_provider = ?, compiled_config = ?, compiled_at = ?, compile_status =
|
|
1873
|
+
SET compiled_provider = ?, compiled_config = ?, compiled_at = ?, compile_status = ?,
|
|
1874
|
+
updated_at = ?
|
|
1921
1875
|
WHERE id = (
|
|
1922
1876
|
SELECT context_row_id
|
|
1923
1877
|
FROM mirror_identity
|
|
1924
1878
|
WHERE domain = 'notes' AND module_project = ? AND module_row_id = ?
|
|
1925
|
-
)`).run(args.fields.compiledProvider, args.fields.compiledConfig, args.fields.compiledAt, args.fields.compileStatus, args.moduleProject, args.moduleRowId);
|
|
1879
|
+
)`).run(args.fields.compiledProvider, args.fields.compiledConfig, args.fields.compiledAt, args.fields.compileStatus, Date.now(), args.moduleProject, args.moduleRowId);
|
|
1926
1880
|
return result.changes === 1;
|
|
1927
1881
|
});
|
|
1928
1882
|
}
|
|
@@ -2002,37 +1956,46 @@ function applyMemoryRow(db, feed, statements) {
|
|
|
2002
1956
|
log(`[magic-context] skipping memory mirror update for module ${moduleProject}/${feed.module_row_id}: context row ${contextId} belongs to ${existing.project_path}`);
|
|
2003
1957
|
return;
|
|
2004
1958
|
}
|
|
1959
|
+
const retainedRecencySnapshot = parsedMemorySnapshot(snapshotJson, row);
|
|
1960
|
+
const recencySnapshot = hasSnapshotField(row, "updated_at") ? row : hasSnapshotField(row, "classified_at") ? { ...retainedRecencySnapshot, classified_at: row.classified_at } : retainedRecencySnapshot;
|
|
1961
|
+
const recencyGuard = guardMemorySnapshotByRecency({
|
|
1962
|
+
row,
|
|
1963
|
+
snapshot: recencySnapshot,
|
|
1964
|
+
existing
|
|
1965
|
+
});
|
|
1966
|
+
const projectedRow = recencyGuard.effectiveRow;
|
|
2005
1967
|
const has = (key) => hasSnapshotField(row, key);
|
|
2006
|
-
const nullableNumber = (key, previous) => has(key) ? typeof
|
|
2007
|
-
const nullableString = (key, previous) => has(key) ? rowNullableString(
|
|
2008
|
-
const hasSuperseded = has("superseded_by_memory_id");
|
|
1968
|
+
const nullableNumber = (key, previous) => has(key) ? typeof projectedRow[key] === "number" && Number.isFinite(projectedRow[key]) ? projectedRow[key] : null : previous ?? null;
|
|
1969
|
+
const nullableString = (key, previous) => has(key) ? rowNullableString(projectedRow, key) : previous ?? null;
|
|
1970
|
+
const hasSuperseded = has("superseded_by_memory_id") && !recencyGuard.hostUpdatedNewer;
|
|
2009
1971
|
const previousHash = existing?.normalized_hash;
|
|
2010
|
-
statements.updateMemory.run(has("project_path") ? rowString(
|
|
2011
|
-
if (hasSuperseded && typeof
|
|
2012
|
-
const translated = mirrorIdentity(db, "memories", moduleProject,
|
|
1972
|
+
statements.updateMemory.run(has("project_path") ? rowString(projectedRow, "project_path") : existing?.project_path ?? moduleProject, has("category") ? rowString(projectedRow, "category", "CONSTRAINTS") : existing?.category ?? "CONSTRAINTS", has("content") ? rowString(projectedRow, "content") : existing?.content ?? "", has("normalized_hash") ? rowString(projectedRow, "normalized_hash") : existing?.normalized_hash ?? "", has("importance") ? typeof projectedRow.importance === "number" && Number.isFinite(projectedRow.importance) ? projectedRow.importance : null : existing?.importance ?? null, has("scope") ? rowString(projectedRow, "scope", "project") : existing?.scope ?? "project", has("shareable") ? rowNumber(projectedRow, "shareable") : existing?.shareable ?? 0, nullableString("source_session_id", existing?.source_session_id), nullableString("source_type", existing?.source_type), has("seen_count") ? rowNumber(projectedRow, "seen_count", 1) : existing?.seen_count ?? 1, has("retrieval_count") ? rowNumber(projectedRow, "retrieval_count") : existing?.retrieval_count ?? 0, has("first_seen_at") ? rowNumber(projectedRow, "first_seen_at") : existing?.first_seen_at ?? 0, has("created_at") ? rowNumber(projectedRow, "created_at") : existing?.created_at ?? 0, has("updated_at") ? rowNumber(projectedRow, "updated_at") : existing?.updated_at ?? 0, has("last_seen_at") ? rowNumber(projectedRow, "last_seen_at") : existing?.last_seen_at ?? 0, nullableNumber("last_retrieved_at", existing?.last_retrieved_at), has("status") ? rowString(projectedRow, "status", "active") : existing?.status ?? "active", nullableNumber("expires_at", existing?.expires_at), has("verification_status") ? rowString(projectedRow, "verification_status", "unverified") : existing?.verification_status ?? "unverified", nullableNumber("verified_at", existing?.verified_at), nullableNumber("classified_at", existing?.classified_at), hasSuperseded ? null : existing?.superseded_by_memory_id ?? null, nullableString("merged_from", existing?.merged_from), nullableString("metadata_json", existing?.metadata_json), nullableString("mural_cue", existing?.mural_cue), nullableString("mural_cue_hash", existing?.mural_cue_hash), nullableNumber("mural_cue_at", existing?.mural_cue_at), has("mural_cue_rejection_count") ? rowNumber(projectedRow, "mural_cue_rejection_count") : existing?.mural_cue_rejection_count ?? 0, contextId);
|
|
1973
|
+
if (hasSuperseded && typeof projectedRow.superseded_by_memory_id === "number") {
|
|
1974
|
+
const translated = mirrorIdentity(db, "memories", moduleProject, projectedRow.superseded_by_memory_id, statements);
|
|
2013
1975
|
if (translated) {
|
|
2014
|
-
statements.updateSuperseded.run(translated.context_row_id, contextId);
|
|
1976
|
+
statements.updateSuperseded.run(translated.context_row_id, Date.now(), contextId);
|
|
2015
1977
|
statements.deletePendingReference.run(moduleProject, feed.module_row_id);
|
|
2016
1978
|
} else {
|
|
2017
|
-
statements.upsertPendingReference.run(moduleProject, feed.module_row_id,
|
|
1979
|
+
statements.upsertPendingReference.run(moduleProject, feed.module_row_id, projectedRow.superseded_by_memory_id);
|
|
2018
1980
|
}
|
|
2019
1981
|
} else if (hasSuperseded) {
|
|
2020
1982
|
statements.deletePendingReference.run(moduleProject, feed.module_row_id);
|
|
2021
1983
|
}
|
|
2022
|
-
const appliedHash = has("normalized_hash") ? rowString(
|
|
1984
|
+
const appliedHash = has("normalized_hash") ? rowString(projectedRow, "normalized_hash") : previousHash;
|
|
2023
1985
|
if (previousHash !== appliedHash && appliedHash !== undefined) {
|
|
2024
1986
|
statements.deleteMemoryEmbeddings.run(contextId);
|
|
2025
1987
|
}
|
|
2026
|
-
if (has("mapping")) {
|
|
1988
|
+
if (has("mapping") && !recencyGuard.hostVerificationNewer) {
|
|
2027
1989
|
statements.deleteMemoryVerifications.run(contextId);
|
|
2028
|
-
if (Array.isArray(
|
|
1990
|
+
if (Array.isArray(projectedRow.mapping)) {
|
|
2029
1991
|
const files = [
|
|
2030
|
-
...new Set(
|
|
1992
|
+
...new Set(projectedRow.mapping.filter((file) => typeof file === "string").sort())
|
|
2031
1993
|
];
|
|
2032
|
-
const verifiedAt = rowNumber(
|
|
2033
|
-
const mappedAt = rowNumber(
|
|
1994
|
+
const verifiedAt = rowNumber(projectedRow, "verified_at");
|
|
1995
|
+
const mappedAt = rowNumber(projectedRow, "updated_at", Date.now());
|
|
1996
|
+
const mappingOrigin = projectedRow.mapping_origin === "host_rejected_fallback" ? "host_rejected_fallback" : "mapper";
|
|
2034
1997
|
for (const file of files.length > 0 ? files : [""]) {
|
|
2035
|
-
statements.insertMemoryVerification.run(contextId, file, verifiedAt, mappedAt);
|
|
1998
|
+
statements.insertMemoryVerification.run(contextId, file, verifiedAt, mappedAt, mappingOrigin);
|
|
2036
1999
|
}
|
|
2037
2000
|
}
|
|
2038
2001
|
}
|
|
@@ -2058,7 +2021,11 @@ function repairNullClobberedMemoryRows(statements) {
|
|
|
2058
2021
|
const importance = hasSnapshotField(snapshot, "importance") && typeof snapshot.importance === "number" && Number.isFinite(snapshot.importance) ? snapshot.importance : null;
|
|
2059
2022
|
if (sourceType === null && importance === null)
|
|
2060
2023
|
continue;
|
|
2061
|
-
|
|
2024
|
+
const snapshotVintage = Math.max(memorySnapshotTimestamp(snapshot, "updated_at"), memorySnapshotTimestamp(snapshot, "classified_at"));
|
|
2025
|
+
const hostVintage = Math.max(candidate.updated_at ?? 0, candidate.classified_at ?? 0);
|
|
2026
|
+
if (hostVintage > snapshotVintage)
|
|
2027
|
+
continue;
|
|
2028
|
+
statements.repairMemory.run(sourceType, importance, Date.now(), candidate.id, snapshotVintage, snapshotVintage, sourceType, importance);
|
|
2062
2029
|
}
|
|
2063
2030
|
statements.clearRepairPending.run(Date.now());
|
|
2064
2031
|
}
|
|
@@ -2083,9 +2050,17 @@ function contextNoteId(db, feed, moduleProject, statements) {
|
|
|
2083
2050
|
return contextId;
|
|
2084
2051
|
}
|
|
2085
2052
|
function translateMemoryReferences(statements) {
|
|
2086
|
-
statements.translateMemoryReferences.run();
|
|
2053
|
+
statements.translateMemoryReferences.run(Date.now());
|
|
2087
2054
|
statements.clearTranslatedReferences.run();
|
|
2088
2055
|
}
|
|
2056
|
+
function resolvePendingMemoryReferencesForDrain(db) {
|
|
2057
|
+
withPrivilegedWriter(db, () => {
|
|
2058
|
+
db.transaction(() => {
|
|
2059
|
+
const statements = prepareMirrorPageStatements(db);
|
|
2060
|
+
translateMemoryReferences(statements);
|
|
2061
|
+
}).immediate();
|
|
2062
|
+
});
|
|
2063
|
+
}
|
|
2089
2064
|
function applyNoteRow(db, feed, statements) {
|
|
2090
2065
|
const row = feed.full_row_snapshot;
|
|
2091
2066
|
const moduleProject = rowString(row, "project_path");
|
|
@@ -2623,7 +2598,7 @@ var CATEGORY_DEFAULT_TTL = {
|
|
|
2623
2598
|
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
2624
2599
|
import { createHash as createHash3 } from "node:crypto";
|
|
2625
2600
|
import { existsSync, realpathSync, statSync } from "node:fs";
|
|
2626
|
-
import { homedir
|
|
2601
|
+
import { homedir } from "node:os";
|
|
2627
2602
|
import path from "node:path";
|
|
2628
2603
|
var GIT_TIMEOUT_MS = 5000;
|
|
2629
2604
|
var TRANSIENT_FAILURE_COOLDOWN_MS = 5 * 60 * 1000;
|
|
@@ -2637,7 +2612,7 @@ var dubiousOwnershipLoggedDirectories = new Set;
|
|
|
2637
2612
|
var dubiousOwnershipWarnedDirectories = new Set;
|
|
2638
2613
|
var transientGitIdentityReuseLoggedDirectories = new Set;
|
|
2639
2614
|
var execFileSyncForIdentity = execFileSync2;
|
|
2640
|
-
var userHomeDirectoryForIdentity = () =>
|
|
2615
|
+
var userHomeDirectoryForIdentity = () => homedir();
|
|
2641
2616
|
var nowMs = () => Date.now();
|
|
2642
2617
|
|
|
2643
2618
|
class ProjectIdentityError extends Error {
|
|
@@ -5405,6 +5380,15 @@ var MIGRATIONS = [
|
|
|
5405
5380
|
);
|
|
5406
5381
|
`);
|
|
5407
5382
|
}
|
|
5383
|
+
},
|
|
5384
|
+
{
|
|
5385
|
+
version: 82,
|
|
5386
|
+
description: "record the origin of memory file-independent mappings",
|
|
5387
|
+
up(db) {
|
|
5388
|
+
if (!tableExists2(db, "memory_verifications"))
|
|
5389
|
+
return;
|
|
5390
|
+
ensureColumn(db, "memory_verifications", "mapping_origin", "TEXT NOT NULL DEFAULT 'mapper'");
|
|
5391
|
+
}
|
|
5408
5392
|
}
|
|
5409
5393
|
];
|
|
5410
5394
|
var LATEST_MIGRATION_VERSION = MIGRATIONS.reduce((max, m) => Math.max(max, m.version), 0);
|
|
@@ -5450,6 +5434,7 @@ function runMigrations(db) {
|
|
|
5450
5434
|
let migration;
|
|
5451
5435
|
let currentVersion = 0;
|
|
5452
5436
|
try {
|
|
5437
|
+
const transactionStartedAt = performance.now();
|
|
5453
5438
|
const applied = db.transaction(() => {
|
|
5454
5439
|
currentVersion = getCurrentVersion(db);
|
|
5455
5440
|
migration = MIGRATIONS.find((candidate) => candidate.version > currentVersion && !isMigrationApplied(db, candidate.version));
|
|
@@ -5464,6 +5449,7 @@ function runMigrations(db) {
|
|
|
5464
5449
|
db.prepare("INSERT INTO schema_migrations (version, description, applied_at) VALUES (?, ?, ?)").run(migration.version, migration.description, Date.now());
|
|
5465
5450
|
return true;
|
|
5466
5451
|
}).immediate();
|
|
5452
|
+
logSlowWriteTransaction("migration-runner", transactionStartedAt);
|
|
5467
5453
|
if (!applied || !migration)
|
|
5468
5454
|
break;
|
|
5469
5455
|
if (migration.version <= 61)
|
|
@@ -5488,7 +5474,9 @@ function runMigrations(db) {
|
|
|
5488
5474
|
}
|
|
5489
5475
|
if (touchedLegacyAuthorityBatch) {
|
|
5490
5476
|
try {
|
|
5477
|
+
const transactionStartedAt = performance.now();
|
|
5491
5478
|
db.transaction(() => installLatestAuthorityTriggers(db)).immediate();
|
|
5479
|
+
logSlowWriteTransaction("migration-runner", transactionStartedAt);
|
|
5492
5480
|
} catch (error) {
|
|
5493
5481
|
throw new Error(`Migration authority-trigger postcondition failed: ${error instanceof Error ? error.message : String(error)}. Database may need manual repair.`);
|
|
5494
5482
|
}
|
|
@@ -5524,7 +5512,7 @@ import { createHash as createHash5 } from "node:crypto";
|
|
|
5524
5512
|
// src/hooks/magic-context/read-session-formatting.ts
|
|
5525
5513
|
import { existsSync as existsSync2, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
|
|
5526
5514
|
import { createRequire } from "node:module";
|
|
5527
|
-
import { homedir as
|
|
5515
|
+
import { homedir as homedir2 } from "node:os";
|
|
5528
5516
|
import { dirname, join as join2, resolve } from "node:path";
|
|
5529
5517
|
import { pathToFileURL } from "node:url";
|
|
5530
5518
|
|
|
@@ -5641,7 +5629,7 @@ var tokenizerLoadPromise;
|
|
|
5641
5629
|
var tokenizerWarningSent = false;
|
|
5642
5630
|
function tokenizerPackageRoots() {
|
|
5643
5631
|
const cwd = process.cwd();
|
|
5644
|
-
const openCodeCache = join2(process.env.XDG_CACHE_HOME ?? join2(
|
|
5632
|
+
const openCodeCache = join2(process.env.XDG_CACHE_HOME ?? join2(homedir2(), ".cache"), "opencode");
|
|
5645
5633
|
const roots = [cwd, openCodeCache];
|
|
5646
5634
|
const candidates = [];
|
|
5647
5635
|
for (const root of roots) {
|
|
@@ -6209,7 +6197,7 @@ function getSchemaFenceRejection() {
|
|
|
6209
6197
|
function getMigrationOnOpenRefusal() {
|
|
6210
6198
|
return lastMigrationOnOpenRefusal;
|
|
6211
6199
|
}
|
|
6212
|
-
var LATEST_SUPPORTED_VERSION =
|
|
6200
|
+
var LATEST_SUPPORTED_VERSION = 82;
|
|
6213
6201
|
var PERMISSIONS_ENFORCEABLE = process.platform !== "win32";
|
|
6214
6202
|
var defaultStoragePermissionFs = { chmodSync, mkdirSync };
|
|
6215
6203
|
var storagePermissionFs = defaultStoragePermissionFs;
|
|
@@ -6958,8 +6946,10 @@ function initializeDatabase(db) {
|
|
|
6958
6946
|
-- verified_at=0 means "mapped (files known) but not yet content-verified".
|
|
6959
6947
|
-- map-memories sets mapped_at + verified_at=0; verify sets verified_at=now.
|
|
6960
6948
|
verified_at INTEGER NOT NULL,
|
|
6961
|
-
|
|
6962
|
-
|
|
6949
|
+
mapped_at INTEGER NOT NULL DEFAULT 0,
|
|
6950
|
+
-- Distinguishes mapper-authored independence from a host rejection fallback.
|
|
6951
|
+
mapping_origin TEXT NOT NULL DEFAULT 'mapper',
|
|
6952
|
+
PRIMARY KEY (memory_id, file_path)
|
|
6963
6953
|
);
|
|
6964
6954
|
CREATE INDEX IF NOT EXISTS idx_memory_verifications_memory ON memory_verifications(memory_id);
|
|
6965
6955
|
|
|
@@ -7151,8 +7141,6 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
|
|
|
7151
7141
|
updated_at INTEGER NOT NULL,
|
|
7152
7142
|
harness TEXT NOT NULL DEFAULT 'opencode'
|
|
7153
7143
|
);
|
|
7154
|
-
CREATE INDEX IF NOT EXISTS idx_message_history_index_orphan_sweep
|
|
7155
|
-
ON message_history_index(harness, session_id, updated_at);
|
|
7156
7144
|
|
|
7157
7145
|
CREATE TABLE IF NOT EXISTS message_history_source (
|
|
7158
7146
|
session_id TEXT NOT NULL,
|
|
@@ -7739,6 +7727,10 @@ CREATE INDEX IF NOT EXISTS idx_dream_queue_pending ON dream_queue(started_at, en
|
|
|
7739
7727
|
ensureColumn(db, "recomp_compartments", "harness", "TEXT NOT NULL DEFAULT 'opencode'");
|
|
7740
7728
|
ensureColumn(db, "recomp_facts", "harness", "TEXT NOT NULL DEFAULT 'opencode'");
|
|
7741
7729
|
ensureColumn(db, "message_history_index", "harness", "TEXT NOT NULL DEFAULT 'opencode'");
|
|
7730
|
+
db.exec(`
|
|
7731
|
+
CREATE INDEX IF NOT EXISTS idx_message_history_index_orphan_sweep
|
|
7732
|
+
ON message_history_index(harness, session_id, updated_at);
|
|
7733
|
+
`);
|
|
7742
7734
|
ensureColumn(db, "workspaces", "share_categories", `TEXT NOT NULL DEFAULT '["CONSTRAINTS"]'`);
|
|
7743
7735
|
}
|
|
7744
7736
|
var CHANNEL2_CLAIM_TTL_MS = 10 * 60000;
|
|
@@ -8608,15 +8600,32 @@ function buildToolArcs(messages) {
|
|
|
8608
8600
|
}
|
|
8609
8601
|
return arcs.sort((a, b) => a.invOrdinal - b.invOrdinal || (a.resOrdinal ?? Number.MAX_SAFE_INTEGER) - (b.resOrdinal ?? Number.MAX_SAFE_INTEGER));
|
|
8610
8602
|
}
|
|
8603
|
+
function fenceBoundaryForCompletedToolArcs(candidate, arcs, publicationFloorOrdinal) {
|
|
8604
|
+
const completed = arcs.filter((arc) => arc.resOrdinal !== null).map((arc) => ({ invocation: arc.invOrdinal, result: arc.resOrdinal }));
|
|
8605
|
+
const component = completed.filter((arc) => completedToolArcCrossesBoundary(arc.invocation, arc.result, candidate));
|
|
8606
|
+
if (component.length === 0)
|
|
8607
|
+
return candidate;
|
|
8608
|
+
for (let pass = 0;pass <= completed.length; pass += 1) {
|
|
8609
|
+
const minInvocation2 = Math.min(...component.map((arc) => arc.invocation));
|
|
8610
|
+
const maxResult2 = Math.max(...component.map((arc) => arc.result));
|
|
8611
|
+
const before = component.length;
|
|
8612
|
+
for (const arc of completed) {
|
|
8613
|
+
if (arc.invocation <= maxResult2 && arc.result >= minInvocation2 && !component.includes(arc)) {
|
|
8614
|
+
component.push(arc);
|
|
8615
|
+
}
|
|
8616
|
+
}
|
|
8617
|
+
if (component.length === before)
|
|
8618
|
+
break;
|
|
8619
|
+
}
|
|
8620
|
+
const minInvocation = Math.min(...component.map((arc) => arc.invocation));
|
|
8621
|
+
const maxResult = Math.max(...component.map((arc) => arc.result));
|
|
8622
|
+
return minInvocation < publicationFloorOrdinal ? maxResult + 1 : minInvocation;
|
|
8623
|
+
}
|
|
8611
8624
|
function fenceBoundaryForToolArcs(candidate, arcs, lastCompartmentEndOrdinal, recentOpenArcCutoff) {
|
|
8612
|
-
|
|
8625
|
+
const boundary = fenceBoundaryForCompletedToolArcs(candidate, arcs, lastCompartmentEndOrdinal + 1);
|
|
8613
8626
|
for (const arc of arcs) {
|
|
8614
|
-
if (arc.resOrdinal !== null)
|
|
8615
|
-
if (completedToolArcCrossesBoundary(arc.invOrdinal, arc.resOrdinal, boundary)) {
|
|
8616
|
-
boundary = arc.resOrdinal + 1;
|
|
8617
|
-
}
|
|
8627
|
+
if (arc.resOrdinal !== null)
|
|
8618
8628
|
continue;
|
|
8619
|
-
}
|
|
8620
8629
|
if (arc.invOrdinal < recentOpenArcCutoff)
|
|
8621
8630
|
continue;
|
|
8622
8631
|
if (arc.invOrdinal >= lastCompartmentEndOrdinal + 1 && arc.invOrdinal < boundary) {
|
|
@@ -10446,6 +10455,13 @@ function isProviderOverflowReconfirmed(sessionId) {
|
|
|
10446
10455
|
function getEmergencyRecoveryArmedAt(sessionId) {
|
|
10447
10456
|
return emergencyRecoveryArmedAtBySession.get(sessionId) ?? null;
|
|
10448
10457
|
}
|
|
10458
|
+
function describeProtectedTailDrainBudgetSkip(result) {
|
|
10459
|
+
const state2 = result.budgetState;
|
|
10460
|
+
if (!state2)
|
|
10461
|
+
return "historian skip: internal drain budget spent";
|
|
10462
|
+
const resetMinutes = Math.max(1, Math.ceil(state2.resetInMs / 60000));
|
|
10463
|
+
return `historian skip: internal drain budget spent (${state2.spentTokens}/${state2.limitTokens} tokens; resets in ${resetMinutes}m)`;
|
|
10464
|
+
}
|
|
10449
10465
|
var CAS_RETRY_LIMIT = 5;
|
|
10450
10466
|
var AUTO_SEARCH_NO_HINT_REASONS = new Set([
|
|
10451
10467
|
"below-threshold",
|
|
@@ -10825,19 +10841,28 @@ function reserveProtectedTailDrainTokens(args) {
|
|
|
10825
10841
|
const now = args.now ?? Date.now();
|
|
10826
10842
|
const requested = Math.max(0, Math.floor(args.trueRawTokens));
|
|
10827
10843
|
if (requested === 0) {
|
|
10828
|
-
return {
|
|
10844
|
+
return {
|
|
10845
|
+
ok: true,
|
|
10846
|
+
reservedTokens: 0,
|
|
10847
|
+
overQuotaBypass: false,
|
|
10848
|
+
reservation: null,
|
|
10849
|
+
budgetState: null
|
|
10850
|
+
};
|
|
10829
10851
|
}
|
|
10830
10852
|
let result = {
|
|
10831
10853
|
ok: false,
|
|
10832
10854
|
reservedTokens: 0,
|
|
10833
10855
|
overQuotaBypass: false,
|
|
10834
10856
|
reservation: null,
|
|
10835
|
-
|
|
10857
|
+
budgetState: null,
|
|
10858
|
+
skippedReason: "internal drain budget spent"
|
|
10836
10859
|
};
|
|
10837
10860
|
args.db.transaction(() => {
|
|
10838
10861
|
ensureSessionMetaRow(args.db, args.sessionId);
|
|
10839
10862
|
let meta = loadProtectedTailMeta(args.db, args.sessionId);
|
|
10840
|
-
|
|
10863
|
+
const windowStartedAt = meta.protectedTailDrainWindowStartedAt;
|
|
10864
|
+
const windowExpired = windowStartedAt <= 0 || windowStartedAt > now || now - windowStartedAt >= DRAIN_WINDOW_MS;
|
|
10865
|
+
if (windowExpired) {
|
|
10841
10866
|
args.db.prepare(`UPDATE session_meta
|
|
10842
10867
|
SET protected_tail_drain_window_started_at = ?, protected_tail_drain_tokens = 0
|
|
10843
10868
|
WHERE session_id = ?`).run(now, args.sessionId);
|
|
@@ -10862,22 +10887,35 @@ function reserveProtectedTailDrainTokens(args) {
|
|
|
10862
10887
|
const remaining = Math.max(0, budget - meta.protectedTailDrainTokens);
|
|
10863
10888
|
let reserved = Math.min(requested, args.perRunCap, remaining);
|
|
10864
10889
|
let bypass = false;
|
|
10865
|
-
const inFailureBackoff = meta.historianDrainFailureAt > 0 && now - meta.historianDrainFailureAt < EMERGENCY_DRAIN_FAILURE_BACKOFF_MS;
|
|
10890
|
+
const inFailureBackoff = meta.historianDrainFailureAt > 0 && meta.historianDrainFailureAt <= now && now - meta.historianDrainFailureAt < EMERGENCY_DRAIN_FAILURE_BACKOFF_MS;
|
|
10866
10891
|
if (reserved <= 0 && latchActive && !inFailureBackoff) {
|
|
10867
10892
|
reserved = Math.min(requested, args.perRunCap);
|
|
10868
10893
|
bypass = true;
|
|
10869
10894
|
}
|
|
10870
|
-
|
|
10895
|
+
const activeWindowStartedAt = meta.protectedTailDrainWindowStartedAt;
|
|
10896
|
+
const budgetState = (spentTokens) => ({
|
|
10897
|
+
windowStartedAt: activeWindowStartedAt,
|
|
10898
|
+
resetsAt: activeWindowStartedAt + DRAIN_WINDOW_MS,
|
|
10899
|
+
resetInMs: Math.max(0, activeWindowStartedAt + DRAIN_WINDOW_MS - now),
|
|
10900
|
+
spentTokens,
|
|
10901
|
+
limitTokens: budget
|
|
10902
|
+
});
|
|
10903
|
+
if (reserved <= 0) {
|
|
10904
|
+
result = {
|
|
10905
|
+
...result,
|
|
10906
|
+
budgetState: budgetState(meta.protectedTailDrainTokens)
|
|
10907
|
+
};
|
|
10871
10908
|
return;
|
|
10909
|
+
}
|
|
10872
10910
|
args.db.prepare(`UPDATE session_meta
|
|
10873
|
-
SET
|
|
10874
|
-
|
|
10875
|
-
WHERE session_id = ?`).run(now, reserved, args.sessionId);
|
|
10911
|
+
SET protected_tail_drain_tokens = COALESCE(protected_tail_drain_tokens, 0) + ?
|
|
10912
|
+
WHERE session_id = ?`).run(reserved, args.sessionId);
|
|
10876
10913
|
result = {
|
|
10877
10914
|
ok: true,
|
|
10878
10915
|
reservedTokens: reserved,
|
|
10879
10916
|
overQuotaBypass: bypass,
|
|
10880
|
-
reservation: { sessionId: args.sessionId, runId: args.runId, tokens: reserved }
|
|
10917
|
+
reservation: { sessionId: args.sessionId, runId: args.runId, tokens: reserved },
|
|
10918
|
+
budgetState: budgetState(meta.protectedTailDrainTokens + reserved)
|
|
10881
10919
|
};
|
|
10882
10920
|
})();
|
|
10883
10921
|
return result;
|
|
@@ -10955,19 +10993,38 @@ function parseChannel1NudgeState(raw) {
|
|
|
10955
10993
|
try {
|
|
10956
10994
|
const parsed = JSON.parse(raw);
|
|
10957
10995
|
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
10958
|
-
|
|
10996
|
+
const state2 = {
|
|
10959
10997
|
level: normalizeLastNudgeLevel(parsed.level),
|
|
10960
10998
|
ordinal: typeof parsed.ordinal === "number" ? Math.max(0, Math.round(parsed.ordinal)) : 0
|
|
10961
10999
|
};
|
|
11000
|
+
if (parsed.postReduceGracePending === true)
|
|
11001
|
+
state2.postReduceGracePending = true;
|
|
11002
|
+
if (typeof parsed.postReduceGraceBaselineU === "number" && Number.isFinite(parsed.postReduceGraceBaselineU)) {
|
|
11003
|
+
state2.postReduceGraceBaselineU = Math.max(0, Math.round(parsed.postReduceGraceBaselineU));
|
|
11004
|
+
}
|
|
11005
|
+
const preLevel = normalizeLastNudgeLevel(parsed.postReduceGracePreLevel);
|
|
11006
|
+
if (preLevel !== "" || parsed.postReduceGracePreLevel === "") {
|
|
11007
|
+
state2.postReduceGracePreLevel = preLevel;
|
|
11008
|
+
}
|
|
11009
|
+
return state2;
|
|
10962
11010
|
}
|
|
10963
11011
|
} catch {}
|
|
10964
11012
|
return { level: normalizeLastNudgeLevel(raw), ordinal: 0 };
|
|
10965
11013
|
}
|
|
10966
11014
|
function serializeChannel1NudgeState(value) {
|
|
10967
|
-
|
|
11015
|
+
const serialized = {
|
|
10968
11016
|
level: normalizeLastNudgeLevel(value.level),
|
|
10969
11017
|
ordinal: Math.max(0, Math.round(value.ordinal))
|
|
10970
|
-
}
|
|
11018
|
+
};
|
|
11019
|
+
if (value.postReduceGracePending === true)
|
|
11020
|
+
serialized.postReduceGracePending = true;
|
|
11021
|
+
if (value.postReduceGraceBaselineU !== undefined) {
|
|
11022
|
+
serialized.postReduceGraceBaselineU = Math.max(0, Math.round(value.postReduceGraceBaselineU));
|
|
11023
|
+
}
|
|
11024
|
+
if (value.postReduceGracePreLevel !== undefined) {
|
|
11025
|
+
serialized.postReduceGracePreLevel = normalizeLastNudgeLevel(value.postReduceGracePreLevel);
|
|
11026
|
+
}
|
|
11027
|
+
return JSON.stringify(serialized);
|
|
10971
11028
|
}
|
|
10972
11029
|
function getLastNudgeUndropped(db, sessionId) {
|
|
10973
11030
|
const result = db.prepare("SELECT last_nudge_undropped FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
@@ -10989,20 +11046,36 @@ function setChannel1NudgeState(db, sessionId, value) {
|
|
|
10989
11046
|
db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(value), sessionId);
|
|
10990
11047
|
})();
|
|
10991
11048
|
}
|
|
10992
|
-
function
|
|
10993
|
-
db.transaction(() => {
|
|
11049
|
+
function markChannel1PostReduceGracePending(db, sessionId) {
|
|
11050
|
+
return db.transaction(() => {
|
|
10994
11051
|
ensureSessionMetaRow(db, sessionId);
|
|
10995
|
-
|
|
11052
|
+
const current = getChannel1NudgeState(db, sessionId);
|
|
11053
|
+
const next = {
|
|
11054
|
+
level: current.level,
|
|
11055
|
+
ordinal: current.ordinal,
|
|
11056
|
+
postReduceGracePending: true,
|
|
11057
|
+
postReduceGracePreLevel: current.level
|
|
11058
|
+
};
|
|
11059
|
+
db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(next), sessionId);
|
|
11060
|
+
return next;
|
|
10996
11061
|
})();
|
|
10997
11062
|
}
|
|
10998
|
-
function
|
|
10999
|
-
|
|
11000
|
-
db.transaction(() => {
|
|
11063
|
+
function captureChannel1PostReduceGraceBaseline(db, sessionId, measuredUndropped) {
|
|
11064
|
+
return db.transaction(() => {
|
|
11001
11065
|
ensureSessionMetaRow(db, sessionId);
|
|
11002
|
-
const
|
|
11003
|
-
|
|
11066
|
+
const current = getChannel1NudgeState(db, sessionId);
|
|
11067
|
+
if (current.postReduceGracePending !== true)
|
|
11068
|
+
return current;
|
|
11069
|
+
const baselineU = Math.max(0, Math.round(measuredUndropped));
|
|
11070
|
+
const next = {
|
|
11071
|
+
level: current.level,
|
|
11072
|
+
ordinal: current.ordinal,
|
|
11073
|
+
postReduceGraceBaselineU: baselineU,
|
|
11074
|
+
postReduceGracePreLevel: current.postReduceGracePreLevel ?? current.level
|
|
11075
|
+
};
|
|
11076
|
+
db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(next), sessionId);
|
|
11077
|
+
return next;
|
|
11004
11078
|
})();
|
|
11005
|
-
return changed;
|
|
11006
11079
|
}
|
|
11007
11080
|
function isChannel2StateRow(row) {
|
|
11008
11081
|
return typeof row === "object" && row !== null && typeof row.channel2_nudge_state === "string";
|
|
@@ -11533,6 +11606,33 @@ function addTrailingBlankDecisions(db, sessionId, additions, options) {
|
|
|
11533
11606
|
sessionLog(sessionId, `trailing_blank_decisions CAS: ${CAS_RETRY_LIMIT} retries exhausted`);
|
|
11534
11607
|
return false;
|
|
11535
11608
|
}
|
|
11609
|
+
function demoteTrailingBlankKeepDecisions(db, sessionId, messageIds) {
|
|
11610
|
+
const ids = new Set(messageIds);
|
|
11611
|
+
if (ids.size === 0)
|
|
11612
|
+
return [];
|
|
11613
|
+
ensureSessionMetaRow(db, sessionId);
|
|
11614
|
+
for (let attempt = 0;attempt < CAS_RETRY_LIMIT; attempt += 1) {
|
|
11615
|
+
const row = db.prepare("SELECT trailing_blank_decisions FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
11616
|
+
const rawStored = row ? row.trailing_blank_decisions ?? null : null;
|
|
11617
|
+
const current = parseTrailingBlankDecisions(rawStored);
|
|
11618
|
+
const demotedIds = [];
|
|
11619
|
+
for (const id of ids) {
|
|
11620
|
+
const decision = current.get(id);
|
|
11621
|
+
if (decision === "keep" || decision?.startsWith("keep:") === true) {
|
|
11622
|
+
current.set(id, "strip");
|
|
11623
|
+
demotedIds.push(id);
|
|
11624
|
+
}
|
|
11625
|
+
}
|
|
11626
|
+
if (demotedIds.length === 0)
|
|
11627
|
+
return [];
|
|
11628
|
+
const nextBlob = JSON.stringify(Object.fromEntries(current));
|
|
11629
|
+
const result = db.prepare("UPDATE session_meta SET trailing_blank_decisions = ? WHERE session_id = ? AND trailing_blank_decisions IS ?").run(nextBlob, sessionId, rawStored);
|
|
11630
|
+
if (result.changes > 0)
|
|
11631
|
+
return demotedIds;
|
|
11632
|
+
}
|
|
11633
|
+
sessionLog(sessionId, `trailing_blank_decisions demotion CAS: ${CAS_RETRY_LIMIT} retries exhausted`);
|
|
11634
|
+
return null;
|
|
11635
|
+
}
|
|
11536
11636
|
function getStaleReduceStrippedIds(db, sessionId) {
|
|
11537
11637
|
const row = db.prepare("SELECT stale_reduce_stripped_ids FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
11538
11638
|
return new Set(parseStrippedBlob(row?.stale_reduce_stripped_ids));
|
|
@@ -12974,7 +13074,8 @@ function measureTailHygiene(input) {
|
|
|
12974
13074
|
continue;
|
|
12975
13075
|
}
|
|
12976
13076
|
if (type === "text") {
|
|
12977
|
-
const
|
|
13077
|
+
const rawContent = firstString(part, ["text", "content"]);
|
|
13078
|
+
const content = rawContent === null ? null : stripChannel1ReminderSpans(rawContent);
|
|
12978
13079
|
if (!content || isDropSentinel(content)) {
|
|
12979
13080
|
parts.push(excludedSnapshot(`${key}\x00excluded`, part));
|
|
12980
13081
|
continue;
|
|
@@ -13124,7 +13225,8 @@ function refreshTailHygieneBaseline(input) {
|
|
|
13124
13225
|
evaluable: true,
|
|
13125
13226
|
generationInvalidated: false,
|
|
13126
13227
|
baselineParts: measured.parts,
|
|
13127
|
-
contentSignature: measured.contentSignature
|
|
13228
|
+
contentSignature: measured.contentSignature,
|
|
13229
|
+
channel1PostReduceGrace: input.previous?.channel1PostReduceGrace
|
|
13128
13230
|
};
|
|
13129
13231
|
}
|
|
13130
13232
|
const prefix = sameMeasuredPrefix(input.previous.baselineParts, measured.parts);
|
|
@@ -13186,47 +13288,74 @@ function decideChannel1(input) {
|
|
|
13186
13288
|
const tailTokens = Math.max(0, input.baselineT + input.turnDeltaT);
|
|
13187
13289
|
const undroppedTokens = Math.min(tailTokens, Math.max(0, input.baselineU + input.turnDeltaU));
|
|
13188
13290
|
const severity = Math.min(1, Math.max(0, undroppedTokens / Math.max(tailTokens, 1)));
|
|
13189
|
-
const
|
|
13190
|
-
|
|
13191
|
-
|
|
13192
|
-
|
|
13291
|
+
const previousLevel = input.lastNudgeLevel;
|
|
13292
|
+
let lastNudge = Math.max(0, input.lastNudgeUndropped);
|
|
13293
|
+
let nextLevel = previousLevel;
|
|
13294
|
+
let clearPostReduceGrace = false;
|
|
13295
|
+
const quiet = (level2 = "gentle") => ({
|
|
13193
13296
|
fire: false,
|
|
13194
|
-
|
|
13297
|
+
sticky: false,
|
|
13298
|
+
level: level2,
|
|
13195
13299
|
undroppedTokens,
|
|
13196
13300
|
tailTokens,
|
|
13197
13301
|
severity,
|
|
13198
13302
|
nextLastNudge: lastNudge,
|
|
13199
|
-
nextLastNudgeLevel:
|
|
13303
|
+
nextLastNudgeLevel: nextLevel,
|
|
13304
|
+
clearPostReduceGrace
|
|
13200
13305
|
});
|
|
13201
13306
|
if (input.evaluable === false || input.generationInvalidated === true)
|
|
13202
13307
|
return quiet();
|
|
13203
|
-
if (input.hasRecentReduce)
|
|
13204
|
-
return quiet();
|
|
13205
|
-
if (tailTokens < CHANNEL1_MIN_TOKENS)
|
|
13206
|
-
return quiet();
|
|
13207
|
-
if (undroppedTokens < CHANNEL1_FLOOR_TOKENS || undroppedTokens === 0)
|
|
13208
|
-
return quiet();
|
|
13209
|
-
if (severity < S_GENTLE)
|
|
13308
|
+
if (input.hasRecentReduce || input.postReduceGracePending)
|
|
13210
13309
|
return quiet();
|
|
13211
|
-
let level;
|
|
13212
|
-
if (severity >=
|
|
13213
|
-
|
|
13214
|
-
|
|
13215
|
-
|
|
13216
|
-
|
|
13217
|
-
|
|
13218
|
-
|
|
13219
|
-
|
|
13220
|
-
|
|
13310
|
+
let level = "";
|
|
13311
|
+
if (tailTokens >= CHANNEL1_MIN_TOKENS && undroppedTokens >= CHANNEL1_FLOOR_TOKENS && severity >= S_GENTLE) {
|
|
13312
|
+
if (severity >= S_URGENT)
|
|
13313
|
+
level = "urgent";
|
|
13314
|
+
else if (severity >= S_FIRM)
|
|
13315
|
+
level = "firm";
|
|
13316
|
+
else
|
|
13317
|
+
level = "gentle";
|
|
13318
|
+
}
|
|
13319
|
+
const previousRank = previousLevel === "" ? 0 : LEVEL_RANK[previousLevel];
|
|
13320
|
+
const currentRank = level === "" ? 0 : LEVEL_RANK[level];
|
|
13321
|
+
const graceBaseline = input.postReduceGraceBaselineU;
|
|
13322
|
+
if (graceBaseline !== undefined) {
|
|
13323
|
+
const preReduceLevel = input.postReduceGracePreLevel ?? previousLevel;
|
|
13324
|
+
const preReduceRank = preReduceLevel === "" ? 0 : LEVEL_RANK[preReduceLevel];
|
|
13325
|
+
const regrowthReached = undroppedTokens - Math.max(0, graceBaseline) >= channel1RefireTokens(tailTokens);
|
|
13326
|
+
const escalatedAbovePreReduceBand = currentRank > preReduceRank;
|
|
13327
|
+
if (!regrowthReached && !escalatedAbovePreReduceBand) {
|
|
13328
|
+
return quiet(level === "" ? "gentle" : level);
|
|
13329
|
+
}
|
|
13330
|
+
clearPostReduceGrace = true;
|
|
13331
|
+
}
|
|
13332
|
+
if (level === "") {
|
|
13333
|
+
nextLevel = "";
|
|
13334
|
+
lastNudge = 0;
|
|
13221
13335
|
return quiet();
|
|
13336
|
+
}
|
|
13337
|
+
if (currentRank < previousRank) {
|
|
13338
|
+
nextLevel = level;
|
|
13339
|
+
lastNudge = undroppedTokens;
|
|
13340
|
+
return quiet(level);
|
|
13341
|
+
}
|
|
13342
|
+
const crossedFromBelow = currentRank > previousRank;
|
|
13343
|
+
const cadenceReached = currentRank === previousRank && undroppedTokens - lastNudge >= channel1RefireTokens(tailTokens);
|
|
13344
|
+
const currentTurn = input.currentRealUserTurnCount;
|
|
13345
|
+
const lastFireTurn = input.lastFireOrdinal;
|
|
13346
|
+
const stickyTurnGapReached = currentTurn === undefined || lastFireTurn === undefined || lastFireTurn > currentTurn || currentTurn - lastFireTurn >= CHANNEL1_STICKY_REAL_USER_TURN_GAP;
|
|
13347
|
+
if (!crossedFromBelow && (!cadenceReached || !stickyTurnGapReached))
|
|
13348
|
+
return quiet(level);
|
|
13222
13349
|
return {
|
|
13223
13350
|
fire: true,
|
|
13351
|
+
sticky: !crossedFromBelow,
|
|
13224
13352
|
level,
|
|
13225
13353
|
undroppedTokens,
|
|
13226
13354
|
tailTokens,
|
|
13227
13355
|
severity,
|
|
13228
13356
|
nextLastNudge: undroppedTokens,
|
|
13229
|
-
nextLastNudgeLevel: level
|
|
13357
|
+
nextLastNudgeLevel: level,
|
|
13358
|
+
clearPostReduceGrace
|
|
13230
13359
|
};
|
|
13231
13360
|
}
|
|
13232
13361
|
var CHANNEL2_SEVERITY_THRESHOLD = 0.75;
|
|
@@ -13263,44 +13392,42 @@ function formatOldestReclaimableHint(hint) {
|
|
|
13263
13392
|
return rendered.length > 0 ? `
|
|
13264
13393
|
oldest reclaimable: ${rendered}.` : "";
|
|
13265
13394
|
}
|
|
13266
|
-
function
|
|
13267
|
-
|
|
13268
|
-
|
|
13395
|
+
function reclaimableToolOutputCount(parts) {
|
|
13396
|
+
return parts.filter((part) => part.kind === "toolOutput" && part.uTokens > 0).length;
|
|
13397
|
+
}
|
|
13398
|
+
function formatReclaimableOutputSummary(count, tokens) {
|
|
13399
|
+
const outputCount = Math.max(0, Math.floor(count));
|
|
13400
|
+
const outputs = outputCount === 0 ? "spent tool outputs" : `${outputCount} spent tool output${outputCount === 1 ? "" : "s"}`;
|
|
13401
|
+
return `${outputs} (~${approxThousands(tokens)} tokens)`;
|
|
13402
|
+
}
|
|
13403
|
+
function buildChannel2Reminder(undroppedTokens, reclaimableToolOutputs, hint) {
|
|
13404
|
+
const summary = formatReclaimableOutputSummary(reclaimableToolOutputs, undroppedTokens);
|
|
13269
13405
|
const hintText = formatOldestReclaimableHint(hint);
|
|
13270
13406
|
return `<system-reminder>
|
|
13271
|
-
` + `Routine housekeeping:
|
|
13407
|
+
` + `Routine housekeeping: ${summary} are reclaimable — make a ctx_reduce pass at a natural stopping point.${hintText}
|
|
13272
13408
|
` + `</system-reminder>`;
|
|
13273
13409
|
}
|
|
13274
|
-
var CHANNEL1_STICKY_REAL_USER_TURN_GAP =
|
|
13275
|
-
function
|
|
13276
|
-
|
|
13277
|
-
return false;
|
|
13278
|
-
if (input.lastOrdinal > input.currentRealUserTurnCount)
|
|
13279
|
-
return false;
|
|
13280
|
-
const gap = input.currentRealUserTurnCount - input.lastOrdinal;
|
|
13281
|
-
return gap >= 0 && gap < CHANNEL1_STICKY_REAL_USER_TURN_GAP;
|
|
13282
|
-
}
|
|
13283
|
-
function buildChannel1Reminder(level, undroppedTokens, usableWindowTokens, hint, sticky = false) {
|
|
13410
|
+
var CHANNEL1_STICKY_REAL_USER_TURN_GAP = 5;
|
|
13411
|
+
function buildChannel1Reminder(level, undroppedTokens, reclaimableToolOutputs, hint, sticky = false) {
|
|
13412
|
+
const summary = formatReclaimableOutputSummary(reclaimableToolOutputs, undroppedTokens);
|
|
13284
13413
|
const hintText = formatOldestReclaimableHint(hint);
|
|
13285
13414
|
if (sticky) {
|
|
13286
13415
|
return `
|
|
13287
13416
|
|
|
13288
13417
|
<system-reminder>
|
|
13289
|
-
Reminder:
|
|
13418
|
+
Reminder: ${summary} are still reclaimable — ctx_reduce them at a natural stopping point.${hintText}
|
|
13290
13419
|
</system-reminder>`;
|
|
13291
13420
|
}
|
|
13292
|
-
const amount = approxThousands(undroppedTokens);
|
|
13293
|
-
const usableWindow = approxThousands(usableWindowTokens);
|
|
13294
13421
|
let body;
|
|
13295
13422
|
switch (level) {
|
|
13296
13423
|
case "gentle":
|
|
13297
|
-
body = `Housekeeping:
|
|
13424
|
+
body = `Housekeeping: ${summary} are reclaimable — drop the ones you have already processed with ctx_reduce at a natural stopping point.`;
|
|
13298
13425
|
break;
|
|
13299
13426
|
case "firm":
|
|
13300
|
-
body = `Housekeeping:
|
|
13427
|
+
body = `Housekeeping: ${summary} are reclaimable — make a ctx_reduce pass at a natural stopping point.`;
|
|
13301
13428
|
break;
|
|
13302
13429
|
case "urgent":
|
|
13303
|
-
body = `Housekeeping backlog:
|
|
13430
|
+
body = `Housekeeping backlog: ${summary} are reclaimable — a ctx_reduce pass is due.`;
|
|
13304
13431
|
break;
|
|
13305
13432
|
}
|
|
13306
13433
|
return `
|
|
@@ -13361,8 +13488,8 @@ function planEmergencyDrop(input) {
|
|
|
13361
13488
|
if (!Number.isFinite(currentTotalInputTokens) || currentTotalInputTokens <= 0) {
|
|
13362
13489
|
return noop("unknown-usage");
|
|
13363
13490
|
}
|
|
13364
|
-
if (hasPriorDrop
|
|
13365
|
-
return noop(
|
|
13491
|
+
if (hasPriorDrop) {
|
|
13492
|
+
return noop(`pressure-episode-latched (prior sample ${priorInputSample}; awaiting exit or independent bust)`);
|
|
13366
13493
|
}
|
|
13367
13494
|
let tailTokens = 0;
|
|
13368
13495
|
for (const tag of floorTags) {
|
|
@@ -13472,12 +13599,50 @@ function getUpdateTagDropModeStatement(db) {
|
|
|
13472
13599
|
var updateTagByteSizeStatements = new WeakMap;
|
|
13473
13600
|
var updateTagInputByteSizeStatements = new WeakMap;
|
|
13474
13601
|
var CONTENT_ID_SUFFIX = /:(?:p|file)\d+$/;
|
|
13602
|
+
var RECENT_OWNER_SCAN_PAGE_SIZE = 128;
|
|
13603
|
+
var recentTagOwnerStatements = new WeakMap;
|
|
13475
13604
|
function ownerMessageIdForTagRow(row) {
|
|
13476
13605
|
if (row.type === "tool") {
|
|
13477
13606
|
return row.tool_owner_message_id ?? row.message_id;
|
|
13478
13607
|
}
|
|
13479
13608
|
return row.message_id.replace(CONTENT_ID_SUFFIX, "");
|
|
13480
13609
|
}
|
|
13610
|
+
function getRecentTagOwnerStatement(db) {
|
|
13611
|
+
let statement = recentTagOwnerStatements.get(db);
|
|
13612
|
+
if (!statement) {
|
|
13613
|
+
statement = db.prepare(`SELECT type, message_id, tool_owner_message_id
|
|
13614
|
+
FROM tags
|
|
13615
|
+
WHERE session_id = ?
|
|
13616
|
+
ORDER BY tag_number DESC, id DESC
|
|
13617
|
+
LIMIT ? OFFSET ?`);
|
|
13618
|
+
recentTagOwnerStatements.set(db, statement);
|
|
13619
|
+
}
|
|
13620
|
+
return statement;
|
|
13621
|
+
}
|
|
13622
|
+
function getRecentTagOwnerMessageIds(db, sessionId, maxOwners) {
|
|
13623
|
+
const recent = new Set;
|
|
13624
|
+
if (!Number.isFinite(maxOwners) || maxOwners <= 0)
|
|
13625
|
+
return recent;
|
|
13626
|
+
const statement = getRecentTagOwnerStatement(db);
|
|
13627
|
+
let offset = 0;
|
|
13628
|
+
while (recent.size < maxOwners) {
|
|
13629
|
+
const rows = statement.all(sessionId, RECENT_OWNER_SCAN_PAGE_SIZE, offset);
|
|
13630
|
+
for (const row of rows) {
|
|
13631
|
+
if (typeof row.type !== "string" || typeof row.message_id !== "string")
|
|
13632
|
+
continue;
|
|
13633
|
+
const ownerId = row.type === "tool" ? typeof row.tool_owner_message_id === "string" ? row.tool_owner_message_id : null : row.message_id.replace(CONTENT_ID_SUFFIX, "");
|
|
13634
|
+
if (!ownerId || recent.has(ownerId))
|
|
13635
|
+
continue;
|
|
13636
|
+
recent.add(ownerId);
|
|
13637
|
+
if (recent.size >= maxOwners)
|
|
13638
|
+
break;
|
|
13639
|
+
}
|
|
13640
|
+
if (rows.length < RECENT_OWNER_SCAN_PAGE_SIZE)
|
|
13641
|
+
break;
|
|
13642
|
+
offset += rows.length;
|
|
13643
|
+
}
|
|
13644
|
+
return recent;
|
|
13645
|
+
}
|
|
13481
13646
|
var RECLAIM_HINT_EXCLUDED_TOOLS = new Set([
|
|
13482
13647
|
"ask",
|
|
13483
13648
|
"bash_kill",
|
|
@@ -14601,15 +14766,15 @@ import {
|
|
|
14601
14766
|
unlinkSync as unlinkSync2,
|
|
14602
14767
|
writeFileSync
|
|
14603
14768
|
} from "node:fs";
|
|
14604
|
-
import { homedir as
|
|
14769
|
+
import { homedir as homedir3 } from "node:os";
|
|
14605
14770
|
import { basename as basename2, dirname as dirname3, isAbsolute, join as join5 } from "node:path";
|
|
14606
14771
|
var CONFIG_FILE_BASENAME = "magic-context";
|
|
14607
14772
|
var MOVED_MARKER_SUFFIX = ".MOVED_READPLEASE";
|
|
14608
14773
|
function homeDir() {
|
|
14609
14774
|
if (process.platform === "win32") {
|
|
14610
|
-
return process.env.USERPROFILE || process.env.HOME ||
|
|
14775
|
+
return process.env.USERPROFILE || process.env.HOME || homedir3();
|
|
14611
14776
|
}
|
|
14612
|
-
return process.env.HOME ||
|
|
14777
|
+
return process.env.HOME || homedir3();
|
|
14613
14778
|
}
|
|
14614
14779
|
function configHome() {
|
|
14615
14780
|
const xdg = process.env.XDG_CONFIG_HOME;
|
|
@@ -15590,6 +15755,7 @@ var memoryImportanceColumnCache = new WeakMap;
|
|
|
15590
15755
|
var memoryScopeColumnCache = new WeakMap;
|
|
15591
15756
|
var memoryShareableColumnCache = new WeakMap;
|
|
15592
15757
|
var memoryClassifiedAtColumnCache = new WeakMap;
|
|
15758
|
+
var memoryVerificationsTableCache = new WeakMap;
|
|
15593
15759
|
function hasMemoryImportanceColumn(db) {
|
|
15594
15760
|
const cached = memoryImportanceColumnCache.get(db);
|
|
15595
15761
|
if (cached !== undefined)
|
|
@@ -17148,7 +17314,7 @@ function countSessionCompartmentEmbedCoverage(db, projectPath, sessionId, modelI
|
|
|
17148
17314
|
import { createHash as createHash14, randomUUID as randomUUID2 } from "node:crypto";
|
|
17149
17315
|
|
|
17150
17316
|
// src/config/schema/magic-context.ts
|
|
17151
|
-
import { homedir as
|
|
17317
|
+
import { homedir as homedir4 } from "node:os";
|
|
17152
17318
|
|
|
17153
17319
|
// ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/external.js
|
|
17154
17320
|
var exports_external = {};
|
|
@@ -17775,7 +17941,7 @@ __export(exports_util, {
|
|
|
17775
17941
|
createTransparentProxy: () => createTransparentProxy,
|
|
17776
17942
|
defineLazy: () => defineLazy,
|
|
17777
17943
|
esc: () => esc,
|
|
17778
|
-
escapeRegex: () =>
|
|
17944
|
+
escapeRegex: () => escapeRegex,
|
|
17779
17945
|
explicitlyAborted: () => explicitlyAborted,
|
|
17780
17946
|
extend: () => extend,
|
|
17781
17947
|
finalizeIssue: () => finalizeIssue,
|
|
@@ -18052,7 +18218,7 @@ var primitiveTypes = /* @__PURE__ */ new Set([
|
|
|
18052
18218
|
"symbol",
|
|
18053
18219
|
"undefined"
|
|
18054
18220
|
]);
|
|
18055
|
-
function
|
|
18221
|
+
function escapeRegex(str) {
|
|
18056
18222
|
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
18057
18223
|
}
|
|
18058
18224
|
function clone(inst, def, params) {
|
|
@@ -18762,7 +18928,7 @@ function emoji() {
|
|
|
18762
18928
|
var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
|
|
18763
18929
|
var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
|
|
18764
18930
|
var mac = (delimiter) => {
|
|
18765
|
-
const escapedDelim =
|
|
18931
|
+
const escapedDelim = escapeRegex(delimiter ?? ":");
|
|
18766
18932
|
return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
|
|
18767
18933
|
};
|
|
18768
18934
|
var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
|
|
@@ -19263,7 +19429,7 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins
|
|
|
19263
19429
|
});
|
|
19264
19430
|
var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
|
|
19265
19431
|
$ZodCheck.init(inst, def);
|
|
19266
|
-
const escapedRegex =
|
|
19432
|
+
const escapedRegex = escapeRegex(def.includes);
|
|
19267
19433
|
const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
|
|
19268
19434
|
def.pattern = pattern;
|
|
19269
19435
|
inst._zod.onattach.push((inst2) => {
|
|
@@ -19287,7 +19453,7 @@ var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst,
|
|
|
19287
19453
|
});
|
|
19288
19454
|
var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
|
|
19289
19455
|
$ZodCheck.init(inst, def);
|
|
19290
|
-
const pattern = new RegExp(`^${
|
|
19456
|
+
const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
|
|
19291
19457
|
def.pattern ?? (def.pattern = pattern);
|
|
19292
19458
|
inst._zod.onattach.push((inst2) => {
|
|
19293
19459
|
const bag = inst2._zod.bag;
|
|
@@ -19310,7 +19476,7 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i
|
|
|
19310
19476
|
});
|
|
19311
19477
|
var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
|
|
19312
19478
|
$ZodCheck.init(inst, def);
|
|
19313
|
-
const pattern = new RegExp(`.*${
|
|
19479
|
+
const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
|
|
19314
19480
|
def.pattern ?? (def.pattern = pattern);
|
|
19315
19481
|
inst._zod.onattach.push((inst2) => {
|
|
19316
19482
|
const bag = inst2._zod.bag;
|
|
@@ -20957,7 +21123,7 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
|
|
|
20957
21123
|
const values = getEnumValues(def.entries);
|
|
20958
21124
|
const valuesSet = new Set(values);
|
|
20959
21125
|
inst._zod.values = valuesSet;
|
|
20960
|
-
inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ?
|
|
21126
|
+
inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
|
|
20961
21127
|
inst._zod.parse = (payload, _ctx) => {
|
|
20962
21128
|
const input = payload.value;
|
|
20963
21129
|
if (valuesSet.has(input)) {
|
|
@@ -20979,7 +21145,7 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
|
|
|
20979
21145
|
}
|
|
20980
21146
|
const values = new Set(def.values);
|
|
20981
21147
|
inst._zod.values = values;
|
|
20982
|
-
inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ?
|
|
21148
|
+
inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
|
|
20983
21149
|
inst._zod.parse = (payload, _ctx) => {
|
|
20984
21150
|
const input = payload.value;
|
|
20985
21151
|
if (values.has(input)) {
|
|
@@ -21344,7 +21510,7 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i
|
|
|
21344
21510
|
const end = source.endsWith("$") ? source.length - 1 : source.length;
|
|
21345
21511
|
regexParts.push(source.slice(start, end));
|
|
21346
21512
|
} else if (part === null || primitiveTypes.has(typeof part)) {
|
|
21347
|
-
regexParts.push(
|
|
21513
|
+
regexParts.push(escapeRegex(`${part}`));
|
|
21348
21514
|
} else {
|
|
21349
21515
|
throw new Error(`Invalid template literal part: ${part}`);
|
|
21350
21516
|
}
|
|
@@ -31831,9 +31997,9 @@ var EmbeddingFallbackProviderSchema = exports_external.enum(["local", "openai-co
|
|
|
31831
31997
|
function expandConfigPath(value) {
|
|
31832
31998
|
const trimmed = value.trim();
|
|
31833
31999
|
if (trimmed === "~")
|
|
31834
|
-
return
|
|
32000
|
+
return homedir4();
|
|
31835
32001
|
if (trimmed.startsWith("~/"))
|
|
31836
|
-
return `${
|
|
32002
|
+
return `${homedir4()}/${trimmed.slice(2)}`;
|
|
31837
32003
|
return trimmed;
|
|
31838
32004
|
}
|
|
31839
32005
|
var BaseEmbeddingConfigSchema = exports_external.object({
|
|
@@ -34319,33 +34485,123 @@ function startLockHeartbeat(lockPath) {
|
|
|
34319
34485
|
timer.unref?.();
|
|
34320
34486
|
return () => clearInterval(timer);
|
|
34321
34487
|
}
|
|
34322
|
-
|
|
34323
|
-
|
|
34488
|
+
var localEmbeddingRuntimeMode = "native";
|
|
34489
|
+
var wasmRuntimeInjected = false;
|
|
34490
|
+
var isElectronForRuntime = () => typeof process !== "undefined" && Boolean(process.versions?.electron);
|
|
34491
|
+
var importWasmOrtForRuntime = async () => {
|
|
34492
|
+
const ortWebSpec = `onnxruntime-${"web"}`;
|
|
34493
|
+
return await import(ortWebSpec);
|
|
34494
|
+
};
|
|
34495
|
+
var importTransformersForRuntime = async () => {
|
|
34496
|
+
const transformersSpec = "@huggingface/transformers";
|
|
34497
|
+
return await import(transformersSpec);
|
|
34498
|
+
};
|
|
34499
|
+
var importTransformersWasmFallbackForRuntime = async () => {
|
|
34500
|
+
const { createRequire: createRequireFn } = await import("node:module");
|
|
34501
|
+
const requireFn = createRequireFn(import.meta.url);
|
|
34502
|
+
const nodeEntry = requireFn.resolve("@huggingface/transformers");
|
|
34503
|
+
const webEntry = pathToFileURL2(join6(dirname5(nodeEntry), "transformers.web.js")).href;
|
|
34504
|
+
return await import(webEntry);
|
|
34505
|
+
};
|
|
34506
|
+
var modelCacheDirForRuntime = () => join6(getMagicContextStorageDir(), "models");
|
|
34507
|
+
var logForRuntime = log;
|
|
34508
|
+
var injectWasmOrtForRuntime = injectWasmOrt;
|
|
34509
|
+
async function ensureWasmOrtInjected() {
|
|
34510
|
+
if (wasmRuntimeInjected)
|
|
34511
|
+
return true;
|
|
34512
|
+
if (!await injectWasmOrtForRuntime())
|
|
34324
34513
|
return false;
|
|
34325
|
-
|
|
34514
|
+
wasmRuntimeInjected = true;
|
|
34515
|
+
return true;
|
|
34516
|
+
}
|
|
34517
|
+
async function injectWasmOrt() {
|
|
34518
|
+
if (wasmRuntimeInjected)
|
|
34519
|
+
return true;
|
|
34326
34520
|
try {
|
|
34327
|
-
const
|
|
34328
|
-
const ortWeb = await import(ortWebSpec);
|
|
34521
|
+
const ortWeb = await importWasmOrtForRuntime();
|
|
34329
34522
|
try {
|
|
34330
34523
|
const { createRequire: createRequireFn } = await import("node:module");
|
|
34331
34524
|
const requireFn = createRequireFn(import.meta.url);
|
|
34332
34525
|
const mainEntry = requireFn.resolve("onnxruntime-web");
|
|
34333
34526
|
const distDir = dirname5(mainEntry);
|
|
34334
|
-
const wasmPathsPrefix = `${pathToFileURL2(distDir).href}/`;
|
|
34335
34527
|
if (ortWeb.env?.wasm) {
|
|
34336
|
-
ortWeb.env.wasm.wasmPaths =
|
|
34528
|
+
ortWeb.env.wasm.wasmPaths = `${pathToFileURL2(distDir).href}/`;
|
|
34337
34529
|
}
|
|
34338
34530
|
} catch (pathError) {
|
|
34339
34531
|
log("[magic-context] could not resolve local onnxruntime-web/dist, falling back to default WASM paths:", pathError instanceof Error ? pathError.message : String(pathError));
|
|
34340
34532
|
}
|
|
34341
34533
|
globalThis[Symbol.for("onnxruntime")] = ortWeb;
|
|
34342
|
-
|
|
34534
|
+
wasmRuntimeInjected = true;
|
|
34343
34535
|
return true;
|
|
34344
34536
|
} catch (error51) {
|
|
34345
|
-
log("[magic-context] failed to inject onnxruntime-web
|
|
34537
|
+
log("[magic-context] failed to inject onnxruntime-web:", error51 instanceof Error ? error51.message : String(error51));
|
|
34346
34538
|
return false;
|
|
34347
34539
|
}
|
|
34348
34540
|
}
|
|
34541
|
+
function likelyMuslHint() {
|
|
34542
|
+
if (process.platform !== "linux" || typeof process.report?.getReport !== "function")
|
|
34543
|
+
return "";
|
|
34544
|
+
try {
|
|
34545
|
+
const report = process.report.getReport();
|
|
34546
|
+
return typeof report.header?.glibcVersionRuntime === "string" ? "" : " Linux process report has no glibc runtime version (musl likely).";
|
|
34547
|
+
} catch {
|
|
34548
|
+
return "";
|
|
34549
|
+
}
|
|
34550
|
+
}
|
|
34551
|
+
function localEmbeddingRuntimeIsDisabled() {
|
|
34552
|
+
return localEmbeddingRuntimeMode === "disabled";
|
|
34553
|
+
}
|
|
34554
|
+
function disableLocalEmbeddingsAfterRuntimeFailure(detail) {
|
|
34555
|
+
localEmbeddingRuntimeMode = "disabled";
|
|
34556
|
+
logForRuntime(`[magic-context] local embeddings are disabled because both the onnxruntime-node native binding and the onnxruntime-web (WASM) fallback failed to load. Native failure: ${detail}. Run \`npx @cortexkit/magic-context@latest doctor\` for repair guidance (use \`doctor --force\` to reinstall cached plugin packages), or configure an \`openai-compatible\` embedding HTTP endpoint. Existing memories are unaffected.`);
|
|
34557
|
+
}
|
|
34558
|
+
async function loadTransformersForLocalEmbedding() {
|
|
34559
|
+
if (localEmbeddingRuntimeMode === "disabled") {
|
|
34560
|
+
throw new Error("local embedding runtime is disabled");
|
|
34561
|
+
}
|
|
34562
|
+
if (localEmbeddingRuntimeMode === "wasm") {
|
|
34563
|
+
if (!await ensureWasmOrtInjected()) {
|
|
34564
|
+
disableLocalEmbeddingsAfterRuntimeFailure("the previously selected WASM runtime is unavailable");
|
|
34565
|
+
throw new Error("onnxruntime-web failed to load");
|
|
34566
|
+
}
|
|
34567
|
+
try {
|
|
34568
|
+
return { module: await importTransformersWasmFallbackForRuntime(), usesWasm: true };
|
|
34569
|
+
} catch (wasmError) {
|
|
34570
|
+
disableLocalEmbeddingsAfterRuntimeFailure("the previously selected WASM runtime failed to load");
|
|
34571
|
+
throw wasmError;
|
|
34572
|
+
}
|
|
34573
|
+
}
|
|
34574
|
+
const electron = isElectronForRuntime();
|
|
34575
|
+
if (electron) {
|
|
34576
|
+
const wasInjected = wasmRuntimeInjected;
|
|
34577
|
+
if (await ensureWasmOrtInjected()) {
|
|
34578
|
+
if (!wasInjected) {
|
|
34579
|
+
logForRuntime("[magic-context] Electron detected — using onnxruntime-web (WASM) for embeddings (bypasses onnxruntime-node native load)");
|
|
34580
|
+
}
|
|
34581
|
+
return { module: await importTransformersForRuntime(), usesWasm: true };
|
|
34582
|
+
}
|
|
34583
|
+
}
|
|
34584
|
+
try {
|
|
34585
|
+
return { module: await importTransformersForRuntime(), usesWasm: false };
|
|
34586
|
+
} catch (nativeError) {
|
|
34587
|
+
if (!isNativeRuntimeMissingError(nativeError) || electron) {
|
|
34588
|
+
throw nativeError;
|
|
34589
|
+
}
|
|
34590
|
+
if (!await ensureWasmOrtInjected()) {
|
|
34591
|
+
disableLocalEmbeddingsAfterRuntimeFailure(nativeError instanceof Error ? nativeError.message : String(nativeError));
|
|
34592
|
+
throw nativeError;
|
|
34593
|
+
}
|
|
34594
|
+
localEmbeddingRuntimeMode = "wasm";
|
|
34595
|
+
try {
|
|
34596
|
+
const module = await importTransformersWasmFallbackForRuntime();
|
|
34597
|
+
logForRuntime("[magic-context] onnxruntime-node failed to load; using onnxruntime-web (WASM) for local embeddings. WASM inference is slower than native; a remote `openai-compatible` provider may be faster." + likelyMuslHint());
|
|
34598
|
+
return { module, usesWasm: true };
|
|
34599
|
+
} catch (wasmError) {
|
|
34600
|
+
disableLocalEmbeddingsAfterRuntimeFailure(nativeError instanceof Error ? nativeError.message : String(nativeError));
|
|
34601
|
+
throw wasmError;
|
|
34602
|
+
}
|
|
34603
|
+
}
|
|
34604
|
+
}
|
|
34349
34605
|
var DEFAULT_LOCAL_DTYPE = "fp32";
|
|
34350
34606
|
async function withQuietConsole(fn) {
|
|
34351
34607
|
const origWarn = console.warn;
|
|
@@ -34363,7 +34619,6 @@ async function withQuietConsole(fn) {
|
|
|
34363
34619
|
console.error = origError;
|
|
34364
34620
|
}
|
|
34365
34621
|
}
|
|
34366
|
-
var nativeRuntimeMissing = false;
|
|
34367
34622
|
function isNativeRuntimeMissingError(error51) {
|
|
34368
34623
|
const message = error51 instanceof Error ? error51.message : String(error51 ?? "");
|
|
34369
34624
|
const lower = message.toLowerCase();
|
|
@@ -34447,7 +34702,7 @@ class LocalEmbeddingProvider {
|
|
|
34447
34702
|
if (this.pipeline) {
|
|
34448
34703
|
return true;
|
|
34449
34704
|
}
|
|
34450
|
-
if (
|
|
34705
|
+
if (localEmbeddingRuntimeMode === "disabled") {
|
|
34451
34706
|
return false;
|
|
34452
34707
|
}
|
|
34453
34708
|
if (this.initPromise) {
|
|
@@ -34459,15 +34714,13 @@ class LocalEmbeddingProvider {
|
|
|
34459
34714
|
if (this.disposing) {
|
|
34460
34715
|
return;
|
|
34461
34716
|
}
|
|
34462
|
-
const
|
|
34463
|
-
const transformersSpec = "@huggingface/transformers";
|
|
34464
|
-
const transformersModule = await import(transformersSpec);
|
|
34717
|
+
const { module: transformersModule, usesWasm } = await loadTransformersForLocalEmbedding();
|
|
34465
34718
|
const env = transformersModule.env;
|
|
34466
34719
|
const LogLevel = transformersModule.LogLevel;
|
|
34467
34720
|
if (LogLevel && "ERROR" in LogLevel) {
|
|
34468
34721
|
env.logLevel = LogLevel.ERROR;
|
|
34469
34722
|
}
|
|
34470
|
-
const modelCacheDir =
|
|
34723
|
+
const modelCacheDir = modelCacheDirForRuntime();
|
|
34471
34724
|
try {
|
|
34472
34725
|
if (shouldEnforcePrivateStoragePermissions()) {
|
|
34473
34726
|
mkdirSync3(modelCacheDir, { recursive: true, mode: 448 });
|
|
@@ -34494,7 +34747,7 @@ class LocalEmbeddingProvider {
|
|
|
34494
34747
|
try {
|
|
34495
34748
|
const pipeline = await withQuietConsole(() => createPipeline("feature-extraction", this.model, {
|
|
34496
34749
|
dtype: this.dtype,
|
|
34497
|
-
...
|
|
34750
|
+
...usesWasm ? { device: "auto" } : {}
|
|
34498
34751
|
}));
|
|
34499
34752
|
if (this.disposing) {
|
|
34500
34753
|
await pipeline.dispose?.();
|
|
@@ -34526,10 +34779,9 @@ class LocalEmbeddingProvider {
|
|
|
34526
34779
|
await releaseLock();
|
|
34527
34780
|
}
|
|
34528
34781
|
} catch (error51) {
|
|
34529
|
-
if (isNativeRuntimeMissingError(error51)) {
|
|
34530
|
-
|
|
34531
|
-
|
|
34532
|
-
} else {
|
|
34782
|
+
if (!localEmbeddingRuntimeIsDisabled() && isNativeRuntimeMissingError(error51)) {
|
|
34783
|
+
disableLocalEmbeddingsAfterRuntimeFailure(error51 instanceof Error ? error51.message : String(error51));
|
|
34784
|
+
} else if (!localEmbeddingRuntimeIsDisabled()) {
|
|
34533
34785
|
log("[magic-context] embedding model failed to load:", error51);
|
|
34534
34786
|
}
|
|
34535
34787
|
this.pipeline = null;
|
|
@@ -35122,6 +35374,13 @@ function markProjectLoadUntrusted(projectIdentity) {
|
|
|
35122
35374
|
untrustedLoadProjects.add(projectIdentity);
|
|
35123
35375
|
}
|
|
35124
35376
|
var testProviderFactory = null;
|
|
35377
|
+
|
|
35378
|
+
class TestProviderFactoryRequiredError extends Error {
|
|
35379
|
+
constructor() {
|
|
35380
|
+
super("test constructed a network-capable embedding provider without a test factory — install _setTestProviderFactoryForProject or set embedding.provider off in the fixture");
|
|
35381
|
+
this.name = "TestProviderFactoryRequiredError";
|
|
35382
|
+
}
|
|
35383
|
+
}
|
|
35125
35384
|
function synapseConfigFields(config2) {
|
|
35126
35385
|
const raw = config2;
|
|
35127
35386
|
return {
|
|
@@ -35237,11 +35496,14 @@ function resolveEmbeddingConfig(config2) {
|
|
|
35237
35496
|
throw new Error("Unknown embedding provider");
|
|
35238
35497
|
}
|
|
35239
35498
|
function createProvider(config2, context) {
|
|
35499
|
+
if (config2.provider === "off") {
|
|
35500
|
+
return null;
|
|
35501
|
+
}
|
|
35240
35502
|
if (testProviderFactory) {
|
|
35241
35503
|
return testProviderFactory(config2);
|
|
35242
35504
|
}
|
|
35243
|
-
if (
|
|
35244
|
-
|
|
35505
|
+
if (process.env.MAGIC_CONTEXT_TEST_DATA_DIR?.trim()) {
|
|
35506
|
+
throw new TestProviderFactoryRequiredError;
|
|
35245
35507
|
}
|
|
35246
35508
|
if (config2.provider === "openai-compatible") {
|
|
35247
35509
|
return new OpenAICompatibleEmbeddingProvider({
|
|
@@ -36850,13 +37112,13 @@ function placeholders3(values) {
|
|
|
36850
37112
|
function uniqueSortedFiles(files) {
|
|
36851
37113
|
return Array.from(new Set(files.filter((file2) => file2 !== MEMORY_VERIFICATION_SENTINEL))).sort();
|
|
36852
37114
|
}
|
|
36853
|
-
function recordMemoryMapping(db, memoryId, normalizedFiles, now) {
|
|
37115
|
+
function recordMemoryMapping(db, memoryId, normalizedFiles, now, mappingOrigin = "mapper") {
|
|
36854
37116
|
const realFiles = uniqueSortedFiles(normalizedFiles);
|
|
36855
37117
|
const filesToWrite = realFiles.length > 0 ? realFiles : [MEMORY_VERIFICATION_SENTINEL];
|
|
36856
37118
|
db.prepare("DELETE FROM memory_verifications WHERE memory_id = ?").run(memoryId);
|
|
36857
|
-
const insert = db.prepare("INSERT INTO memory_verifications (memory_id, file_path, verified_at, mapped_at) VALUES (?, ?, 0, ?)");
|
|
37119
|
+
const insert = db.prepare("INSERT INTO memory_verifications (memory_id, file_path, verified_at, mapped_at, mapping_origin) VALUES (?, ?, 0, ?, ?)");
|
|
36858
37120
|
for (const file2 of filesToWrite) {
|
|
36859
|
-
insert.run(memoryId, file2, now);
|
|
37121
|
+
insert.run(memoryId, file2, now, mappingOrigin);
|
|
36860
37122
|
}
|
|
36861
37123
|
return filesToWrite.length;
|
|
36862
37124
|
}
|
|
@@ -36864,7 +37126,7 @@ function recordMemoryVerifications(db, memoryId, normalizedFiles, now) {
|
|
|
36864
37126
|
const realFiles = uniqueSortedFiles(normalizedFiles);
|
|
36865
37127
|
const filesToWrite = realFiles.length > 0 ? realFiles : [MEMORY_VERIFICATION_SENTINEL];
|
|
36866
37128
|
db.prepare("DELETE FROM memory_verifications WHERE memory_id = ?").run(memoryId);
|
|
36867
|
-
const insert = db.prepare("INSERT INTO memory_verifications (memory_id, file_path, verified_at, mapped_at) VALUES (?, ?, ?,
|
|
37129
|
+
const insert = db.prepare("INSERT INTO memory_verifications (memory_id, file_path, verified_at, mapped_at, mapping_origin) VALUES (?, ?, ?, ?, 'mapper')");
|
|
36868
37130
|
for (const file2 of filesToWrite) {
|
|
36869
37131
|
insert.run(memoryId, file2, now, now);
|
|
36870
37132
|
}
|
|
@@ -36886,7 +37148,7 @@ function getMemoryVerifications(db, memoryIds) {
|
|
|
36886
37148
|
const result = new Map;
|
|
36887
37149
|
if (ids.length === 0)
|
|
36888
37150
|
return result;
|
|
36889
|
-
const rows = db.prepare(`SELECT memory_id, file_path, verified_at, mapped_at
|
|
37151
|
+
const rows = db.prepare(`SELECT memory_id, file_path, verified_at, mapped_at, mapping_origin
|
|
36890
37152
|
FROM memory_verifications
|
|
36891
37153
|
WHERE memory_id IN (${placeholders3(ids)})
|
|
36892
37154
|
ORDER BY memory_id, file_path`).all(...ids);
|
|
@@ -36894,6 +37156,7 @@ function getMemoryVerifications(db, memoryIds) {
|
|
|
36894
37156
|
const existing = result.get(row.memory_id) ?? {
|
|
36895
37157
|
files: [],
|
|
36896
37158
|
hasSentinel: false,
|
|
37159
|
+
mappingOrigin: "mapper",
|
|
36897
37160
|
verifiedAt: 0,
|
|
36898
37161
|
mappedAt: 0
|
|
36899
37162
|
};
|
|
@@ -36902,6 +37165,9 @@ function getMemoryVerifications(db, memoryIds) {
|
|
|
36902
37165
|
} else if (!existing.files.includes(row.file_path)) {
|
|
36903
37166
|
existing.files.push(row.file_path);
|
|
36904
37167
|
}
|
|
37168
|
+
if (row.mapping_origin === "host_rejected_fallback") {
|
|
37169
|
+
existing.mappingOrigin = "host_rejected_fallback";
|
|
37170
|
+
}
|
|
36905
37171
|
existing.verifiedAt = Math.max(existing.verifiedAt, row.verified_at);
|
|
36906
37172
|
existing.mappedAt = Math.max(existing.mappedAt, row.mapped_at ?? 0);
|
|
36907
37173
|
result.set(row.memory_id, existing);
|
|
@@ -37621,12 +37887,14 @@ function dropMarkerSummaryTag(db, sessionId, summaryMessageId) {
|
|
|
37621
37887
|
updateTagStatus(db, sessionId, tagNumber, "dropped");
|
|
37622
37888
|
}
|
|
37623
37889
|
function persistMarkerStateAndDropReplacedTag(db, sessionId, state2, replacedSummaryMessageId) {
|
|
37890
|
+
const transactionStartedAt = performance.now();
|
|
37624
37891
|
db.transaction(() => {
|
|
37625
37892
|
setPersistedCompactionMarkerState(db, sessionId, state2);
|
|
37626
37893
|
if (replacedSummaryMessageId !== null) {
|
|
37627
37894
|
dropMarkerSummaryTag(db, sessionId, replacedSummaryMessageId);
|
|
37628
37895
|
}
|
|
37629
37896
|
})();
|
|
37897
|
+
logSlowWriteTransaction("marker-drain", transactionStartedAt);
|
|
37630
37898
|
}
|
|
37631
37899
|
function validatePendingTarget(db, sessionId, pending) {
|
|
37632
37900
|
const ocMessage = getOpenCodeMessageById(sessionId, pending.endMessageId);
|
|
@@ -40599,7 +40867,8 @@ function injectTemporalMarkers(messages) {
|
|
|
40599
40867
|
continue;
|
|
40600
40868
|
const msg = raw;
|
|
40601
40869
|
const role = msg.info?.role;
|
|
40602
|
-
|
|
40870
|
+
const authoredUser = role === "user" && Array.isArray(msg.parts) && hasMeaningfulUserText(msg.parts);
|
|
40871
|
+
if (prev !== null && authoredUser) {
|
|
40603
40872
|
const prevTime = prev.info?.time;
|
|
40604
40873
|
const currTime = msg.info?.time;
|
|
40605
40874
|
if (prevTime?.created !== undefined && currTime?.created !== undefined) {
|
|
@@ -41277,7 +41546,7 @@ function readCurrentM0SnapshotMarkersUncached(args) {
|
|
|
41277
41546
|
toolSetHash: hard.toolSetHash ?? "",
|
|
41278
41547
|
modelKey: piModelRefToCanonical(hard.modelKey),
|
|
41279
41548
|
projectIdentity: args.projectPath ?? null,
|
|
41280
|
-
muralEnabled: args.muralEnabled === true,
|
|
41549
|
+
muralEnabled: args.memoryEnabled !== false && args.muralEnabled === true,
|
|
41281
41550
|
renderBudgetIdentity: renderBudgetIdentity(args.memoryInjectionBudgetTokens, args.historyBudgetTokens)
|
|
41282
41551
|
}
|
|
41283
41552
|
};
|
|
@@ -41293,7 +41562,7 @@ function refreshVolatileMarkerInputs(markers, args) {
|
|
|
41293
41562
|
toolSetHash: hard.toolSetHash ?? "",
|
|
41294
41563
|
modelKey: hard.modelKey,
|
|
41295
41564
|
projectIdentity: args.projectPath ?? null,
|
|
41296
|
-
muralEnabled: args.muralEnabled === true,
|
|
41565
|
+
muralEnabled: args.memoryEnabled !== false && args.muralEnabled === true,
|
|
41297
41566
|
renderBudgetIdentity: renderBudgetIdentity(args.memoryInjectionBudgetTokens, args.historyBudgetTokens)
|
|
41298
41567
|
};
|
|
41299
41568
|
}
|
|
@@ -41366,6 +41635,10 @@ function snapshotMarkersFromCachedM0(state2) {
|
|
|
41366
41635
|
renderBudgetIdentity: cachedUpgradeIdentity.renderBudgetIdentity
|
|
41367
41636
|
};
|
|
41368
41637
|
}
|
|
41638
|
+
var MEMORY_DERIVED_BLOCK_PATTERN = /<(?:project-memory|user-profile|new-user-profile|memory-updates|memory-mural)(?:>|\s)/;
|
|
41639
|
+
function cachedMemoryDerivedSurfacePresent(state2) {
|
|
41640
|
+
return [state2.cachedM0Bytes, state2.cachedM1Bytes].some((bytes) => bytes !== null && MEMORY_DERIVED_BLOCK_PATTERN.test(bytes.toString("utf8")));
|
|
41641
|
+
}
|
|
41369
41642
|
function mustMaterialize(args) {
|
|
41370
41643
|
if (!args.state.cachedM0Bytes)
|
|
41371
41644
|
return { value: true, reason: "first_render" };
|
|
@@ -41374,6 +41647,9 @@ function mustMaterialize(args) {
|
|
|
41374
41647
|
const hard = args.hardSignals ?? EMPTY_HARD_SIGNALS;
|
|
41375
41648
|
const current = readCurrentM0SnapshotMarkers(args);
|
|
41376
41649
|
const cachedUpgradeIdentity = decodeCachedM0UpgradeIdentity(args.state.cachedM0UpgradeState);
|
|
41650
|
+
if (args.memoryEnabled === false && cachedMemoryDerivedSurfacePresent(args.state)) {
|
|
41651
|
+
return { value: true, reason: "render_config" };
|
|
41652
|
+
}
|
|
41377
41653
|
if (cachedUpgradeIdentity.compartmentRenderEpoch !== current.compartmentRenderEpoch) {
|
|
41378
41654
|
return { value: true, reason: "compartment_render_epoch" };
|
|
41379
41655
|
}
|
|
@@ -41728,7 +42004,7 @@ function historySliceTokens(m0Text) {
|
|
|
41728
42004
|
return slice ? estimateTokens(slice) : 0;
|
|
41729
42005
|
}
|
|
41730
42006
|
function resolveMuralForM0(options, projectPath, modelKey, budgetTokens) {
|
|
41731
|
-
if (!options.muralEnabled)
|
|
42007
|
+
if (options.memoryEnabled === false || !options.muralEnabled)
|
|
41732
42008
|
return;
|
|
41733
42009
|
return resolveMuralWire(options.db, projectPath, modelKey, true, budgetTokens);
|
|
41734
42010
|
}
|
|
@@ -41763,6 +42039,7 @@ function materializeM0(options) {
|
|
|
41763
42039
|
projectPath,
|
|
41764
42040
|
projectDirectory,
|
|
41765
42041
|
injectDocs: options.injectDocs,
|
|
42042
|
+
memoryEnabled: options.memoryEnabled,
|
|
41766
42043
|
muralEnabled: options.muralEnabled,
|
|
41767
42044
|
memoryInjectionBudgetTokens: options.memoryInjectionBudgetTokens,
|
|
41768
42045
|
historyBudgetTokens: options.historyBudgetTokens,
|
|
@@ -41777,7 +42054,7 @@ function materializeM0(options) {
|
|
|
41777
42054
|
compartments = options.compactionOff ? [] : readM0Compartments(options.db, options.sessionId);
|
|
41778
42055
|
facts = [];
|
|
41779
42056
|
memories = projectPath ? workspace.isWorkspaced ? getMemoriesByProjects(options.db, workspace.expandedIdentities, ["active", "permanent"], foldMaterializedAt, workspace.ownIdentities, workspace.shareCategories) : getMemoriesByProject(options.db, projectPath, ["active", "permanent"], foldMaterializedAt) : [];
|
|
41780
|
-
userMemories = safeGetActiveUserMemories(options.db);
|
|
42057
|
+
userMemories = options.memoryEnabled === false ? [] : safeGetActiveUserMemories(options.db);
|
|
41781
42058
|
options.db.exec("COMMIT");
|
|
41782
42059
|
} catch (error51) {
|
|
41783
42060
|
try {
|
|
@@ -41795,7 +42072,7 @@ function materializeM0(options) {
|
|
|
41795
42072
|
})
|
|
41796
42073
|
};
|
|
41797
42074
|
const trimmed = workspace.isWorkspaced ? trimWorkspaceMemoriesToBudgetV2(options.sessionId, memories, memoryBudget, workspace, memoryRenderOptions) : trimMemoriesToBudgetV2(options.sessionId, memories, memoryBudget);
|
|
41798
|
-
const mural = options.mural ?? resolveMuralForM0(options, projectPath, snapshotMarkers.modelKey, memoryBudget);
|
|
42075
|
+
const mural = options.memoryEnabled === false ? undefined : options.mural ?? resolveMuralForM0(options, projectPath, snapshotMarkers.modelKey, memoryBudget);
|
|
41799
42076
|
let decayPressureMultiplier = 1;
|
|
41800
42077
|
let m0Text = renderM0({
|
|
41801
42078
|
projectDocs: docs.renderedBlock,
|
|
@@ -42038,7 +42315,7 @@ ${newCompartments.map((compartment) => renderCompartmentAtTier(compartment, 1)).
|
|
|
42038
42315
|
if (newMemoriesBlock)
|
|
42039
42316
|
blocks.push(newMemoriesBlock);
|
|
42040
42317
|
const currentUserProfileVersion = getGlobalUserProfileVersion(options.db);
|
|
42041
|
-
if (currentUserProfileVersion !== markers.projectUserProfileVersion) {
|
|
42318
|
+
if (options.memoryEnabled !== false && currentUserProfileVersion !== markers.projectUserProfileVersion) {
|
|
42042
42319
|
const profileBlock = renderUserProfileBlock(trimUserMemoriesToBudget(safeGetActiveUserMemories(options.db), Math.max(1, Math.floor((options.userProfileBudgetTokens ?? DEFAULT_USER_PROFILE_BUDGET_TOKENS) * 0.25))), "new-user-profile");
|
|
42043
42320
|
if (profileBlock)
|
|
42044
42321
|
blocks.push(profileBlock);
|
|
@@ -42256,6 +42533,7 @@ function renderFreshM0NonPersisted(options) {
|
|
|
42256
42533
|
projectPath,
|
|
42257
42534
|
projectDirectory,
|
|
42258
42535
|
injectDocs: options.injectDocs,
|
|
42536
|
+
memoryEnabled: options.memoryEnabled,
|
|
42259
42537
|
muralEnabled: options.muralEnabled,
|
|
42260
42538
|
memoryInjectionBudgetTokens: options.memoryInjectionBudgetTokens,
|
|
42261
42539
|
historyBudgetTokens: options.historyBudgetTokens,
|
|
@@ -42270,7 +42548,7 @@ function renderFreshM0NonPersisted(options) {
|
|
|
42270
42548
|
snapshotMarkers.materializedAt = options.state.cachedM0MaterializedAt ?? 0;
|
|
42271
42549
|
const compartments = options.compactionOff ? [] : withCompartmentDates(options.sessionId, readM0Compartments(options.db, options.sessionId), options.temporalAwareness);
|
|
42272
42550
|
const memories = projectPath ? workspace.isWorkspaced ? getMemoriesByProjects(options.db, workspace.expandedIdentities, ["active", "permanent"], snapshotMarkers.materializedAt, workspace.ownIdentities, workspace.shareCategories) : getMemoriesByProject(options.db, projectPath, ["active", "permanent"], snapshotMarkers.materializedAt) : [];
|
|
42273
|
-
const userMemories = safeGetActiveUserMemories(options.db);
|
|
42551
|
+
const userMemories = options.memoryEnabled === false ? [] : safeGetActiveUserMemories(options.db);
|
|
42274
42552
|
const memoryBudget = options.memoryInjectionBudgetTokens ?? DEFAULT_MEMORY_BUDGET_TOKENS;
|
|
42275
42553
|
const memoryRenderOptions = {
|
|
42276
42554
|
sourceNameByMemoryId: sourceNamesForMemories({
|
|
@@ -42281,7 +42559,7 @@ function renderFreshM0NonPersisted(options) {
|
|
|
42281
42559
|
};
|
|
42282
42560
|
const trimmed = workspace.isWorkspaced ? trimWorkspaceMemoriesToBudgetV2(options.sessionId, memories, memoryBudget, workspace, memoryRenderOptions) : trimMemoriesToBudgetV2(options.sessionId, memories, memoryBudget);
|
|
42283
42561
|
const budget = options.historyBudgetTokens ?? DEFAULT_HISTORY_BUDGET_TOKENS;
|
|
42284
|
-
const mural = options.mural ?? resolveMuralForM0(options, projectPath, snapshotMarkers.modelKey, memoryBudget);
|
|
42562
|
+
const mural = options.memoryEnabled === false ? undefined : options.mural ?? resolveMuralForM0(options, projectPath, snapshotMarkers.modelKey, memoryBudget);
|
|
42285
42563
|
let decayPressureMultiplier = 1;
|
|
42286
42564
|
let m0Text = renderM0({
|
|
42287
42565
|
projectDocs: docs.renderedBlock,
|
|
@@ -42357,6 +42635,7 @@ function injectM0M1(options) {
|
|
|
42357
42635
|
hardSignals: options.hardSignals,
|
|
42358
42636
|
workspaceIdentitySet: options.workspaceIdentitySet,
|
|
42359
42637
|
injectDocs: options.injectDocs,
|
|
42638
|
+
memoryEnabled: options.memoryEnabled,
|
|
42360
42639
|
muralEnabled: options.muralEnabled,
|
|
42361
42640
|
memoryInjectionBudgetTokens: options.memoryInjectionBudgetTokens,
|
|
42362
42641
|
historyBudgetTokens: options.historyBudgetTokens
|
|
@@ -42688,23 +42967,33 @@ function fenceWrapupBoundaryForToolArcs(args) {
|
|
|
42688
42967
|
return boundary;
|
|
42689
42968
|
}
|
|
42690
42969
|
function applyHeadCap(args) {
|
|
42691
|
-
const {
|
|
42970
|
+
const {
|
|
42971
|
+
index,
|
|
42972
|
+
protectedTailStart,
|
|
42973
|
+
offset,
|
|
42974
|
+
arcs,
|
|
42975
|
+
lastCompartmentEndOrdinal,
|
|
42976
|
+
capTokens,
|
|
42977
|
+
recentOpenArcCutoff
|
|
42978
|
+
} = args;
|
|
42692
42979
|
if (offset >= protectedTailStart)
|
|
42693
42980
|
return { eligibleEndOrdinal: offset, oversizeAtomicUnit: false };
|
|
42694
42981
|
let end = index.findHeadEndForCap(offset, protectedTailStart, capTokens);
|
|
42695
42982
|
let oversizeAtomicUnit = end === offset + 1 && index.tokenForOrdinal(offset) > capTokens;
|
|
42983
|
+
const completedFence = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1);
|
|
42984
|
+
if (completedFence > end) {
|
|
42985
|
+
end = Math.min(protectedTailStart, completedFence);
|
|
42986
|
+
if (index.rangeTokens(offset, end) > capTokens)
|
|
42987
|
+
oversizeAtomicUnit = true;
|
|
42988
|
+
} else {
|
|
42989
|
+
end = completedFence;
|
|
42990
|
+
}
|
|
42696
42991
|
for (const arc of arcs) {
|
|
42697
42992
|
const resOrdinal = arc.resOrdinal;
|
|
42698
42993
|
if (resOrdinal === null) {
|
|
42699
42994
|
if (arc.invOrdinal >= recentOpenArcCutoff && arc.invOrdinal >= offset && arc.invOrdinal < end) {
|
|
42700
42995
|
end = Math.min(end, arc.invOrdinal);
|
|
42701
42996
|
}
|
|
42702
|
-
continue;
|
|
42703
|
-
}
|
|
42704
|
-
if (arc.invOrdinal < end && end <= resOrdinal) {
|
|
42705
|
-
end = Math.min(protectedTailStart, resOrdinal + 1);
|
|
42706
|
-
if (index.rangeTokens(Math.max(offset, arc.invOrdinal), end) > capTokens)
|
|
42707
|
-
oversizeAtomicUnit = true;
|
|
42708
42997
|
}
|
|
42709
42998
|
}
|
|
42710
42999
|
if (end <= offset && offset < protectedTailStart) {
|
|
@@ -45111,9 +45400,9 @@ async function runCompartmentAgent(deps) {
|
|
|
45111
45400
|
executeThresholdPercentage: boundarySnapshot.executeThresholdPercentage
|
|
45112
45401
|
});
|
|
45113
45402
|
if (!reserve.ok) {
|
|
45114
|
-
sessionLog(sessionId,
|
|
45403
|
+
sessionLog(sessionId, describeProtectedTailDrainBudgetSkip(reserve));
|
|
45115
45404
|
telemetry.status = "noop";
|
|
45116
|
-
telemetry.failureReason = "protected-tail drain
|
|
45405
|
+
telemetry.failureReason = "internal protected-tail drain budget spent";
|
|
45117
45406
|
return;
|
|
45118
45407
|
}
|
|
45119
45408
|
drainReservation = reserve.reservation;
|
|
@@ -45245,6 +45534,7 @@ ${chunkText}`,
|
|
|
45245
45534
|
return;
|
|
45246
45535
|
}
|
|
45247
45536
|
let published = false;
|
|
45537
|
+
const transactionStartedAt = performance.now();
|
|
45248
45538
|
db.exec("BEGIN IMMEDIATE");
|
|
45249
45539
|
try {
|
|
45250
45540
|
if (!isCompartmentLeaseHeld(db, sessionId, holderId)) {
|
|
@@ -45291,6 +45581,7 @@ ${chunkText}`,
|
|
|
45291
45581
|
}
|
|
45292
45582
|
db.exec("COMMIT");
|
|
45293
45583
|
published = true;
|
|
45584
|
+
logSlowWriteTransaction("historian-publish", transactionStartedAt);
|
|
45294
45585
|
} finally {
|
|
45295
45586
|
if (!published) {
|
|
45296
45587
|
try {
|
|
@@ -45429,6 +45720,7 @@ function insertRecompCompartmentRows(db, sessionId, compartments, now) {
|
|
|
45429
45720
|
}
|
|
45430
45721
|
function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
|
|
45431
45722
|
const now = Date.now();
|
|
45723
|
+
const transactionStartedAt = performance.now();
|
|
45432
45724
|
db.exec("BEGIN IMMEDIATE");
|
|
45433
45725
|
let finished = false;
|
|
45434
45726
|
try {
|
|
@@ -45457,6 +45749,7 @@ function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
|
|
|
45457
45749
|
clearCachedM0M1(db, sessionId);
|
|
45458
45750
|
db.exec("COMMIT");
|
|
45459
45751
|
finished = true;
|
|
45752
|
+
logSlowWriteTransaction("historian-publish:recomp", transactionStartedAt);
|
|
45460
45753
|
return { compartments: staging.compartments, facts: staging.facts };
|
|
45461
45754
|
} finally {
|
|
45462
45755
|
if (!finished) {
|
|
@@ -46796,4 +47089,4 @@ async function runUpgradeMemoryMigration(ctx, sessionId, migrationDirectory) {
|
|
|
46796
47089
|
}
|
|
46797
47090
|
}
|
|
46798
47091
|
|
|
46799
|
-
export { withContentLanguageDirective, buildPrimaryLanguageDirective, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, resolveLegacyConfigSourcesForHarness, migrateMagicContextConfigLocations, exports_external, DEFAULT_PROTECTED_TAGS, parseCron, nextOccurrence, nextDueAtMs, promptSurfaceConfigIdentity, resolvePromptSurface, resolveModelConfigOrDefault, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, DEFAULT_LOCAL_EMBEDDING_MODEL, PER_HARNESS_MIGRATION_INVENTORY, ConfigProfilesSchema, MagicContextConfigSchema, getOpenCodeDbPath, removeMcOwnedCompactionMarkers, hasShareabilitySensitiveText, isFailClosedBlockingError, shouldBypassFailClosedBlock, resolveAgentNameFromMessages, createFailClosedController, recordHookInitFailure, clearHookInitFailure, getLastHookInitFailure, ProjectIdentityError, resolveProjectIdentityStrict, takeDubiousOwnershipProjectIdentityWarning, resolveProjectIdentity, resolveProjectIdentityForSession, normalizeStoredProjectPath, storedPathBelongsToIdentity, isLinkedGitWorktree, recordSessionProjectIdentity, beginBootQuietPeriod, bootQuietRemainingMs, scheduleAfterBootQuiet, rpcPortDir, rpcPortFilePath, isPidAlive, parseRpcPortFile, registerModuleNoteEvaluationBridge, getModuleNoteEvaluationBridge, getContextStoreUuid, ensureContextStoreUuid, getAuthorityManagedMarker, reconcileAuthorityProject, checksumAuthoritySeedRows, prepareAuthority, drainAuthority, getMirrorCursor, applyMirroredNoteCompileFields, applyMirrorPage, pullMemoryMirrorOnce, V2_MEMORY_CATEGORIES, CATEGORY_PRIORITY, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, resolveStoredPathWorkspaceIdentity, storedPathBelongsToWorkspace, sourceNameForMemory, computeWorkspaceEpochFingerprint, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, getCurrentToolSetHash, recordToolDefinition, getMeasuredToolDefinitionTokens, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, runSqliteOptimize, openDatabase, openDatabaseAsync, isDatabasePersisted, getDatabasePersistenceError, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, clearRecompStaging, isRawCompactionSummaryInfo, extractInMemoryMessageViews, buildInMemoryTailRawMessages, isRecord, estimateTrueRawMessageTokens, invalidateTrueRawTokenCache, stripPersistedAssistantText, byteSize, stripTagPrefix, prependTag, isThinkingPart, isTextPart, isToolPartWithOutput, isFilePart, buildFileSourceContent, isEditTool, partHasCompletedResult, extractToolCallObservation, ToolMutationBatch, createToolDropTarget, setRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, primeInMemoryTailRawMessageCache, readRawSessionMessageOrdinalPage, getRawSessionStoredMessageCount, readRawSessionMessagePartsById, readRawSessionMessageOrdinalById, readRawSessionMessageById, readSessionChunk, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getIndexedMessageCorpusSize, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, deleteIndexedMessage, clearIndexedMessages, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordEmbeddingMeasurement, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, getEmergencyRecoveryArmedAt, loadPersistedUsage, loadProtectedTailMeta, resetProtectedTailNoEligibleHead, getWrapupInProgressState, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, resetLastNudgeCycle, resetLastNudgeCycleIfTailShrank, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, getNoteNudgeAnchors, getAutoSearchHintDecisions, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, removeNoteNudgeAnchorByMessageId, removeAutoSearchHintDecisionByMessageId, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, setNoteLastReadAt, getHistorianFailureState, clearHistorianFailureState, getOverflowState, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, removeStrippedPlaceholderId, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, peekDeferredExecutePending, setDeferredExecutePendingIfAbsent, clearDeferredExecutePendingIfMatches, getSessionsWithPendingMarker, setSessionWorkMetrics, getNotes, addNote, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, updateNote, dismissNote, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectMemoryEpoch, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, CTX_REDUCE_KEEP, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchanged, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, toolOutputTokens, decideChannel1, evaluateChannel2, buildChannel2Reminder, shouldUseStickyChannel1Reminder, buildChannel1Reminder, estimateEmergencyDropReclaimTokens, planEmergencyDrop, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, getActiveTagTokenTotalsByMessage, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, updateTagMessageId, deleteTagsByMessageId, getMaxTagNumberBySession, getTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTailHygieneTags, getDroppedTagsBySession, getTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, getCandidateToolOwners, pickNearestPriorOwner, createChildSessionWithFence, detectOverflow, resolveFallbackChain, modelBodyField, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, extractLatestAssistantText, hasLengthCappedOutput, setKeepSubagents, shouldKeepSubagents, recordChildInvocation, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, Priority, AdmissionClass, StaleRouteHandleError, SocketClosedError, SocketTimeoutError, SubcClient, isConsumerReconnectTransient, connectionFileExists, getCompartmentEvents, loadCompartmentChunkEmbeddingsForSearch, cosineSimilarity, SYNAPSE_DEFAULT_MODEL, SynapseEmbeddingProvider, computeNormalizedHash, saveCommitEmbedding, loadProjectCommitEmbeddings, loadUnembeddedCommits, countEmbeddedCommits, upsertCommits, getLatestIndexedCommitTimeMs, enforceProjectCap, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, saveEmbeddingIfHashMatches, getProjectEmbeddings, peekProjectEmbeddings, invalidateProject, invalidateMemory, markProjectLoadUntrusted, contentSha256, sweepStaleEmbeddingIdentitiesForProject, registerProjectEmbedding, registerProjectShadowEmbedding, getShadowEmbeddingMeasurementCohort, getPrimaryEmbeddingMeasurementCohort, embedShadowTextForProject, enqueueShadowEmbeddingItems, registerProjectInObservationMode, getProjectEmbeddingSnapshot, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, isEmbeddingEnabled, embedText, ensureMemoryEmbeddings, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, ModuleMemoryAuthorityError, insertMemory, insertMemoryIdempotent, getMemoryByHash, getMemoriesByProject, buildWorkspaceMemorySqlFilter, getMemoriesByProjects, getMaxMemoryIdForProjects, readNewMemoriesForM1Union, getMemoryById, getMemoriesByIds, updateMemorySeenCount, updateMemoryRetrievalCount, setMemoryClassification, supersededMemory, mergeMemoryStats, archiveMemory, getMemoryCountsByStatus, sanitizeFtsQuery, searchMemoriesFTS, searchMemoriesFTSUnion, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getMural, BoundedSessionMap, registerLkgPersistence, LKG_SNAPSHOT_ARRAY, LKG_SNAPSHOT_OBJECT, LKG_SNAPSHOT_KEY, LKG_SNAPSHOT_STRING, LKG_SNAPSHOT_NUMBER, LKG_SNAPSHOT_BOOLEAN, LKG_SNAPSHOT_NULL, LKG_SNAPSHOT_UNDEFINED, incrementalLkgContentDigests, lkgContentDigest, captureSlot, getSlot, dropSlot, noteEntry, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, extractM0Block, resolveMuralWire, MARKER_SUMMARY_TEXT, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, formatDate, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, prepareCompartmentInjection, renderCompartmentInjection, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, injectM0M1, RECOVERY_NO_HEAD_LIMIT, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, isRecompFailure, isRecompSkip, isRecompComplete, extractRecompReason, contextualizeUpgradeReason, setRecompStarting, setRecompNote, setRecompTerminal, runManagedRecomp, runManagedUpgrade };
|
|
47092
|
+
export { withContentLanguageDirective, buildPrimaryLanguageDirective, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, resolveLegacyConfigSourcesForHarness, migrateMagicContextConfigLocations, exports_external, DEFAULT_PROTECTED_TAGS, parseCron, nextOccurrence, nextDueAtMs, promptSurfaceConfigIdentity, resolvePromptSurface, resolveModelConfigOrDefault, DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE, DEFAULT_HISTORIAN_TIMEOUT_MS, DEFAULT_LOCAL_EMBEDDING_MODEL, PER_HARNESS_MIGRATION_INVENTORY, ConfigProfilesSchema, MagicContextConfigSchema, getOpenCodeDbPath, removeMcOwnedCompactionMarkers, isFailClosedBlockingError, shouldBypassFailClosedBlock, resolveAgentNameFromMessages, createFailClosedController, recordHookInitFailure, clearHookInitFailure, getLastHookInitFailure, ProjectIdentityError, resolveProjectIdentityStrict, takeDubiousOwnershipProjectIdentityWarning, resolveProjectIdentity, resolveProjectIdentityForSession, normalizeStoredProjectPath, storedPathBelongsToIdentity, isLinkedGitWorktree, recordSessionProjectIdentity, beginBootQuietPeriod, bootQuietRemainingMs, scheduleAfterBootQuiet, rpcPortDir, rpcPortFilePath, isPidAlive, parseRpcPortFile, observeAuthorityRouting, registerModuleNoteEvaluationBridge, getModuleNoteEvaluationBridge, getContextStoreUuid, ensureContextStoreUuid, getAuthorityManagedMarker, reconcileAuthorityProject, checksumAuthoritySeedRows, prepareAuthority, drainAuthority, getMirrorCursor, applyMirroredNoteCompileFields, applyMirrorPage, pullMemoryMirrorOnce, V2_MEMORY_CATEGORIES, CATEGORY_PRIORITY, resolveWorkspaceShareCategories, resolveWorkspaceIdentitySet, expandWorkspaceIdentitySetWithAliases, resolveStoredPathWorkspaceIdentity, storedPathBelongsToWorkspace, sourceNameForMemory, computeWorkspaceEpochFingerprint, textMentionsRecentCommit, hasMeaningfulUserText, extractTexts, extractToolCallSummaries, preloadTokenizer, estimateTokens, normalizeText, getCurrentToolSetHash, recordToolDefinition, getMeasuredToolDefinitionTokens, getSchemaFenceRejection, getMigrationOnOpenRefusal, LATEST_SUPPORTED_VERSION, getDatabasePath, getPersistedSchemaVersion, setSqlitePragmaConfig, runSqliteOptimize, openDatabase, openDatabaseAsync, isDatabasePersisted, getDatabasePersistenceError, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, clearRecompStaging, isRawCompactionSummaryInfo, extractInMemoryMessageViews, buildInMemoryTailRawMessages, isRecord, estimateTrueRawMessageTokens, invalidateTrueRawTokenCache, stripPersistedAssistantText, byteSize, stripTagPrefix, prependTag, isThinkingPart, isTextPart, isToolPartWithOutput, isFilePart, buildFileSourceContent, isEditTool, partHasCompletedResult, extractToolCallObservation, ToolMutationBatch, createToolDropTarget, setRawMessageProvider, cleanUserText, withRawSessionMessageCache, readRawSessionMessages, primeTailRawMessageCache, primeInMemoryTailRawMessageCache, readRawSessionMessageOrdinalPage, getRawSessionStoredMessageCount, readRawSessionMessagePartsById, readRawSessionMessageOrdinalById, readRawSessionMessageById, readSessionChunk, getMessageIndexSourceIdentity, isMessageIndexSourceCurrent, getLastIndexedOrdinal, getIndexedMessageCorpusSize, getMessageIndexReconciliationStartOrdinal, isMessageIndexReconciledThrough, deleteIndexedMessage, clearIndexedMessages, indexSingleMessage, indexMessagesAfterOrdinal, sweepOrphanedOpenCodeMessageIndexes, recordEmbeddingMeasurement, getMaxM0MutationId, queueMemoryMutation, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationIdForProjects, MAX_EXECUTE_THRESHOLD, escalationBands, isEmergencyRecoveryArmed, isProviderOverflowReconfirmed, getEmergencyRecoveryArmedAt, loadPersistedUsage, loadProtectedTailMeta, resetProtectedTailNoEligibleHead, getWrapupInProgressState, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, getPersistedReasoningWatermark, setPersistedReasoningWatermark, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, getNoteNudgeAnchors, getAutoSearchHintDecisions, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, pruneAutoSearchHintDecisions, removeNoteNudgeAnchorByMessageId, removeAutoSearchHintDecisionByMessageId, getPersistedTodoPermissionDenied, setPersistedTodoPermissionDenied, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, setNoteLastReadAt, getHistorianFailureState, clearHistorianFailureState, getOverflowState, recordOverflowDetected, recordDetectedContextLimit, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, removeStrippedPlaceholderId, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getTrailingBlankDecisions, addTrailingBlankDecisions, demoteTrailingBlankKeepDecisions, getStaleReduceStrippedIds, addStaleReduceStrippedIds, getProcessedImageStrippedIds, addProcessedImageStrippedIds, getPendingCompactionMarkerState, clearPendingCompactionMarkerStateIf, peekDeferredExecutePending, setDeferredExecutePendingIfAbsent, clearDeferredExecutePendingIfMatches, getSessionsWithPendingMarker, setSessionWorkMetrics, getNotes, addNote, getSessionNotes, getPendingSmartNotes, getReadySmartNotes, updateNote, dismissNote, markNoteReady, markNoteChecked, queuePendingOp, getPendingOps, clearPendingOps, removePendingOp, PRIMER_CANDIDATE_TTL_MS, PRIMER_CANDIDATE_MAX_AGE_MS, primerOccurrenceKey, primerOccurrenceUtcDay, updatePrimerCandidateEmbedding, getPrimerCandidatesByIds, getPrimerCandidatesForPromotion, countPrimerCandidatesForProject, getActivePrimers, createPrimer, updatePrimerSupport, updatePrimerAnswer, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectMemoryEpoch, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, CTX_REDUCE_KEEP, estimateImageTokensFromDataUrl, normalizeTodoStateJson, buildSyntheticTodoPart, computeSyntheticCallId, isSyntheticTodoPart, countRealUserMessages, tailHygieneStructuralSignature, sameTailHygieneStructuralSignature, refreshTailHygieneBaseline, effectiveTailHygiene, assertTailHygieneContentUnchanged, CHANNEL1_SENTINEL, CHANNEL1_FLOOR_TOKENS, toolOutputTokens, decideChannel1, evaluateChannel2, reclaimableToolOutputCount, buildChannel2Reminder, buildChannel1Reminder, estimateEmergencyDropReclaimTokens, planEmergencyDrop, getRecentTagOwnerMessageIds, AGE_RECLAIM_MIN_TOKENS, getOldestActiveUnprotectedToolTags, getActiveToolTagsForAgeReclaim, getTriggerTagTokenUpperBound, getActiveTagTokenTotalsByMessage, tagTokenCountIsNull, backfillTagTokenCounts, insertTag, updateTagStatus, updateTagDropMode, updateCavemanDepth, updateTagMessageId, deleteTagsByMessageId, getMaxTagNumberBySession, getTagNumberByMessageId, deriveTagLoadFloor, getTagsBySession, getActiveTagsBySession, getTailHygieneTags, getDroppedTagsBySession, getTagsByNumbers, getMaxDroppedTagNumber, getToolTagNumberByOwner, getNullOwnerToolTag, adoptNullOwnerToolTag, getCandidateToolOwners, pickNearestPriorOwner, createChildSessionWithFence, detectOverflow, resolveFallbackChain, modelBodyField, toModelEntry, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, promptSurfaceHashMaterial, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, extractLatestAssistantText, hasLengthCappedOutput, setKeepSubagents, shouldKeepSubagents, recordChildInvocation, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, Priority, AdmissionClass, StaleRouteHandleError, SocketClosedError, SocketTimeoutError, SubcClient, isConsumerReconnectTransient, connectionFileExists, getCompartmentEvents, loadCompartmentChunkEmbeddingsForSearch, cosineSimilarity, SYNAPSE_DEFAULT_MODEL, SynapseEmbeddingProvider, computeNormalizedHash, saveCommitEmbedding, loadProjectCommitEmbeddings, loadUnembeddedCommits, countEmbeddedCommits, upsertCommits, getLatestIndexedCommitTimeMs, enforceProjectCap, GIT_SWEEP_LEASE_RENEWAL_MS, acquireGitSweepLease, renewGitSweepLease, markGitSweepSuccessAndRelease, parkGitSweepNonIndexable, releaseGitSweepLease, saveEmbeddingIfHashMatches, getProjectEmbeddings, peekProjectEmbeddings, invalidateProject, invalidateMemory, markProjectLoadUntrusted, contentSha256, sweepStaleEmbeddingIdentitiesForProject, registerProjectEmbedding, registerProjectShadowEmbedding, getShadowEmbeddingMeasurementCohort, getPrimaryEmbeddingMeasurementCohort, embedShadowTextForProject, enqueueShadowEmbeddingItems, registerProjectInObservationMode, getProjectEmbeddingSnapshot, embedTextForProject, embedBatchForProject, embedItemsForProject, embedUnembeddedMemoriesForProject, drainCommitBacklogForProject, embedSessionCompartmentChunks, getEmbeddingCoverageStatus, isEmbeddingEnabled, embedText, ensureMemoryEmbeddings, computeCueContentHash, hasMuralCueColumns, getMuralCueState, memoryNeedsCue, setMuralCue, recordMuralCueRejection, hasMemoryShareableColumn, hasMemoryClassifiedAtColumn, getUnclassifiedMemoryIds, ModuleMemoryAuthorityError, insertMemory, insertMemoryIdempotent, getMemoryByHash, getMemoriesByProject, buildWorkspaceMemorySqlFilter, getMemoriesByProjects, getMaxMemoryIdForProjects, readNewMemoriesForM1Union, getMemoryById, getMemoriesByIds, updateMemorySeenCount, updateMemoryRetrievalCount, setMemoryClassification, supersededMemory, mergeMemoryStats, archiveMemory, getMemoryCountsByStatus, sanitizeFtsQuery, searchMemoriesFTS, searchMemoriesFTSUnion, recordMemoryMapping, recordMemoryVerifications, getUnmappedMemoryIds, clearMemoryVerifications, getMemoryVerifications, resolveGitTopLevel, readGitHead, readGitChangedFilesSince, readGitFileChangeTimesSince, verificationFileExists, normalizeVerificationFiles, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getMural, BoundedSessionMap, registerLkgPersistence, LKG_SNAPSHOT_ARRAY, LKG_SNAPSHOT_OBJECT, LKG_SNAPSHOT_KEY, LKG_SNAPSHOT_STRING, LKG_SNAPSHOT_NUMBER, LKG_SNAPSHOT_BOOLEAN, LKG_SNAPSHOT_NULL, LKG_SNAPSHOT_UNDEFINED, incrementalLkgContentDigests, lkgContentDigest, captureSlot, getSlot, dropSlot, noteEntry, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, MARKER_SUMMARY_TEXT, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, resolveMuralWire, extractM0Block, formatDate, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, prepareCompartmentInjection, renderCompartmentInjection, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, injectM0M1, RECOVERY_NO_HEAD_LIMIT, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, isRecompFailure, isRecompSkip, isRecompComplete, extractRecompReason, contextualizeUpgradeReason, setRecompStarting, setRecompNote, setRecompTerminal, runManagedRecomp, runManagedUpgrade };
|