@cortexkit/opencode-magic-context 0.40.1 → 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/{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/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/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-x64cmpej.js → index-w8rkbhn6.js} +505 -301
- package/dist/{index-rw0qrkvq.js → index-x9dmzyp5.js} +17 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2892 -2302
- 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-dtgww0f0.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 +1 -1
- 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
|
|
|
@@ -8610,15 +8600,32 @@ function buildToolArcs(messages) {
|
|
|
8610
8600
|
}
|
|
8611
8601
|
return arcs.sort((a, b) => a.invOrdinal - b.invOrdinal || (a.resOrdinal ?? Number.MAX_SAFE_INTEGER) - (b.resOrdinal ?? Number.MAX_SAFE_INTEGER));
|
|
8612
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
|
+
}
|
|
8613
8624
|
function fenceBoundaryForToolArcs(candidate, arcs, lastCompartmentEndOrdinal, recentOpenArcCutoff) {
|
|
8614
|
-
|
|
8625
|
+
const boundary = fenceBoundaryForCompletedToolArcs(candidate, arcs, lastCompartmentEndOrdinal + 1);
|
|
8615
8626
|
for (const arc of arcs) {
|
|
8616
|
-
if (arc.resOrdinal !== null)
|
|
8617
|
-
if (completedToolArcCrossesBoundary(arc.invOrdinal, arc.resOrdinal, boundary)) {
|
|
8618
|
-
boundary = arc.resOrdinal + 1;
|
|
8619
|
-
}
|
|
8627
|
+
if (arc.resOrdinal !== null)
|
|
8620
8628
|
continue;
|
|
8621
|
-
}
|
|
8622
8629
|
if (arc.invOrdinal < recentOpenArcCutoff)
|
|
8623
8630
|
continue;
|
|
8624
8631
|
if (arc.invOrdinal >= lastCompartmentEndOrdinal + 1 && arc.invOrdinal < boundary) {
|
|
@@ -10448,6 +10455,13 @@ function isProviderOverflowReconfirmed(sessionId) {
|
|
|
10448
10455
|
function getEmergencyRecoveryArmedAt(sessionId) {
|
|
10449
10456
|
return emergencyRecoveryArmedAtBySession.get(sessionId) ?? null;
|
|
10450
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
|
+
}
|
|
10451
10465
|
var CAS_RETRY_LIMIT = 5;
|
|
10452
10466
|
var AUTO_SEARCH_NO_HINT_REASONS = new Set([
|
|
10453
10467
|
"below-threshold",
|
|
@@ -10827,19 +10841,28 @@ function reserveProtectedTailDrainTokens(args) {
|
|
|
10827
10841
|
const now = args.now ?? Date.now();
|
|
10828
10842
|
const requested = Math.max(0, Math.floor(args.trueRawTokens));
|
|
10829
10843
|
if (requested === 0) {
|
|
10830
|
-
return {
|
|
10844
|
+
return {
|
|
10845
|
+
ok: true,
|
|
10846
|
+
reservedTokens: 0,
|
|
10847
|
+
overQuotaBypass: false,
|
|
10848
|
+
reservation: null,
|
|
10849
|
+
budgetState: null
|
|
10850
|
+
};
|
|
10831
10851
|
}
|
|
10832
10852
|
let result = {
|
|
10833
10853
|
ok: false,
|
|
10834
10854
|
reservedTokens: 0,
|
|
10835
10855
|
overQuotaBypass: false,
|
|
10836
10856
|
reservation: null,
|
|
10837
|
-
|
|
10857
|
+
budgetState: null,
|
|
10858
|
+
skippedReason: "internal drain budget spent"
|
|
10838
10859
|
};
|
|
10839
10860
|
args.db.transaction(() => {
|
|
10840
10861
|
ensureSessionMetaRow(args.db, args.sessionId);
|
|
10841
10862
|
let meta = loadProtectedTailMeta(args.db, args.sessionId);
|
|
10842
|
-
|
|
10863
|
+
const windowStartedAt = meta.protectedTailDrainWindowStartedAt;
|
|
10864
|
+
const windowExpired = windowStartedAt <= 0 || windowStartedAt > now || now - windowStartedAt >= DRAIN_WINDOW_MS;
|
|
10865
|
+
if (windowExpired) {
|
|
10843
10866
|
args.db.prepare(`UPDATE session_meta
|
|
10844
10867
|
SET protected_tail_drain_window_started_at = ?, protected_tail_drain_tokens = 0
|
|
10845
10868
|
WHERE session_id = ?`).run(now, args.sessionId);
|
|
@@ -10864,22 +10887,35 @@ function reserveProtectedTailDrainTokens(args) {
|
|
|
10864
10887
|
const remaining = Math.max(0, budget - meta.protectedTailDrainTokens);
|
|
10865
10888
|
let reserved = Math.min(requested, args.perRunCap, remaining);
|
|
10866
10889
|
let bypass = false;
|
|
10867
|
-
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;
|
|
10868
10891
|
if (reserved <= 0 && latchActive && !inFailureBackoff) {
|
|
10869
10892
|
reserved = Math.min(requested, args.perRunCap);
|
|
10870
10893
|
bypass = true;
|
|
10871
10894
|
}
|
|
10872
|
-
|
|
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
|
+
};
|
|
10873
10908
|
return;
|
|
10909
|
+
}
|
|
10874
10910
|
args.db.prepare(`UPDATE session_meta
|
|
10875
|
-
SET
|
|
10876
|
-
|
|
10877
|
-
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);
|
|
10878
10913
|
result = {
|
|
10879
10914
|
ok: true,
|
|
10880
10915
|
reservedTokens: reserved,
|
|
10881
10916
|
overQuotaBypass: bypass,
|
|
10882
|
-
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)
|
|
10883
10919
|
};
|
|
10884
10920
|
})();
|
|
10885
10921
|
return result;
|
|
@@ -10957,19 +10993,38 @@ function parseChannel1NudgeState(raw) {
|
|
|
10957
10993
|
try {
|
|
10958
10994
|
const parsed = JSON.parse(raw);
|
|
10959
10995
|
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
10960
|
-
|
|
10996
|
+
const state2 = {
|
|
10961
10997
|
level: normalizeLastNudgeLevel(parsed.level),
|
|
10962
10998
|
ordinal: typeof parsed.ordinal === "number" ? Math.max(0, Math.round(parsed.ordinal)) : 0
|
|
10963
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;
|
|
10964
11010
|
}
|
|
10965
11011
|
} catch {}
|
|
10966
11012
|
return { level: normalizeLastNudgeLevel(raw), ordinal: 0 };
|
|
10967
11013
|
}
|
|
10968
11014
|
function serializeChannel1NudgeState(value) {
|
|
10969
|
-
|
|
11015
|
+
const serialized = {
|
|
10970
11016
|
level: normalizeLastNudgeLevel(value.level),
|
|
10971
11017
|
ordinal: Math.max(0, Math.round(value.ordinal))
|
|
10972
|
-
}
|
|
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);
|
|
10973
11028
|
}
|
|
10974
11029
|
function getLastNudgeUndropped(db, sessionId) {
|
|
10975
11030
|
const result = db.prepare("SELECT last_nudge_undropped FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
@@ -10991,20 +11046,36 @@ function setChannel1NudgeState(db, sessionId, value) {
|
|
|
10991
11046
|
db.prepare("UPDATE session_meta SET last_nudge_level = ? WHERE session_id = ?").run(serializeChannel1NudgeState(value), sessionId);
|
|
10992
11047
|
})();
|
|
10993
11048
|
}
|
|
10994
|
-
function
|
|
10995
|
-
db.transaction(() => {
|
|
11049
|
+
function markChannel1PostReduceGracePending(db, sessionId) {
|
|
11050
|
+
return db.transaction(() => {
|
|
10996
11051
|
ensureSessionMetaRow(db, sessionId);
|
|
10997
|
-
|
|
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;
|
|
10998
11061
|
})();
|
|
10999
11062
|
}
|
|
11000
|
-
function
|
|
11001
|
-
|
|
11002
|
-
db.transaction(() => {
|
|
11063
|
+
function captureChannel1PostReduceGraceBaseline(db, sessionId, measuredUndropped) {
|
|
11064
|
+
return db.transaction(() => {
|
|
11003
11065
|
ensureSessionMetaRow(db, sessionId);
|
|
11004
|
-
const
|
|
11005
|
-
|
|
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;
|
|
11006
11078
|
})();
|
|
11007
|
-
return changed;
|
|
11008
11079
|
}
|
|
11009
11080
|
function isChannel2StateRow(row) {
|
|
11010
11081
|
return typeof row === "object" && row !== null && typeof row.channel2_nudge_state === "string";
|
|
@@ -11535,6 +11606,33 @@ function addTrailingBlankDecisions(db, sessionId, additions, options) {
|
|
|
11535
11606
|
sessionLog(sessionId, `trailing_blank_decisions CAS: ${CAS_RETRY_LIMIT} retries exhausted`);
|
|
11536
11607
|
return false;
|
|
11537
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
|
+
}
|
|
11538
11636
|
function getStaleReduceStrippedIds(db, sessionId) {
|
|
11539
11637
|
const row = db.prepare("SELECT stale_reduce_stripped_ids FROM session_meta WHERE session_id = ?").get(sessionId);
|
|
11540
11638
|
return new Set(parseStrippedBlob(row?.stale_reduce_stripped_ids));
|
|
@@ -12976,7 +13074,8 @@ function measureTailHygiene(input) {
|
|
|
12976
13074
|
continue;
|
|
12977
13075
|
}
|
|
12978
13076
|
if (type === "text") {
|
|
12979
|
-
const
|
|
13077
|
+
const rawContent = firstString(part, ["text", "content"]);
|
|
13078
|
+
const content = rawContent === null ? null : stripChannel1ReminderSpans(rawContent);
|
|
12980
13079
|
if (!content || isDropSentinel(content)) {
|
|
12981
13080
|
parts.push(excludedSnapshot(`${key}\x00excluded`, part));
|
|
12982
13081
|
continue;
|
|
@@ -13126,7 +13225,8 @@ function refreshTailHygieneBaseline(input) {
|
|
|
13126
13225
|
evaluable: true,
|
|
13127
13226
|
generationInvalidated: false,
|
|
13128
13227
|
baselineParts: measured.parts,
|
|
13129
|
-
contentSignature: measured.contentSignature
|
|
13228
|
+
contentSignature: measured.contentSignature,
|
|
13229
|
+
channel1PostReduceGrace: input.previous?.channel1PostReduceGrace
|
|
13130
13230
|
};
|
|
13131
13231
|
}
|
|
13132
13232
|
const prefix = sameMeasuredPrefix(input.previous.baselineParts, measured.parts);
|
|
@@ -13188,47 +13288,74 @@ function decideChannel1(input) {
|
|
|
13188
13288
|
const tailTokens = Math.max(0, input.baselineT + input.turnDeltaT);
|
|
13189
13289
|
const undroppedTokens = Math.min(tailTokens, Math.max(0, input.baselineU + input.turnDeltaU));
|
|
13190
13290
|
const severity = Math.min(1, Math.max(0, undroppedTokens / Math.max(tailTokens, 1)));
|
|
13191
|
-
const
|
|
13192
|
-
|
|
13193
|
-
|
|
13194
|
-
|
|
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") => ({
|
|
13195
13296
|
fire: false,
|
|
13196
|
-
|
|
13297
|
+
sticky: false,
|
|
13298
|
+
level: level2,
|
|
13197
13299
|
undroppedTokens,
|
|
13198
13300
|
tailTokens,
|
|
13199
13301
|
severity,
|
|
13200
13302
|
nextLastNudge: lastNudge,
|
|
13201
|
-
nextLastNudgeLevel:
|
|
13303
|
+
nextLastNudgeLevel: nextLevel,
|
|
13304
|
+
clearPostReduceGrace
|
|
13202
13305
|
});
|
|
13203
13306
|
if (input.evaluable === false || input.generationInvalidated === true)
|
|
13204
13307
|
return quiet();
|
|
13205
|
-
if (input.hasRecentReduce)
|
|
13206
|
-
return quiet();
|
|
13207
|
-
if (tailTokens < CHANNEL1_MIN_TOKENS)
|
|
13308
|
+
if (input.hasRecentReduce || input.postReduceGracePending)
|
|
13208
13309
|
return quiet();
|
|
13209
|
-
|
|
13210
|
-
|
|
13211
|
-
|
|
13212
|
-
|
|
13213
|
-
|
|
13214
|
-
|
|
13215
|
-
|
|
13216
|
-
|
|
13217
|
-
|
|
13218
|
-
|
|
13219
|
-
|
|
13220
|
-
const
|
|
13221
|
-
|
|
13222
|
-
|
|
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;
|
|
13223
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);
|
|
13224
13349
|
return {
|
|
13225
13350
|
fire: true,
|
|
13351
|
+
sticky: !crossedFromBelow,
|
|
13226
13352
|
level,
|
|
13227
13353
|
undroppedTokens,
|
|
13228
13354
|
tailTokens,
|
|
13229
13355
|
severity,
|
|
13230
13356
|
nextLastNudge: undroppedTokens,
|
|
13231
|
-
nextLastNudgeLevel: level
|
|
13357
|
+
nextLastNudgeLevel: level,
|
|
13358
|
+
clearPostReduceGrace
|
|
13232
13359
|
};
|
|
13233
13360
|
}
|
|
13234
13361
|
var CHANNEL2_SEVERITY_THRESHOLD = 0.75;
|
|
@@ -13265,44 +13392,42 @@ function formatOldestReclaimableHint(hint) {
|
|
|
13265
13392
|
return rendered.length > 0 ? `
|
|
13266
13393
|
oldest reclaimable: ${rendered}.` : "";
|
|
13267
13394
|
}
|
|
13268
|
-
function
|
|
13269
|
-
|
|
13270
|
-
|
|
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);
|
|
13271
13405
|
const hintText = formatOldestReclaimableHint(hint);
|
|
13272
13406
|
return `<system-reminder>
|
|
13273
|
-
` + `Routine housekeeping:
|
|
13407
|
+
` + `Routine housekeeping: ${summary} are reclaimable — make a ctx_reduce pass at a natural stopping point.${hintText}
|
|
13274
13408
|
` + `</system-reminder>`;
|
|
13275
13409
|
}
|
|
13276
|
-
var CHANNEL1_STICKY_REAL_USER_TURN_GAP =
|
|
13277
|
-
function
|
|
13278
|
-
|
|
13279
|
-
return false;
|
|
13280
|
-
if (input.lastOrdinal > input.currentRealUserTurnCount)
|
|
13281
|
-
return false;
|
|
13282
|
-
const gap = input.currentRealUserTurnCount - input.lastOrdinal;
|
|
13283
|
-
return gap >= 0 && gap < CHANNEL1_STICKY_REAL_USER_TURN_GAP;
|
|
13284
|
-
}
|
|
13285
|
-
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);
|
|
13286
13413
|
const hintText = formatOldestReclaimableHint(hint);
|
|
13287
13414
|
if (sticky) {
|
|
13288
13415
|
return `
|
|
13289
13416
|
|
|
13290
13417
|
<system-reminder>
|
|
13291
|
-
Reminder:
|
|
13418
|
+
Reminder: ${summary} are still reclaimable — ctx_reduce them at a natural stopping point.${hintText}
|
|
13292
13419
|
</system-reminder>`;
|
|
13293
13420
|
}
|
|
13294
|
-
const amount = approxThousands(undroppedTokens);
|
|
13295
|
-
const usableWindow = approxThousands(usableWindowTokens);
|
|
13296
13421
|
let body;
|
|
13297
13422
|
switch (level) {
|
|
13298
13423
|
case "gentle":
|
|
13299
|
-
body = `Housekeeping:
|
|
13424
|
+
body = `Housekeeping: ${summary} are reclaimable — drop the ones you have already processed with ctx_reduce at a natural stopping point.`;
|
|
13300
13425
|
break;
|
|
13301
13426
|
case "firm":
|
|
13302
|
-
body = `Housekeeping:
|
|
13427
|
+
body = `Housekeeping: ${summary} are reclaimable — make a ctx_reduce pass at a natural stopping point.`;
|
|
13303
13428
|
break;
|
|
13304
13429
|
case "urgent":
|
|
13305
|
-
body = `Housekeeping backlog:
|
|
13430
|
+
body = `Housekeeping backlog: ${summary} are reclaimable — a ctx_reduce pass is due.`;
|
|
13306
13431
|
break;
|
|
13307
13432
|
}
|
|
13308
13433
|
return `
|
|
@@ -13363,8 +13488,8 @@ function planEmergencyDrop(input) {
|
|
|
13363
13488
|
if (!Number.isFinite(currentTotalInputTokens) || currentTotalInputTokens <= 0) {
|
|
13364
13489
|
return noop("unknown-usage");
|
|
13365
13490
|
}
|
|
13366
|
-
if (hasPriorDrop
|
|
13367
|
-
return noop(
|
|
13491
|
+
if (hasPriorDrop) {
|
|
13492
|
+
return noop(`pressure-episode-latched (prior sample ${priorInputSample}; awaiting exit or independent bust)`);
|
|
13368
13493
|
}
|
|
13369
13494
|
let tailTokens = 0;
|
|
13370
13495
|
for (const tag of floorTags) {
|
|
@@ -13474,12 +13599,50 @@ function getUpdateTagDropModeStatement(db) {
|
|
|
13474
13599
|
var updateTagByteSizeStatements = new WeakMap;
|
|
13475
13600
|
var updateTagInputByteSizeStatements = new WeakMap;
|
|
13476
13601
|
var CONTENT_ID_SUFFIX = /:(?:p|file)\d+$/;
|
|
13602
|
+
var RECENT_OWNER_SCAN_PAGE_SIZE = 128;
|
|
13603
|
+
var recentTagOwnerStatements = new WeakMap;
|
|
13477
13604
|
function ownerMessageIdForTagRow(row) {
|
|
13478
13605
|
if (row.type === "tool") {
|
|
13479
13606
|
return row.tool_owner_message_id ?? row.message_id;
|
|
13480
13607
|
}
|
|
13481
13608
|
return row.message_id.replace(CONTENT_ID_SUFFIX, "");
|
|
13482
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
|
+
}
|
|
13483
13646
|
var RECLAIM_HINT_EXCLUDED_TOOLS = new Set([
|
|
13484
13647
|
"ask",
|
|
13485
13648
|
"bash_kill",
|
|
@@ -14603,15 +14766,15 @@ import {
|
|
|
14603
14766
|
unlinkSync as unlinkSync2,
|
|
14604
14767
|
writeFileSync
|
|
14605
14768
|
} from "node:fs";
|
|
14606
|
-
import { homedir as
|
|
14769
|
+
import { homedir as homedir3 } from "node:os";
|
|
14607
14770
|
import { basename as basename2, dirname as dirname3, isAbsolute, join as join5 } from "node:path";
|
|
14608
14771
|
var CONFIG_FILE_BASENAME = "magic-context";
|
|
14609
14772
|
var MOVED_MARKER_SUFFIX = ".MOVED_READPLEASE";
|
|
14610
14773
|
function homeDir() {
|
|
14611
14774
|
if (process.platform === "win32") {
|
|
14612
|
-
return process.env.USERPROFILE || process.env.HOME ||
|
|
14775
|
+
return process.env.USERPROFILE || process.env.HOME || homedir3();
|
|
14613
14776
|
}
|
|
14614
|
-
return process.env.HOME ||
|
|
14777
|
+
return process.env.HOME || homedir3();
|
|
14615
14778
|
}
|
|
14616
14779
|
function configHome() {
|
|
14617
14780
|
const xdg = process.env.XDG_CONFIG_HOME;
|
|
@@ -15592,6 +15755,7 @@ var memoryImportanceColumnCache = new WeakMap;
|
|
|
15592
15755
|
var memoryScopeColumnCache = new WeakMap;
|
|
15593
15756
|
var memoryShareableColumnCache = new WeakMap;
|
|
15594
15757
|
var memoryClassifiedAtColumnCache = new WeakMap;
|
|
15758
|
+
var memoryVerificationsTableCache = new WeakMap;
|
|
15595
15759
|
function hasMemoryImportanceColumn(db) {
|
|
15596
15760
|
const cached = memoryImportanceColumnCache.get(db);
|
|
15597
15761
|
if (cached !== undefined)
|
|
@@ -17150,7 +17314,7 @@ function countSessionCompartmentEmbedCoverage(db, projectPath, sessionId, modelI
|
|
|
17150
17314
|
import { createHash as createHash14, randomUUID as randomUUID2 } from "node:crypto";
|
|
17151
17315
|
|
|
17152
17316
|
// src/config/schema/magic-context.ts
|
|
17153
|
-
import { homedir as
|
|
17317
|
+
import { homedir as homedir4 } from "node:os";
|
|
17154
17318
|
|
|
17155
17319
|
// ../../node_modules/.bun/zod@4.4.3/node_modules/zod/v4/classic/external.js
|
|
17156
17320
|
var exports_external = {};
|
|
@@ -17777,7 +17941,7 @@ __export(exports_util, {
|
|
|
17777
17941
|
createTransparentProxy: () => createTransparentProxy,
|
|
17778
17942
|
defineLazy: () => defineLazy,
|
|
17779
17943
|
esc: () => esc,
|
|
17780
|
-
escapeRegex: () =>
|
|
17944
|
+
escapeRegex: () => escapeRegex,
|
|
17781
17945
|
explicitlyAborted: () => explicitlyAborted,
|
|
17782
17946
|
extend: () => extend,
|
|
17783
17947
|
finalizeIssue: () => finalizeIssue,
|
|
@@ -18054,7 +18218,7 @@ var primitiveTypes = /* @__PURE__ */ new Set([
|
|
|
18054
18218
|
"symbol",
|
|
18055
18219
|
"undefined"
|
|
18056
18220
|
]);
|
|
18057
|
-
function
|
|
18221
|
+
function escapeRegex(str) {
|
|
18058
18222
|
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
18059
18223
|
}
|
|
18060
18224
|
function clone(inst, def, params) {
|
|
@@ -18764,7 +18928,7 @@ function emoji() {
|
|
|
18764
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])$/;
|
|
18765
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}|:))$/;
|
|
18766
18930
|
var mac = (delimiter) => {
|
|
18767
|
-
const escapedDelim =
|
|
18931
|
+
const escapedDelim = escapeRegex(delimiter ?? ":");
|
|
18768
18932
|
return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
|
|
18769
18933
|
};
|
|
18770
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])$/;
|
|
@@ -19265,7 +19429,7 @@ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (ins
|
|
|
19265
19429
|
});
|
|
19266
19430
|
var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
|
|
19267
19431
|
$ZodCheck.init(inst, def);
|
|
19268
|
-
const escapedRegex =
|
|
19432
|
+
const escapedRegex = escapeRegex(def.includes);
|
|
19269
19433
|
const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
|
|
19270
19434
|
def.pattern = pattern;
|
|
19271
19435
|
inst._zod.onattach.push((inst2) => {
|
|
@@ -19289,7 +19453,7 @@ var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst,
|
|
|
19289
19453
|
});
|
|
19290
19454
|
var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
|
|
19291
19455
|
$ZodCheck.init(inst, def);
|
|
19292
|
-
const pattern = new RegExp(`^${
|
|
19456
|
+
const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
|
|
19293
19457
|
def.pattern ?? (def.pattern = pattern);
|
|
19294
19458
|
inst._zod.onattach.push((inst2) => {
|
|
19295
19459
|
const bag = inst2._zod.bag;
|
|
@@ -19312,7 +19476,7 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i
|
|
|
19312
19476
|
});
|
|
19313
19477
|
var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
|
|
19314
19478
|
$ZodCheck.init(inst, def);
|
|
19315
|
-
const pattern = new RegExp(`.*${
|
|
19479
|
+
const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
|
|
19316
19480
|
def.pattern ?? (def.pattern = pattern);
|
|
19317
19481
|
inst._zod.onattach.push((inst2) => {
|
|
19318
19482
|
const bag = inst2._zod.bag;
|
|
@@ -20959,7 +21123,7 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
|
|
|
20959
21123
|
const values = getEnumValues(def.entries);
|
|
20960
21124
|
const valuesSet = new Set(values);
|
|
20961
21125
|
inst._zod.values = valuesSet;
|
|
20962
|
-
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("|")})$`);
|
|
20963
21127
|
inst._zod.parse = (payload, _ctx) => {
|
|
20964
21128
|
const input = payload.value;
|
|
20965
21129
|
if (valuesSet.has(input)) {
|
|
@@ -20981,7 +21145,7 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
|
|
|
20981
21145
|
}
|
|
20982
21146
|
const values = new Set(def.values);
|
|
20983
21147
|
inst._zod.values = values;
|
|
20984
|
-
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("|")})$`);
|
|
20985
21149
|
inst._zod.parse = (payload, _ctx) => {
|
|
20986
21150
|
const input = payload.value;
|
|
20987
21151
|
if (values.has(input)) {
|
|
@@ -21346,7 +21510,7 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i
|
|
|
21346
21510
|
const end = source.endsWith("$") ? source.length - 1 : source.length;
|
|
21347
21511
|
regexParts.push(source.slice(start, end));
|
|
21348
21512
|
} else if (part === null || primitiveTypes.has(typeof part)) {
|
|
21349
|
-
regexParts.push(
|
|
21513
|
+
regexParts.push(escapeRegex(`${part}`));
|
|
21350
21514
|
} else {
|
|
21351
21515
|
throw new Error(`Invalid template literal part: ${part}`);
|
|
21352
21516
|
}
|
|
@@ -31833,9 +31997,9 @@ var EmbeddingFallbackProviderSchema = exports_external.enum(["local", "openai-co
|
|
|
31833
31997
|
function expandConfigPath(value) {
|
|
31834
31998
|
const trimmed = value.trim();
|
|
31835
31999
|
if (trimmed === "~")
|
|
31836
|
-
return
|
|
32000
|
+
return homedir4();
|
|
31837
32001
|
if (trimmed.startsWith("~/"))
|
|
31838
|
-
return `${
|
|
32002
|
+
return `${homedir4()}/${trimmed.slice(2)}`;
|
|
31839
32003
|
return trimmed;
|
|
31840
32004
|
}
|
|
31841
32005
|
var BaseEmbeddingConfigSchema = exports_external.object({
|
|
@@ -35210,6 +35374,13 @@ function markProjectLoadUntrusted(projectIdentity) {
|
|
|
35210
35374
|
untrustedLoadProjects.add(projectIdentity);
|
|
35211
35375
|
}
|
|
35212
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
|
+
}
|
|
35213
35384
|
function synapseConfigFields(config2) {
|
|
35214
35385
|
const raw = config2;
|
|
35215
35386
|
return {
|
|
@@ -35325,11 +35496,14 @@ function resolveEmbeddingConfig(config2) {
|
|
|
35325
35496
|
throw new Error("Unknown embedding provider");
|
|
35326
35497
|
}
|
|
35327
35498
|
function createProvider(config2, context) {
|
|
35499
|
+
if (config2.provider === "off") {
|
|
35500
|
+
return null;
|
|
35501
|
+
}
|
|
35328
35502
|
if (testProviderFactory) {
|
|
35329
35503
|
return testProviderFactory(config2);
|
|
35330
35504
|
}
|
|
35331
|
-
if (
|
|
35332
|
-
|
|
35505
|
+
if (process.env.MAGIC_CONTEXT_TEST_DATA_DIR?.trim()) {
|
|
35506
|
+
throw new TestProviderFactoryRequiredError;
|
|
35333
35507
|
}
|
|
35334
35508
|
if (config2.provider === "openai-compatible") {
|
|
35335
35509
|
return new OpenAICompatibleEmbeddingProvider({
|
|
@@ -36938,13 +37112,13 @@ function placeholders3(values) {
|
|
|
36938
37112
|
function uniqueSortedFiles(files) {
|
|
36939
37113
|
return Array.from(new Set(files.filter((file2) => file2 !== MEMORY_VERIFICATION_SENTINEL))).sort();
|
|
36940
37114
|
}
|
|
36941
|
-
function recordMemoryMapping(db, memoryId, normalizedFiles, now) {
|
|
37115
|
+
function recordMemoryMapping(db, memoryId, normalizedFiles, now, mappingOrigin = "mapper") {
|
|
36942
37116
|
const realFiles = uniqueSortedFiles(normalizedFiles);
|
|
36943
37117
|
const filesToWrite = realFiles.length > 0 ? realFiles : [MEMORY_VERIFICATION_SENTINEL];
|
|
36944
37118
|
db.prepare("DELETE FROM memory_verifications WHERE memory_id = ?").run(memoryId);
|
|
36945
|
-
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, ?, ?)");
|
|
36946
37120
|
for (const file2 of filesToWrite) {
|
|
36947
|
-
insert.run(memoryId, file2, now);
|
|
37121
|
+
insert.run(memoryId, file2, now, mappingOrigin);
|
|
36948
37122
|
}
|
|
36949
37123
|
return filesToWrite.length;
|
|
36950
37124
|
}
|
|
@@ -36952,7 +37126,7 @@ function recordMemoryVerifications(db, memoryId, normalizedFiles, now) {
|
|
|
36952
37126
|
const realFiles = uniqueSortedFiles(normalizedFiles);
|
|
36953
37127
|
const filesToWrite = realFiles.length > 0 ? realFiles : [MEMORY_VERIFICATION_SENTINEL];
|
|
36954
37128
|
db.prepare("DELETE FROM memory_verifications WHERE memory_id = ?").run(memoryId);
|
|
36955
|
-
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')");
|
|
36956
37130
|
for (const file2 of filesToWrite) {
|
|
36957
37131
|
insert.run(memoryId, file2, now, now);
|
|
36958
37132
|
}
|
|
@@ -36974,7 +37148,7 @@ function getMemoryVerifications(db, memoryIds) {
|
|
|
36974
37148
|
const result = new Map;
|
|
36975
37149
|
if (ids.length === 0)
|
|
36976
37150
|
return result;
|
|
36977
|
-
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
|
|
36978
37152
|
FROM memory_verifications
|
|
36979
37153
|
WHERE memory_id IN (${placeholders3(ids)})
|
|
36980
37154
|
ORDER BY memory_id, file_path`).all(...ids);
|
|
@@ -36982,6 +37156,7 @@ function getMemoryVerifications(db, memoryIds) {
|
|
|
36982
37156
|
const existing = result.get(row.memory_id) ?? {
|
|
36983
37157
|
files: [],
|
|
36984
37158
|
hasSentinel: false,
|
|
37159
|
+
mappingOrigin: "mapper",
|
|
36985
37160
|
verifiedAt: 0,
|
|
36986
37161
|
mappedAt: 0
|
|
36987
37162
|
};
|
|
@@ -36990,6 +37165,9 @@ function getMemoryVerifications(db, memoryIds) {
|
|
|
36990
37165
|
} else if (!existing.files.includes(row.file_path)) {
|
|
36991
37166
|
existing.files.push(row.file_path);
|
|
36992
37167
|
}
|
|
37168
|
+
if (row.mapping_origin === "host_rejected_fallback") {
|
|
37169
|
+
existing.mappingOrigin = "host_rejected_fallback";
|
|
37170
|
+
}
|
|
36993
37171
|
existing.verifiedAt = Math.max(existing.verifiedAt, row.verified_at);
|
|
36994
37172
|
existing.mappedAt = Math.max(existing.mappedAt, row.mapped_at ?? 0);
|
|
36995
37173
|
result.set(row.memory_id, existing);
|
|
@@ -37709,12 +37887,14 @@ function dropMarkerSummaryTag(db, sessionId, summaryMessageId) {
|
|
|
37709
37887
|
updateTagStatus(db, sessionId, tagNumber, "dropped");
|
|
37710
37888
|
}
|
|
37711
37889
|
function persistMarkerStateAndDropReplacedTag(db, sessionId, state2, replacedSummaryMessageId) {
|
|
37890
|
+
const transactionStartedAt = performance.now();
|
|
37712
37891
|
db.transaction(() => {
|
|
37713
37892
|
setPersistedCompactionMarkerState(db, sessionId, state2);
|
|
37714
37893
|
if (replacedSummaryMessageId !== null) {
|
|
37715
37894
|
dropMarkerSummaryTag(db, sessionId, replacedSummaryMessageId);
|
|
37716
37895
|
}
|
|
37717
37896
|
})();
|
|
37897
|
+
logSlowWriteTransaction("marker-drain", transactionStartedAt);
|
|
37718
37898
|
}
|
|
37719
37899
|
function validatePendingTarget(db, sessionId, pending) {
|
|
37720
37900
|
const ocMessage = getOpenCodeMessageById(sessionId, pending.endMessageId);
|
|
@@ -41366,7 +41546,7 @@ function readCurrentM0SnapshotMarkersUncached(args) {
|
|
|
41366
41546
|
toolSetHash: hard.toolSetHash ?? "",
|
|
41367
41547
|
modelKey: piModelRefToCanonical(hard.modelKey),
|
|
41368
41548
|
projectIdentity: args.projectPath ?? null,
|
|
41369
|
-
muralEnabled: args.muralEnabled === true,
|
|
41549
|
+
muralEnabled: args.memoryEnabled !== false && args.muralEnabled === true,
|
|
41370
41550
|
renderBudgetIdentity: renderBudgetIdentity(args.memoryInjectionBudgetTokens, args.historyBudgetTokens)
|
|
41371
41551
|
}
|
|
41372
41552
|
};
|
|
@@ -41382,7 +41562,7 @@ function refreshVolatileMarkerInputs(markers, args) {
|
|
|
41382
41562
|
toolSetHash: hard.toolSetHash ?? "",
|
|
41383
41563
|
modelKey: hard.modelKey,
|
|
41384
41564
|
projectIdentity: args.projectPath ?? null,
|
|
41385
|
-
muralEnabled: args.muralEnabled === true,
|
|
41565
|
+
muralEnabled: args.memoryEnabled !== false && args.muralEnabled === true,
|
|
41386
41566
|
renderBudgetIdentity: renderBudgetIdentity(args.memoryInjectionBudgetTokens, args.historyBudgetTokens)
|
|
41387
41567
|
};
|
|
41388
41568
|
}
|
|
@@ -41455,6 +41635,10 @@ function snapshotMarkersFromCachedM0(state2) {
|
|
|
41455
41635
|
renderBudgetIdentity: cachedUpgradeIdentity.renderBudgetIdentity
|
|
41456
41636
|
};
|
|
41457
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
|
+
}
|
|
41458
41642
|
function mustMaterialize(args) {
|
|
41459
41643
|
if (!args.state.cachedM0Bytes)
|
|
41460
41644
|
return { value: true, reason: "first_render" };
|
|
@@ -41463,6 +41647,9 @@ function mustMaterialize(args) {
|
|
|
41463
41647
|
const hard = args.hardSignals ?? EMPTY_HARD_SIGNALS;
|
|
41464
41648
|
const current = readCurrentM0SnapshotMarkers(args);
|
|
41465
41649
|
const cachedUpgradeIdentity = decodeCachedM0UpgradeIdentity(args.state.cachedM0UpgradeState);
|
|
41650
|
+
if (args.memoryEnabled === false && cachedMemoryDerivedSurfacePresent(args.state)) {
|
|
41651
|
+
return { value: true, reason: "render_config" };
|
|
41652
|
+
}
|
|
41466
41653
|
if (cachedUpgradeIdentity.compartmentRenderEpoch !== current.compartmentRenderEpoch) {
|
|
41467
41654
|
return { value: true, reason: "compartment_render_epoch" };
|
|
41468
41655
|
}
|
|
@@ -41817,7 +42004,7 @@ function historySliceTokens(m0Text) {
|
|
|
41817
42004
|
return slice ? estimateTokens(slice) : 0;
|
|
41818
42005
|
}
|
|
41819
42006
|
function resolveMuralForM0(options, projectPath, modelKey, budgetTokens) {
|
|
41820
|
-
if (!options.muralEnabled)
|
|
42007
|
+
if (options.memoryEnabled === false || !options.muralEnabled)
|
|
41821
42008
|
return;
|
|
41822
42009
|
return resolveMuralWire(options.db, projectPath, modelKey, true, budgetTokens);
|
|
41823
42010
|
}
|
|
@@ -41852,6 +42039,7 @@ function materializeM0(options) {
|
|
|
41852
42039
|
projectPath,
|
|
41853
42040
|
projectDirectory,
|
|
41854
42041
|
injectDocs: options.injectDocs,
|
|
42042
|
+
memoryEnabled: options.memoryEnabled,
|
|
41855
42043
|
muralEnabled: options.muralEnabled,
|
|
41856
42044
|
memoryInjectionBudgetTokens: options.memoryInjectionBudgetTokens,
|
|
41857
42045
|
historyBudgetTokens: options.historyBudgetTokens,
|
|
@@ -41866,7 +42054,7 @@ function materializeM0(options) {
|
|
|
41866
42054
|
compartments = options.compactionOff ? [] : readM0Compartments(options.db, options.sessionId);
|
|
41867
42055
|
facts = [];
|
|
41868
42056
|
memories = projectPath ? workspace.isWorkspaced ? getMemoriesByProjects(options.db, workspace.expandedIdentities, ["active", "permanent"], foldMaterializedAt, workspace.ownIdentities, workspace.shareCategories) : getMemoriesByProject(options.db, projectPath, ["active", "permanent"], foldMaterializedAt) : [];
|
|
41869
|
-
userMemories = safeGetActiveUserMemories(options.db);
|
|
42057
|
+
userMemories = options.memoryEnabled === false ? [] : safeGetActiveUserMemories(options.db);
|
|
41870
42058
|
options.db.exec("COMMIT");
|
|
41871
42059
|
} catch (error51) {
|
|
41872
42060
|
try {
|
|
@@ -41884,7 +42072,7 @@ function materializeM0(options) {
|
|
|
41884
42072
|
})
|
|
41885
42073
|
};
|
|
41886
42074
|
const trimmed = workspace.isWorkspaced ? trimWorkspaceMemoriesToBudgetV2(options.sessionId, memories, memoryBudget, workspace, memoryRenderOptions) : trimMemoriesToBudgetV2(options.sessionId, memories, memoryBudget);
|
|
41887
|
-
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);
|
|
41888
42076
|
let decayPressureMultiplier = 1;
|
|
41889
42077
|
let m0Text = renderM0({
|
|
41890
42078
|
projectDocs: docs.renderedBlock,
|
|
@@ -42127,7 +42315,7 @@ ${newCompartments.map((compartment) => renderCompartmentAtTier(compartment, 1)).
|
|
|
42127
42315
|
if (newMemoriesBlock)
|
|
42128
42316
|
blocks.push(newMemoriesBlock);
|
|
42129
42317
|
const currentUserProfileVersion = getGlobalUserProfileVersion(options.db);
|
|
42130
|
-
if (currentUserProfileVersion !== markers.projectUserProfileVersion) {
|
|
42318
|
+
if (options.memoryEnabled !== false && currentUserProfileVersion !== markers.projectUserProfileVersion) {
|
|
42131
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");
|
|
42132
42320
|
if (profileBlock)
|
|
42133
42321
|
blocks.push(profileBlock);
|
|
@@ -42345,6 +42533,7 @@ function renderFreshM0NonPersisted(options) {
|
|
|
42345
42533
|
projectPath,
|
|
42346
42534
|
projectDirectory,
|
|
42347
42535
|
injectDocs: options.injectDocs,
|
|
42536
|
+
memoryEnabled: options.memoryEnabled,
|
|
42348
42537
|
muralEnabled: options.muralEnabled,
|
|
42349
42538
|
memoryInjectionBudgetTokens: options.memoryInjectionBudgetTokens,
|
|
42350
42539
|
historyBudgetTokens: options.historyBudgetTokens,
|
|
@@ -42359,7 +42548,7 @@ function renderFreshM0NonPersisted(options) {
|
|
|
42359
42548
|
snapshotMarkers.materializedAt = options.state.cachedM0MaterializedAt ?? 0;
|
|
42360
42549
|
const compartments = options.compactionOff ? [] : withCompartmentDates(options.sessionId, readM0Compartments(options.db, options.sessionId), options.temporalAwareness);
|
|
42361
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) : [];
|
|
42362
|
-
const userMemories = safeGetActiveUserMemories(options.db);
|
|
42551
|
+
const userMemories = options.memoryEnabled === false ? [] : safeGetActiveUserMemories(options.db);
|
|
42363
42552
|
const memoryBudget = options.memoryInjectionBudgetTokens ?? DEFAULT_MEMORY_BUDGET_TOKENS;
|
|
42364
42553
|
const memoryRenderOptions = {
|
|
42365
42554
|
sourceNameByMemoryId: sourceNamesForMemories({
|
|
@@ -42370,7 +42559,7 @@ function renderFreshM0NonPersisted(options) {
|
|
|
42370
42559
|
};
|
|
42371
42560
|
const trimmed = workspace.isWorkspaced ? trimWorkspaceMemoriesToBudgetV2(options.sessionId, memories, memoryBudget, workspace, memoryRenderOptions) : trimMemoriesToBudgetV2(options.sessionId, memories, memoryBudget);
|
|
42372
42561
|
const budget = options.historyBudgetTokens ?? DEFAULT_HISTORY_BUDGET_TOKENS;
|
|
42373
|
-
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);
|
|
42374
42563
|
let decayPressureMultiplier = 1;
|
|
42375
42564
|
let m0Text = renderM0({
|
|
42376
42565
|
projectDocs: docs.renderedBlock,
|
|
@@ -42446,6 +42635,7 @@ function injectM0M1(options) {
|
|
|
42446
42635
|
hardSignals: options.hardSignals,
|
|
42447
42636
|
workspaceIdentitySet: options.workspaceIdentitySet,
|
|
42448
42637
|
injectDocs: options.injectDocs,
|
|
42638
|
+
memoryEnabled: options.memoryEnabled,
|
|
42449
42639
|
muralEnabled: options.muralEnabled,
|
|
42450
42640
|
memoryInjectionBudgetTokens: options.memoryInjectionBudgetTokens,
|
|
42451
42641
|
historyBudgetTokens: options.historyBudgetTokens
|
|
@@ -42777,23 +42967,33 @@ function fenceWrapupBoundaryForToolArcs(args) {
|
|
|
42777
42967
|
return boundary;
|
|
42778
42968
|
}
|
|
42779
42969
|
function applyHeadCap(args) {
|
|
42780
|
-
const {
|
|
42970
|
+
const {
|
|
42971
|
+
index,
|
|
42972
|
+
protectedTailStart,
|
|
42973
|
+
offset,
|
|
42974
|
+
arcs,
|
|
42975
|
+
lastCompartmentEndOrdinal,
|
|
42976
|
+
capTokens,
|
|
42977
|
+
recentOpenArcCutoff
|
|
42978
|
+
} = args;
|
|
42781
42979
|
if (offset >= protectedTailStart)
|
|
42782
42980
|
return { eligibleEndOrdinal: offset, oversizeAtomicUnit: false };
|
|
42783
42981
|
let end = index.findHeadEndForCap(offset, protectedTailStart, capTokens);
|
|
42784
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
|
+
}
|
|
42785
42991
|
for (const arc of arcs) {
|
|
42786
42992
|
const resOrdinal = arc.resOrdinal;
|
|
42787
42993
|
if (resOrdinal === null) {
|
|
42788
42994
|
if (arc.invOrdinal >= recentOpenArcCutoff && arc.invOrdinal >= offset && arc.invOrdinal < end) {
|
|
42789
42995
|
end = Math.min(end, arc.invOrdinal);
|
|
42790
42996
|
}
|
|
42791
|
-
continue;
|
|
42792
|
-
}
|
|
42793
|
-
if (arc.invOrdinal < end && end <= resOrdinal) {
|
|
42794
|
-
end = Math.min(protectedTailStart, resOrdinal + 1);
|
|
42795
|
-
if (index.rangeTokens(Math.max(offset, arc.invOrdinal), end) > capTokens)
|
|
42796
|
-
oversizeAtomicUnit = true;
|
|
42797
42997
|
}
|
|
42798
42998
|
}
|
|
42799
42999
|
if (end <= offset && offset < protectedTailStart) {
|
|
@@ -45200,9 +45400,9 @@ async function runCompartmentAgent(deps) {
|
|
|
45200
45400
|
executeThresholdPercentage: boundarySnapshot.executeThresholdPercentage
|
|
45201
45401
|
});
|
|
45202
45402
|
if (!reserve.ok) {
|
|
45203
|
-
sessionLog(sessionId,
|
|
45403
|
+
sessionLog(sessionId, describeProtectedTailDrainBudgetSkip(reserve));
|
|
45204
45404
|
telemetry.status = "noop";
|
|
45205
|
-
telemetry.failureReason = "protected-tail drain
|
|
45405
|
+
telemetry.failureReason = "internal protected-tail drain budget spent";
|
|
45206
45406
|
return;
|
|
45207
45407
|
}
|
|
45208
45408
|
drainReservation = reserve.reservation;
|
|
@@ -45334,6 +45534,7 @@ ${chunkText}`,
|
|
|
45334
45534
|
return;
|
|
45335
45535
|
}
|
|
45336
45536
|
let published = false;
|
|
45537
|
+
const transactionStartedAt = performance.now();
|
|
45337
45538
|
db.exec("BEGIN IMMEDIATE");
|
|
45338
45539
|
try {
|
|
45339
45540
|
if (!isCompartmentLeaseHeld(db, sessionId, holderId)) {
|
|
@@ -45380,6 +45581,7 @@ ${chunkText}`,
|
|
|
45380
45581
|
}
|
|
45381
45582
|
db.exec("COMMIT");
|
|
45382
45583
|
published = true;
|
|
45584
|
+
logSlowWriteTransaction("historian-publish", transactionStartedAt);
|
|
45383
45585
|
} finally {
|
|
45384
45586
|
if (!published) {
|
|
45385
45587
|
try {
|
|
@@ -45518,6 +45720,7 @@ function insertRecompCompartmentRows(db, sessionId, compartments, now) {
|
|
|
45518
45720
|
}
|
|
45519
45721
|
function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
|
|
45520
45722
|
const now = Date.now();
|
|
45723
|
+
const transactionStartedAt = performance.now();
|
|
45521
45724
|
db.exec("BEGIN IMMEDIATE");
|
|
45522
45725
|
let finished = false;
|
|
45523
45726
|
try {
|
|
@@ -45546,6 +45749,7 @@ function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
|
|
|
45546
45749
|
clearCachedM0M1(db, sessionId);
|
|
45547
45750
|
db.exec("COMMIT");
|
|
45548
45751
|
finished = true;
|
|
45752
|
+
logSlowWriteTransaction("historian-publish:recomp", transactionStartedAt);
|
|
45549
45753
|
return { compartments: staging.compartments, facts: staging.facts };
|
|
45550
45754
|
} finally {
|
|
45551
45755
|
if (!finished) {
|
|
@@ -46885,4 +47089,4 @@ async function runUpgradeMemoryMigration(ctx, sessionId, migrationDirectory) {
|
|
|
46885
47089
|
}
|
|
46886
47090
|
}
|
|
46887
47091
|
|
|
46888
|
-
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 };
|