@cortexkit/opencode-magic-context 0.49.91 → 0.49.93
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auto-search-worker.js +3 -3
- package/dist/chunk-embedding-write-worker.js +2 -2
- package/dist/{conflict-warning-hook-kbq6ppjf.js → conflict-warning-hook-exf96bpt.js} +3 -3
- package/dist/{context-6qq5e1ry.js → context-jpxthqxg.js} +98 -77
- package/dist/{embedding-backfill-w0yq71q2.js → embedding-backfill-6wzc4p2n.js} +4 -4
- package/dist/embedding-worker.js +2 -2
- package/dist/features/magic-context/memory/embedding-local.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-worker-client.d.ts +3 -0
- package/dist/features/magic-context/memory/embedding-worker-client.d.ts.map +1 -1
- package/dist/features/magic-context/overflow-detection.d.ts +7 -1
- package/dist/features/magic-context/overflow-detection.d.ts.map +1 -1
- package/dist/features/magic-context/storage-meta-persisted.d.ts +13 -3
- package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
- package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-parser.d.ts +2 -0
- package/dist/hooks/magic-context/compartment-parser.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-types.d.ts +5 -5
- package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-validation.d.ts +3 -0
- package/dist/hooks/magic-context/compartment-runner-validation.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-trigger.d.ts +2 -1
- package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
- package/dist/hooks/magic-context/event-handler.d.ts +4 -0
- package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
- package/dist/hooks/magic-context/event-resolvers.d.ts +5 -0
- package/dist/hooks/magic-context/event-resolvers.d.ts.map +1 -1
- package/dist/hooks/magic-context/historian-drain-gate.d.ts +15 -0
- package/dist/hooks/magic-context/historian-drain-gate.d.ts.map +1 -1
- package/dist/hooks/magic-context/historian-prompt.generated.d.ts +1 -1
- package/dist/hooks/magic-context/historian-prompt.generated.d.ts.map +1 -1
- package/dist/hooks/magic-context/historian-publish-stage-logger.d.ts +5 -0
- package/dist/hooks/magic-context/historian-publish-stage-logger.d.ts.map +1 -1
- package/dist/hooks/magic-context/hook.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-measured-request.d.ts +1 -0
- package/dist/hooks/magic-context/lkg-measured-request.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-persist.d.ts.map +1 -1
- package/dist/hooks/magic-context/lkg-replay.d.ts +1 -0
- package/dist/hooks/magic-context/lkg-replay.d.ts.map +1 -1
- package/dist/hooks/magic-context/provider-overflow-notice.d.ts +8 -0
- package/dist/hooks/magic-context/provider-overflow-notice.d.ts.map +1 -0
- package/dist/hooks/magic-context/read-session-db.d.ts +2 -0
- package/dist/hooks/magic-context/read-session-db.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts +5 -0
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/{index-czz0w2c4.js → index-01h7tqe3.js} +11 -0
- package/dist/{index-r6r2eh90.js → index-1kem0xxx.js} +4 -4
- package/dist/{index-f25ha337.js → index-5zrzg8r1.js} +1 -1
- package/dist/{index-6zewd2n5.js → index-9ffntwyr.js} +1 -1
- package/dist/{index-mq97qmb8.js → index-dr6bd4c8.js} +3 -3
- package/dist/{index-83qd3n7s.js → index-et39x9k3.js} +1 -1
- package/dist/{index-nmkv8yvs.js → index-fpjnjxyx.js} +2 -2
- package/dist/{index-ran2b3fn.js → index-g5c67kay.js} +75 -67
- package/dist/{index-7rgnh11t.js → index-g6y2wk32.js} +5 -5
- package/dist/{index-e8my7q6m.js → index-g9qtxv87.js} +8 -8
- package/dist/{index-5wgdbj2h.js → index-gqfy38m9.js} +2 -2
- package/dist/{index-3yw525kb.js → index-hee64h6k.js} +6 -6
- package/dist/{index-xn9efn18.js → index-hes3k87g.js} +12 -5
- package/dist/{index-sr8dmp7p.js → index-j2w79s9r.js} +76 -6
- package/dist/{index-qna2ra0s.js → index-jba6ny4m.js} +27 -3
- package/dist/{index-dva352qe.js → index-kty5k23y.js} +1 -1
- package/dist/{index-ywgv1xcb.js → index-mjy2k9jr.js} +1 -1
- package/dist/{index-3n376ann.js → index-n9kd68vc.js} +2 -2
- package/dist/{index-capcna4r.js → index-pnawfv4e.js} +1 -1
- package/dist/{index-6t7jvp76.js → index-rz47hf2m.js} +3 -3
- package/dist/{index-x40zr813.js → index-sp5pvs95.js} +9 -1
- package/dist/{index-ydhymf0b.js → index-ttdk2w0z.js} +3 -3
- package/dist/{index-gqhebzxx.js → index-xr1t0fxb.js} +90 -25
- package/dist/{index-m6vhxsce.js → index-y2vshk67.js} +92 -70
- package/dist/{index-6nqz8hsz.js → index-y915t3ey.js} +1 -1
- package/dist/{index-wfahebsc.js → index-yqha238s.js} +47 -26
- package/dist/{index-febyth5n.js → index-za1yx1m4.js} +1375 -1310
- package/dist/index.js +83 -46
- package/dist/{message-index-bounded-wvnp6fcp.js → message-index-bounded-vjrnptar.js} +5 -5
- package/dist/migration-worker.js +2 -2
- package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
- package/dist/{project-embedding-registry-8je0xg18.js → project-embedding-registry-m8zcmrsg.js} +3 -3
- package/dist/raw-ordinal-warmup-worker.js +4 -4
- package/dist/{read-session-chunk-j4hjc1pk.js → read-session-chunk-zkzdc0e5.js} +4 -4
- package/dist/{recomp-orchestrator-ps1c8c5h.js → recomp-orchestrator-qb2hymj5.js} +17 -17
- package/dist/{render-nfj7280n.js → render-34p0kek8.js} +11 -11
- package/dist/{search-archive-1etwnve4.js → search-archive-08ppk0q5.js} +6 -6
- package/dist/{search-3r8b0jfa.js → search-e9bb9hpx.js} +13 -13
- package/dist/{send-session-notification-gzxz88vq.js → send-session-notification-0779tyd9.js} +2 -2
- package/dist/{storage-tags-nh2ftqhx.js → storage-tags-gk7gjkqt.js} +2 -2
- package/dist/{store-reader-a2v34xnh.js → store-reader-qbq6q4v0.js} +1 -1
- package/dist/{store-019k3ek7.js → store-yr443ye8.js} +2 -2
- package/dist/{transform-postprocess-phase-tqp968w4.js → transform-postprocess-phase-neds90e3.js} +18 -18
- package/dist/v2/auto-search-worker.js +3 -3
- package/dist/v2/chunk-embedding-write-worker.js +2 -2
- package/dist/v2/{context-d57v8c10.js → context-ctsd80vc.js} +168 -121
- package/dist/v2/{embedding-backfill-95m72gxa.js → embedding-backfill-40g0anxh.js} +4 -4
- package/dist/v2/embedding-worker.js +2 -2
- package/dist/v2/fold/host-media.d.ts.map +1 -1
- package/dist/v2/fold/native-replay.d.ts +1 -0
- package/dist/v2/fold/native-replay.d.ts.map +1 -1
- package/dist/v2/fold/restore.d.ts +15 -0
- package/dist/v2/fold/restore.d.ts.map +1 -1
- package/dist/v2/hidden-child-native.d.ts.map +1 -1
- package/dist/v2/hidden-run-holder.d.ts +4 -4
- package/dist/v2/hooks/overflow-recovery.d.ts +6 -0
- package/dist/v2/hooks/overflow-recovery.d.ts.map +1 -1
- package/dist/v2/{message-index-bounded-2nhbwry6.js → message-index-bounded-1vew9c37.js} +5 -5
- package/dist/v2/migration-worker.js +2 -2
- package/dist/v2/{project-embedding-registry-fcxf4qht.js → project-embedding-registry-je5jam7y.js} +3 -3
- package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
- package/dist/v2/{read-session-chunk-jrrhwxgx.js → read-session-chunk-09sre4xv.js} +4 -4
- package/dist/v2/{recomp-orchestrator-n79hdd7n.js → recomp-orchestrator-mgcty3we.js} +17 -17
- package/dist/v2/{render-7emcjdt1.js → render-ygcmyn9x.js} +11 -11
- package/dist/v2/{search-archive-fpjbmxcx.js → search-archive-nrsqqmk5.js} +6 -6
- package/dist/v2/{search-vz2cpgr0.js → search-gmye6n25.js} +12 -12
- package/dist/v2/{send-session-notification-zazaxxpf.js → send-session-notification-v69y04f5.js} +2 -2
- package/dist/v2/{server-vsqmkvxc.js → server-00adcfjd.js} +1 -1
- package/dist/v2/{server-kwsqytwj.js → server-2xm0gxke.js} +1 -1
- package/dist/v2/{server-r4816kwv.js → server-4ecpanyn.js} +47 -26
- package/dist/v2/{server-7e89a2kf.js → server-6chcnnhq.js} +12 -5
- package/dist/v2/{server-hgfd6c3e.js → server-6x40bnb7.js} +2 -2
- package/dist/v2/{server-vfa7byfa.js → server-bnkc9kph.js} +5 -5
- package/dist/v2/{server-n431vzn5.js → server-btgnkr9z.js} +2 -2
- package/dist/v2/{server-4axv6kq6.js → server-cvp9w5gs.js} +1375 -1310
- package/dist/v2/{server-4bfk1sky.js → server-dgsjamm4.js} +3 -3
- package/dist/v2/{server-rz6g5xne.js → server-e6xneh68.js} +1 -1
- package/dist/v2/{server-q2ap5cty.js → server-g53asaqt.js} +3 -3
- package/dist/v2/{server-6250cxzs.js → server-gs2251jr.js} +1 -1
- package/dist/v2/{server-8r32etq0.js → server-jkj1dq6j.js} +27 -3
- package/dist/v2/{server-b4efn08m.js → server-k1xc2bw1.js} +1 -1
- package/dist/v2/{server-3z8rhacq.js → server-myp4pc6x.js} +7 -7
- package/dist/v2/{server-72k2r3kt.js → server-pcarsvj2.js} +2 -2
- package/dist/v2/{server-0h875f56.js → server-rkj44mez.js} +76 -6
- package/dist/v2/{server-8ps3717t.js → server-vc5fta6s.js} +3 -3
- package/dist/v2/{server-j9cm1czj.js → server-vtgeyhq6.js} +11 -0
- package/dist/v2/{server-xmgvy3cq.js → server-x69fqsvz.js} +1 -1
- package/dist/v2/{server-q104czn6.js → server-z9czv2vb.js} +90 -25
- package/dist/v2/server.js +4 -4
- package/dist/v2/{storage-tags-t0f9njdp.js → storage-tags-nccqr0kr.js} +2 -2
- package/dist/v2/{store-q3ef5rvz.js → store-enef5jcn.js} +2 -2
- package/dist/v2/{store-reader-wc01y2rc.js → store-reader-jbaqv1yp.js} +1 -1
- package/dist/v2/store-reader.d.ts +16 -0
- package/dist/v2/store-reader.d.ts.map +1 -1
- package/dist/v2/{v2-archive-reader-9p84yzk5.js → v2-archive-reader-7vmng8q7.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-acebazx8.js → wrapup-orchestrator-7r4y0bf6.js} +17 -17
- package/dist/{v2-archive-reader-w1bbaqe8.js → v2-archive-reader-7s90gfax.js} +1 -1
- package/dist/{wrapup-orchestrator-fwbe0mvm.js → wrapup-orchestrator-m2p89973.js} +18 -18
- package/package.json +1 -1
- package/src/config/schema/magic-context.ts +1 -1
- package/src/shared/models-dev-cache.test.ts +15 -0
- /package/dist/v2/{server-3ap5dmhc.js → server-5hwf5c7r.js} +0 -0
|
@@ -35,7 +35,7 @@ import {
|
|
|
35
35
|
getRawSessionTagKeysThrough2,
|
|
36
36
|
getLegacyProtectedTailStartOrdinal2,
|
|
37
37
|
readSessionChunk2
|
|
38
|
-
} from "./index-
|
|
38
|
+
} from "./index-dr6bd4c8.js";
|
|
39
39
|
import {
|
|
40
40
|
getHarness2,
|
|
41
41
|
harnessOwnsOpenCodeStore2
|
|
@@ -93,7 +93,7 @@ import {
|
|
|
93
93
|
ConfigProfilesSchema,
|
|
94
94
|
MagicContextConfigSchema,
|
|
95
95
|
LIVE_RELOAD_CONFIG_PATHS
|
|
96
|
-
} from "./index-
|
|
96
|
+
} from "./index-y915t3ey.js";
|
|
97
97
|
import {
|
|
98
98
|
providerMass,
|
|
99
99
|
calibrationForModelKey,
|
|
@@ -123,7 +123,7 @@ import {
|
|
|
123
123
|
LATEST_SUPPORTED_VERSION,
|
|
124
124
|
getPersistedSchemaVersion,
|
|
125
125
|
openDatabase
|
|
126
|
-
} from "./index-
|
|
126
|
+
} from "./index-gqfy38m9.js";
|
|
127
127
|
import {
|
|
128
128
|
areRustHistorianSyntheticParts2,
|
|
129
129
|
isStrictGapHealingMessage2,
|
|
@@ -140,7 +140,7 @@ import {
|
|
|
140
140
|
resolveStoredPathWorkspaceIdentity,
|
|
141
141
|
sourceNameForMemory,
|
|
142
142
|
computeWorkspaceEpochFingerprint
|
|
143
|
-
} from "./index-
|
|
143
|
+
} from "./index-jba6ny4m.js";
|
|
144
144
|
import {
|
|
145
145
|
BoundedSessionMap
|
|
146
146
|
} from "./index-mg9s2rc3.js";
|
|
@@ -212,14 +212,14 @@ import {
|
|
|
212
212
|
getProjectState,
|
|
213
213
|
recordSubagentInvocation,
|
|
214
214
|
getLatestHistorianInvocationId
|
|
215
|
-
} from "./index-
|
|
215
|
+
} from "./index-yqha238s.js";
|
|
216
216
|
import {
|
|
217
217
|
clearCompressionDepth,
|
|
218
218
|
clearCompressionDepthRange,
|
|
219
219
|
toMessageIndexSource,
|
|
220
220
|
clearIndexedMessagesInTransaction,
|
|
221
221
|
indexSourcesAfterOrdinal
|
|
222
|
-
} from "./index-
|
|
222
|
+
} from "./index-pnawfv4e.js";
|
|
223
223
|
import {
|
|
224
224
|
stripWellFormedLeadingTagPrefix,
|
|
225
225
|
peelLeadingMcTagNotation,
|
|
@@ -237,6 +237,7 @@ import {
|
|
|
237
237
|
recordProtectedTailPublicationFloor,
|
|
238
238
|
recordProtectedTailNoEligibleHead,
|
|
239
239
|
isWrapupInProgress,
|
|
240
|
+
getProtectedTailDrainBudgetSkip,
|
|
240
241
|
reserveProtectedTailDrainTokens,
|
|
241
242
|
clearEmergencyDrainLatch,
|
|
242
243
|
recordHistorianDrainFailure,
|
|
@@ -269,17 +270,17 @@ import {
|
|
|
269
270
|
foldShrunkPartTags2,
|
|
270
271
|
getTagNumberByMessageId2,
|
|
271
272
|
getActiveTagsBySession2
|
|
272
|
-
} from "./index-
|
|
273
|
+
} from "./index-xr1t0fxb.js";
|
|
273
274
|
import {
|
|
274
275
|
openCodeDbExists,
|
|
275
276
|
withReadOnlySessionDb,
|
|
276
277
|
getMessageTimesFromOpenCodeDb
|
|
277
|
-
} from "./index-
|
|
278
|
+
} from "./index-sp5pvs95.js";
|
|
278
279
|
import {
|
|
279
280
|
getSessionNotes,
|
|
280
281
|
getReadySmartNotes,
|
|
281
282
|
insertPrimerCandidates
|
|
282
|
-
} from "./index-
|
|
283
|
+
} from "./index-mjy2k9jr.js";
|
|
283
284
|
import {
|
|
284
285
|
pushNotification2
|
|
285
286
|
} from "./index-y14pawe1.js";
|
|
@@ -297,13 +298,13 @@ import {
|
|
|
297
298
|
getProjectChunkEmbeddingModelId2,
|
|
298
299
|
getProjectEmbeddingMaxInputTokens2,
|
|
299
300
|
embedItemsWindowBounded2
|
|
300
|
-
} from "./index-
|
|
301
|
+
} from "./index-n9kd68vc.js";
|
|
301
302
|
import {
|
|
302
303
|
renderUserFacingFailure,
|
|
303
304
|
userFacingFailureCode,
|
|
304
305
|
promoteSessionFactsDurable,
|
|
305
306
|
embedPromotedFacts
|
|
306
|
-
} from "./index-
|
|
307
|
+
} from "./index-ttdk2w0z.js";
|
|
307
308
|
import {
|
|
308
309
|
isMarkerCandidateBasisCurrent2,
|
|
309
310
|
invalidateMarkerCandidateBasis2,
|
|
@@ -317,7 +318,7 @@ import {
|
|
|
317
318
|
} from "./index-832w615x.js";
|
|
318
319
|
import {
|
|
319
320
|
sendStatusNotification2
|
|
320
|
-
} from "./index-
|
|
321
|
+
} from "./index-9ffntwyr.js";
|
|
321
322
|
import {
|
|
322
323
|
retreatPastHostUnservedRows,
|
|
323
324
|
snapTerminalCompartmentToServedRow,
|
|
@@ -3888,6 +3889,10 @@ Facts capture stable properties of the project that survive past any single comp
|
|
|
3888
3889
|
- One fact bullet = exactly one rule/default/constraint/decision/name.
|
|
3889
3890
|
- If a new fact contradicts a \`<project_memory>\` entry, emit the new fact as you observe it. **Do not write "X was Y but now Z" framing — the dreamer handles contradiction resolution.** Your job is to report what is true in this chunk; the dreamer reconciles.
|
|
3890
3891
|
|
|
3892
|
+
Prefix every <facts> bullet with the compartment it came from: \`* [at_compartment=N] Fact text\`.
|
|
3893
|
+
- N is the 1-based index of the compartment above that the fact came from (the same convention as events).
|
|
3894
|
+
- When you can't tell which compartment, write \`* [at_compartment=unknown] Fact text\`. Never guess.
|
|
3895
|
+
|
|
3891
3896
|
### The 5 categories
|
|
3892
3897
|
|
|
3893
3898
|
Each statement maps to exactly one category. If a statement seems to fit two categories, you have not understood it sharply enough — re-read it and pick the category that captures the durable signal.
|
|
@@ -4203,19 +4208,19 @@ Closing tags must match their opening tier tag (e.g. \`<p1>...</p1>\`, never \`<
|
|
|
4203
4208
|
</compartments>
|
|
4204
4209
|
<facts>
|
|
4205
4210
|
<PROJECT_RULES>
|
|
4206
|
-
* Fact text
|
|
4211
|
+
* [at_compartment=N] Fact text
|
|
4207
4212
|
</PROJECT_RULES>
|
|
4208
4213
|
<ARCHITECTURE>
|
|
4209
|
-
* Fact text
|
|
4214
|
+
* [at_compartment=N] Fact text
|
|
4210
4215
|
</ARCHITECTURE>
|
|
4211
4216
|
<CONSTRAINTS>
|
|
4212
|
-
* Fact text
|
|
4217
|
+
* [at_compartment=N] Fact text
|
|
4213
4218
|
</CONSTRAINTS>
|
|
4214
4219
|
<CONFIG_VALUES>
|
|
4215
|
-
* Fact text
|
|
4220
|
+
* [at_compartment=N] Fact text
|
|
4216
4221
|
</CONFIG_VALUES>
|
|
4217
4222
|
<NAMING>
|
|
4218
|
-
* Fact text
|
|
4223
|
+
* [at_compartment=N] Fact text
|
|
4219
4224
|
</NAMING>
|
|
4220
4225
|
</facts>
|
|
4221
4226
|
<events>
|
|
@@ -4747,7 +4752,7 @@ function isHiddenRunHolder(id) {
|
|
|
4747
4752
|
return id.startsWith(HOLDER_PREFIX);
|
|
4748
4753
|
}
|
|
4749
4754
|
function supportsQuietHiddenChildren(version) {
|
|
4750
|
-
return
|
|
4755
|
+
return version !== "2.3.0";
|
|
4751
4756
|
}
|
|
4752
4757
|
function matchesHiddenRunLocation(wanted, returned) {
|
|
4753
4758
|
return sameProjectDirectory(wanted, returned ?? "");
|
|
@@ -6933,6 +6938,9 @@ function mapParsedCompartmentsToChunk(compartments, chunk, sequenceOffset) {
|
|
|
6933
6938
|
}
|
|
6934
6939
|
|
|
6935
6940
|
// src/hooks/magic-context/historian-publish-stage-logger.ts
|
|
6941
|
+
function logWeakTailFactPromotion(sessionId, promotion) {
|
|
6942
|
+
sessionLog2(sessionId, `historian weak-tail fact promotion: reason=${promotion.reason} facts_stored=${promotion.stored} facts_not_stored=${promotion.emitted - promotion.stored}`);
|
|
6943
|
+
}
|
|
6936
6944
|
function startHistorianPublishStage(sessionId, stage, extra) {
|
|
6937
6945
|
const suffix = extra ? ` ${extra}` : "";
|
|
6938
6946
|
sessionLog2(sessionId, `historian publish stage: stage=${stage} status=started elapsed=0.0ms${suffix}`);
|
|
@@ -6992,6 +7000,9 @@ function shouldDiscardLastHistorianCompartment(compartments, chunk) {
|
|
|
6992
7000
|
const lookaheadMargin = chunk.endIndex - last.endMessage;
|
|
6993
7001
|
return lookaheadMargin <= HISTORIAN_BOUNDARY_HEALING_SLACK && !boundarySplitsCompletedToolArc(previous.endMessage + 1, chunk.completedToolArcs);
|
|
6994
7002
|
}
|
|
7003
|
+
function retainAnchoredHistorianFacts(facts, trustedCount) {
|
|
7004
|
+
return facts.filter(({ originCompartmentIndex }) => originCompartmentIndex !== undefined && originCompartmentIndex >= 1 && originCompartmentIndex <= trustedCount);
|
|
7005
|
+
}
|
|
6995
7006
|
function validateHistorianOutput(text, sessionId, chunk, _priorCompartments, sequenceOffset) {
|
|
6996
7007
|
const parseStarted = startHistorianPublishStage(sessionId, "parse", `response_chars=${text.length}`);
|
|
6997
7008
|
const parsed = parseCompartmentOutput(text);
|
|
@@ -12840,21 +12851,21 @@ Acorn Suite made JWT tenant_id the single tenant authority across REST, GraphQL,
|
|
|
12840
12851
|
</compartment>
|
|
12841
12852
|
<facts>
|
|
12842
12853
|
<PROJECT_RULES>
|
|
12843
|
-
* All tenant-scoped Acorn Suite handlers must call requireTenantContext(req) and fail closed; do not recover missing tenant_id from orgSlug or X-Org-Slug.
|
|
12844
|
-
* Acorn Suite auth changes must include both REST and GraphQL tenant-boundary tests before merge.
|
|
12854
|
+
* [at_compartment=1] All tenant-scoped Acorn Suite handlers must call requireTenantContext(req) and fail closed; do not recover missing tenant_id from orgSlug or X-Org-Slug.
|
|
12855
|
+
* [at_compartment=1] Acorn Suite auth changes must include both REST and GraphQL tenant-boundary tests before merge.
|
|
12845
12856
|
</PROJECT_RULES>
|
|
12846
12857
|
<ARCHITECTURE>
|
|
12847
|
-
* Acorn Suite uses JWT tenant_id as the single tenant authority so REST, GraphQL, and Prisma filters share one isolation model.
|
|
12848
|
-
* Platform support bypass is modeled as a service actor, not as a tenant wildcard.
|
|
12858
|
+
* [at_compartment=1] Acorn Suite uses JWT tenant_id as the single tenant authority so REST, GraphQL, and Prisma filters share one isolation model.
|
|
12859
|
+
* [at_compartment=1] Platform support bypass is modeled as a service actor, not as a tenant wildcard.
|
|
12849
12860
|
</ARCHITECTURE>
|
|
12850
12861
|
<CONSTRAINTS>
|
|
12851
|
-
* X-Org-Slug and route orgSlug are presentation hints only; using them as tenant authority can produce cross-tenant reads when cached dashboard URLs are stale.
|
|
12862
|
+
* [at_compartment=1] X-Org-Slug and route orgSlug are presentation hints only; using them as tenant authority can produce cross-tenant reads when cached dashboard URLs are stale.
|
|
12852
12863
|
</CONSTRAINTS>
|
|
12853
12864
|
<CONFIG_VALUES>
|
|
12854
|
-
* Acorn Suite tenant-boundary fixtures live under apps/api/test/tenant-boundary/ and use seed tenants acme_lab and beta_works.
|
|
12865
|
+
* [at_compartment=1] Acorn Suite tenant-boundary fixtures live under apps/api/test/tenant-boundary/ and use seed tenants acme_lab and beta_works.
|
|
12855
12866
|
</CONFIG_VALUES>
|
|
12856
12867
|
<NAMING>
|
|
12857
|
-
* The shared auth helper is named requireTenantContext; "resolveTenantMaybe" was rejected because it implied fallback behavior.
|
|
12868
|
+
* [at_compartment=1] The shared auth helper is named requireTenantContext; "resolveTenantMaybe" was rejected because it implied fallback behavior.
|
|
12858
12869
|
</NAMING>
|
|
12859
12870
|
</facts>
|
|
12860
12871
|
<events>
|
|
@@ -12901,19 +12912,19 @@ OpLog; SnapshotCache; vector_clock; max_ops_before_compact=10000; crates/chorus-
|
|
|
12901
12912
|
</compartment>
|
|
12902
12913
|
<facts>
|
|
12903
12914
|
<ARCHITECTURE>
|
|
12904
|
-
* Chorus document state is defined by the op log in causal order (vector clocks); materialized snapshots are derived-on-read cache entries, not the source of truth.
|
|
12915
|
+
* [at_compartment=7] Chorus document state is defined by the op log in causal order (vector clocks); materialized snapshots are derived-on-read cache entries, not the source of truth.
|
|
12905
12916
|
</ARCHITECTURE>
|
|
12906
12917
|
<CONSTRAINTS>
|
|
12907
|
-
* Chorus SnapshotCache invalidation must be synchronous on new op arrival; async invalidation causes stale reads visible to concurrent editing clients (observed: up to 200 ms staleness in async prototype).
|
|
12918
|
+
* [at_compartment=7] Chorus SnapshotCache invalidation must be synchronous on new op arrival; async invalidation causes stale reads visible to concurrent editing clients (observed: up to 200 ms staleness in async prototype).
|
|
12908
12919
|
</CONSTRAINTS>
|
|
12909
12920
|
<PROJECT_RULES>
|
|
12910
|
-
* Never mutate a Chorus materialized snapshot directly; always append an op to the log and re-derive the snapshot.
|
|
12921
|
+
* [at_compartment=7] Never mutate a Chorus materialized snapshot directly; always append an op to the log and re-derive the snapshot.
|
|
12911
12922
|
</PROJECT_RULES>
|
|
12912
12923
|
<NAMING>
|
|
12913
|
-
* Chorus core types: OpLog (crates/chorus-core/src/log.rs), SnapshotCache (crates/chorus-core/src/snapshot.rs).
|
|
12924
|
+
* [at_compartment=7] Chorus core types: OpLog (crates/chorus-core/src/log.rs), SnapshotCache (crates/chorus-core/src/snapshot.rs).
|
|
12914
12925
|
</NAMING>
|
|
12915
12926
|
<CONFIG_VALUES>
|
|
12916
|
-
* Chorus compaction threshold: max_ops_before_compact=10000 per document.
|
|
12927
|
+
* [at_compartment=7] Chorus compaction threshold: max_ops_before_compact=10000 per document.
|
|
12917
12928
|
</CONFIG_VALUES>
|
|
12918
12929
|
</facts>
|
|
12919
12930
|
<events>
|
|
@@ -12956,28 +12967,28 @@ The durable decision was to allow standby replicas to do read-heavy reconcile wo
|
|
|
12956
12967
|
</compartment>
|
|
12957
12968
|
<facts>
|
|
12958
12969
|
<PROJECT_RULES>
|
|
12959
|
-
* Reconciler code may compute desired state before lease acquisition, but every status or finalizer write must pass through LeaseGuard.
|
|
12960
|
-
* Any new cleanup step must be idempotent across repeated reconcile loops before it is attached to finalizer removal.
|
|
12970
|
+
* [at_compartment=1] Reconciler code may compute desired state before lease acquisition, but every status or finalizer write must pass through LeaseGuard.
|
|
12971
|
+
* [at_compartment=1] Any new cleanup step must be idempotent across repeated reconcile loops before it is attached to finalizer removal.
|
|
12961
12972
|
</PROJECT_RULES>
|
|
12962
12973
|
<ARCHITECTURE>
|
|
12963
|
-
* The controller is split into observe, plan, and commit so standby replicas can do expensive reads without risking conflicting writes.
|
|
12964
|
-
* Status carries an observedPlan hash so downstream tools can detect desired-versus-applied drift without diffing child resources.
|
|
12974
|
+
* [at_compartment=1] The controller is split into observe, plan, and commit so standby replicas can do expensive reads without risking conflicting writes.
|
|
12975
|
+
* [at_compartment=1] Status carries an observedPlan hash so downstream tools can detect desired-versus-applied drift without diffing child resources.
|
|
12965
12976
|
</ARCHITECTURE>
|
|
12966
12977
|
<CONSTRAINTS>
|
|
12967
|
-
* In a multi-control-plane cluster, standby reconciles can race with the active leader; unrestricted status writes make object health lie even when spec is unchanged.
|
|
12978
|
+
* [at_compartment=1] In a multi-control-plane cluster, standby reconciles can race with the active leader; unrestricted status writes make object health lie even when spec is unchanged.
|
|
12968
12979
|
</CONSTRAINTS>
|
|
12969
12980
|
<CONFIG_VALUES>
|
|
12970
|
-
* Leader election lease name: workspacemesh-controller-lock.
|
|
12971
|
-
* Drift hash status field: status.observedPlan.
|
|
12981
|
+
* [at_compartment=1] Leader election lease name: workspacemesh-controller-lock.
|
|
12982
|
+
* [at_compartment=1] Drift hash status field: status.observedPlan.
|
|
12972
12983
|
</CONFIG_VALUES>
|
|
12973
12984
|
<NAMING>
|
|
12974
|
-
* The controller write gate wrapper is named LeaseGuard.
|
|
12985
|
+
* [at_compartment=1] The controller write gate wrapper is named LeaseGuard.
|
|
12975
12986
|
</NAMING>
|
|
12976
12987
|
</facts>`
|
|
12977
12988
|
},
|
|
12978
12989
|
{
|
|
12979
12990
|
importance: 94,
|
|
12980
|
-
block: '<compartment start="415" end="612" title="Tenant isolation: chose Postgres RLS over schema-per-tenant" episode_type="design" importance="94">\n<p1>\nWorked through the tenant isolation model for the new control plane. Three candidates on the table: (a) schema-per-tenant with `search_path` switching, (b) database-per-tenant, (c) shared schema with Postgres Row-Level Security policies keyed on `tenant_id`. Spent the morning sketching how each interacts with our migration tooling, connection pooling (pgbouncer in transaction mode), and the analytics replica.\n\nU: I keep getting pulled toward schema-per-tenant because it feels "more isolated" but I want to be talked out of it if RLS holds up\n\nSchema-per-tenant blows up under pgbouncer transaction-pooling — `SET search_path` is session-state and gets lost between transactions; the per-tenant search_path either has to be set on every transaction (expensive, race-prone) or we drop pgbouncer (kills our connection economy). Database-per-tenant solves isolation cleanly but our migration tooling (sqlx) doesn\'t have a clean fan-out story and we\'d need to build one. Also onboarding latency goes from ~50ms to ~30s because we\'d need to provision a DB.\n\nLanded on RLS. Every tenant-scoped table gets `tenant_id uuid not null`, an `ENABLE ROW LEVEL SECURITY` declaration, and a policy `USING (tenant_id = current_setting(\'app.current_tenant\')::uuid)`. The current tenant is set via `SET LOCAL app.current_tenant = \'...\'` at the start of every request transaction — `SET LOCAL` is transaction-scoped so it survives pgbouncer transaction mode cleanly. Wrote a middleware in `internal/db/tenant.go` that wraps every request in a transaction and sets the value.\n\nU: what about the analytics replica, does RLS work the same there\n\nYes — RLS policies replicate via logical replication; the analytics service connects with a separate role that also has RLS enforced. The escape hatch for cross-tenant analytics is a dedicated `analytics_admin` role with `BYPASSRLS`, used only by the scheduled aggregation job, never by interactive code paths.\n\nU: ok and write down that if anyone ever calls SET ROLE to escape RLS in app code i\'m going to lose my mind\n\nDocumented. Added a lint rule in `tools/sqllint/` that flags `SET ROLE`, `BYPASSRLS`, and unqualified table access in `internal/handlers/`.\n</p1>\n<p2>\nTenant isolation decision: Postgres RLS keyed on `tenant_id`, set per-transaction via `SET LOCAL app.current_tenant`. Rejected schema-per-tenant (breaks pgbouncer transaction mode) and database-per-tenant (sqlx migration fan-out cost + 30s onboarding latency). Analytics uses a separate role with BYPASSRLS for the scheduled aggregator only. U: "if anyone ever calls SET ROLE to escape RLS in app code i\'m going to lose my mind." Lint rule added in `tools/sqllint/`.\n</p2>\n<p3>\nChose RLS with `tenant_id` and `SET LOCAL app.current_tenant` per request. BYPASSRLS reserved for the scheduled analytics aggregator role only; app code is lint-enforced to never bypass.\n</p3>\n<p4>\nRLS on tenant_id; SET LOCAL app.current_tenant; BYPASSRLS = analytics_admin only\n</p4>\n</compartment>\n<facts>\n<ARCHITECTURE>\n* Tenant isolation is enforced at the database layer via Postgres RLS keyed on `tenant_id`, not via schema separation. Chosen because `SET LOCAL` is transaction-scoped and survives pgbouncer transaction-mode pooling, where session-scoped `search_path` switching does not.\n</ARCHITECTURE>\n<PROJECT_RULES>\n* Every tenant-scoped table must declare `tenant_id uuid not null` and `ENABLE ROW LEVEL SECURITY` with a policy referencing `current_setting(\'app.current_tenant\')`.\n* Application code must never call `SET ROLE` or use `BYPASSRLS` roles. `tools/sqllint/` enforces this in CI.\n</PROJECT_RULES>\n<CONSTRAINTS>\n* `SET search_path` is session-scoped and is silently lost between transactions when running behind pgbouncer in transaction pooling mode — making schema-per-tenant impractical for our deployment.\n</CONSTRAINTS>\n<CONFIG_VALUES>\n* Per-request tenant context is set via `SET LOCAL app.current_tenant = \'<uuid>\'` inside the request transaction opened by `internal/db/tenant.go`.\n</CONFIG_VALUES>\n<NAMING>\n* The privileged analytics role is `analytics_admin` (the only role with `BYPASSRLS`); used exclusively by the scheduled aggregation job.\n</NAMING>\n</facts>\n<events>\n<trajectory_correction at_compartment="3">\n <summary>Considered and rejected schema-per-tenant in favor of RLS after realizing it was incompatible with the existing pgbouncer setup.</summary>\n <before_strategy>Lean toward schema-per-tenant for "stronger" isolation feel.</before_strategy>\n <correction_source>self_review</correction_source>\n <correction_signal>Realized `SET search_path` is session-scoped and doesn\'t survive pgbouncer transaction-mode pooling.</correction_signal>\n <after_strategy>Adopt RLS with `SET LOCAL app.current_tenant` per transaction.</after_strategy>\n <evidence>"I keep getting pulled toward schema-per-tenant... I want to be talked out of it if RLS holds up"</evidence>\n</trajectory_correction>\n</events>\n<user_observations>\n* User asks to be argued out of intuitive-but-weakly-supported design preferences rather than rubber-stamped on them.\n* User pre-emptively codifies "rules to avoid future temptation" — translating decisions into lint rules and written prohibitions in the same session.\n</user_observations>'
|
|
12991
|
+
block: '<compartment start="415" end="612" title="Tenant isolation: chose Postgres RLS over schema-per-tenant" episode_type="design" importance="94">\n<p1>\nWorked through the tenant isolation model for the new control plane. Three candidates on the table: (a) schema-per-tenant with `search_path` switching, (b) database-per-tenant, (c) shared schema with Postgres Row-Level Security policies keyed on `tenant_id`. Spent the morning sketching how each interacts with our migration tooling, connection pooling (pgbouncer in transaction mode), and the analytics replica.\n\nU: I keep getting pulled toward schema-per-tenant because it feels "more isolated" but I want to be talked out of it if RLS holds up\n\nSchema-per-tenant blows up under pgbouncer transaction-pooling — `SET search_path` is session-state and gets lost between transactions; the per-tenant search_path either has to be set on every transaction (expensive, race-prone) or we drop pgbouncer (kills our connection economy). Database-per-tenant solves isolation cleanly but our migration tooling (sqlx) doesn\'t have a clean fan-out story and we\'d need to build one. Also onboarding latency goes from ~50ms to ~30s because we\'d need to provision a DB.\n\nLanded on RLS. Every tenant-scoped table gets `tenant_id uuid not null`, an `ENABLE ROW LEVEL SECURITY` declaration, and a policy `USING (tenant_id = current_setting(\'app.current_tenant\')::uuid)`. The current tenant is set via `SET LOCAL app.current_tenant = \'...\'` at the start of every request transaction — `SET LOCAL` is transaction-scoped so it survives pgbouncer transaction mode cleanly. Wrote a middleware in `internal/db/tenant.go` that wraps every request in a transaction and sets the value.\n\nU: what about the analytics replica, does RLS work the same there\n\nYes — RLS policies replicate via logical replication; the analytics service connects with a separate role that also has RLS enforced. The escape hatch for cross-tenant analytics is a dedicated `analytics_admin` role with `BYPASSRLS`, used only by the scheduled aggregation job, never by interactive code paths.\n\nU: ok and write down that if anyone ever calls SET ROLE to escape RLS in app code i\'m going to lose my mind\n\nDocumented. Added a lint rule in `tools/sqllint/` that flags `SET ROLE`, `BYPASSRLS`, and unqualified table access in `internal/handlers/`.\n</p1>\n<p2>\nTenant isolation decision: Postgres RLS keyed on `tenant_id`, set per-transaction via `SET LOCAL app.current_tenant`. Rejected schema-per-tenant (breaks pgbouncer transaction mode) and database-per-tenant (sqlx migration fan-out cost + 30s onboarding latency). Analytics uses a separate role with BYPASSRLS for the scheduled aggregator only. U: "if anyone ever calls SET ROLE to escape RLS in app code i\'m going to lose my mind." Lint rule added in `tools/sqllint/`.\n</p2>\n<p3>\nChose RLS with `tenant_id` and `SET LOCAL app.current_tenant` per request. BYPASSRLS reserved for the scheduled analytics aggregator role only; app code is lint-enforced to never bypass.\n</p3>\n<p4>\nRLS on tenant_id; SET LOCAL app.current_tenant; BYPASSRLS = analytics_admin only\n</p4>\n</compartment>\n<facts>\n<ARCHITECTURE>\n* [at_compartment=3] Tenant isolation is enforced at the database layer via Postgres RLS keyed on `tenant_id`, not via schema separation. Chosen because `SET LOCAL` is transaction-scoped and survives pgbouncer transaction-mode pooling, where session-scoped `search_path` switching does not.\n</ARCHITECTURE>\n<PROJECT_RULES>\n* [at_compartment=3] Every tenant-scoped table must declare `tenant_id uuid not null` and `ENABLE ROW LEVEL SECURITY` with a policy referencing `current_setting(\'app.current_tenant\')`.\n* [at_compartment=3] Application code must never call `SET ROLE` or use `BYPASSRLS` roles. `tools/sqllint/` enforces this in CI.\n</PROJECT_RULES>\n<CONSTRAINTS>\n* [at_compartment=3] `SET search_path` is session-scoped and is silently lost between transactions when running behind pgbouncer in transaction pooling mode — making schema-per-tenant impractical for our deployment.\n</CONSTRAINTS>\n<CONFIG_VALUES>\n* [at_compartment=3] Per-request tenant context is set via `SET LOCAL app.current_tenant = \'<uuid>\'` inside the request transaction opened by `internal/db/tenant.go`.\n</CONFIG_VALUES>\n<NAMING>\n* [at_compartment=3] The privileged analytics role is `analytics_admin` (the only role with `BYPASSRLS`); used exclusively by the scheduled aggregation job.\n</NAMING>\n</facts>\n<events>\n<trajectory_correction at_compartment="3">\n <summary>Considered and rejected schema-per-tenant in favor of RLS after realizing it was incompatible with the existing pgbouncer setup.</summary>\n <before_strategy>Lean toward schema-per-tenant for "stronger" isolation feel.</before_strategy>\n <correction_source>self_review</correction_source>\n <correction_signal>Realized `SET search_path` is session-scoped and doesn\'t survive pgbouncer transaction-mode pooling.</correction_signal>\n <after_strategy>Adopt RLS with `SET LOCAL app.current_tenant` per transaction.</after_strategy>\n <evidence>"I keep getting pulled toward schema-per-tenant... I want to be talked out of it if RLS holds up"</evidence>\n</trajectory_correction>\n</events>\n<user_observations>\n* User asks to be argued out of intuitive-but-weakly-supported design preferences rather than rubber-stamped on them.\n* User pre-emptively codifies "rules to avoid future temptation" — translating decisions into lint rules and written prohibitions in the same session.\n</user_observations>'
|
|
12981
12992
|
},
|
|
12982
12993
|
{
|
|
12983
12994
|
importance: 92,
|
|
@@ -13005,22 +13016,22 @@ Tenant authorization now flows from membership state rather than browser-selecte
|
|
|
13005
13016
|
</compartment>
|
|
13006
13017
|
<facts>
|
|
13007
13018
|
<PROJECT_RULES>
|
|
13008
|
-
* New authenticated handlers must derive tenant access from server-resolved membership state, never from request body, query, or cookie tenant IDs.
|
|
13009
|
-
* Any endpoint bypassing TenantGuard needs an explicit integration test covering membership revocation.
|
|
13019
|
+
* [at_compartment=1] New authenticated handlers must derive tenant access from server-resolved membership state, never from request body, query, or cookie tenant IDs.
|
|
13020
|
+
* [at_compartment=1] Any endpoint bypassing TenantGuard needs an explicit integration test covering membership revocation.
|
|
13010
13021
|
</PROJECT_RULES>
|
|
13011
13022
|
<ARCHITECTURE>
|
|
13012
|
-
* Session tokens carry user_id and active_membership_id; tenant and role are rehydrated server-side so revocation and membership changes apply without waiting for session expiry.
|
|
13013
|
-
* Billing, files, and audit services consume a middleware-built TenantContext instead of parsing auth material independently.
|
|
13023
|
+
* [at_compartment=1] Session tokens carry user_id and active_membership_id; tenant and role are rehydrated server-side so revocation and membership changes apply without waiting for session expiry.
|
|
13024
|
+
* [at_compartment=1] Billing, files, and audit services consume a middleware-built TenantContext instead of parsing auth material independently.
|
|
13014
13025
|
</ARCHITECTURE>
|
|
13015
13026
|
<CONSTRAINTS>
|
|
13016
|
-
* Browser-supplied orgId values are unsafe for tenant authorization because users can belong to multiple tenants and stale tabs can replay old selections.
|
|
13027
|
+
* [at_compartment=1] Browser-supplied orgId values are unsafe for tenant authorization because users can belong to multiple tenants and stale tabs can replay old selections.
|
|
13017
13028
|
</CONSTRAINTS>
|
|
13018
13029
|
<CONFIG_VALUES>
|
|
13019
|
-
* Internal tenant hop header: x-ledgerleaf-tenant-id.
|
|
13020
|
-
* Auth claim name: active_membership_id.
|
|
13030
|
+
* [at_compartment=1] Internal tenant hop header: x-ledgerleaf-tenant-id.
|
|
13031
|
+
* [at_compartment=1] Auth claim name: active_membership_id.
|
|
13021
13032
|
</CONFIG_VALUES>
|
|
13022
13033
|
<NAMING>
|
|
13023
|
-
* The auth boundary middleware is named TenantGuard and the resolver behind it is TenantContextResolver.
|
|
13034
|
+
* [at_compartment=1] The auth boundary middleware is named TenantGuard and the resolver behind it is TenantContextResolver.
|
|
13024
13035
|
</NAMING>
|
|
13025
13036
|
</facts>
|
|
13026
13037
|
<user_observations>
|
|
@@ -13055,16 +13066,16 @@ internal/leaderelection/release.go shim removed; PreStop hook; lease 30s / retry
|
|
|
13055
13066
|
</compartment>
|
|
13056
13067
|
<facts>
|
|
13057
13068
|
<PROJECT_RULES>
|
|
13058
|
-
* Do not wrap or shim controller-runtime leader-election internals — extend via its config surface only. Package \`internal/leaderelection/\` is CODEOWNERS-locked for this reason.
|
|
13069
|
+
* [at_compartment=1] Do not wrap or shim controller-runtime leader-election internals — extend via its config surface only. Package \`internal/leaderelection/\` is CODEOWNERS-locked for this reason.
|
|
13059
13070
|
</PROJECT_RULES>
|
|
13060
13071
|
<ARCHITECTURE>
|
|
13061
|
-
* Leader-election release path must run unobstructed during SIGTERM so the kube-apiserver can transfer the lease before the pod's Node disappears.
|
|
13072
|
+
* [at_compartment=1] Leader-election release path must run unobstructed during SIGTERM so the kube-apiserver can transfer the lease before the pod's Node disappears.
|
|
13062
13073
|
</ARCHITECTURE>
|
|
13063
13074
|
<CONSTRAINTS>
|
|
13064
|
-
* Suppressing errors during graceful shutdown can mask actual API calls in flight; the suppression boundary must be drawn around logging, not around the network call itself.
|
|
13075
|
+
* [at_compartment=1] Suppressing errors during graceful shutdown can mask actual API calls in flight; the suppression boundary must be drawn around logging, not around the network call itself.
|
|
13065
13076
|
</CONSTRAINTS>
|
|
13066
13077
|
<CONFIG_VALUES>
|
|
13067
|
-
* Operator leader-election: lease duration 30s, retry period 5s, PreStop hook 5s.
|
|
13078
|
+
* [at_compartment=1] Operator leader-election: lease duration 30s, retry period 5s, PreStop hook 5s.
|
|
13068
13079
|
</CONFIG_VALUES>
|
|
13069
13080
|
</facts>
|
|
13070
13081
|
<events>
|
|
@@ -13106,19 +13117,19 @@ run_id; pipeline_run; IntegrityError; idempotent retry; {pipeline_name}_{YYYYMMD
|
|
|
13106
13117
|
</compartment>
|
|
13107
13118
|
<facts>
|
|
13108
13119
|
<ARCHITECTURE>
|
|
13109
|
-
* All Luminary ETL pipeline loads are idempotent via run_id deduplication; any run can be safely retried without risk of double-counting or partial loads.
|
|
13120
|
+
* [at_compartment=1] All Luminary ETL pipeline loads are idempotent via run_id deduplication; any run can be safely retried without risk of double-counting or partial loads.
|
|
13110
13121
|
</ARCHITECTURE>
|
|
13111
13122
|
<PROJECT_RULES>
|
|
13112
|
-
* Every Luminary pipeline run must generate and log a run_id to the pipeline_run table before any target writes begin.
|
|
13123
|
+
* [at_compartment=1] Every Luminary pipeline run must generate and log a run_id to the pipeline_run table before any target writes begin.
|
|
13113
13124
|
</PROJECT_RULES>
|
|
13114
13125
|
<CONSTRAINTS>
|
|
13115
|
-
* Luminary run_id uniqueness is enforced by a DB unique constraint on (target_table, run_id); a duplicate run_id raises IntegrityError, not a silent skip — retry logic must catch IntegrityError explicitly.
|
|
13126
|
+
* [at_compartment=1] Luminary run_id uniqueness is enforced by a DB unique constraint on (target_table, run_id); a duplicate run_id raises IntegrityError, not a silent skip — retry logic must catch IntegrityError explicitly.
|
|
13116
13127
|
</CONSTRAINTS>
|
|
13117
13128
|
<NAMING>
|
|
13118
|
-
* Luminary idempotency primitives: run_id (string dedup key), pipeline_run (dedup table), orchestrator/runner.py (retry logic with IntegrityError handling).
|
|
13129
|
+
* [at_compartment=1] Luminary idempotency primitives: run_id (string dedup key), pipeline_run (dedup table), orchestrator/runner.py (retry logic with IntegrityError handling).
|
|
13119
13130
|
</NAMING>
|
|
13120
13131
|
<CONFIG_VALUES>
|
|
13121
|
-
* Luminary run_id format: {pipeline_name}_{YYYYMMDD}_{uuid4_prefix8} (e.g., orders_daily_20250523_a3f92c11).
|
|
13132
|
+
* [at_compartment=1] Luminary run_id format: {pipeline_name}_{YYYYMMDD}_{uuid4_prefix8} (e.g., orders_daily_20250523_a3f92c11).
|
|
13122
13133
|
</CONFIG_VALUES>
|
|
13123
13134
|
</facts>`
|
|
13124
13135
|
},
|
|
@@ -13142,20 +13153,20 @@ Harborlight sharding is namespace-scoped: one operator binary can run cluster-wi
|
|
|
13142
13153
|
</compartment>
|
|
13143
13154
|
<facts>
|
|
13144
13155
|
<PROJECT_RULES>
|
|
13145
|
-
* Harborlight CRD changes must regenerate manifests, deepcopy code, RBAC, and envtest fixtures before merge.
|
|
13156
|
+
* [at_compartment=5] Harborlight CRD changes must regenerate manifests, deepcopy code, RBAC, and envtest fixtures before merge.
|
|
13146
13157
|
</PROJECT_RULES>
|
|
13147
13158
|
<ARCHITECTURE>
|
|
13148
|
-
* Harborlight uses one controller process with per-namespace Lease objects so failover does not move unrelated tenants.
|
|
13149
|
-
* QueueShard.status.observedLeaseUID records reconciler-observed lease identity; QueueShard.spec remains user intent only.
|
|
13159
|
+
* [at_compartment=5] Harborlight uses one controller process with per-namespace Lease objects so failover does not move unrelated tenants.
|
|
13160
|
+
* [at_compartment=5] QueueShard.status.observedLeaseUID records reconciler-observed lease identity; QueueShard.spec remains user intent only.
|
|
13150
13161
|
</ARCHITECTURE>
|
|
13151
13162
|
<CONSTRAINTS>
|
|
13152
|
-
* Kubernetes Lease renewTime is unreliable for Harborlight ownership decisions under node clock skew.
|
|
13163
|
+
* [at_compartment=5] Kubernetes Lease renewTime is unreliable for Harborlight ownership decisions under node clock skew.
|
|
13153
13164
|
</CONSTRAINTS>
|
|
13154
13165
|
<CONFIG_VALUES>
|
|
13155
|
-
* Harborlight QueueShard lease timing is duration 18s, renew deadline 12s, retry period 3s.
|
|
13166
|
+
* [at_compartment=5] Harborlight QueueShard lease timing is duration 18s, renew deadline 12s, retry period 3s.
|
|
13156
13167
|
</CONFIG_VALUES>
|
|
13157
13168
|
<NAMING>
|
|
13158
|
-
* The Harborlight CRD kind is QueueShard; "WorkPartition" was rejected as too generic.
|
|
13169
|
+
* [at_compartment=5] The Harborlight CRD kind is QueueShard; "WorkPartition" was rejected as too generic.
|
|
13159
13170
|
</NAMING>
|
|
13160
13171
|
</facts>
|
|
13161
13172
|
<events>
|
|
@@ -13190,13 +13201,13 @@ CAN RX no longer allocates or sends BLE notifications inside the ISR; frames are
|
|
|
13190
13201
|
</compartment>
|
|
13191
13202
|
<facts>
|
|
13192
13203
|
<PROJECT_RULES>
|
|
13193
|
-
* Pawprint firmware ISR paths must not allocate; enqueue to can_rx_ring and wake deferred work instead.
|
|
13204
|
+
* [at_compartment=3] Pawprint firmware ISR paths must not allocate; enqueue to can_rx_ring and wake deferred work instead.
|
|
13194
13205
|
</PROJECT_RULES>
|
|
13195
13206
|
<CONSTRAINTS>
|
|
13196
|
-
* nRF52840 BLE notification from IRQ context can trigger supervisor reset when SoftDevice holds the radio lock.
|
|
13207
|
+
* [at_compartment=3] nRF52840 BLE notification from IRQ context can trigger supervisor reset when SoftDevice holds the radio lock.
|
|
13197
13208
|
</CONSTRAINTS>
|
|
13198
13209
|
<CONFIG_VALUES>
|
|
13199
|
-
* Pawprint can_rx_ring depth is 32 frames, with overflow counted by can_rx_ring_overrun.
|
|
13210
|
+
* [at_compartment=3] Pawprint can_rx_ring depth is 32 frames, with overflow counted by can_rx_ring_overrun.
|
|
13200
13211
|
</CONFIG_VALUES>
|
|
13201
13212
|
</facts>
|
|
13202
13213
|
<events>
|
|
@@ -13233,10 +13244,10 @@ unscale_ → clip_grad_norm_ → step
|
|
|
13233
13244
|
</compartment>
|
|
13234
13245
|
<facts>
|
|
13235
13246
|
<CONSTRAINTS>
|
|
13236
|
-
* \`torch.nn.utils.clip_grad_norm_\` called on still-scaled fp16 gradients overflows silently, returns inf, drives the clip ratio to 0, and zeros parameters on the next optimizer step.
|
|
13247
|
+
* [at_compartment=2] \`torch.nn.utils.clip_grad_norm_\` called on still-scaled fp16 gradients overflows silently, returns inf, drives the clip ratio to 0, and zeros parameters on the next optimizer step.
|
|
13237
13248
|
</CONSTRAINTS>
|
|
13238
13249
|
<ARCHITECTURE>
|
|
13239
|
-
* In mixed-precision training, gradient clipping is computed against TRUE gradient magnitudes — \`scaler.unscale_(optimizer)\` must run before any norm-based clipping.
|
|
13250
|
+
* [at_compartment=2] In mixed-precision training, gradient clipping is computed against TRUE gradient magnitudes — \`scaler.unscale_(optimizer)\` must run before any norm-based clipping.
|
|
13240
13251
|
</ARCHITECTURE>
|
|
13241
13252
|
</facts>
|
|
13242
13253
|
<events>
|
|
@@ -13275,13 +13286,13 @@ LoomDoc wraps Y.Doc; HLC (physical_ms, logical, node_id); skew cap 300s
|
|
|
13275
13286
|
</compartment>
|
|
13276
13287
|
<facts>
|
|
13277
13288
|
<ARCHITECTURE>
|
|
13278
|
-
* Document conflict resolution uses a two-layer model: Yjs handles concurrent per-character positioning, while a hybrid logical clock on top orders structural operations across regions. The split exists because Yjs's intrinsic ordering doesn't carry cross-region semantics for whole-node operations.
|
|
13289
|
+
* [at_compartment=1] Document conflict resolution uses a two-layer model: Yjs handles concurrent per-character positioning, while a hybrid logical clock on top orders structural operations across regions. The split exists because Yjs's intrinsic ordering doesn't carry cross-region semantics for whole-node operations.
|
|
13279
13290
|
</ARCHITECTURE>
|
|
13280
13291
|
<CONSTRAINTS>
|
|
13281
|
-
* Incoming HLC values whose physical component is more than 300 seconds ahead of local are rejected — clients with worse skew can't participate in collaboration until they correct.
|
|
13292
|
+
* [at_compartment=1] Incoming HLC values whose physical component is more than 300 seconds ahead of local are rejected — clients with worse skew can't participate in collaboration until they correct.
|
|
13282
13293
|
</CONSTRAINTS>
|
|
13283
13294
|
<NAMING>
|
|
13284
|
-
* CRDT library: Yjs (rejected Automerge for merge-cost scaling on ~50k-char documents). Our wrapper type is \`LoomDoc\`.
|
|
13295
|
+
* [at_compartment=1] CRDT library: Yjs (rejected Automerge for merge-cost scaling on ~50k-char documents). Our wrapper type is \`LoomDoc\`.
|
|
13285
13296
|
</NAMING>
|
|
13286
13297
|
</facts>`
|
|
13287
13298
|
},
|
|
@@ -13305,21 +13316,21 @@ Billetto made proration credits auditable by storing them in its own ledger tabl
|
|
|
13305
13316
|
</compartment>
|
|
13306
13317
|
<facts>
|
|
13307
13318
|
<PROJECT_RULES>
|
|
13308
|
-
* Billetto billing migrations must include a rollback dry-run against test/fixtures/billing-ledger/.
|
|
13319
|
+
* [at_compartment=1] Billetto billing migrations must include a rollback dry-run against test/fixtures/billing-ledger/.
|
|
13309
13320
|
</PROJECT_RULES>
|
|
13310
13321
|
<ARCHITECTURE>
|
|
13311
|
-
* Billetto represents credits as account_credit_entries tied to invoice_line_id, not as Stripe metadata.
|
|
13312
|
-
* Billetto proration calculation is idempotent around subscription_version and reuses existing ledger entries on retry.
|
|
13322
|
+
* [at_compartment=1] Billetto represents credits as account_credit_entries tied to invoice_line_id, not as Stripe metadata.
|
|
13323
|
+
* [at_compartment=1] Billetto proration calculation is idempotent around subscription_version and reuses existing ledger entries on retry.
|
|
13313
13324
|
</ARCHITECTURE>
|
|
13314
13325
|
<CONSTRAINTS>
|
|
13315
|
-
* Stripe invoice metadata is not a durable Billetto credit ledger because dashboard edits can mutate it outside the app.
|
|
13326
|
+
* [at_compartment=1] Stripe invoice metadata is not a durable Billetto credit ledger because dashboard edits can mutate it outside the app.
|
|
13316
13327
|
</CONSTRAINTS>
|
|
13317
13328
|
<CONFIG_VALUES>
|
|
13318
|
-
* Billetto credit_kind enum values are unused_time, plan_downgrade, and manual_adjustment.
|
|
13319
|
-
* Billetto Stripe idempotency key format for proration is proration:{account_id}:{subscription_version}:{invoice_id}.
|
|
13329
|
+
* [at_compartment=1] Billetto credit_kind enum values are unused_time, plan_downgrade, and manual_adjustment.
|
|
13330
|
+
* [at_compartment=1] Billetto Stripe idempotency key format for proration is proration:{account_id}:{subscription_version}:{invoice_id}.
|
|
13320
13331
|
</CONFIG_VALUES>
|
|
13321
13332
|
<NAMING>
|
|
13322
|
-
* The Billetto credit ledger table is named account_credit_entries; "negative_invoice_lines" was rejected.
|
|
13333
|
+
* [at_compartment=1] The Billetto credit ledger table is named account_credit_entries; "negative_invoice_lines" was rejected.
|
|
13323
13334
|
</NAMING>
|
|
13324
13335
|
</facts>`
|
|
13325
13336
|
},
|
|
@@ -13341,10 +13352,10 @@ Nereid contrastive training stabilized after restoring per-worker augmentation s
|
|
|
13341
13352
|
</compartment>
|
|
13342
13353
|
<facts>
|
|
13343
13354
|
<CONSTRAINTS>
|
|
13344
|
-
* Nereid's contrastive trainer can diverge if augmentation_seed is shared across dataloader workers.
|
|
13355
|
+
* [at_compartment=2] Nereid's contrastive trainer can diverge if augmentation_seed is shared across dataloader workers.
|
|
13345
13356
|
</CONSTRAINTS>
|
|
13346
13357
|
<CONFIG_VALUES>
|
|
13347
|
-
* Nereid worker augmentation seed formula is base_seed + worker_id + epoch * 1009.
|
|
13358
|
+
* [at_compartment=2] Nereid worker augmentation seed formula is base_seed + worker_id + epoch * 1009.
|
|
13348
13359
|
</CONFIG_VALUES>
|
|
13349
13360
|
</facts>
|
|
13350
13361
|
<events>
|
|
@@ -13383,19 +13394,19 @@ billing.stripe_event_idempotency; key = event.id; TTL 90d
|
|
|
13383
13394
|
</compartment>
|
|
13384
13395
|
<facts>
|
|
13385
13396
|
<PROJECT_RULES>
|
|
13386
|
-
* Idempotency for any external webhook source must key on the provider's event identifier (e.g. Stripe \`event.id\`), never on delivery-level signatures or timestamps. Stored response body+status is returned on duplicate.
|
|
13397
|
+
* [at_compartment=8] Idempotency for any external webhook source must key on the provider's event identifier (e.g. Stripe \`event.id\`), never on delivery-level signatures or timestamps. Stored response body+status is returned on duplicate.
|
|
13387
13398
|
</PROJECT_RULES>
|
|
13388
13399
|
<CONSTRAINTS>
|
|
13389
|
-
* Stripe webhook signatures and timestamps are regenerated per delivery attempt — they CANNOT be used as idempotency keys because retries of the same event produce different signatures.
|
|
13400
|
+
* [at_compartment=8] Stripe webhook signatures and timestamps are regenerated per delivery attempt — they CANNOT be used as idempotency keys because retries of the same event produce different signatures.
|
|
13390
13401
|
</CONSTRAINTS>
|
|
13391
13402
|
<ARCHITECTURE>
|
|
13392
|
-
* Webhook idempotency uses a write-through pattern: the handler's full response is captured inside the same transaction that records the event_id, so replays return byte-identical responses without re-executing side effects.
|
|
13403
|
+
* [at_compartment=8] Webhook idempotency uses a write-through pattern: the handler's full response is captured inside the same transaction that records the event_id, so replays return byte-identical responses without re-executing side effects.
|
|
13393
13404
|
</ARCHITECTURE>
|
|
13394
13405
|
<CONFIG_VALUES>
|
|
13395
|
-
* \`billing.stripe_event_idempotency\` table; primary key on \`event_id\`; row TTL 90 days; wrapper in \`internal/billing/webhooks/idempotent.go\`.
|
|
13406
|
+
* [at_compartment=8] \`billing.stripe_event_idempotency\` table; primary key on \`event_id\`; row TTL 90 days; wrapper in \`internal/billing/webhooks/idempotent.go\`.
|
|
13396
13407
|
</CONFIG_VALUES>
|
|
13397
13408
|
<NAMING>
|
|
13398
|
-
* Webhook idempotency table is \`billing.stripe_event_idempotency\`. Future provider-specific tables follow the pattern \`<provider>_event_idempotency\`.
|
|
13409
|
+
* [at_compartment=8] Webhook idempotency table is \`billing.stripe_event_idempotency\`. Future provider-specific tables follow the pattern \`<provider>_event_idempotency\`.
|
|
13399
13410
|
</NAMING>
|
|
13400
13411
|
</facts>
|
|
13401
13412
|
<events>
|
|
@@ -13438,13 +13449,13 @@ JWT refresh; tenant_roles; access_token_ttl=900s; refresh_token_ttl=86400s; auth
|
|
|
13438
13449
|
</compartment>
|
|
13439
13450
|
<facts>
|
|
13440
13451
|
<CONSTRAINTS>
|
|
13441
|
-
* Tethys JWT access tokens carry tenant_roles at issue time; role changes do not invalidate existing tokens — a revoked role remains usable until token expiry (up to access_token_ttl=900 s for clients that don't refresh).
|
|
13452
|
+
* [at_compartment=15] Tethys JWT access tokens carry tenant_roles at issue time; role changes do not invalidate existing tokens — a revoked role remains usable until token expiry (up to access_token_ttl=900 s for clients that don't refresh).
|
|
13442
13453
|
</CONSTRAINTS>
|
|
13443
13454
|
<PROJECT_RULES>
|
|
13444
|
-
* Tethys token refresh must always re-fetch tenant_roles from the DB; never carry role claims forward from the incoming token.
|
|
13455
|
+
* [at_compartment=15] Tethys token refresh must always re-fetch tenant_roles from the DB; never carry role claims forward from the incoming token.
|
|
13445
13456
|
</PROJECT_RULES>
|
|
13446
13457
|
<CONFIG_VALUES>
|
|
13447
|
-
* Tethys token TTLs: access_token_ttl=900 s, refresh_token_ttl=86400 s.
|
|
13458
|
+
* [at_compartment=15] Tethys token TTLs: access_token_ttl=900 s, refresh_token_ttl=86400 s.
|
|
13448
13459
|
</CONFIG_VALUES>
|
|
13449
13460
|
</facts>
|
|
13450
13461
|
<events>
|
|
@@ -13464,7 +13475,7 @@ JWT refresh; tenant_roles; access_token_ttl=900s; refresh_token_ttl=86400s; auth
|
|
|
13464
13475
|
},
|
|
13465
13476
|
{
|
|
13466
13477
|
importance: 74,
|
|
13467
|
-
block: '<compartment start="760" end="848" title="HLS segment numbering migration from 5-digit to 9-digit indices" episode_type="refactor,infra" importance="74">\n<p1>\nThe transcoder\'s HLS output was using `segment_%05d.ts` — five digits, max 99,999 segments. For a 24/7 live channel at 6s segments that\'s ~7 days before wraparound, and we just hit a wraparound on `channel-news-east` Friday night that broke the playlist sliding window for ~40 minutes before paging on-call noticed.\n\nMigrated to `segment_%09d.ts` everywhere. Touched `transcoder/hls/segmenter.go` for the writer, `transcoder/hls/playlist.go` for the manifest builder, and the CDN purge job\'s glob in `ops/purge-stale-segments.sh`. The CDN cache config didn\'t need changes — the glob was already `segment_*.ts`. Backfill is a no-op because old playlists naturally roll off the sliding window within an hour.\n\nCodified in the writer: any future segment-index format change must keep monotonic ordering AND must always be lexicographically sortable. The 5-digit choice was actually fine lexicographically until wraparound — the failure mode was running out of namespace, not ordering.\n</p1>\n<p2>\nHLS segment naming widened from `%05d` to `%09d` after a live-channel wraparound broke playlist sliding-window on `channel-news-east`. Changes in `transcoder/hls/segmenter.go` and `transcoder/hls/playlist.go`. Naming rule documented: segment indices must always be zero-padded to remain lexicographically sortable, with enough digits for a year of continuous segments at our minimum segment duration.\n</p2>\n<p3>\nHLS segment indices widened after a live-channel index wraparound.\n</p3>\n<p4>\nsegment_%09d.ts; transcoder/hls/\n</p4>\n</compartment>\n<facts>\n<CONFIG_VALUES>\n* HLS segment filename format: `segment_%09d.ts` (writer in `transcoder/hls/segmenter.go`, manifest builder in `transcoder/hls/playlist.go`).\n</CONFIG_VALUES>\n<PROJECT_RULES>\n* HLS segment indices must be zero-padded to a width sufficient for at least one year of continuous output at the minimum supported segment duration. Lexicographic sortability is required for CDN purge globbing.\n</PROJECT_RULES>\n</facts>\n<events>\n<causal_incident at_compartment="5">\n <summary>Live channel playback window broke for ~40 minutes after HLS segment index wrapped from 99,999 back to 0.</summary>\n <affected_surface>edit_pipeline</affected_surface>\n <symptom>Playlist sliding window on `channel-news-east` stopped advancing; viewers saw frozen live feed for ~40 minutes.</symptom>\n <cause_summary>5-digit segment index namespace exhausted on a continuously-running channel; new segments lexicographically sorted before old ones, breaking the manifest builder\'s ordering assumption.</cause_summary>\n <disposition>fixed</disposition>\n <evidence>On-call paged on viewer drop in channel-news-east; logs showed segment files alternating between `segment_99998.ts` and `segment_00000.ts` in the same directory.</evidence>\n <fix_summary>Widened format to `segment_%09d.ts` across writer, manifest builder, and CDN purge glob.</fix_summary>\n</causal_incident>\n</events>'
|
|
13478
|
+
block: '<compartment start="760" end="848" title="HLS segment numbering migration from 5-digit to 9-digit indices" episode_type="refactor,infra" importance="74">\n<p1>\nThe transcoder\'s HLS output was using `segment_%05d.ts` — five digits, max 99,999 segments. For a 24/7 live channel at 6s segments that\'s ~7 days before wraparound, and we just hit a wraparound on `channel-news-east` Friday night that broke the playlist sliding window for ~40 minutes before paging on-call noticed.\n\nMigrated to `segment_%09d.ts` everywhere. Touched `transcoder/hls/segmenter.go` for the writer, `transcoder/hls/playlist.go` for the manifest builder, and the CDN purge job\'s glob in `ops/purge-stale-segments.sh`. The CDN cache config didn\'t need changes — the glob was already `segment_*.ts`. Backfill is a no-op because old playlists naturally roll off the sliding window within an hour.\n\nCodified in the writer: any future segment-index format change must keep monotonic ordering AND must always be lexicographically sortable. The 5-digit choice was actually fine lexicographically until wraparound — the failure mode was running out of namespace, not ordering.\n</p1>\n<p2>\nHLS segment naming widened from `%05d` to `%09d` after a live-channel wraparound broke playlist sliding-window on `channel-news-east`. Changes in `transcoder/hls/segmenter.go` and `transcoder/hls/playlist.go`. Naming rule documented: segment indices must always be zero-padded to remain lexicographically sortable, with enough digits for a year of continuous segments at our minimum segment duration.\n</p2>\n<p3>\nHLS segment indices widened after a live-channel index wraparound.\n</p3>\n<p4>\nsegment_%09d.ts; transcoder/hls/\n</p4>\n</compartment>\n<facts>\n<CONFIG_VALUES>\n* [at_compartment=5] HLS segment filename format: `segment_%09d.ts` (writer in `transcoder/hls/segmenter.go`, manifest builder in `transcoder/hls/playlist.go`).\n</CONFIG_VALUES>\n<PROJECT_RULES>\n* [at_compartment=5] HLS segment indices must be zero-padded to a width sufficient for at least one year of continuous output at the minimum supported segment duration. Lexicographic sortability is required for CDN purge globbing.\n</PROJECT_RULES>\n</facts>\n<events>\n<causal_incident at_compartment="5">\n <summary>Live channel playback window broke for ~40 minutes after HLS segment index wrapped from 99,999 back to 0.</summary>\n <affected_surface>edit_pipeline</affected_surface>\n <symptom>Playlist sliding window on `channel-news-east` stopped advancing; viewers saw frozen live feed for ~40 minutes.</symptom>\n <cause_summary>5-digit segment index namespace exhausted on a continuously-running channel; new segments lexicographically sorted before old ones, breaking the manifest builder\'s ordering assumption.</cause_summary>\n <disposition>fixed</disposition>\n <evidence>On-call paged on viewer drop in channel-news-east; logs showed segment files alternating between `segment_99998.ts` and `segment_00000.ts` in the same directory.</evidence>\n <fix_summary>Widened format to `segment_%09d.ts` across writer, manifest builder, and CDN purge glob.</fix_summary>\n</causal_incident>\n</events>'
|
|
13468
13479
|
},
|
|
13469
13480
|
{
|
|
13470
13481
|
importance: 74,
|
|
@@ -13484,16 +13495,16 @@ Partition membership changes now fence planner statistics through partition_epoc
|
|
|
13484
13495
|
</compartment>
|
|
13485
13496
|
<facts>
|
|
13486
13497
|
<PROJECT_RULES>
|
|
13487
|
-
* Any catalog change affecting partition membership needs a planner regression under tests/sql/partition_pruning_regress.slt.
|
|
13498
|
+
* [at_compartment=13] Any catalog change affecting partition membership needs a planner regression under tests/sql/partition_pruning_regress.slt.
|
|
13488
13499
|
</PROJECT_RULES>
|
|
13489
13500
|
<ARCHITECTURE>
|
|
13490
|
-
* Planner stats cache keys include partition_epoch so partition topology changes invalidate selectivity estimates without clearing the whole cache.
|
|
13501
|
+
* [at_compartment=13] Planner stats cache keys include partition_epoch so partition topology changes invalidate selectivity estimates without clearing the whole cache.
|
|
13491
13502
|
</ARCHITECTURE>
|
|
13492
13503
|
<CONSTRAINTS>
|
|
13493
|
-
* Child partition attach and detach can make NDV and selectivity data unsafe even when the parent table schema is unchanged.
|
|
13504
|
+
* [at_compartment=13] Child partition attach and detach can make NDV and selectivity data unsafe even when the parent table schema is unchanged.
|
|
13494
13505
|
</CONSTRAINTS>
|
|
13495
13506
|
<CONFIG_VALUES>
|
|
13496
|
-
* New planner cache key field: partition_epoch.
|
|
13507
|
+
* [at_compartment=13] New planner cache key field: partition_epoch.
|
|
13497
13508
|
</CONFIG_VALUES>
|
|
13498
13509
|
</facts>
|
|
13499
13510
|
<events>
|
|
@@ -13528,13 +13539,13 @@ CollabPad CRDT ordering now follows document clocks rather than server receive t
|
|
|
13528
13539
|
</compartment>
|
|
13529
13540
|
<facts>
|
|
13530
13541
|
<ARCHITECTURE>
|
|
13531
|
-
* CollabPad orders CRDT operations by (lamport, site_id); server receivedAt is telemetry only.
|
|
13542
|
+
* [at_compartment=10] CollabPad orders CRDT operations by (lamport, site_id); server receivedAt is telemetry only.
|
|
13532
13543
|
</ARCHITECTURE>
|
|
13533
13544
|
<CONSTRAINTS>
|
|
13534
|
-
* WebRTC reconnect can deliver buffered CollabPad ops older than a websocket ack, so receivedAt cannot be used as causal order.
|
|
13545
|
+
* [at_compartment=10] WebRTC reconnect can deliver buffered CollabPad ops older than a websocket ack, so receivedAt cannot be used as causal order.
|
|
13535
13546
|
</CONSTRAINTS>
|
|
13536
13547
|
<NAMING>
|
|
13537
|
-
* CollabPad's editing-site field is named site_id rather than clientId because multiple browser contexts can share one account.
|
|
13548
|
+
* [at_compartment=10] CollabPad's editing-site field is named site_id rather than clientId because multiple browser contexts can share one account.
|
|
13538
13549
|
</NAMING>
|
|
13539
13550
|
</facts>
|
|
13540
13551
|
<events>
|
|
@@ -13571,10 +13582,10 @@ bond_table partition 0x7E000–0x7FFFF; pm_static.yml
|
|
|
13571
13582
|
</compartment>
|
|
13572
13583
|
<facts>
|
|
13573
13584
|
<CONSTRAINTS>
|
|
13574
|
-
* nRF SDK 2.6.0 bond manager (with \`NRF_FSTORAGE_API_FDS\`) writes its bond table to the top 8KB of flash regardless of the partition manifest — the SDK does not consult \`pm_static.yml\`.
|
|
13585
|
+
* [at_compartment=6] nRF SDK 2.6.0 bond manager (with \`NRF_FSTORAGE_API_FDS\`) writes its bond table to the top 8KB of flash regardless of the partition manifest — the SDK does not consult \`pm_static.yml\`.
|
|
13575
13586
|
</CONSTRAINTS>
|
|
13576
13587
|
<CONFIG_VALUES>
|
|
13577
|
-
* \`bond_table\` partition reserved at 0x7E000–0x7FFFF in \`pm_static.yml\`. OTA pre-swap erase range narrowed to 0x70000–0x7DFFF.
|
|
13588
|
+
* [at_compartment=6] \`bond_table\` partition reserved at 0x7E000–0x7FFFF in \`pm_static.yml\`. OTA pre-swap erase range narrowed to 0x70000–0x7DFFF.
|
|
13578
13589
|
</CONFIG_VALUES>
|
|
13579
13590
|
</facts>
|
|
13580
13591
|
<events>
|
|
@@ -13611,10 +13622,10 @@ leader election; Lease resource; VESPER_LEASE_DURATION_S; VESPER_RENEW_INTERVAL_
|
|
|
13611
13622
|
</compartment>
|
|
13612
13623
|
<facts>
|
|
13613
13624
|
<ARCHITECTURE>
|
|
13614
|
-
* Vesper controller uses Kubernetes Lease-based leader election; non-holder replicas skip the reconcile loop entirely and only run health probes.
|
|
13625
|
+
* [at_compartment=1] Vesper controller uses Kubernetes Lease-based leader election; non-holder replicas skip the reconcile loop entirely and only run health probes.
|
|
13615
13626
|
</ARCHITECTURE>
|
|
13616
13627
|
<CONFIG_VALUES>
|
|
13617
|
-
* Vesper leader election defaults: VESPER_LEASE_DURATION_S=30, VESPER_RENEW_INTERVAL_S=10, VESPER_ACQUIRE_DEADLINE_S=8 (all overridable via env).
|
|
13628
|
+
* [at_compartment=1] Vesper leader election defaults: VESPER_LEASE_DURATION_S=30, VESPER_RENEW_INTERVAL_S=10, VESPER_ACQUIRE_DEADLINE_S=8 (all overridable via env).
|
|
13618
13629
|
</CONFIG_VALUES>
|
|
13619
13630
|
</facts>`
|
|
13620
13631
|
},
|
|
@@ -13646,13 +13657,13 @@ onPreInstall; onPostInstall; onRemove; schema_version; dependency-declaration or
|
|
|
13646
13657
|
</compartment>
|
|
13647
13658
|
<facts>
|
|
13648
13659
|
<ARCHITECTURE>
|
|
13649
|
-
* boltpkg plugin hooks execute in plugin dependency-declaration order, not registration order; deterministic and matches user expectations about dependency sequencing.
|
|
13660
|
+
* [at_compartment=17] boltpkg plugin hooks execute in plugin dependency-declaration order, not registration order; deterministic and matches user expectations about dependency sequencing.
|
|
13650
13661
|
</ARCHITECTURE>
|
|
13651
13662
|
<NAMING>
|
|
13652
|
-
* boltpkg plugin lifecycle hooks: onPreInstall, onPostInstall, onRemove (src/plugin/types.ts).
|
|
13663
|
+
* [at_compartment=17] boltpkg plugin lifecycle hooks: onPreInstall, onPostInstall, onRemove (src/plugin/types.ts).
|
|
13653
13664
|
</NAMING>
|
|
13654
13665
|
<PROJECT_RULES>
|
|
13655
|
-
* boltpkg plugin manifests must include schema_version; the loader rejects manifests with unrecognized schema versions to prevent silently running mismatched plugins.
|
|
13666
|
+
* [at_compartment=17] boltpkg plugin manifests must include schema_version; the loader rejects manifests with unrecognized schema versions to prevent silently running mismatched plugins.
|
|
13656
13667
|
</PROJECT_RULES>
|
|
13657
13668
|
</facts>
|
|
13658
13669
|
<events>
|
|
@@ -13684,16 +13695,16 @@ Subscription MRR history moved into a daily fact table instead of being reconstr
|
|
|
13684
13695
|
</compartment>
|
|
13685
13696
|
<facts>
|
|
13686
13697
|
<PROJECT_RULES>
|
|
13687
|
-
* Northstar DW subscription backfills should use the backfill_subscription_day dbt macro instead of ad hoc DELETE and INSERT queries.
|
|
13698
|
+
* [at_compartment=1] Northstar DW subscription backfills should use the backfill_subscription_day dbt macro instead of ad hoc DELETE and INSERT queries.
|
|
13688
13699
|
</PROJECT_RULES>
|
|
13689
13700
|
<ARCHITECTURE>
|
|
13690
|
-
* Northstar DW answers historical MRR from fct_subscription_day daily snapshots rather than replaying raw billing events at query time.
|
|
13701
|
+
* [at_compartment=1] Northstar DW answers historical MRR from fct_subscription_day daily snapshots rather than replaying raw billing events at query time.
|
|
13691
13702
|
</ARCHITECTURE>
|
|
13692
13703
|
<CONFIG_VALUES>
|
|
13693
|
-
* fct_subscription_day is materialized incrementally with unique key account_id, subscription_id, and date_day.
|
|
13704
|
+
* [at_compartment=1] fct_subscription_day is materialized incrementally with unique key account_id, subscription_id, and date_day.
|
|
13694
13705
|
</CONFIG_VALUES>
|
|
13695
13706
|
<NAMING>
|
|
13696
|
-
* The subscription daily snapshot model is named fct_subscription_day.
|
|
13707
|
+
* [at_compartment=1] The subscription daily snapshot model is named fct_subscription_day.
|
|
13697
13708
|
</NAMING>
|
|
13698
13709
|
</facts>`
|
|
13699
13710
|
},
|
|
@@ -13721,10 +13732,10 @@ bucket width 50; K=24; asymmetric expansion down-only first 60s
|
|
|
13721
13732
|
</compartment>
|
|
13722
13733
|
<facts>
|
|
13723
13734
|
<CONFIG_VALUES>
|
|
13724
|
-
* Matchmaking: bucket width 50 MMR, K-factor 24, native-bucket wait 60s, down-only expansion phase 60s, symmetric expansion after 120s.
|
|
13735
|
+
* [at_compartment=1] Matchmaking: bucket width 50 MMR, K-factor 24, native-bucket wait 60s, down-only expansion phase 60s, symmetric expansion after 120s.
|
|
13725
13736
|
</CONFIG_VALUES>
|
|
13726
13737
|
<ARCHITECTURE>
|
|
13727
|
-
* Matchmaking expands the candidate bucket asymmetrically (down-only first) for high-rank players because the skill distribution is right-truncated — there are no buckets above them to expand into, and expanding symmetrically produces visible mismatches.
|
|
13738
|
+
* [at_compartment=1] Matchmaking expands the candidate bucket asymmetrically (down-only first) for high-rank players because the skill distribution is right-truncated — there are no buckets above them to expand into, and expanding symmetrically produces visible mismatches.
|
|
13728
13739
|
</ARCHITECTURE>
|
|
13729
13740
|
</facts>
|
|
13730
13741
|
<user_observations>
|
|
@@ -13747,7 +13758,7 @@ PDF page rotation is captured before OCR rasterization so Tesseract sees the cor
|
|
|
13747
13758
|
</compartment>
|
|
13748
13759
|
<facts>
|
|
13749
13760
|
<CONSTRAINTS>
|
|
13750
|
-
* QuillOCR cannot rely on pdfimages output for page rotation when Poppler emits JBIG2 masks; rotation must be read from pdfinfo before rasterization.
|
|
13761
|
+
* [at_compartment=8] QuillOCR cannot rely on pdfimages output for page rotation when Poppler emits JBIG2 masks; rotation must be read from pdfinfo before rasterization.
|
|
13751
13762
|
</CONSTRAINTS>
|
|
13752
13763
|
</facts>
|
|
13753
13764
|
<events>
|
|
@@ -13778,13 +13789,13 @@ Synonym edits are now shipped by building and promoting a shadow index, not by r
|
|
|
13778
13789
|
</compartment>
|
|
13779
13790
|
<facts>
|
|
13780
13791
|
<PROJECT_RULES>
|
|
13781
|
-
* Search schema changes and synonym changes ship through the same shadow-index promotion workflow.
|
|
13792
|
+
* [at_compartment=1] Search schema changes and synonym changes ship through the same shadow-index promotion workflow.
|
|
13782
13793
|
</PROJECT_RULES>
|
|
13783
13794
|
<ARCHITECTURE>
|
|
13784
|
-
* Synonym changes are applied by building a shadow index and swapping aliases, not by reloading the hot index in place.
|
|
13795
|
+
* [at_compartment=1] Synonym changes are applied by building a shadow index and swapping aliases, not by reloading the hot index in place.
|
|
13785
13796
|
</ARCHITECTURE>
|
|
13786
13797
|
<NAMING>
|
|
13787
|
-
* The paired search aliases are products_live and products_next.
|
|
13798
|
+
* [at_compartment=1] The paired search aliases are products_live and products_next.
|
|
13788
13799
|
</NAMING>
|
|
13789
13800
|
</facts>`
|
|
13790
13801
|
},
|
|
@@ -13806,16 +13817,16 @@ Ranked duo matchmaking now preserves parties even when it increases queue time.
|
|
|
13806
13817
|
</compartment>
|
|
13807
13818
|
<facts>
|
|
13808
13819
|
<PROJECT_RULES>
|
|
13809
|
-
* Arcade Relay matchmaker must not split a party_id across ranked lobbies; widen match criteria before breaking party constraints.
|
|
13820
|
+
* [at_compartment=1] Arcade Relay matchmaker must not split a party_id across ranked lobbies; widen match criteria before breaking party constraints.
|
|
13810
13821
|
</PROJECT_RULES>
|
|
13811
13822
|
<CONFIG_VALUES>
|
|
13812
|
-
* Arcade Relay ranked_duo MMR window widens by 75 every 15s up to 450.
|
|
13823
|
+
* [at_compartment=1] Arcade Relay ranked_duo MMR window widens by 75 every 15s up to 450.
|
|
13813
13824
|
</CONFIG_VALUES>
|
|
13814
13825
|
</facts>`
|
|
13815
13826
|
},
|
|
13816
13827
|
{
|
|
13817
13828
|
importance: 52,
|
|
13818
|
-
block: '<compartment start="1201" end="1264" title="Slowly-changing-dim fix in dim_customer dbt model" episode_type="refactor,bug" importance="52">\n<p1>\n`dim_customer` was implementing a hand-rolled Type-2 SCD with `valid_from`/`valid_to` columns and a `is_current` flag, updated by a UDF that fired on row change. The UDF had a race window where two concurrent upstream loads could both stamp `is_current=true` on overlapping rows for the same customer_id.\n\nMigrated to dbt snapshots (`snapshots/dim_customer.sql`) with `strategy=\'timestamp\'` on `updated_at`. Snapshot runs single-threaded by design; no race window. Backfilled the snapshot from the existing dim — diffed against the old table, 14 customers had overlapping `is_current` windows, all resolved by taking the latest by `updated_at`. Old UDF and trigger removed.\n</p1>\n<p2>\n`dim_customer` SCD reimplemented as a dbt snapshot (timestamp strategy on `updated_at`) replacing a hand-rolled trigger+UDF that had a concurrent-update race. Backfill resolved 14 customers with overlapping is_current windows.\n</p2>\n<p3>\nCustomer SCD moved from custom triggers to dbt snapshots.\n</p3>\n<p4>\nsnapshots/dim_customer.sql; strategy=timestamp on updated_at\n</p4>\n</compartment>\n<facts>\n<PROJECT_RULES>\n* Type-2 SCD modeling uses dbt snapshots with the `timestamp` strategy. Hand-rolled SCD via triggers/UDFs is not permitted because it has no race-free coordination across concurrent upstream loads.\n</PROJECT_RULES>\n</facts>'
|
|
13829
|
+
block: '<compartment start="1201" end="1264" title="Slowly-changing-dim fix in dim_customer dbt model" episode_type="refactor,bug" importance="52">\n<p1>\n`dim_customer` was implementing a hand-rolled Type-2 SCD with `valid_from`/`valid_to` columns and a `is_current` flag, updated by a UDF that fired on row change. The UDF had a race window where two concurrent upstream loads could both stamp `is_current=true` on overlapping rows for the same customer_id.\n\nMigrated to dbt snapshots (`snapshots/dim_customer.sql`) with `strategy=\'timestamp\'` on `updated_at`. Snapshot runs single-threaded by design; no race window. Backfilled the snapshot from the existing dim — diffed against the old table, 14 customers had overlapping `is_current` windows, all resolved by taking the latest by `updated_at`. Old UDF and trigger removed.\n</p1>\n<p2>\n`dim_customer` SCD reimplemented as a dbt snapshot (timestamp strategy on `updated_at`) replacing a hand-rolled trigger+UDF that had a concurrent-update race. Backfill resolved 14 customers with overlapping is_current windows.\n</p2>\n<p3>\nCustomer SCD moved from custom triggers to dbt snapshots.\n</p3>\n<p4>\nsnapshots/dim_customer.sql; strategy=timestamp on updated_at\n</p4>\n</compartment>\n<facts>\n<PROJECT_RULES>\n* [at_compartment=1] Type-2 SCD modeling uses dbt snapshots with the `timestamp` strategy. Hand-rolled SCD via triggers/UDFs is not permitted because it has no race-free coordination across concurrent upstream loads.\n</PROJECT_RULES>\n</facts>'
|
|
13819
13830
|
},
|
|
13820
13831
|
{
|
|
13821
13832
|
importance: 48,
|
|
@@ -13854,10 +13865,10 @@ tesseract=5.3.3; docker/ocr/Dockerfile; upstream #4117
|
|
|
13854
13865
|
</compartment>
|
|
13855
13866
|
<facts>
|
|
13856
13867
|
<CONFIG_VALUES>
|
|
13857
|
-
* \`docker/ocr/Dockerfile\` pins \`tesseract-ocr=5.3.3\` with apt version + SHA pin. Unpin only after upstream #4117 resolves.
|
|
13868
|
+
* [at_compartment=10] \`docker/ocr/Dockerfile\` pins \`tesseract-ocr=5.3.3\` with apt version + SHA pin. Unpin only after upstream #4117 resolves.
|
|
13858
13869
|
</CONFIG_VALUES>
|
|
13859
13870
|
<CONSTRAINTS>
|
|
13860
|
-
* Tesseract 5.3.4 regresses multi-column layout detection (column-detection heuristic in LSTM postprocessing changed). Single-column accuracy is unaffected.
|
|
13871
|
+
* [at_compartment=10] Tesseract 5.3.4 regresses multi-column layout detection (column-detection heuristic in LSTM postprocessing changed). Single-column accuracy is unaffected.
|
|
13861
13872
|
</CONSTRAINTS>
|
|
13862
13873
|
</facts>
|
|
13863
13874
|
<events>
|
|
@@ -13890,10 +13901,10 @@ Snapbench recording examples became runnable instead of descriptive only.
|
|
|
13890
13901
|
</compartment>
|
|
13891
13902
|
<facts>
|
|
13892
13903
|
<CONFIG_VALUES>
|
|
13893
|
-
* Snapbench's default snapshot directory is .snapbench/.
|
|
13904
|
+
* [at_compartment=1] Snapbench's default snapshot directory is .snapbench/.
|
|
13894
13905
|
</CONFIG_VALUES>
|
|
13895
13906
|
<NAMING>
|
|
13896
|
-
* The Snapbench capture subcommand is named snapbench record.
|
|
13907
|
+
* [at_compartment=1] The Snapbench capture subcommand is named snapbench record.
|
|
13897
13908
|
</NAMING>
|
|
13898
13909
|
</facts>
|
|
13899
13910
|
<user_observations>
|
|
@@ -13926,7 +13937,7 @@ HLS; pts discontinuity; last_pts; -copyts; hls.go
|
|
|
13926
13937
|
</compartment>
|
|
13927
13938
|
<facts>
|
|
13928
13939
|
<CONSTRAINTS>
|
|
13929
|
-
* Meridian's ffmpeg HLS mux requires the -copyts flag when chaining segments; without it pts is rescaled per-segment and playback gaps appear at boundaries under some codec configurations.
|
|
13940
|
+
* [at_compartment=8] Meridian's ffmpeg HLS mux requires the -copyts flag when chaining segments; without it pts is rescaled per-segment and playback gaps appear at boundaries under some codec configurations.
|
|
13930
13941
|
</CONSTRAINTS>
|
|
13931
13942
|
</facts>
|
|
13932
13943
|
<events>
|
|
@@ -13943,7 +13954,7 @@ HLS; pts discontinuity; last_pts; -copyts; hls.go
|
|
|
13943
13954
|
},
|
|
13944
13955
|
{
|
|
13945
13956
|
importance: 36,
|
|
13946
|
-
block: '<compartment start="1533" end="1617" title="Statistics-refresh hook on bulk-load completion in query planner integration" episode_type="feature,refactor" importance="36">\n<p1>\nThe embedded analytics DB\'s query planner uses table statistics that get stale after large bulk loads (>1M rows), causing the next query against the loaded table to pick a sequential scan even when a covering index would crush it. Added a `post_bulk_load` hook in `internal/storage/loader.go` that triggers an asynchronous `ANALYZE` against the affected tables. The hook is opt-in per loader because some flows already know they\'ll be followed by a manual ANALYZE; default is on.\n\nVerified the planner picks the index on the post-load query in the affected analytics benchmark — query went from 18s to 240ms.\n</p1>\n<p2>\nBulk loader (`internal/storage/loader.go`) now fires an async `ANALYZE` via a `post_bulk_load` hook after >1M-row loads to keep planner stats fresh. Affected benchmark: 18s → 240ms.\n</p2>\n<p3>\nBulk loader triggers asynchronous statistics refresh on large loads to keep the planner from picking sequential scans.\n</p3>\n<p4>\npost_bulk_load hook; internal/storage/loader.go\n</p4>\n</compartment>\n<facts>\n<ARCHITECTURE>\n* Bulk-load paths are responsible for refreshing planner statistics on the tables they touch — the planner does not auto-trigger ANALYZE on bulk-loaded tables, and stale stats cause it to choose sequential scans over covering indexes.\n</ARCHITECTURE>\n</facts>'
|
|
13957
|
+
block: '<compartment start="1533" end="1617" title="Statistics-refresh hook on bulk-load completion in query planner integration" episode_type="feature,refactor" importance="36">\n<p1>\nThe embedded analytics DB\'s query planner uses table statistics that get stale after large bulk loads (>1M rows), causing the next query against the loaded table to pick a sequential scan even when a covering index would crush it. Added a `post_bulk_load` hook in `internal/storage/loader.go` that triggers an asynchronous `ANALYZE` against the affected tables. The hook is opt-in per loader because some flows already know they\'ll be followed by a manual ANALYZE; default is on.\n\nVerified the planner picks the index on the post-load query in the affected analytics benchmark — query went from 18s to 240ms.\n</p1>\n<p2>\nBulk loader (`internal/storage/loader.go`) now fires an async `ANALYZE` via a `post_bulk_load` hook after >1M-row loads to keep planner stats fresh. Affected benchmark: 18s → 240ms.\n</p2>\n<p3>\nBulk loader triggers asynchronous statistics refresh on large loads to keep the planner from picking sequential scans.\n</p3>\n<p4>\npost_bulk_load hook; internal/storage/loader.go\n</p4>\n</compartment>\n<facts>\n<ARCHITECTURE>\n* [at_compartment=1] Bulk-load paths are responsible for refreshing planner statistics on the tables they touch — the planner does not auto-trigger ANALYZE on bulk-loaded tables, and stale stats cause it to choose sequential scans over covering indexes.\n</ARCHITECTURE>\n</facts>'
|
|
13947
13958
|
},
|
|
13948
13959
|
{
|
|
13949
13960
|
importance: 36,
|
|
@@ -13978,7 +13989,7 @@ Polaris; data/preprocessed/; preprocessor.py; polaris.preprocess; preprocess.yam
|
|
|
13978
13989
|
</compartment>
|
|
13979
13990
|
<facts>
|
|
13980
13991
|
<CONFIG_VALUES>
|
|
13981
|
-
* Polaris preprocessed dataset cache dir: data/preprocessed/; triggered via python -m polaris.preprocess --config configs/preprocess.yaml; cache key: dataset name + SHA256 of preprocessing config.
|
|
13992
|
+
* [at_compartment=1] Polaris preprocessed dataset cache dir: data/preprocessed/; triggered via python -m polaris.preprocess --config configs/preprocess.yaml; cache key: dataset name + SHA256 of preprocessing config.
|
|
13982
13993
|
</CONFIG_VALUES>
|
|
13983
13994
|
</facts>`
|
|
13984
13995
|
},
|
|
@@ -14001,10 +14012,10 @@ The SKU importer now defaults to a safe preview workflow instead of assuming liv
|
|
|
14001
14012
|
</compartment>
|
|
14002
14013
|
<facts>
|
|
14003
14014
|
<PROJECT_RULES>
|
|
14004
|
-
* New operational import commands should default to preview mode unless an explicit apply flag is present.
|
|
14015
|
+
* [at_compartment=15] New operational import commands should default to preview mode unless an explicit apply flag is present.
|
|
14005
14016
|
</PROJECT_RULES>
|
|
14006
14017
|
<CONFIG_VALUES>
|
|
14007
|
-
* Destructive execution flag: --apply; preview mode is the default when it is absent.
|
|
14018
|
+
* [at_compartment=15] Destructive execution flag: --apply; preview mode is the default when it is absent.
|
|
14008
14019
|
</CONFIG_VALUES>
|
|
14009
14020
|
</facts>
|
|
14010
14021
|
<events>
|
|
@@ -14037,7 +14048,7 @@ Invalid IoT telemetry is retained in a DLQ instead of silently disappearing.
|
|
|
14037
14048
|
</compartment>
|
|
14038
14049
|
<facts>
|
|
14039
14050
|
<CONFIG_VALUES>
|
|
14040
|
-
* BeaconMesh malformed raw telemetry is routed to Kafka topic telemetry.raw.dlq.v2.
|
|
14051
|
+
* [at_compartment=1] BeaconMesh malformed raw telemetry is routed to Kafka topic telemetry.raw.dlq.v2.
|
|
14041
14052
|
</CONFIG_VALUES>
|
|
14042
14053
|
</facts>`
|
|
14043
14054
|
},
|
|
@@ -14059,7 +14070,7 @@ Mobile offline sync shipped with a narrow notes-only scope.
|
|
|
14059
14070
|
</compartment>
|
|
14060
14071
|
<facts>
|
|
14061
14072
|
<CONFIG_VALUES>
|
|
14062
|
-
* Harbor Notes offline sync MVP includes note title and body only; attachments and comment threads remain online-only.
|
|
14073
|
+
* [at_compartment=1] Harbor Notes offline sync MVP includes note title and body only; attachments and comment threads remain online-only.
|
|
14063
14074
|
</CONFIG_VALUES>
|
|
14064
14075
|
</facts>`
|
|
14065
14076
|
},
|
|
@@ -14085,10 +14096,10 @@ Low-confidence scan rotation is now handled through a manual override path, with
|
|
|
14085
14096
|
</compartment>
|
|
14086
14097
|
<facts>
|
|
14087
14098
|
<CONSTRAINTS>
|
|
14088
|
-
* OCR angle predictions below a high confidence threshold are not reliable enough for unattended page rotation on messy multi-scan uploads.
|
|
14099
|
+
* [at_compartment=19] OCR angle predictions below a high confidence threshold are not reliable enough for unattended page rotation on messy multi-scan uploads.
|
|
14089
14100
|
</CONSTRAINTS>
|
|
14090
14101
|
<CONFIG_VALUES>
|
|
14091
|
-
* Automatic rotation threshold: angle_confidence 0.98 or higher.
|
|
14102
|
+
* [at_compartment=19] Automatic rotation threshold: angle_confidence 0.98 or higher.
|
|
14092
14103
|
</CONFIG_VALUES>
|
|
14093
14104
|
</facts>
|
|
14094
14105
|
<events>
|
|
@@ -14162,7 +14173,7 @@ This was a scoped replay, not a lasting data-model change: the useful outcome wa
|
|
|
14162
14173
|
</compartment>
|
|
14163
14174
|
<facts>
|
|
14164
14175
|
<CONFIG_VALUES>
|
|
14165
|
-
* The orders repair workflow is keyed off landed_at partitions rather than invoice_date.
|
|
14176
|
+
* [at_compartment=5] The orders repair workflow is keyed off landed_at partitions rather than invoice_date.
|
|
14166
14177
|
</CONFIG_VALUES>
|
|
14167
14178
|
</facts>
|
|
14168
14179
|
<events>
|
|
@@ -14207,13 +14218,13 @@ README install path fixed for Apple Silicon.
|
|
|
14207
14218
|
</compartment>
|
|
14208
14219
|
<facts>
|
|
14209
14220
|
<NAMING>
|
|
14210
|
-
* On darwin-arm64 (Apple Silicon), the installed binary path is \`/opt/homebrew/bin/loomctl\`. On darwin-x86_64 and Linux, it remains \`/usr/local/bin/loomctl\`.
|
|
14221
|
+
* [at_compartment=1] On darwin-arm64 (Apple Silicon), the installed binary path is \`/opt/homebrew/bin/loomctl\`. On darwin-x86_64 and Linux, it remains \`/usr/local/bin/loomctl\`.
|
|
14211
14222
|
</NAMING>
|
|
14212
14223
|
</facts>`
|
|
14213
14224
|
},
|
|
14214
14225
|
{
|
|
14215
14226
|
importance: 17,
|
|
14216
|
-
block: '<compartment start="1734" end="1768" title="Rename internal `bilUtil` helper to `invoiceMath`" episode_type="refactor" importance="17">\n<p1>\nThe `bilUtil` package in the billing service was a holdover name from a partial rename — `bil` was the original short prefix before we standardized on `invoice`. Renamed to `invoiceMath` since that\'s what the package actually does (rounding, proration, tax-base math). No behavior change. Updated callers, ran tests, done.\n</p1>\n<p2>\nRenamed `bilUtil` package to `invoiceMath` to match its actual responsibility.\n</p2>\n<p3>\nNaming cleanup in the billing service.\n</p3>\n<p4/>\n</compartment>\n<facts>\n<NAMING>\n* Billing math helpers live in package `invoiceMath` (rounding, proration, tax-base computation). The prior name `bilUtil` is deprecated.\n</NAMING>\n</facts>'
|
|
14227
|
+
block: '<compartment start="1734" end="1768" title="Rename internal `bilUtil` helper to `invoiceMath`" episode_type="refactor" importance="17">\n<p1>\nThe `bilUtil` package in the billing service was a holdover name from a partial rename — `bil` was the original short prefix before we standardized on `invoice`. Renamed to `invoiceMath` since that\'s what the package actually does (rounding, proration, tax-base math). No behavior change. Updated callers, ran tests, done.\n</p1>\n<p2>\nRenamed `bilUtil` package to `invoiceMath` to match its actual responsibility.\n</p2>\n<p3>\nNaming cleanup in the billing service.\n</p3>\n<p4/>\n</compartment>\n<facts>\n<NAMING>\n* [at_compartment=1] Billing math helpers live in package `invoiceMath` (rounding, proration, tax-base computation). The prior name `bilUtil` is deprecated.\n</NAMING>\n</facts>'
|
|
14217
14228
|
},
|
|
14218
14229
|
{
|
|
14219
14230
|
importance: 14,
|
|
@@ -14255,7 +14266,7 @@ kind; ci/kind-config.yaml; kindest/node:v1.29.2; integration.yml
|
|
|
14255
14266
|
</compartment>
|
|
14256
14267
|
<facts>
|
|
14257
14268
|
<CONFIG_VALUES>
|
|
14258
|
-
* Vesper CI kind cluster: config ci/kind-config.yaml, node image kindest/node:v1.29.2.
|
|
14269
|
+
* [at_compartment=1] Vesper CI kind cluster: config ci/kind-config.yaml, node image kindest/node:v1.29.2.
|
|
14259
14270
|
</CONFIG_VALUES>
|
|
14260
14271
|
</facts>`
|
|
14261
14272
|
},
|
|
@@ -14312,7 +14323,7 @@ False start: attempted-and-reverted controller-runtime cache bypass.
|
|
|
14312
14323
|
</compartment>
|
|
14313
14324
|
<facts>
|
|
14314
14325
|
<CONSTRAINTS>
|
|
14315
|
-
* controller-runtime's cache is itself informer-backed; "going direct to informers" doesn't remove any indirection and gives no latency benefit.
|
|
14326
|
+
* [at_compartment=18] controller-runtime's cache is itself informer-backed; "going direct to informers" doesn't remove any indirection and gives no latency benefit.
|
|
14316
14327
|
</CONSTRAINTS>
|
|
14317
14328
|
</facts>
|
|
14318
14329
|
<events>
|
|
@@ -14437,7 +14448,7 @@ Captured high-load CAN bus limitation in firmware docs.
|
|
|
14437
14448
|
</compartment>
|
|
14438
14449
|
<facts>
|
|
14439
14450
|
<CONSTRAINTS>
|
|
14440
|
-
* CAN bus arbitration on the current MCU fails under >80% bus load; requires priority inversion mitigation in the driver.
|
|
14451
|
+
* [at_compartment=1] CAN bus arbitration on the current MCU fails under >80% bus load; requires priority inversion mitigation in the driver.
|
|
14441
14452
|
</CONSTRAINTS>
|
|
14442
14453
|
</facts>`
|
|
14443
14454
|
},
|
|
@@ -14487,7 +14498,7 @@ Docs examples section was renamed.
|
|
|
14487
14498
|
</compartment>
|
|
14488
14499
|
<facts>
|
|
14489
14500
|
<NAMING>
|
|
14490
|
-
* AstraKit's docs navigation label for examples is "Cookbook", not "Recipes".
|
|
14501
|
+
* [at_compartment=1] AstraKit's docs navigation label for examples is "Cookbook", not "Recipes".
|
|
14491
14502
|
</NAMING>
|
|
14492
14503
|
</facts>`
|
|
14493
14504
|
}
|
|
@@ -16340,764 +16351,552 @@ function queueDropsForCompartmentalizedMessages(db, sessionId, upToMessageIndex,
|
|
|
16340
16351
|
queuePreparedCompartmentDrops(db, prepareCompartmentDrops(db, sessionId, upToMessageIndex, observedKeys, fromMessageIndex));
|
|
16341
16352
|
}
|
|
16342
16353
|
|
|
16343
|
-
// src/hooks/magic-context/
|
|
16344
|
-
|
|
16345
|
-
|
|
16346
|
-
|
|
16347
|
-
|
|
16348
|
-
|
|
16349
|
-
|
|
16350
|
-
const state = getHistorianFailureState(db, sessionId);
|
|
16351
|
-
const count = state.failureCount;
|
|
16352
|
-
let since = null;
|
|
16353
|
-
if (count > 0) {
|
|
16354
|
-
const recorded = count - Math.max(0, options.unrecordedFailures ?? 0);
|
|
16355
|
-
if (recorded <= 0) {
|
|
16356
|
-
since = state.lastFailureAt;
|
|
16357
|
-
} else {
|
|
16358
|
-
const times = getRecentFailedHistorianRunTimes(db, sessionId, recorded);
|
|
16359
|
-
since = times.length === recorded ? times[recorded - 1] ?? null : null;
|
|
16360
|
-
}
|
|
16354
|
+
// src/hooks/magic-context/file-token-coverage.ts
|
|
16355
|
+
function omitIncompleteFileTokenTotals(db, sessionId, messages, totals) {
|
|
16356
|
+
const filesByMessage = new Map;
|
|
16357
|
+
for (const message of messages) {
|
|
16358
|
+
const count = message.parts.filter(isFilePart).length;
|
|
16359
|
+
if (count > 0 && totals.has(message.id))
|
|
16360
|
+
filesByMessage.set(message.id, count);
|
|
16361
16361
|
}
|
|
16362
|
-
|
|
16362
|
+
if (filesByMessage.size === 0)
|
|
16363
|
+
return totals;
|
|
16364
|
+
const rows = db.prepare(`
|
|
16365
|
+
SELECT o.value AS owner, COUNT(t.id) AS count
|
|
16366
|
+
FROM json_each(?) o LEFT JOIN tags t
|
|
16367
|
+
ON t.session_id = ? AND t.type = 'file'
|
|
16368
|
+
AND t.message_id >= o.value || ':file'
|
|
16369
|
+
AND t.message_id < o.value || ':file;'
|
|
16370
|
+
GROUP BY o.value
|
|
16371
|
+
`).all(JSON.stringify([...filesByMessage.keys()]), sessionId);
|
|
16372
|
+
for (const row of rows) {
|
|
16373
|
+
if (row.count < (filesByMessage.get(row.owner) ?? 0))
|
|
16374
|
+
totals.delete(row.owner);
|
|
16375
|
+
}
|
|
16376
|
+
return totals;
|
|
16363
16377
|
}
|
|
16364
|
-
|
|
16365
|
-
|
|
16366
|
-
|
|
16367
|
-
|
|
16368
|
-
const today = new Date(now);
|
|
16369
|
-
const sameDay = date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
|
|
16370
|
-
return sameDay ? clock : `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock}`;
|
|
16378
|
+
|
|
16379
|
+
// src/hooks/magic-context/protected-tail-boundary.ts
|
|
16380
|
+
function describeBoundaryDiagnostics(snapshot) {
|
|
16381
|
+
return `boundaryDiagnostics=${JSON.stringify(snapshot.diagnostics ?? { unavailable: true, boundaryReason: snapshot.boundaryReason })}`;
|
|
16371
16382
|
}
|
|
16372
|
-
function
|
|
16373
|
-
|
|
16374
|
-
|
|
16383
|
+
function boundaryDiagnostics(args) {
|
|
16384
|
+
return {
|
|
16385
|
+
...args,
|
|
16386
|
+
capTier: args.usagePercentage >= 95 ? "95" : args.usagePercentage >= 80 ? "80" : "normal",
|
|
16387
|
+
drainBudget: "not-reserved; does-not-size-cap"
|
|
16388
|
+
};
|
|
16375
16389
|
}
|
|
16376
|
-
|
|
16377
|
-
|
|
16390
|
+
var ALPHA = 0.3;
|
|
16391
|
+
var FLOOR_RATIO = 0.08;
|
|
16392
|
+
var FLOOR_MIN = 2000;
|
|
16393
|
+
var FLOOR_MAX = 12000;
|
|
16394
|
+
var ABS_CAP = 96000;
|
|
16395
|
+
var MAX_USABLE_RATIO = 0.4;
|
|
16396
|
+
var RESERVED_HEADROOM_MIN = 1000;
|
|
16397
|
+
var RESERVED_HEADROOM_RATIO = 0.02;
|
|
16398
|
+
var NON_EMERGENCY_MAX_CAP = 250000;
|
|
16399
|
+
var FORCE80_MAX_CAP = 500000;
|
|
16400
|
+
var FORCE95_MAX_CAP = 750000;
|
|
16401
|
+
var NORMAL_HYSTERESIS_TOKENS = 256;
|
|
16402
|
+
var RECOVERY_NO_HEAD_LIMIT = 2;
|
|
16403
|
+
function clampPercentage(value) {
|
|
16404
|
+
if (!Number.isFinite(value))
|
|
16405
|
+
return 0;
|
|
16406
|
+
return Math.max(0, Math.min(100, value));
|
|
16378
16407
|
}
|
|
16379
|
-
function
|
|
16380
|
-
|
|
16381
|
-
return text.length > maxChars ? `${text.slice(0, maxChars - 1).trimEnd()}…` : text;
|
|
16408
|
+
function clampOrdinal(value, rawMessageCount) {
|
|
16409
|
+
return Math.max(1, Math.min(rawMessageCount + 1, Math.floor(value)));
|
|
16382
16410
|
}
|
|
16383
|
-
function
|
|
16384
|
-
|
|
16411
|
+
function deriveProtectedTailTokenTarget(args) {
|
|
16412
|
+
const safeContextLimit = Number.isFinite(args.contextLimit) && args.contextLimit > 0 ? args.contextLimit : 128000;
|
|
16413
|
+
const safeThreshold = Number.isFinite(args.executeThresholdPercentage) ? Math.max(0, args.executeThresholdPercentage) : 65;
|
|
16414
|
+
const usable = Math.max(1, Math.round(safeContextLimit * safeThreshold / 100));
|
|
16415
|
+
const usage = clampPercentage(args.usagePercentage);
|
|
16416
|
+
const triggerBudget = args.triggerBudget ?? deriveTriggerBudget2(safeContextLimit, safeThreshold);
|
|
16417
|
+
const reserve = Math.max(RESERVED_HEADROOM_MIN, Math.round(usable * RESERVED_HEADROOM_RATIO));
|
|
16418
|
+
const rawN = Math.round(usable * ALPHA * (1 - usage / 100));
|
|
16419
|
+
const floorN = Math.min(FLOOR_MAX, Math.max(FLOOR_MIN, Math.round(usable * FLOOR_RATIO)));
|
|
16420
|
+
const headroom = Math.min(triggerBudget + reserve, Math.floor(usable * 0.5));
|
|
16421
|
+
const ceilingN = Math.max(1, Math.min(ABS_CAP, Math.floor(usable * MAX_USABLE_RATIO), usable - headroom));
|
|
16422
|
+
const effectiveFloor = Math.min(floorN, ceilingN);
|
|
16423
|
+
const N = Math.min(ceilingN, Math.max(effectiveFloor, rawN));
|
|
16424
|
+
return { usable, rawN, floorN, ceilingN, effectiveFloor, N, headroom, triggerBudget, reserve };
|
|
16385
16425
|
}
|
|
16386
|
-
function
|
|
16387
|
-
return
|
|
16426
|
+
function nonEmergencyPerRunCap(usable, N) {
|
|
16427
|
+
return Math.min(NON_EMERGENCY_MAX_CAP, Math.max(2 * N, Math.min(Math.round(0.25 * usable), 1e5)));
|
|
16388
16428
|
}
|
|
16389
|
-
function
|
|
16390
|
-
return
|
|
16429
|
+
function force80PerRunCap(usable, N) {
|
|
16430
|
+
return Math.min(FORCE80_MAX_CAP, Math.max(3 * N, Math.min(Math.round(0.35 * usable), 150000)));
|
|
16391
16431
|
}
|
|
16392
|
-
function
|
|
16393
|
-
return
|
|
16432
|
+
function force95PerRunCap(usable, N) {
|
|
16433
|
+
return Math.min(FORCE95_MAX_CAP, Math.max(4 * N, Math.min(Math.round(0.5 * usable), 250000)));
|
|
16394
16434
|
}
|
|
16395
|
-
function
|
|
16396
|
-
|
|
16435
|
+
function selectPerRunCap(snapshot) {
|
|
16436
|
+
const usable = Math.max(1, Math.round(snapshot.contextLimit * snapshot.executeThresholdPercentage / 100));
|
|
16437
|
+
if (snapshot.usagePercentage >= 95)
|
|
16438
|
+
return force95PerRunCap(usable, snapshot.N);
|
|
16439
|
+
if (snapshot.usagePercentage >= 80)
|
|
16440
|
+
return force80PerRunCap(usable, snapshot.N);
|
|
16441
|
+
return nonEmergencyPerRunCap(usable, snapshot.N);
|
|
16442
|
+
}
|
|
16443
|
+
function boundaryMessageId(index, ordinal) {
|
|
16444
|
+
if (ordinal < 1 || ordinal > index.rawMessageCount)
|
|
16397
16445
|
return null;
|
|
16398
|
-
|
|
16399
|
-
return `Summary runs failed in a row: ${failures.count}${since}.`;
|
|
16446
|
+
return index.messageIdAtOrdinal(ordinal);
|
|
16400
16447
|
}
|
|
16401
|
-
function
|
|
16402
|
-
|
|
16448
|
+
function isSemanticBoundaryCandidate(messageParts, role) {
|
|
16449
|
+
if (role === "user" && hasMeaningfulUserText2(messageParts))
|
|
16450
|
+
return true;
|
|
16451
|
+
if (messageParts.some((part) => String(typeof part === "object" && part !== null && "type" in part ? part.type : "") === "tool")) {
|
|
16452
|
+
return true;
|
|
16453
|
+
}
|
|
16454
|
+
return false;
|
|
16403
16455
|
}
|
|
16404
|
-
function
|
|
16405
|
-
const
|
|
16406
|
-
|
|
16407
|
-
const
|
|
16408
|
-
|
|
16409
|
-
|
|
16410
|
-
|
|
16411
|
-
|
|
16412
|
-
|
|
16413
|
-
|
|
16414
|
-
|
|
16415
|
-
} else if (run && run.endedAt === undefined) {
|
|
16416
|
-
sentences.push(run.startedAt !== undefined ? `${subject} is still running after ${formatHistorianSeconds(now - run.startedAt)} s.` : `${subject} is still running.`);
|
|
16417
|
-
} else if (run) {
|
|
16418
|
-
sentences.push(`${subject} finished after the wait ended.`);
|
|
16456
|
+
function semanticSnapBoundary(args) {
|
|
16457
|
+
const { messages, index, candidate, scaledN, lastCompartmentEndOrdinal } = args;
|
|
16458
|
+
let snapped = candidate;
|
|
16459
|
+
for (const message of messages) {
|
|
16460
|
+
if (message.ordinal > candidate)
|
|
16461
|
+
break;
|
|
16462
|
+
if (message.ordinal < lastCompartmentEndOrdinal + 1)
|
|
16463
|
+
continue;
|
|
16464
|
+
if (!isSemanticBoundaryCandidate(message.parts, message.role))
|
|
16465
|
+
continue;
|
|
16466
|
+
snapped = message.ordinal;
|
|
16419
16467
|
}
|
|
16420
|
-
if (
|
|
16421
|
-
|
|
16468
|
+
if (snapped === candidate)
|
|
16469
|
+
return candidate;
|
|
16470
|
+
const extraTokens = index.suffixTokensFromOrdinal(snapped) - index.suffixTokensFromOrdinal(candidate);
|
|
16471
|
+
if (extraTokens > Math.min(Math.round(1.5 * scaledN), 48000))
|
|
16472
|
+
return candidate;
|
|
16473
|
+
const snappedMessage = messages.find((message) => message.ordinal === snapped);
|
|
16474
|
+
if (snappedMessage?.role === "user" && index.tokenForOrdinal(snapped) > Math.max(2 * scaledN, 64000)) {
|
|
16475
|
+
return candidate;
|
|
16422
16476
|
}
|
|
16423
|
-
|
|
16424
|
-
if (streak)
|
|
16425
|
-
sentences.push(streak);
|
|
16426
|
-
sentences.push(ACTIONS);
|
|
16427
|
-
return sentences.join(" ");
|
|
16428
|
-
}
|
|
16429
|
-
function describeRepeatedHistorianFailures(input) {
|
|
16430
|
-
const now = input.now ?? Date.now();
|
|
16431
|
-
const { failures } = input;
|
|
16432
|
-
const facts = [
|
|
16433
|
-
streakSentence(failures, now) ?? "Summary runs are failing.",
|
|
16434
|
-
...input.chunk ? [`Last chunk: ${chunkLabel(input.chunk)}.`] : [],
|
|
16435
|
-
...failures.lastError ? [
|
|
16436
|
-
endSentence(`Last error: ${quoteError(failures.lastError, WARNING_ERROR_MAX_CHARS)}`)
|
|
16437
|
-
] : [],
|
|
16438
|
-
`${capitalize(usageClause(input.usagePercentage))}; at 95% a turn can be refused if no summary finishes in time.`
|
|
16439
|
-
];
|
|
16440
|
-
return [
|
|
16441
|
-
"## Magic Context — History summaries keep failing",
|
|
16442
|
-
"",
|
|
16443
|
-
facts.join(" "),
|
|
16444
|
-
"",
|
|
16445
|
-
ACTIONS
|
|
16446
|
-
].join(`
|
|
16447
|
-
`);
|
|
16477
|
+
return snapped;
|
|
16448
16478
|
}
|
|
16449
|
-
|
|
16450
|
-
|
|
16451
|
-
|
|
16452
|
-
|
|
16453
|
-
|
|
16454
|
-
|
|
16455
|
-
|
|
16456
|
-
|
|
16479
|
+
function snapWrapupBoundaryToUser(args) {
|
|
16480
|
+
const { messages, index, candidate, offset, triggerBudget } = args;
|
|
16481
|
+
if (candidate <= offset)
|
|
16482
|
+
return candidate;
|
|
16483
|
+
const snapTokenLimit = Math.min(Math.max(triggerBudget, 2000), 48000);
|
|
16484
|
+
for (let ordinal = candidate;ordinal >= offset; ordinal -= 1) {
|
|
16485
|
+
const message = messages.find((m) => m.ordinal === ordinal);
|
|
16486
|
+
if (!message)
|
|
16487
|
+
continue;
|
|
16488
|
+
if (message.role !== "user" || !hasMeaningfulUserText2(message.parts))
|
|
16489
|
+
continue;
|
|
16490
|
+
const extraTokens = index.rangeTokens(ordinal, candidate);
|
|
16491
|
+
if (extraTokens <= snapTokenLimit)
|
|
16492
|
+
return ordinal;
|
|
16493
|
+
return candidate;
|
|
16457
16494
|
}
|
|
16458
|
-
|
|
16459
|
-
return true;
|
|
16495
|
+
return candidate;
|
|
16460
16496
|
}
|
|
16461
|
-
function
|
|
16462
|
-
|
|
16463
|
-
|
|
16464
|
-
|
|
16497
|
+
function fenceWrapupBoundaryForToolArcs(args) {
|
|
16498
|
+
let boundary = args.candidate;
|
|
16499
|
+
const maxPasses = args.arcs.length + 1;
|
|
16500
|
+
for (let pass = 0;pass < maxPasses; pass += 1) {
|
|
16501
|
+
let next = boundary;
|
|
16502
|
+
for (const arc of args.arcs) {
|
|
16503
|
+
if (arc.resOrdinal === null) {
|
|
16504
|
+
continue;
|
|
16505
|
+
}
|
|
16506
|
+
if (arc.invOrdinal >= args.lastCompartmentEndOrdinal + 1 && completedToolArcCrossesBoundary(arc.invOrdinal, arc.resOrdinal, next)) {
|
|
16507
|
+
next = arc.invOrdinal;
|
|
16508
|
+
}
|
|
16509
|
+
}
|
|
16510
|
+
if (next === boundary)
|
|
16511
|
+
return boundary;
|
|
16512
|
+
boundary = next;
|
|
16465
16513
|
}
|
|
16466
|
-
|
|
16467
|
-
unrecordedFailures: input.unrecordedFailures
|
|
16468
|
-
});
|
|
16469
|
-
return describeRepeatedHistorianFailures({
|
|
16470
|
-
chunk: input.chunk,
|
|
16471
|
-
failures: { ...failures, count: input.failureCount },
|
|
16472
|
-
usagePercentage: loadPersistedUsage(input.db, input.sessionId)?.usage.percentage,
|
|
16473
|
-
now
|
|
16474
|
-
});
|
|
16475
|
-
}
|
|
16476
|
-
|
|
16477
|
-
// src/hooks/magic-context/historian-history-wait.ts
|
|
16478
|
-
var historyWaits = new Map;
|
|
16479
|
-
function newestMessageId(snapshot) {
|
|
16480
|
-
try {
|
|
16481
|
-
const count = getRawSessionMessageOrdinalCount2(snapshot.sessionId);
|
|
16482
|
-
const ids = readRawSessionMessageIdOrdinalsForRange2(snapshot.sessionId, count, count);
|
|
16483
|
-
const newest = ids.keys().next().value;
|
|
16484
|
-
if (newest)
|
|
16485
|
-
return newest;
|
|
16486
|
-
} catch {}
|
|
16487
|
-
return snapshot.rawLastMessageIdAtTrigger;
|
|
16488
|
-
}
|
|
16489
|
-
function recoveryWindow(snapshot, percentage) {
|
|
16490
|
-
return percentage >= escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage || snapshot.emergencyTailScale !== undefined;
|
|
16491
|
-
}
|
|
16492
|
-
function clearHistorianHistoryWait(sessionId) {
|
|
16493
|
-
historyWaits.delete(sessionId);
|
|
16514
|
+
return boundary;
|
|
16494
16515
|
}
|
|
16495
|
-
function
|
|
16496
|
-
const
|
|
16497
|
-
|
|
16498
|
-
|
|
16499
|
-
|
|
16500
|
-
|
|
16501
|
-
|
|
16502
|
-
|
|
16503
|
-
|
|
16504
|
-
|
|
16516
|
+
function applyHeadCap(args) {
|
|
16517
|
+
const {
|
|
16518
|
+
index,
|
|
16519
|
+
protectedTailStart,
|
|
16520
|
+
offset,
|
|
16521
|
+
arcs,
|
|
16522
|
+
lastCompartmentEndOrdinal,
|
|
16523
|
+
capTokens,
|
|
16524
|
+
recentOpenArcCutoff
|
|
16525
|
+
} = args;
|
|
16526
|
+
const diagnostics = {
|
|
16527
|
+
offset,
|
|
16528
|
+
capEnd: offset,
|
|
16529
|
+
capTokenSum: 0,
|
|
16530
|
+
completedFence: { from: offset, to: offset, arcs: [], tokenMass: 0 },
|
|
16531
|
+
oversizeAdmission: { from: offset, to: offset },
|
|
16532
|
+
openArcClamp: { from: offset, to: offset },
|
|
16533
|
+
completedRefence: { from: offset, to: offset, arcs: [], tokenMass: 0 },
|
|
16534
|
+
eligibleEnd: offset
|
|
16535
|
+
};
|
|
16536
|
+
if (offset >= protectedTailStart) {
|
|
16537
|
+
args.observeDiagnostics?.(diagnostics);
|
|
16538
|
+
return { eligibleEndOrdinal: offset, oversizeAtomicUnit: false };
|
|
16539
|
+
}
|
|
16540
|
+
let end = index.findHeadEndForCap(offset, protectedTailStart, capTokens);
|
|
16541
|
+
diagnostics.capEnd = end;
|
|
16542
|
+
diagnostics.capTokenSum = index.rangeTokens(offset, end);
|
|
16543
|
+
let oversizeAtomicUnit = end === offset + 1 && index.tokenForOrdinal(offset) > capTokens;
|
|
16544
|
+
let completedFence = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1, (component) => {
|
|
16545
|
+
diagnostics.completedFence.arcs = component.map((arc) => ({
|
|
16546
|
+
assistant: arc.invocation,
|
|
16547
|
+
result: arc.result
|
|
16548
|
+
}));
|
|
16549
|
+
diagnostics.completedFence.tokenMass = index.rangeTokens(Math.min(...component.map((arc) => arc.invocation)), Math.max(...component.map((arc) => arc.result)) + 1);
|
|
16505
16550
|
});
|
|
16506
|
-
|
|
16507
|
-
|
|
16508
|
-
|
|
16509
|
-
if (
|
|
16510
|
-
|
|
16511
|
-
|
|
16512
|
-
|
|
16513
|
-
try {
|
|
16514
|
-
const order = compareRawSessionMessageOrder2(snapshot.sessionId, newest, wait.newestMessageId);
|
|
16515
|
-
if (order === null || order > 0)
|
|
16516
|
-
return false;
|
|
16517
|
-
} catch {}
|
|
16551
|
+
diagnostics.completedFence.from = end;
|
|
16552
|
+
diagnostics.completedFence.to = completedFence;
|
|
16553
|
+
diagnostics.oversizeAdmission.from = completedFence;
|
|
16554
|
+
if (completedFence <= offset && end > offset) {
|
|
16555
|
+
const afterFirstArc = fenceBoundaryForCompletedToolArcs(end, arcs, offset + 1);
|
|
16556
|
+
if (afterFirstArc <= protectedTailStart)
|
|
16557
|
+
completedFence = afterFirstArc;
|
|
16518
16558
|
}
|
|
16519
|
-
|
|
16520
|
-
|
|
16521
|
-
|
|
16522
|
-
if (
|
|
16523
|
-
|
|
16524
|
-
|
|
16525
|
-
|
|
16526
|
-
return false;
|
|
16559
|
+
diagnostics.oversizeAdmission.to = completedFence;
|
|
16560
|
+
if (completedFence > end) {
|
|
16561
|
+
end = Math.min(protectedTailStart, completedFence);
|
|
16562
|
+
if (index.rangeTokens(offset, end) > capTokens)
|
|
16563
|
+
oversizeAtomicUnit = true;
|
|
16564
|
+
} else {
|
|
16565
|
+
end = completedFence;
|
|
16527
16566
|
}
|
|
16528
|
-
|
|
16529
|
-
|
|
16530
|
-
|
|
16531
|
-
|
|
16532
|
-
|
|
16533
|
-
|
|
16534
|
-
|
|
16535
|
-
|
|
16536
|
-
|
|
16537
|
-
No session notes or smart notes.`;
|
|
16538
|
-
function noteTouchedAt(note) {
|
|
16539
|
-
return note.updatedAt > 0 ? note.updatedAt : note.createdAt;
|
|
16540
|
-
}
|
|
16541
|
-
function formatNoteAge(touchedAt, nowMs) {
|
|
16542
|
-
const elapsed = Math.max(0, nowMs - touchedAt);
|
|
16543
|
-
const minutes = Math.floor(elapsed / 60000);
|
|
16544
|
-
if (minutes < 60)
|
|
16545
|
-
return `${minutes}m`;
|
|
16546
|
-
const hours = Math.floor(elapsed / 3600000);
|
|
16547
|
-
if (hours < 24)
|
|
16548
|
-
return `${hours}h`;
|
|
16549
|
-
const days = Math.floor(elapsed / 86400000);
|
|
16550
|
-
if (days < 7)
|
|
16551
|
-
return `${days}d`;
|
|
16552
|
-
return `${Math.floor(days / 7)}w`;
|
|
16553
|
-
}
|
|
16554
|
-
function clipNoteTitle(content, max) {
|
|
16555
|
-
const firstLine = (content.split(`
|
|
16556
|
-
`, 1)[0] ?? "").trim();
|
|
16557
|
-
const characters = [...firstLine];
|
|
16558
|
-
if (characters.length <= max)
|
|
16559
|
-
return firstLine;
|
|
16560
|
-
return `${characters.slice(0, max).join("")}…`;
|
|
16561
|
-
}
|
|
16562
|
-
function formatGlanceRow(note, nowMs) {
|
|
16563
|
-
const touchedAt = noteTouchedAt(note);
|
|
16564
|
-
const markers = [];
|
|
16565
|
-
if (note.status !== "active")
|
|
16566
|
-
markers.push(note.status);
|
|
16567
|
-
if (note.type === "smart" && note.status === "pending" && note.checkStatus === "parked") {
|
|
16568
|
-
markers.push(`parked: ${note.readyReason ?? "Condition can't be checked"}`);
|
|
16567
|
+
diagnostics.openArcClamp.from = end;
|
|
16568
|
+
for (const arc of arcs) {
|
|
16569
|
+
const resOrdinal = arc.resOrdinal;
|
|
16570
|
+
if (resOrdinal === null) {
|
|
16571
|
+
if (arc.invOrdinal >= recentOpenArcCutoff && arc.invOrdinal >= offset && arc.invOrdinal < end) {
|
|
16572
|
+
end = Math.min(end, arc.invOrdinal);
|
|
16573
|
+
}
|
|
16574
|
+
}
|
|
16569
16575
|
}
|
|
16570
|
-
|
|
16571
|
-
|
|
16572
|
-
|
|
16573
|
-
|
|
16574
|
-
|
|
16575
|
-
|
|
16576
|
-
|
|
16577
|
-
|
|
16578
|
-
}
|
|
16579
|
-
|
|
16580
|
-
|
|
16581
|
-
|
|
16582
|
-
|
|
16583
|
-
|
|
16584
|
-
|
|
16585
|
-
|
|
16586
|
-
const ordered = orderGlanceNotes(notes);
|
|
16587
|
-
const page = ordered.slice(options.offset, options.offset + options.limit);
|
|
16588
|
-
if (page.length === 0)
|
|
16589
|
-
return EMPTY_READ_REPLY;
|
|
16590
|
-
const rows = page.map((note) => formatGlanceRow(note, options.nowMs)).join(`
|
|
16591
|
-
`);
|
|
16592
|
-
const remaining = ordered.length - options.offset - page.length;
|
|
16593
|
-
const footer = remaining > 0 ? `
|
|
16594
|
-
|
|
16595
|
-
Showing ${page.length} of ${ordered.length} — ${remaining} older: ctx_note(action="read", offset=${options.offset + page.length})` : "";
|
|
16596
|
-
return `## Notes
|
|
16597
|
-
|
|
16598
|
-
${rows}${footer}`;
|
|
16599
|
-
}
|
|
16600
|
-
function formatNoteBody(note, nowMs) {
|
|
16601
|
-
const touchedAt = noteTouchedAt(note);
|
|
16602
|
-
const anchor = note.anchorOrdinal !== null ? ` ↳ @msg ${note.anchorOrdinal}` : "";
|
|
16603
|
-
const head = `- **#${note.id}** · ${formatNoteAge(touchedAt, nowMs)} · ${note.status}: ${note.content}${anchor}`;
|
|
16604
|
-
if (note.type !== "smart")
|
|
16605
|
-
return head;
|
|
16606
|
-
const condition = note.status === "ready" ? note.readyReason ?? note.surfaceCondition ?? "Condition satisfied" : note.surfaceCondition ?? "No condition recorded";
|
|
16607
|
-
const label = note.status === "ready" ? "Condition met" : "Condition";
|
|
16608
|
-
const failure = note.status === "pending" && note.readyReason?.startsWith("Condition can't be checked:") ? `
|
|
16609
|
-
${note.readyReason}` : "";
|
|
16610
|
-
return `${head}
|
|
16611
|
-
${label}: ${condition}${failure}`;
|
|
16612
|
-
}
|
|
16613
|
-
function renderNotesById(entries, nowMs) {
|
|
16614
|
-
const lines = entries.map(({ noteId, note }) => note ? formatNoteBody(note, nowMs) : `- Note #${noteId}: not_found`);
|
|
16615
|
-
return `## Notes by ID
|
|
16616
|
-
|
|
16617
|
-
${lines.join(`
|
|
16618
|
-
|
|
16619
|
-
`)}`;
|
|
16620
|
-
}
|
|
16621
|
-
function formatTraySuffix(tray, nowMs) {
|
|
16622
|
-
if (tray.activeCount <= 0 || tray.oldestTouchedAt === null)
|
|
16623
|
-
return "";
|
|
16624
|
-
return ` ${tray.activeCount} active, oldest ${formatNoteAge(tray.oldestTouchedAt, nowMs)}.`;
|
|
16625
|
-
}
|
|
16626
|
-
function formatWriteReply(noteId, tray, nowMs) {
|
|
16627
|
-
return `Saved session note #${noteId}.${formatTraySuffix(tray, nowMs)}`;
|
|
16628
|
-
}
|
|
16629
|
-
function noteNudgePickIndex(sessionId, counter, poolSize) {
|
|
16630
|
-
if (poolSize <= 0)
|
|
16631
|
-
return 0;
|
|
16632
|
-
const bytes = new TextEncoder().encode(`${sessionId}#${counter}`);
|
|
16633
|
-
let hash = 2166136261;
|
|
16634
|
-
for (const byte of bytes) {
|
|
16635
|
-
hash ^= byte;
|
|
16636
|
-
hash = Math.imul(hash, 16777619) >>> 0;
|
|
16576
|
+
diagnostics.openArcClamp.to = end;
|
|
16577
|
+
diagnostics.completedRefence.from = end;
|
|
16578
|
+
end = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1, (component) => {
|
|
16579
|
+
diagnostics.completedRefence.arcs = component.map((arc) => ({
|
|
16580
|
+
assistant: arc.invocation,
|
|
16581
|
+
result: arc.result
|
|
16582
|
+
}));
|
|
16583
|
+
diagnostics.completedRefence.tokenMass = index.rangeTokens(Math.min(...component.map((arc) => arc.invocation)), Math.max(...component.map((arc) => arc.result)) + 1);
|
|
16584
|
+
});
|
|
16585
|
+
diagnostics.completedRefence.to = end;
|
|
16586
|
+
if (end > protectedTailStart)
|
|
16587
|
+
end = offset;
|
|
16588
|
+
diagnostics.eligibleEnd = end <= offset ? offset : end;
|
|
16589
|
+
args.observeDiagnostics?.(diagnostics);
|
|
16590
|
+
if (end <= offset && offset < protectedTailStart) {
|
|
16591
|
+
return { eligibleEndOrdinal: offset, oversizeAtomicUnit };
|
|
16637
16592
|
}
|
|
16638
|
-
return
|
|
16639
|
-
}
|
|
16640
|
-
function formatNoteNudge(args) {
|
|
16641
|
-
const counts = `${args.readyCount} notes ready, ${args.activeCount} active`;
|
|
16642
|
-
const oldest = args.activeCount > 0 && args.oldestActiveTouchedAt !== null ? ` (oldest ${formatNoteAge(args.oldestActiveTouchedAt, args.nowMs)})` : "";
|
|
16643
|
-
const shown = args.shown ? `: #${args.shown.id} ${clipNoteTitle(args.shown.content, NUDGE_TITLE_MAX)}` : "";
|
|
16644
|
-
return `${counts}${oldest}${shown}`;
|
|
16593
|
+
return { eligibleEndOrdinal: end, oversizeAtomicUnit };
|
|
16645
16594
|
}
|
|
16646
|
-
|
|
16647
|
-
|
|
16648
|
-
|
|
16649
|
-
|
|
16650
|
-
|
|
16651
|
-
|
|
16652
|
-
|
|
16653
|
-
|
|
16654
|
-
|
|
16655
|
-
|
|
16656
|
-
|
|
16657
|
-
|
|
16658
|
-
|
|
16659
|
-
|
|
16660
|
-
|
|
16661
|
-
|
|
16662
|
-
|
|
16663
|
-
|
|
16664
|
-
|
|
16665
|
-
|
|
16666
|
-
|
|
16667
|
-
|
|
16668
|
-
|
|
16669
|
-
|
|
16670
|
-
|
|
16671
|
-
|
|
16672
|
-
|
|
16673
|
-
|
|
16674
|
-
const
|
|
16675
|
-
if (
|
|
16676
|
-
return
|
|
16677
|
-
|
|
16678
|
-
|
|
16679
|
-
|
|
16680
|
-
|
|
16681
|
-
|
|
16682
|
-
|
|
16683
|
-
|
|
16684
|
-
|
|
16685
|
-
|
|
16686
|
-
|
|
16687
|
-
|
|
16688
|
-
|
|
16689
|
-
|
|
16690
|
-
|
|
16691
|
-
|
|
16692
|
-
|
|
16693
|
-
|
|
16694
|
-
|
|
16695
|
-
|
|
16696
|
-
|
|
16697
|
-
|
|
16698
|
-
|
|
16699
|
-
|
|
16700
|
-
|
|
16701
|
-
|
|
16702
|
-
|
|
16703
|
-
|
|
16704
|
-
|
|
16705
|
-
|
|
16706
|
-
|
|
16707
|
-
|
|
16708
|
-
if (!eligibility && !state.triggerMessageId && currentUserMessageId) {
|
|
16709
|
-
setPersistedNoteNudgeTriggerMessageId(db, sessionId, currentUserMessageId);
|
|
16710
|
-
state.triggerMessageId = currentUserMessageId;
|
|
16711
|
-
}
|
|
16712
|
-
if (!eligibility && state.triggerMessageId && currentUserMessageId && state.triggerMessageId === currentUserMessageId) {
|
|
16713
|
-
sessionLog2(sessionId, `note-nudge: deferring — current user message ${currentUserMessageId} is same as trigger-time message`);
|
|
16714
|
-
return null;
|
|
16595
|
+
function resolveProtectedTailBoundary(ctx) {
|
|
16596
|
+
const createdAt = ctx.createdAt ?? Date.now();
|
|
16597
|
+
const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
|
|
16598
|
+
const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
|
|
16599
|
+
const messages = readRawSessionMessageRange2(ctx.sessionId, Math.max(1, offset - 1), absoluteMessageCount);
|
|
16600
|
+
const storedWeights = ctx.storedTokenTotalsForMessages?.(messages.map((m) => m.id), messages);
|
|
16601
|
+
const storedTotals = storedWeights?.totals ?? ctx.storedTokenTotals;
|
|
16602
|
+
const storedRemovedTotals = storedWeights?.summaryRemovedTotals ?? ctx.storedSummaryRemovedTokenTotals;
|
|
16603
|
+
const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
|
|
16604
|
+
providerShapeVersion: ctx.providerShapeVersion,
|
|
16605
|
+
cacheNamespace: ctx.cacheNamespace,
|
|
16606
|
+
calibration: ctx.calibration,
|
|
16607
|
+
absoluteMessageCount,
|
|
16608
|
+
storedTotalForMessage: storedTotals ? (m) => {
|
|
16609
|
+
const v = storedTotals.get(m.id);
|
|
16610
|
+
return v === undefined ? null : v;
|
|
16611
|
+
} : undefined
|
|
16612
|
+
});
|
|
16613
|
+
const summaryRemovedIndex = buildTrueRawTokenIndex(ctx.sessionId, messages, {
|
|
16614
|
+
providerShapeVersion: ctx.providerShapeVersion,
|
|
16615
|
+
cacheNamespace: ctx.cacheNamespace,
|
|
16616
|
+
calibration: ctx.calibration,
|
|
16617
|
+
absoluteMessageCount,
|
|
16618
|
+
measure: "summary-removed",
|
|
16619
|
+
storedTotalForMessage: storedRemovedTotals ? (m) => storedRemovedTotals.get(m.id) ?? null : undefined
|
|
16620
|
+
});
|
|
16621
|
+
const rawMessageCount = index.rawMessageCount;
|
|
16622
|
+
const usagePercentage = clampPercentage(ctx.usage?.percentage ?? 0);
|
|
16623
|
+
const usageInputTokens = Math.max(0, Math.round(ctx.usage?.inputTokens ?? 0));
|
|
16624
|
+
if (rawMessageCount === 0) {
|
|
16625
|
+
return {
|
|
16626
|
+
sessionId: ctx.sessionId,
|
|
16627
|
+
mode: ctx.mode,
|
|
16628
|
+
offset,
|
|
16629
|
+
lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
|
|
16630
|
+
offsetMessageId: null,
|
|
16631
|
+
protectedTailStart: 1,
|
|
16632
|
+
protectedTailStartMessageId: null,
|
|
16633
|
+
eligibleEndOrdinal: 1,
|
|
16634
|
+
eligibleEndMessageId: null,
|
|
16635
|
+
rawMessageCountAtTrigger: 0,
|
|
16636
|
+
rawLastMessageIdAtTrigger: null,
|
|
16637
|
+
N: 0,
|
|
16638
|
+
usagePercentage,
|
|
16639
|
+
usageInputTokens,
|
|
16640
|
+
usageSource: ctx.usageSource,
|
|
16641
|
+
contextLimit: ctx.contextLimit,
|
|
16642
|
+
executeThresholdPercentage: ctx.executeThresholdPercentage,
|
|
16643
|
+
triggerBudget: ctx.triggerBudget,
|
|
16644
|
+
priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
|
|
16645
|
+
migrationFloorActive: ctx.migrationFloorActive,
|
|
16646
|
+
emergencyTailScale: ctx.emergencyTailScale,
|
|
16647
|
+
recovery: ctx.recovery,
|
|
16648
|
+
providerShapeVersion: ctx.providerShapeVersion,
|
|
16649
|
+
cacheNamespace: ctx.cacheNamespace,
|
|
16650
|
+
createdAt,
|
|
16651
|
+
rawRangeFingerprint: "",
|
|
16652
|
+
trueRawEligibleTokens: 0,
|
|
16653
|
+
summaryRemovedEligibleTokens: 0,
|
|
16654
|
+
oversizeAtomicUnit: false,
|
|
16655
|
+
boundaryReason: "empty-session"
|
|
16656
|
+
};
|
|
16715
16657
|
}
|
|
16716
|
-
|
|
16717
|
-
|
|
16718
|
-
|
|
16719
|
-
|
|
16720
|
-
|
|
16658
|
+
if (ctx.mode === "manual-full-recomp") {
|
|
16659
|
+
const arcs = buildToolArcs(messages);
|
|
16660
|
+
const recompTarget = deriveProtectedTailTokenTarget({
|
|
16661
|
+
contextLimit: ctx.contextLimit,
|
|
16662
|
+
executeThresholdPercentage: ctx.executeThresholdPercentage,
|
|
16663
|
+
usagePercentage: 0,
|
|
16664
|
+
triggerBudget: ctx.triggerBudget
|
|
16665
|
+
});
|
|
16666
|
+
const recentOpenArcCutoff = index.findSuffixStartForTokens(recompTarget.N);
|
|
16667
|
+
const firstOpenArc = arcs.find((arc) => arc.resOrdinal === null && arc.invOrdinal >= offset && arc.invOrdinal >= recentOpenArcCutoff);
|
|
16668
|
+
const protectedTailStart = firstOpenArc?.invOrdinal ?? rawMessageCount + 1;
|
|
16669
|
+
const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, protectedTailStart);
|
|
16670
|
+
return {
|
|
16671
|
+
sessionId: ctx.sessionId,
|
|
16672
|
+
mode: ctx.mode,
|
|
16673
|
+
offset,
|
|
16674
|
+
lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
|
|
16675
|
+
offsetMessageId: boundaryMessageId(index, offset),
|
|
16676
|
+
protectedTailStart,
|
|
16677
|
+
protectedTailStartMessageId: null,
|
|
16678
|
+
eligibleEndOrdinal: protectedTailStart,
|
|
16679
|
+
eligibleEndMessageId: boundaryMessageId(index, protectedTailStart - 1),
|
|
16680
|
+
rawMessageCountAtTrigger: rawMessageCount,
|
|
16681
|
+
rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
|
|
16682
|
+
N: 0,
|
|
16683
|
+
usagePercentage: 0,
|
|
16684
|
+
usageInputTokens: 0,
|
|
16685
|
+
usageSource: "manual-none",
|
|
16686
|
+
contextLimit: ctx.contextLimit,
|
|
16687
|
+
executeThresholdPercentage: ctx.executeThresholdPercentage,
|
|
16688
|
+
triggerBudget: ctx.triggerBudget,
|
|
16689
|
+
priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
|
|
16690
|
+
migrationFloorActive: false,
|
|
16691
|
+
emergencyTailScale: ctx.emergencyTailScale,
|
|
16692
|
+
recovery: ctx.recovery,
|
|
16693
|
+
providerShapeVersion: ctx.providerShapeVersion,
|
|
16694
|
+
cacheNamespace: ctx.cacheNamespace,
|
|
16695
|
+
createdAt,
|
|
16696
|
+
rawRangeFingerprint,
|
|
16697
|
+
trueRawEligibleTokens: index.rangeTokens(offset, protectedTailStart),
|
|
16698
|
+
summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, protectedTailStart),
|
|
16699
|
+
oversizeAtomicUnit: false,
|
|
16700
|
+
boundaryReason: firstOpenArc ? "open-tool-arc" : "manual-full-recomp"
|
|
16701
|
+
};
|
|
16721
16702
|
}
|
|
16722
|
-
const
|
|
16723
|
-
|
|
16724
|
-
|
|
16725
|
-
|
|
16726
|
-
|
|
16727
|
-
|
|
16728
|
-
|
|
16703
|
+
const target = deriveProtectedTailTokenTarget({
|
|
16704
|
+
contextLimit: ctx.contextLimit,
|
|
16705
|
+
executeThresholdPercentage: ctx.executeThresholdPercentage,
|
|
16706
|
+
usagePercentage,
|
|
16707
|
+
triggerBudget: ctx.triggerBudget
|
|
16708
|
+
});
|
|
16709
|
+
const scaledN = ctx.emergencyTailScale ? Math.max(1, Math.floor(target.N * ctx.emergencyTailScale)) : target.N;
|
|
16710
|
+
const arcs = buildToolArcs(messages);
|
|
16711
|
+
let boundary = index.findSuffixStartForTokens(scaledN);
|
|
16712
|
+
const recentOpenArcCutoff = boundary;
|
|
16713
|
+
let boundaryReason = boundary === 1 ? "whole-session-smaller-than-tail" : "size-walk";
|
|
16714
|
+
const tokenAtBoundary = index.tokenForOrdinal(boundary);
|
|
16715
|
+
if (boundary <= rawMessageCount && tokenAtBoundary > Math.max(2 * scaledN, 64000) && boundary < rawMessageCount) {
|
|
16716
|
+
boundary += 1;
|
|
16717
|
+
boundaryReason = "huge-message-exception";
|
|
16729
16718
|
}
|
|
16730
|
-
|
|
16731
|
-
|
|
16732
|
-
|
|
16733
|
-
|
|
16734
|
-
|
|
16735
|
-
|
|
16736
|
-
|
|
16719
|
+
boundary = fenceBoundaryForToolArcs(boundary, arcs, ctx.lastCompartmentEndOrdinal, recentOpenArcCutoff);
|
|
16720
|
+
const snapped = semanticSnapBoundary({
|
|
16721
|
+
messages,
|
|
16722
|
+
index,
|
|
16723
|
+
candidate: boundary,
|
|
16724
|
+
scaledN,
|
|
16725
|
+
lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
|
|
16726
|
+
});
|
|
16727
|
+
if (snapped !== boundary)
|
|
16728
|
+
boundaryReason = "semantic-snap";
|
|
16729
|
+
boundary = fenceBoundaryForToolArcs(snapped, arcs, ctx.lastCompartmentEndOrdinal, recentOpenArcCutoff);
|
|
16730
|
+
let runtimeFloor = offset;
|
|
16731
|
+
if (ctx.migrationFloorActive)
|
|
16732
|
+
runtimeFloor = Math.max(runtimeFloor, ctx.priorBoundaryOrdinal);
|
|
16733
|
+
let protectedTailStart = Math.max(boundary, runtimeFloor);
|
|
16734
|
+
const forceMaterializationPercentage = escalationBands(ctx.executeThresholdPercentage).forceMaterializationPercentage;
|
|
16735
|
+
const livePromptFloor = {
|
|
16736
|
+
ordinal: null,
|
|
16737
|
+
from: protectedTailStart,
|
|
16738
|
+
to: protectedTailStart
|
|
16739
|
+
};
|
|
16740
|
+
if (!ctx.emergencyTailScale && usagePercentage < forceMaterializationPercentage) {
|
|
16741
|
+
let lastMeaningfulUserOrdinal = 0;
|
|
16742
|
+
for (let i = messages.length - 1;i >= 0; i--) {
|
|
16743
|
+
const message = messages[i];
|
|
16744
|
+
if (message.role !== "user")
|
|
16745
|
+
continue;
|
|
16746
|
+
if (!hasMeaningfulUserText2(message.parts))
|
|
16747
|
+
continue;
|
|
16748
|
+
lastMeaningfulUserOrdinal = message.ordinal;
|
|
16749
|
+
break;
|
|
16750
|
+
}
|
|
16751
|
+
livePromptFloor.ordinal = lastMeaningfulUserOrdinal || null;
|
|
16752
|
+
livePromptFloor.messageId = boundaryMessageId(index, lastMeaningfulUserOrdinal);
|
|
16753
|
+
if (!ctx.liftLivePromptFloor && lastMeaningfulUserOrdinal >= offset) {
|
|
16754
|
+
protectedTailStart = Math.min(protectedTailStart, lastMeaningfulUserOrdinal);
|
|
16737
16755
|
}
|
|
16738
16756
|
}
|
|
16739
|
-
|
|
16740
|
-
if (
|
|
16741
|
-
|
|
16742
|
-
Reason: `)[1]?.split(`
|
|
16743
|
-
`)[0] ?? "check unavailable";
|
|
16744
|
-
return `Smart note check unavailable: ${reason}. Read ctx_note #${failureNotice.id} for the condition and repair instructions; this is NOT evidence that the condition is met.`;
|
|
16745
|
-
}
|
|
16746
|
-
const parts = [];
|
|
16747
|
-
if (notes.length > 0) {
|
|
16748
|
-
parts.push(`${notes.length} deferred note${notes.length === 1 ? "" : "s"}`);
|
|
16749
|
-
}
|
|
16750
|
-
if (readySmartNotes.length > 0) {
|
|
16751
|
-
parts.push(`${readySmartNotes.length} ready smart note${readySmartNotes.length === 1 ? "" : "s"}`);
|
|
16757
|
+
livePromptFloor.to = protectedTailStart;
|
|
16758
|
+
if (protectedTailStart > offset && index.rangeTokens(offset, protectedTailStart) <= NORMAL_HYSTERESIS_TOKENS) {
|
|
16759
|
+
protectedTailStart = offset;
|
|
16752
16760
|
}
|
|
16753
|
-
|
|
16754
|
-
|
|
16755
|
-
|
|
16756
|
-
|
|
16757
|
-
|
|
16758
|
-
|
|
16759
|
-
|
|
16760
|
-
|
|
16761
|
-
}
|
|
16762
|
-
|
|
16763
|
-
|
|
16764
|
-
|
|
16765
|
-
|
|
16766
|
-
|
|
16767
|
-
|
|
16768
|
-
|
|
16769
|
-
|
|
16770
|
-
|
|
16771
|
-
|
|
16772
|
-
|
|
16773
|
-
|
|
16761
|
+
protectedTailStart = clampOrdinal(protectedTailStart, rawMessageCount);
|
|
16762
|
+
protectedTailStart = retreatPastHostUnservedRows(messages, protectedTailStart, offset);
|
|
16763
|
+
protectedTailStart = Math.max(offset, fenceBoundaryForCompletedToolArcs(protectedTailStart, arcs, 1));
|
|
16764
|
+
const perRunCap = selectPerRunCap({
|
|
16765
|
+
usagePercentage,
|
|
16766
|
+
N: scaledN,
|
|
16767
|
+
contextLimit: ctx.contextLimit,
|
|
16768
|
+
executeThresholdPercentage: ctx.executeThresholdPercentage
|
|
16769
|
+
});
|
|
16770
|
+
let headDiagnostics;
|
|
16771
|
+
const head = applyHeadCap({
|
|
16772
|
+
observeDiagnostics: (value) => {
|
|
16773
|
+
headDiagnostics = value;
|
|
16774
|
+
},
|
|
16775
|
+
index: summaryRemovedIndex,
|
|
16776
|
+
protectedTailStart,
|
|
16777
|
+
offset,
|
|
16778
|
+
arcs,
|
|
16779
|
+
lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal,
|
|
16780
|
+
capTokens: perRunCap,
|
|
16781
|
+
recentOpenArcCutoff
|
|
16782
|
+
});
|
|
16783
|
+
const servedEndOrdinal = retreatPastHostUnservedRows(messages, head.eligibleEndOrdinal, offset);
|
|
16784
|
+
const eligibleEndOrdinal = Math.max(offset, fenceBoundaryForCompletedToolArcs(servedEndOrdinal, arcs, 1));
|
|
16785
|
+
const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, eligibleEndOrdinal);
|
|
16786
|
+
return {
|
|
16787
|
+
sessionId: ctx.sessionId,
|
|
16788
|
+
mode: ctx.mode,
|
|
16789
|
+
offset,
|
|
16790
|
+
lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
|
|
16791
|
+
offsetMessageId: boundaryMessageId(index, offset),
|
|
16792
|
+
protectedTailStart,
|
|
16793
|
+
protectedTailStartMessageId: boundaryMessageId(index, protectedTailStart),
|
|
16794
|
+
eligibleEndOrdinal,
|
|
16795
|
+
eligibleEndMessageId: boundaryMessageId(index, eligibleEndOrdinal - 1),
|
|
16796
|
+
rawMessageCountAtTrigger: rawMessageCount,
|
|
16797
|
+
rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
|
|
16798
|
+
N: scaledN,
|
|
16799
|
+
usagePercentage,
|
|
16800
|
+
usageInputTokens,
|
|
16801
|
+
usageSource: ctx.usageSource,
|
|
16802
|
+
contextLimit: ctx.contextLimit,
|
|
16803
|
+
executeThresholdPercentage: ctx.executeThresholdPercentage,
|
|
16804
|
+
triggerBudget: ctx.triggerBudget,
|
|
16805
|
+
priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
|
|
16806
|
+
migrationFloorActive: ctx.migrationFloorActive,
|
|
16807
|
+
emergencyTailScale: ctx.emergencyTailScale,
|
|
16808
|
+
recovery: ctx.recovery,
|
|
16809
|
+
liftLivePromptFloor: ctx.liftLivePromptFloor === true ? true : undefined,
|
|
16810
|
+
providerShapeVersion: ctx.providerShapeVersion,
|
|
16811
|
+
cacheNamespace: ctx.cacheNamespace,
|
|
16812
|
+
createdAt,
|
|
16813
|
+
rawRangeFingerprint,
|
|
16814
|
+
trueRawEligibleTokens: index.rangeTokens(offset, eligibleEndOrdinal),
|
|
16815
|
+
summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, eligibleEndOrdinal),
|
|
16816
|
+
oversizeAtomicUnit: head.oversizeAtomicUnit,
|
|
16817
|
+
boundaryReason,
|
|
16818
|
+
diagnostics: boundaryDiagnostics({
|
|
16819
|
+
tailTarget: target,
|
|
16820
|
+
usable: target.usable,
|
|
16821
|
+
usagePercentage,
|
|
16822
|
+
N: scaledN,
|
|
16823
|
+
triggerBudget: ctx.triggerBudget,
|
|
16824
|
+
capTokens: perRunCap,
|
|
16825
|
+
sizeWalkStart: recentOpenArcCutoff,
|
|
16826
|
+
protectedTailStart,
|
|
16827
|
+
livePromptFloor,
|
|
16828
|
+
head: headDiagnostics
|
|
16829
|
+
})
|
|
16830
|
+
};
|
|
16774
16831
|
}
|
|
16775
|
-
function
|
|
16776
|
-
|
|
16777
|
-
|
|
16778
|
-
|
|
16779
|
-
|
|
16780
|
-
|
|
16781
|
-
|
|
16782
|
-
|
|
16783
|
-
|
|
16832
|
+
function readLastCompartmentBoundary(db, sessionId) {
|
|
16833
|
+
const row = db.prepare(`SELECT COALESCE(MAX(end_message), -1) AS max_end,
|
|
16834
|
+
(SELECT end_message_id FROM compartments
|
|
16835
|
+
WHERE session_id = ? ORDER BY sequence DESC LIMIT 1) AS end_message_id
|
|
16836
|
+
FROM compartments WHERE session_id = ?`).get(sessionId, sessionId);
|
|
16837
|
+
const endMessageId = row?.end_message_id;
|
|
16838
|
+
return {
|
|
16839
|
+
endOrdinal: typeof row?.max_end === "number" ? row.max_end : -1,
|
|
16840
|
+
endMessageId: typeof endMessageId === "string" && endMessageId.length > 0 ? endMessageId : null
|
|
16841
|
+
};
|
|
16784
16842
|
}
|
|
16785
|
-
function
|
|
16786
|
-
|
|
16787
|
-
|
|
16788
|
-
|
|
16789
|
-
|
|
16790
|
-
|
|
16791
|
-
|
|
16792
|
-
|
|
16793
|
-
|
|
16794
|
-
|
|
16795
|
-
|
|
16796
|
-
|
|
16797
|
-
WHERE id = ? AND type = 'session' AND session_id = ?
|
|
16798
|
-
AND content LIKE 'Smart note #% cannot be checked.%'`).run(Date.now(), Number(noticeId[1]), sessionId);
|
|
16843
|
+
function resolveBoundaryContext(args) {
|
|
16844
|
+
const lastCompartmentBoundary = readLastCompartmentBoundary(args.db, args.sessionId);
|
|
16845
|
+
const lastCompartmentEndOrdinal = lastCompartmentBoundary.endOrdinal;
|
|
16846
|
+
const triggerBudget = deriveTriggerBudget2(args.contextLimit, args.executeThresholdPercentage);
|
|
16847
|
+
let meta = args.protectedTailMeta ?? loadProtectedTailMeta(args.db, args.sessionId);
|
|
16848
|
+
let migrationFloorActive = false;
|
|
16849
|
+
if (meta.protectedTailPolicyVersion < 3) {
|
|
16850
|
+
let legacyBoundary = 1;
|
|
16851
|
+
try {
|
|
16852
|
+
legacyBoundary = getLegacyProtectedTailStartOrdinal2(args.sessionId);
|
|
16853
|
+
} catch (error) {
|
|
16854
|
+
sessionLog2(args.sessionId, "protected-tail migration seed fell back to ordinal 1:", error);
|
|
16799
16855
|
}
|
|
16800
|
-
|
|
16801
|
-
|
|
16802
|
-
|
|
16803
|
-
recordNoteNudgeDeliveryTime(sessionId);
|
|
16804
|
-
}
|
|
16805
|
-
sessionLog2(sessionId, outcome.ok ? `note-nudge: marked delivered, sticky anchor=${messageId} (${outcome.kind})` : `note-nudge: delivery not persisted for anchor=${messageId} (${outcome.kind})`);
|
|
16806
|
-
return outcome;
|
|
16807
|
-
}
|
|
16808
|
-
function clearNoteNudgeTriggerAndCooldown(db, sessionId) {
|
|
16809
|
-
db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
|
|
16810
|
-
lastDeliveredAt.delete(sessionId);
|
|
16811
|
-
}
|
|
16812
|
-
function resetNoteNudgeCooldownOnly(sessionId) {
|
|
16813
|
-
lastDeliveredAt.delete(sessionId);
|
|
16814
|
-
}
|
|
16815
|
-
function clearNoteNudgeTriggerOnly(db, sessionId) {
|
|
16816
|
-
db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
|
|
16817
|
-
}
|
|
16818
|
-
|
|
16819
|
-
// src/hooks/magic-context/persist-filtered-noise.ts
|
|
16820
|
-
function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
|
|
16821
|
-
const rows = chunk.filteredNoiseLines ?? [];
|
|
16822
|
-
const start = chunk.startIndex;
|
|
16823
|
-
if (chunk.text || chunk.messageCount !== 0 || eligibleEnd <= start || rows.length !== eligibleEnd - start || rows.some((row, index) => row.ordinal !== start + index || !row.messageId))
|
|
16824
|
-
return false;
|
|
16825
|
-
const endId = rows[rows.length - 1].messageId;
|
|
16826
|
-
if (!hasRawSessionMessageById2(sessionId, endId)) {
|
|
16827
|
-
sessionLog2(sessionId, `historian skipped a filtered-noise marker for ordinals ${start}-${eligibleEnd - 1}: its end row ${endId} is no longer in the host store`);
|
|
16828
|
-
return false;
|
|
16829
|
-
}
|
|
16830
|
-
const saved = db.transaction(() => {
|
|
16831
|
-
const prior = getCompartments(db, sessionId);
|
|
16832
|
-
const last = prior.at(-1);
|
|
16833
|
-
if ((last?.endMessage ?? 0) + 1 !== start)
|
|
16834
|
-
return false;
|
|
16835
|
-
appendCompartments(db, sessionId, [
|
|
16836
|
-
{
|
|
16837
|
-
sequence: (last?.sequence ?? -1) + 1,
|
|
16838
|
-
startMessage: start,
|
|
16839
|
-
endMessage: eligibleEnd - 1,
|
|
16840
|
-
startMessageId: rows[0].messageId,
|
|
16841
|
-
endMessageId: rows[rows.length - 1].messageId,
|
|
16842
|
-
title: "",
|
|
16843
|
-
content: "",
|
|
16844
|
-
p1: "",
|
|
16845
|
-
p2: "",
|
|
16846
|
-
p3: "",
|
|
16847
|
-
p4: "",
|
|
16848
|
-
episodeType: "filtered-noise",
|
|
16849
|
-
importance: 1
|
|
16850
|
-
}
|
|
16851
|
-
]);
|
|
16852
|
-
return true;
|
|
16853
|
-
}).immediate();
|
|
16854
|
-
if (saved)
|
|
16855
|
-
sessionLog2(sessionId, `historian skipped ordinals ${start}-${eligibleEnd - 1}: all ${rows.length} raw rows excluded by chunk filters (no-content boundary marker)`);
|
|
16856
|
-
return saved;
|
|
16857
|
-
}
|
|
16858
|
-
|
|
16859
|
-
// src/hooks/magic-context/file-token-coverage.ts
|
|
16860
|
-
function omitIncompleteFileTokenTotals(db, sessionId, messages, totals) {
|
|
16861
|
-
const filesByMessage = new Map;
|
|
16862
|
-
for (const message of messages) {
|
|
16863
|
-
const count = message.parts.filter(isFilePart).length;
|
|
16864
|
-
if (count > 0 && totals.has(message.id))
|
|
16865
|
-
filesByMessage.set(message.id, count);
|
|
16866
|
-
}
|
|
16867
|
-
if (filesByMessage.size === 0)
|
|
16868
|
-
return totals;
|
|
16869
|
-
const rows = db.prepare(`
|
|
16870
|
-
SELECT o.value AS owner, COUNT(t.id) AS count
|
|
16871
|
-
FROM json_each(?) o LEFT JOIN tags t
|
|
16872
|
-
ON t.session_id = ? AND t.type = 'file'
|
|
16873
|
-
AND t.message_id >= o.value || ':file'
|
|
16874
|
-
AND t.message_id < o.value || ':file;'
|
|
16875
|
-
GROUP BY o.value
|
|
16876
|
-
`).all(JSON.stringify([...filesByMessage.keys()]), sessionId);
|
|
16877
|
-
for (const row of rows) {
|
|
16878
|
-
if (row.count < (filesByMessage.get(row.owner) ?? 0))
|
|
16879
|
-
totals.delete(row.owner);
|
|
16856
|
+
const seedResult = markProtectedTailPolicyV3Seeded(args.db, args.sessionId, Math.max(1, legacyBoundary));
|
|
16857
|
+
meta = seedResult;
|
|
16858
|
+
migrationFloorActive = seedResult.seeded;
|
|
16880
16859
|
}
|
|
16881
|
-
|
|
16882
|
-
|
|
16883
|
-
|
|
16884
|
-
|
|
16885
|
-
|
|
16886
|
-
|
|
16887
|
-
|
|
16888
|
-
|
|
16860
|
+
const calibration = sessionDecisionCalibration(args.db, args.sessionId);
|
|
16861
|
+
const storedTokenTotalsForMessages = (messageIds, messages = []) => {
|
|
16862
|
+
try {
|
|
16863
|
+
const weights = getAllStatusTagTokenTotalsFlat2(args.db, args.sessionId, args.taggerFloor ?? 0, calibration, messageIds);
|
|
16864
|
+
return {
|
|
16865
|
+
totals: omitIncompleteFileTokenTotals(args.db, args.sessionId, messages, weights.totals),
|
|
16866
|
+
summaryRemovedTotals: weights.summaryRemovedTotals
|
|
16867
|
+
};
|
|
16868
|
+
} catch (error) {
|
|
16869
|
+
sessionLog2(args.sessionId, "protected-tail stored-token map unavailable (live fallback):", error);
|
|
16870
|
+
return;
|
|
16871
|
+
}
|
|
16872
|
+
};
|
|
16889
16873
|
return {
|
|
16890
|
-
|
|
16891
|
-
|
|
16892
|
-
|
|
16874
|
+
sessionId: args.sessionId,
|
|
16875
|
+
mode: args.mode,
|
|
16876
|
+
contextLimit: args.contextLimit,
|
|
16877
|
+
executeThresholdPercentage: args.executeThresholdPercentage,
|
|
16878
|
+
triggerBudget,
|
|
16879
|
+
usage: args.usage ?? null,
|
|
16880
|
+
usageSource: args.usageSource ?? (args.usage ? "live" : "provisional-zero"),
|
|
16881
|
+
lastCompartmentEndOrdinal,
|
|
16882
|
+
lastCompartmentEndMessageId: lastCompartmentBoundary.endMessageId,
|
|
16883
|
+
priorBoundaryOrdinal: meta.priorBoundaryOrdinal,
|
|
16884
|
+
protectedTailPolicyVersion: meta.protectedTailPolicyVersion,
|
|
16885
|
+
migrationFloorActive,
|
|
16886
|
+
emergencyTailScale: args.emergencyTailScale,
|
|
16887
|
+
recovery: args.recovery,
|
|
16888
|
+
liftLivePromptFloor: args.liftLivePromptFloor,
|
|
16889
|
+
providerShapeVersion: args.providerShapeVersion ?? "opencode-v1",
|
|
16890
|
+
cacheNamespace: args.cacheNamespace ?? `opencode:${args.sessionId}`,
|
|
16891
|
+
storedTokenTotalsForMessages,
|
|
16892
|
+
calibration
|
|
16893
16893
|
};
|
|
16894
16894
|
}
|
|
16895
|
-
|
|
16896
|
-
|
|
16897
|
-
var FLOOR_MIN = 2000;
|
|
16898
|
-
var FLOOR_MAX = 12000;
|
|
16899
|
-
var ABS_CAP = 96000;
|
|
16900
|
-
var MAX_USABLE_RATIO = 0.4;
|
|
16901
|
-
var RESERVED_HEADROOM_MIN = 1000;
|
|
16902
|
-
var RESERVED_HEADROOM_RATIO = 0.02;
|
|
16903
|
-
var NON_EMERGENCY_MAX_CAP = 250000;
|
|
16904
|
-
var FORCE80_MAX_CAP = 500000;
|
|
16905
|
-
var FORCE95_MAX_CAP = 750000;
|
|
16906
|
-
var NORMAL_HYSTERESIS_TOKENS = 256;
|
|
16907
|
-
var RECOVERY_NO_HEAD_LIMIT = 2;
|
|
16908
|
-
function clampPercentage(value) {
|
|
16909
|
-
if (!Number.isFinite(value))
|
|
16910
|
-
return 0;
|
|
16911
|
-
return Math.max(0, Math.min(100, value));
|
|
16912
|
-
}
|
|
16913
|
-
function clampOrdinal(value, rawMessageCount) {
|
|
16914
|
-
return Math.max(1, Math.min(rawMessageCount + 1, Math.floor(value)));
|
|
16915
|
-
}
|
|
16916
|
-
function deriveProtectedTailTokenTarget(args) {
|
|
16917
|
-
const safeContextLimit = Number.isFinite(args.contextLimit) && args.contextLimit > 0 ? args.contextLimit : 128000;
|
|
16918
|
-
const safeThreshold = Number.isFinite(args.executeThresholdPercentage) ? Math.max(0, args.executeThresholdPercentage) : 65;
|
|
16919
|
-
const usable = Math.max(1, Math.round(safeContextLimit * safeThreshold / 100));
|
|
16920
|
-
const usage = clampPercentage(args.usagePercentage);
|
|
16921
|
-
const triggerBudget = args.triggerBudget ?? deriveTriggerBudget2(safeContextLimit, safeThreshold);
|
|
16922
|
-
const reserve = Math.max(RESERVED_HEADROOM_MIN, Math.round(usable * RESERVED_HEADROOM_RATIO));
|
|
16923
|
-
const rawN = Math.round(usable * ALPHA * (1 - usage / 100));
|
|
16924
|
-
const floorN = Math.min(FLOOR_MAX, Math.max(FLOOR_MIN, Math.round(usable * FLOOR_RATIO)));
|
|
16925
|
-
const headroom = Math.min(triggerBudget + reserve, Math.floor(usable * 0.5));
|
|
16926
|
-
const ceilingN = Math.max(1, Math.min(ABS_CAP, Math.floor(usable * MAX_USABLE_RATIO), usable - headroom));
|
|
16927
|
-
const effectiveFloor = Math.min(floorN, ceilingN);
|
|
16928
|
-
const N = Math.min(ceilingN, Math.max(effectiveFloor, rawN));
|
|
16929
|
-
return { usable, rawN, floorN, ceilingN, effectiveFloor, N, headroom, triggerBudget, reserve };
|
|
16930
|
-
}
|
|
16931
|
-
function nonEmergencyPerRunCap(usable, N) {
|
|
16932
|
-
return Math.min(NON_EMERGENCY_MAX_CAP, Math.max(2 * N, Math.min(Math.round(0.25 * usable), 1e5)));
|
|
16933
|
-
}
|
|
16934
|
-
function force80PerRunCap(usable, N) {
|
|
16935
|
-
return Math.min(FORCE80_MAX_CAP, Math.max(3 * N, Math.min(Math.round(0.35 * usable), 150000)));
|
|
16936
|
-
}
|
|
16937
|
-
function force95PerRunCap(usable, N) {
|
|
16938
|
-
return Math.min(FORCE95_MAX_CAP, Math.max(4 * N, Math.min(Math.round(0.5 * usable), 250000)));
|
|
16939
|
-
}
|
|
16940
|
-
function selectPerRunCap(snapshot) {
|
|
16941
|
-
const usable = Math.max(1, Math.round(snapshot.contextLimit * snapshot.executeThresholdPercentage / 100));
|
|
16942
|
-
if (snapshot.usagePercentage >= 95)
|
|
16943
|
-
return force95PerRunCap(usable, snapshot.N);
|
|
16944
|
-
if (snapshot.usagePercentage >= 80)
|
|
16945
|
-
return force80PerRunCap(usable, snapshot.N);
|
|
16946
|
-
return nonEmergencyPerRunCap(usable, snapshot.N);
|
|
16947
|
-
}
|
|
16948
|
-
function boundaryMessageId(index, ordinal) {
|
|
16949
|
-
if (ordinal < 1 || ordinal > index.rawMessageCount)
|
|
16950
|
-
return null;
|
|
16951
|
-
return index.messageIdAtOrdinal(ordinal);
|
|
16952
|
-
}
|
|
16953
|
-
function isSemanticBoundaryCandidate(messageParts, role) {
|
|
16954
|
-
if (role === "user" && hasMeaningfulUserText2(messageParts))
|
|
16955
|
-
return true;
|
|
16956
|
-
if (messageParts.some((part) => String(typeof part === "object" && part !== null && "type" in part ? part.type : "") === "tool")) {
|
|
16957
|
-
return true;
|
|
16958
|
-
}
|
|
16959
|
-
return false;
|
|
16960
|
-
}
|
|
16961
|
-
function semanticSnapBoundary(args) {
|
|
16962
|
-
const { messages, index, candidate, scaledN, lastCompartmentEndOrdinal } = args;
|
|
16963
|
-
let snapped = candidate;
|
|
16964
|
-
for (const message of messages) {
|
|
16965
|
-
if (message.ordinal > candidate)
|
|
16966
|
-
break;
|
|
16967
|
-
if (message.ordinal < lastCompartmentEndOrdinal + 1)
|
|
16968
|
-
continue;
|
|
16969
|
-
if (!isSemanticBoundaryCandidate(message.parts, message.role))
|
|
16970
|
-
continue;
|
|
16971
|
-
snapped = message.ordinal;
|
|
16972
|
-
}
|
|
16973
|
-
if (snapped === candidate)
|
|
16974
|
-
return candidate;
|
|
16975
|
-
const extraTokens = index.suffixTokensFromOrdinal(snapped) - index.suffixTokensFromOrdinal(candidate);
|
|
16976
|
-
if (extraTokens > Math.min(Math.round(1.5 * scaledN), 48000))
|
|
16977
|
-
return candidate;
|
|
16978
|
-
const snappedMessage = messages.find((message) => message.ordinal === snapped);
|
|
16979
|
-
if (snappedMessage?.role === "user" && index.tokenForOrdinal(snapped) > Math.max(2 * scaledN, 64000)) {
|
|
16980
|
-
return candidate;
|
|
16981
|
-
}
|
|
16982
|
-
return snapped;
|
|
16983
|
-
}
|
|
16984
|
-
function snapWrapupBoundaryToUser(args) {
|
|
16985
|
-
const { messages, index, candidate, offset, triggerBudget } = args;
|
|
16986
|
-
if (candidate <= offset)
|
|
16987
|
-
return candidate;
|
|
16988
|
-
const snapTokenLimit = Math.min(Math.max(triggerBudget, 2000), 48000);
|
|
16989
|
-
for (let ordinal = candidate;ordinal >= offset; ordinal -= 1) {
|
|
16990
|
-
const message = messages.find((m) => m.ordinal === ordinal);
|
|
16991
|
-
if (!message)
|
|
16992
|
-
continue;
|
|
16993
|
-
if (message.role !== "user" || !hasMeaningfulUserText2(message.parts))
|
|
16994
|
-
continue;
|
|
16995
|
-
const extraTokens = index.rangeTokens(ordinal, candidate);
|
|
16996
|
-
if (extraTokens <= snapTokenLimit)
|
|
16997
|
-
return ordinal;
|
|
16998
|
-
return candidate;
|
|
16999
|
-
}
|
|
17000
|
-
return candidate;
|
|
17001
|
-
}
|
|
17002
|
-
function fenceWrapupBoundaryForToolArcs(args) {
|
|
17003
|
-
let boundary = args.candidate;
|
|
17004
|
-
const maxPasses = args.arcs.length + 1;
|
|
17005
|
-
for (let pass = 0;pass < maxPasses; pass += 1) {
|
|
17006
|
-
let next = boundary;
|
|
17007
|
-
for (const arc of args.arcs) {
|
|
17008
|
-
if (arc.resOrdinal === null) {
|
|
17009
|
-
continue;
|
|
17010
|
-
}
|
|
17011
|
-
if (arc.invOrdinal >= args.lastCompartmentEndOrdinal + 1 && completedToolArcCrossesBoundary(arc.invOrdinal, arc.resOrdinal, next)) {
|
|
17012
|
-
next = arc.invOrdinal;
|
|
17013
|
-
}
|
|
17014
|
-
}
|
|
17015
|
-
if (next === boundary)
|
|
17016
|
-
return boundary;
|
|
17017
|
-
boundary = next;
|
|
17018
|
-
}
|
|
17019
|
-
return boundary;
|
|
17020
|
-
}
|
|
17021
|
-
function applyHeadCap(args) {
|
|
17022
|
-
const {
|
|
17023
|
-
index,
|
|
17024
|
-
protectedTailStart,
|
|
17025
|
-
offset,
|
|
17026
|
-
arcs,
|
|
17027
|
-
lastCompartmentEndOrdinal,
|
|
17028
|
-
capTokens,
|
|
17029
|
-
recentOpenArcCutoff
|
|
17030
|
-
} = args;
|
|
17031
|
-
const diagnostics = {
|
|
17032
|
-
offset,
|
|
17033
|
-
capEnd: offset,
|
|
17034
|
-
capTokenSum: 0,
|
|
17035
|
-
completedFence: { from: offset, to: offset, arcs: [], tokenMass: 0 },
|
|
17036
|
-
oversizeAdmission: { from: offset, to: offset },
|
|
17037
|
-
openArcClamp: { from: offset, to: offset },
|
|
17038
|
-
completedRefence: { from: offset, to: offset, arcs: [], tokenMass: 0 },
|
|
17039
|
-
eligibleEnd: offset
|
|
17040
|
-
};
|
|
17041
|
-
if (offset >= protectedTailStart) {
|
|
17042
|
-
args.observeDiagnostics?.(diagnostics);
|
|
17043
|
-
return { eligibleEndOrdinal: offset, oversizeAtomicUnit: false };
|
|
17044
|
-
}
|
|
17045
|
-
let end = index.findHeadEndForCap(offset, protectedTailStart, capTokens);
|
|
17046
|
-
diagnostics.capEnd = end;
|
|
17047
|
-
diagnostics.capTokenSum = index.rangeTokens(offset, end);
|
|
17048
|
-
let oversizeAtomicUnit = end === offset + 1 && index.tokenForOrdinal(offset) > capTokens;
|
|
17049
|
-
let completedFence = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1, (component) => {
|
|
17050
|
-
diagnostics.completedFence.arcs = component.map((arc) => ({
|
|
17051
|
-
assistant: arc.invocation,
|
|
17052
|
-
result: arc.result
|
|
17053
|
-
}));
|
|
17054
|
-
diagnostics.completedFence.tokenMass = index.rangeTokens(Math.min(...component.map((arc) => arc.invocation)), Math.max(...component.map((arc) => arc.result)) + 1);
|
|
17055
|
-
});
|
|
17056
|
-
diagnostics.completedFence.from = end;
|
|
17057
|
-
diagnostics.completedFence.to = completedFence;
|
|
17058
|
-
diagnostics.oversizeAdmission.from = completedFence;
|
|
17059
|
-
if (completedFence <= offset && end > offset) {
|
|
17060
|
-
const afterFirstArc = fenceBoundaryForCompletedToolArcs(end, arcs, offset + 1);
|
|
17061
|
-
if (afterFirstArc <= protectedTailStart)
|
|
17062
|
-
completedFence = afterFirstArc;
|
|
17063
|
-
}
|
|
17064
|
-
diagnostics.oversizeAdmission.to = completedFence;
|
|
17065
|
-
if (completedFence > end) {
|
|
17066
|
-
end = Math.min(protectedTailStart, completedFence);
|
|
17067
|
-
if (index.rangeTokens(offset, end) > capTokens)
|
|
17068
|
-
oversizeAtomicUnit = true;
|
|
17069
|
-
} else {
|
|
17070
|
-
end = completedFence;
|
|
17071
|
-
}
|
|
17072
|
-
diagnostics.openArcClamp.from = end;
|
|
17073
|
-
for (const arc of arcs) {
|
|
17074
|
-
const resOrdinal = arc.resOrdinal;
|
|
17075
|
-
if (resOrdinal === null) {
|
|
17076
|
-
if (arc.invOrdinal >= recentOpenArcCutoff && arc.invOrdinal >= offset && arc.invOrdinal < end) {
|
|
17077
|
-
end = Math.min(end, arc.invOrdinal);
|
|
17078
|
-
}
|
|
17079
|
-
}
|
|
17080
|
-
}
|
|
17081
|
-
diagnostics.openArcClamp.to = end;
|
|
17082
|
-
diagnostics.completedRefence.from = end;
|
|
17083
|
-
end = fenceBoundaryForCompletedToolArcs(end, arcs, lastCompartmentEndOrdinal + 1, (component) => {
|
|
17084
|
-
diagnostics.completedRefence.arcs = component.map((arc) => ({
|
|
17085
|
-
assistant: arc.invocation,
|
|
17086
|
-
result: arc.result
|
|
17087
|
-
}));
|
|
17088
|
-
diagnostics.completedRefence.tokenMass = index.rangeTokens(Math.min(...component.map((arc) => arc.invocation)), Math.max(...component.map((arc) => arc.result)) + 1);
|
|
17089
|
-
});
|
|
17090
|
-
diagnostics.completedRefence.to = end;
|
|
17091
|
-
if (end > protectedTailStart)
|
|
17092
|
-
end = offset;
|
|
17093
|
-
diagnostics.eligibleEnd = end <= offset ? offset : end;
|
|
17094
|
-
args.observeDiagnostics?.(diagnostics);
|
|
17095
|
-
if (end <= offset && offset < protectedTailStart) {
|
|
17096
|
-
return { eligibleEndOrdinal: offset, oversizeAtomicUnit };
|
|
17097
|
-
}
|
|
17098
|
-
return { eligibleEndOrdinal: end, oversizeAtomicUnit };
|
|
16895
|
+
function resolveOpenCodeProtectedTailBoundary(args) {
|
|
16896
|
+
return resolveProtectedTailBoundary(resolveBoundaryContext(args));
|
|
17099
16897
|
}
|
|
17100
|
-
function
|
|
16898
|
+
function resolveWrapupProtectedTailBoundary(args) {
|
|
16899
|
+
const ctx = resolveBoundaryContext({ ...args, mode: "manual-wrapup" });
|
|
17101
16900
|
const createdAt = ctx.createdAt ?? Date.now();
|
|
17102
16901
|
const offset = Math.max(1, ctx.lastCompartmentEndOrdinal + 1);
|
|
17103
16902
|
const absoluteMessageCount = getCachedAbsoluteMessageCount2(ctx.sessionId) ?? getRawSessionMessageOrdinalCount2(ctx.sessionId);
|
|
@@ -17111,8 +16910,8 @@ function resolveProtectedTailBoundary(ctx) {
|
|
|
17111
16910
|
calibration: ctx.calibration,
|
|
17112
16911
|
absoluteMessageCount,
|
|
17113
16912
|
storedTotalForMessage: storedTotals ? (m) => {
|
|
17114
|
-
const
|
|
17115
|
-
return
|
|
16913
|
+
const value = storedTotals?.get(m.id);
|
|
16914
|
+
return value === undefined ? null : value;
|
|
17116
16915
|
} : undefined
|
|
17117
16916
|
});
|
|
17118
16917
|
const summaryRemovedIndex = buildTrueRawTokenIndex(ctx.sessionId, messages, {
|
|
@@ -17124,151 +16923,58 @@ function resolveProtectedTailBoundary(ctx) {
|
|
|
17124
16923
|
storedTotalForMessage: storedRemovedTotals ? (m) => storedRemovedTotals.get(m.id) ?? null : undefined
|
|
17125
16924
|
});
|
|
17126
16925
|
const rawMessageCount = index.rawMessageCount;
|
|
16926
|
+
const anchorRawMessageCount = Math.max(0, Math.min(rawMessageCount, Math.floor(args.anchorRawMessageCount ?? rawMessageCount)));
|
|
17127
16927
|
const usagePercentage = clampPercentage(ctx.usage?.percentage ?? 0);
|
|
17128
16928
|
const usageInputTokens = Math.max(0, Math.round(ctx.usage?.inputTokens ?? 0));
|
|
17129
|
-
|
|
17130
|
-
|
|
17131
|
-
|
|
17132
|
-
|
|
17133
|
-
|
|
17134
|
-
|
|
17135
|
-
|
|
17136
|
-
|
|
17137
|
-
|
|
17138
|
-
|
|
17139
|
-
eligibleEndMessageId: null,
|
|
17140
|
-
rawMessageCountAtTrigger: 0,
|
|
17141
|
-
rawLastMessageIdAtTrigger: null,
|
|
17142
|
-
N: 0,
|
|
17143
|
-
usagePercentage,
|
|
17144
|
-
usageInputTokens,
|
|
17145
|
-
usageSource: ctx.usageSource,
|
|
17146
|
-
contextLimit: ctx.contextLimit,
|
|
17147
|
-
executeThresholdPercentage: ctx.executeThresholdPercentage,
|
|
17148
|
-
triggerBudget: ctx.triggerBudget,
|
|
17149
|
-
priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
|
|
17150
|
-
migrationFloorActive: ctx.migrationFloorActive,
|
|
17151
|
-
emergencyTailScale: ctx.emergencyTailScale,
|
|
17152
|
-
recovery: ctx.recovery,
|
|
17153
|
-
providerShapeVersion: ctx.providerShapeVersion,
|
|
17154
|
-
cacheNamespace: ctx.cacheNamespace,
|
|
17155
|
-
createdAt,
|
|
17156
|
-
rawRangeFingerprint: "",
|
|
17157
|
-
trueRawEligibleTokens: 0,
|
|
17158
|
-
summaryRemovedEligibleTokens: 0,
|
|
17159
|
-
oversizeAtomicUnit: false,
|
|
17160
|
-
boundaryReason: "empty-session"
|
|
17161
|
-
};
|
|
17162
|
-
}
|
|
17163
|
-
if (ctx.mode === "manual-full-recomp") {
|
|
16929
|
+
const rawMessagesAboveLastCompartment = Math.max(0, anchorRawMessageCount - offset + 1);
|
|
16930
|
+
const keep = Math.max(1, Math.floor(args.messagesToKeep));
|
|
16931
|
+
let targetProtectedTailStart = offset;
|
|
16932
|
+
let boundaryReason = "manual-wrapup-empty";
|
|
16933
|
+
if (rawMessageCount === 0 || rawMessagesAboveLastCompartment <= keep) {
|
|
16934
|
+
targetProtectedTailStart = offset;
|
|
16935
|
+
boundaryReason = rawMessageCount === 0 ? "manual-wrapup-empty" : "manual-wrapup-within-keep";
|
|
16936
|
+
} else {
|
|
16937
|
+
targetProtectedTailStart = anchorRawMessageCount - keep + 1;
|
|
16938
|
+
boundaryReason = "manual-wrapup-keep-watermark";
|
|
17164
16939
|
const arcs = buildToolArcs(messages);
|
|
17165
|
-
const
|
|
17166
|
-
|
|
17167
|
-
|
|
17168
|
-
|
|
17169
|
-
triggerBudget: ctx.triggerBudget
|
|
16940
|
+
const fenced = fenceWrapupBoundaryForToolArcs({
|
|
16941
|
+
candidate: targetProtectedTailStart,
|
|
16942
|
+
arcs,
|
|
16943
|
+
lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
|
|
17170
16944
|
});
|
|
17171
|
-
|
|
17172
|
-
|
|
17173
|
-
|
|
17174
|
-
const
|
|
17175
|
-
|
|
17176
|
-
|
|
17177
|
-
|
|
16945
|
+
if (fenced !== targetProtectedTailStart)
|
|
16946
|
+
boundaryReason = "manual-wrapup-tool-arc";
|
|
16947
|
+
targetProtectedTailStart = fenced;
|
|
16948
|
+
const snapped = snapWrapupBoundaryToUser({
|
|
16949
|
+
messages,
|
|
16950
|
+
index,
|
|
16951
|
+
candidate: targetProtectedTailStart,
|
|
17178
16952
|
offset,
|
|
17179
|
-
|
|
17180
|
-
|
|
17181
|
-
|
|
17182
|
-
|
|
17183
|
-
|
|
17184
|
-
|
|
17185
|
-
|
|
17186
|
-
|
|
17187
|
-
|
|
17188
|
-
|
|
17189
|
-
|
|
17190
|
-
|
|
17191
|
-
|
|
17192
|
-
executeThresholdPercentage: ctx.executeThresholdPercentage,
|
|
17193
|
-
triggerBudget: ctx.triggerBudget,
|
|
17194
|
-
priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
|
|
17195
|
-
migrationFloorActive: false,
|
|
17196
|
-
emergencyTailScale: ctx.emergencyTailScale,
|
|
17197
|
-
recovery: ctx.recovery,
|
|
17198
|
-
providerShapeVersion: ctx.providerShapeVersion,
|
|
17199
|
-
cacheNamespace: ctx.cacheNamespace,
|
|
17200
|
-
createdAt,
|
|
17201
|
-
rawRangeFingerprint,
|
|
17202
|
-
trueRawEligibleTokens: index.rangeTokens(offset, protectedTailStart),
|
|
17203
|
-
summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, protectedTailStart),
|
|
17204
|
-
oversizeAtomicUnit: false,
|
|
17205
|
-
boundaryReason: firstOpenArc ? "open-tool-arc" : "manual-full-recomp"
|
|
17206
|
-
};
|
|
16953
|
+
triggerBudget: ctx.triggerBudget
|
|
16954
|
+
});
|
|
16955
|
+
if (snapped !== targetProtectedTailStart)
|
|
16956
|
+
boundaryReason = "manual-wrapup-user-snap";
|
|
16957
|
+
targetProtectedTailStart = snapped;
|
|
16958
|
+
const refenced = fenceWrapupBoundaryForToolArcs({
|
|
16959
|
+
candidate: targetProtectedTailStart,
|
|
16960
|
+
arcs,
|
|
16961
|
+
lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
|
|
16962
|
+
});
|
|
16963
|
+
if (refenced !== targetProtectedTailStart)
|
|
16964
|
+
boundaryReason = "manual-wrapup-tool-arc";
|
|
16965
|
+
targetProtectedTailStart = refenced;
|
|
17207
16966
|
}
|
|
16967
|
+
targetProtectedTailStart = clampOrdinal(targetProtectedTailStart, rawMessageCount);
|
|
16968
|
+
targetProtectedTailStart = retreatPastHostUnservedRows(messages, targetProtectedTailStart, offset);
|
|
17208
16969
|
const target = deriveProtectedTailTokenTarget({
|
|
17209
16970
|
contextLimit: ctx.contextLimit,
|
|
17210
16971
|
executeThresholdPercentage: ctx.executeThresholdPercentage,
|
|
17211
16972
|
usagePercentage,
|
|
17212
16973
|
triggerBudget: ctx.triggerBudget
|
|
17213
16974
|
});
|
|
17214
|
-
const scaledN = ctx.emergencyTailScale ? Math.max(1, Math.floor(target.N * ctx.emergencyTailScale)) : target.N;
|
|
17215
|
-
const arcs = buildToolArcs(messages);
|
|
17216
|
-
let boundary = index.findSuffixStartForTokens(scaledN);
|
|
17217
|
-
const recentOpenArcCutoff = boundary;
|
|
17218
|
-
let boundaryReason = boundary === 1 ? "whole-session-smaller-than-tail" : "size-walk";
|
|
17219
|
-
const tokenAtBoundary = index.tokenForOrdinal(boundary);
|
|
17220
|
-
if (boundary <= rawMessageCount && tokenAtBoundary > Math.max(2 * scaledN, 64000) && boundary < rawMessageCount) {
|
|
17221
|
-
boundary += 1;
|
|
17222
|
-
boundaryReason = "huge-message-exception";
|
|
17223
|
-
}
|
|
17224
|
-
boundary = fenceBoundaryForToolArcs(boundary, arcs, ctx.lastCompartmentEndOrdinal, recentOpenArcCutoff);
|
|
17225
|
-
const snapped = semanticSnapBoundary({
|
|
17226
|
-
messages,
|
|
17227
|
-
index,
|
|
17228
|
-
candidate: boundary,
|
|
17229
|
-
scaledN,
|
|
17230
|
-
lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
|
|
17231
|
-
});
|
|
17232
|
-
if (snapped !== boundary)
|
|
17233
|
-
boundaryReason = "semantic-snap";
|
|
17234
|
-
boundary = fenceBoundaryForToolArcs(snapped, arcs, ctx.lastCompartmentEndOrdinal, recentOpenArcCutoff);
|
|
17235
|
-
let runtimeFloor = offset;
|
|
17236
|
-
if (ctx.migrationFloorActive)
|
|
17237
|
-
runtimeFloor = Math.max(runtimeFloor, ctx.priorBoundaryOrdinal);
|
|
17238
|
-
let protectedTailStart = Math.max(boundary, runtimeFloor);
|
|
17239
|
-
const forceMaterializationPercentage = escalationBands(ctx.executeThresholdPercentage).forceMaterializationPercentage;
|
|
17240
|
-
const livePromptFloor = {
|
|
17241
|
-
ordinal: null,
|
|
17242
|
-
from: protectedTailStart,
|
|
17243
|
-
to: protectedTailStart
|
|
17244
|
-
};
|
|
17245
|
-
if (!ctx.emergencyTailScale && usagePercentage < forceMaterializationPercentage) {
|
|
17246
|
-
let lastMeaningfulUserOrdinal = 0;
|
|
17247
|
-
for (let i = messages.length - 1;i >= 0; i--) {
|
|
17248
|
-
const message = messages[i];
|
|
17249
|
-
if (message.role !== "user")
|
|
17250
|
-
continue;
|
|
17251
|
-
if (!hasMeaningfulUserText2(message.parts))
|
|
17252
|
-
continue;
|
|
17253
|
-
lastMeaningfulUserOrdinal = message.ordinal;
|
|
17254
|
-
break;
|
|
17255
|
-
}
|
|
17256
|
-
livePromptFloor.ordinal = lastMeaningfulUserOrdinal || null;
|
|
17257
|
-
livePromptFloor.messageId = boundaryMessageId(index, lastMeaningfulUserOrdinal);
|
|
17258
|
-
if (!ctx.liftLivePromptFloor && lastMeaningfulUserOrdinal >= offset) {
|
|
17259
|
-
protectedTailStart = Math.min(protectedTailStart, lastMeaningfulUserOrdinal);
|
|
17260
|
-
}
|
|
17261
|
-
}
|
|
17262
|
-
livePromptFloor.to = protectedTailStart;
|
|
17263
|
-
if (protectedTailStart > offset && index.rangeTokens(offset, protectedTailStart) <= NORMAL_HYSTERESIS_TOKENS) {
|
|
17264
|
-
protectedTailStart = offset;
|
|
17265
|
-
}
|
|
17266
|
-
protectedTailStart = clampOrdinal(protectedTailStart, rawMessageCount);
|
|
17267
|
-
protectedTailStart = retreatPastHostUnservedRows(messages, protectedTailStart, offset);
|
|
17268
|
-
protectedTailStart = Math.max(offset, fenceBoundaryForCompletedToolArcs(protectedTailStart, arcs, 1));
|
|
17269
16975
|
const perRunCap = selectPerRunCap({
|
|
17270
16976
|
usagePercentage,
|
|
17271
|
-
N:
|
|
16977
|
+
N: target.N,
|
|
17272
16978
|
contextLimit: ctx.contextLimit,
|
|
17273
16979
|
executeThresholdPercentage: ctx.executeThresholdPercentage
|
|
17274
16980
|
});
|
|
@@ -17278,29 +16984,28 @@ function resolveProtectedTailBoundary(ctx) {
|
|
|
17278
16984
|
headDiagnostics = value;
|
|
17279
16985
|
},
|
|
17280
16986
|
index: summaryRemovedIndex,
|
|
17281
|
-
protectedTailStart,
|
|
16987
|
+
protectedTailStart: targetProtectedTailStart,
|
|
17282
16988
|
offset,
|
|
17283
|
-
arcs,
|
|
16989
|
+
arcs: buildToolArcs(messages),
|
|
17284
16990
|
lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal,
|
|
17285
16991
|
capTokens: perRunCap,
|
|
17286
|
-
recentOpenArcCutoff
|
|
16992
|
+
recentOpenArcCutoff: targetProtectedTailStart
|
|
17287
16993
|
});
|
|
17288
|
-
const
|
|
17289
|
-
const eligibleEndOrdinal = Math.max(offset, fenceBoundaryForCompletedToolArcs(servedEndOrdinal, arcs, 1));
|
|
16994
|
+
const eligibleEndOrdinal = retreatPastHostUnservedRows(messages, Math.min(head.eligibleEndOrdinal, targetProtectedTailStart), offset);
|
|
17290
16995
|
const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, eligibleEndOrdinal);
|
|
17291
|
-
|
|
16996
|
+
const snapshot = {
|
|
17292
16997
|
sessionId: ctx.sessionId,
|
|
17293
|
-
mode:
|
|
16998
|
+
mode: "manual-wrapup",
|
|
17294
16999
|
offset,
|
|
17295
17000
|
lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
|
|
17296
17001
|
offsetMessageId: boundaryMessageId(index, offset),
|
|
17297
|
-
protectedTailStart,
|
|
17298
|
-
protectedTailStartMessageId: boundaryMessageId(index,
|
|
17002
|
+
protectedTailStart: targetProtectedTailStart,
|
|
17003
|
+
protectedTailStartMessageId: boundaryMessageId(index, targetProtectedTailStart),
|
|
17299
17004
|
eligibleEndOrdinal,
|
|
17300
17005
|
eligibleEndMessageId: boundaryMessageId(index, eligibleEndOrdinal - 1),
|
|
17301
17006
|
rawMessageCountAtTrigger: rawMessageCount,
|
|
17302
17007
|
rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
|
|
17303
|
-
N:
|
|
17008
|
+
N: keep,
|
|
17304
17009
|
usagePercentage,
|
|
17305
17010
|
usageInputTokens,
|
|
17306
17011
|
usageSource: ctx.usageSource,
|
|
@@ -17310,13 +17015,11 @@ function resolveProtectedTailBoundary(ctx) {
|
|
|
17310
17015
|
priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
|
|
17311
17016
|
migrationFloorActive: ctx.migrationFloorActive,
|
|
17312
17017
|
emergencyTailScale: ctx.emergencyTailScale,
|
|
17313
|
-
recovery: ctx.recovery,
|
|
17314
|
-
liftLivePromptFloor: ctx.liftLivePromptFloor === true ? true : undefined,
|
|
17315
17018
|
providerShapeVersion: ctx.providerShapeVersion,
|
|
17316
17019
|
cacheNamespace: ctx.cacheNamespace,
|
|
17317
17020
|
createdAt,
|
|
17318
17021
|
rawRangeFingerprint,
|
|
17319
|
-
trueRawEligibleTokens: index.rangeTokens(offset,
|
|
17022
|
+
trueRawEligibleTokens: index.rangeTokens(offset, targetProtectedTailStart),
|
|
17320
17023
|
summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, eligibleEndOrdinal),
|
|
17321
17024
|
oversizeAtomicUnit: head.oversizeAtomicUnit,
|
|
17322
17025
|
boundaryReason,
|
|
@@ -17324,332 +17027,681 @@ function resolveProtectedTailBoundary(ctx) {
|
|
|
17324
17027
|
tailTarget: target,
|
|
17325
17028
|
usable: target.usable,
|
|
17326
17029
|
usagePercentage,
|
|
17327
|
-
N:
|
|
17030
|
+
N: target.N,
|
|
17328
17031
|
triggerBudget: ctx.triggerBudget,
|
|
17329
17032
|
capTokens: perRunCap,
|
|
17330
|
-
sizeWalkStart:
|
|
17331
|
-
protectedTailStart,
|
|
17332
|
-
livePromptFloor
|
|
17033
|
+
sizeWalkStart: Math.max(offset, anchorRawMessageCount - keep + 1),
|
|
17034
|
+
protectedTailStart: targetProtectedTailStart,
|
|
17035
|
+
livePromptFloor: {
|
|
17036
|
+
ordinal: null,
|
|
17037
|
+
from: targetProtectedTailStart,
|
|
17038
|
+
to: targetProtectedTailStart
|
|
17039
|
+
},
|
|
17333
17040
|
head: headDiagnostics
|
|
17334
17041
|
})
|
|
17335
17042
|
};
|
|
17043
|
+
return {
|
|
17044
|
+
snapshot,
|
|
17045
|
+
rawMessagesAboveLastCompartment,
|
|
17046
|
+
anchorRawMessageCount,
|
|
17047
|
+
targetProtectedTailStart,
|
|
17048
|
+
targetEligibleEndOrdinal: targetProtectedTailStart
|
|
17049
|
+
};
|
|
17050
|
+
}
|
|
17051
|
+
function getRawHistoryEligibility(db, sessionId) {
|
|
17052
|
+
const lastCompartmentEnd = getLastCompartmentEndMessage(db, sessionId);
|
|
17053
|
+
const offset = Math.max(1, lastCompartmentEnd + 1);
|
|
17054
|
+
const absoluteCount = getCachedAbsoluteMessageCount2(sessionId);
|
|
17055
|
+
const rawMessageCount = absoluteCount ?? getRawSessionMessageOrdinalCount2(sessionId);
|
|
17056
|
+
return {
|
|
17057
|
+
lastCompartmentEnd,
|
|
17058
|
+
offset,
|
|
17059
|
+
rawMessageCount,
|
|
17060
|
+
hasRawBeyondLastCompartment: rawMessageCount >= offset
|
|
17061
|
+
};
|
|
17062
|
+
}
|
|
17063
|
+
function hasRunnableCompartmentWindow(snapshot) {
|
|
17064
|
+
if (snapshot.offset >= snapshot.protectedTailStart)
|
|
17065
|
+
return false;
|
|
17066
|
+
if (snapshot.eligibleEndOrdinal <= snapshot.offset)
|
|
17067
|
+
return false;
|
|
17068
|
+
if (snapshot.recovery || snapshot.usagePercentage >= 95 || snapshot.mode === "manual-wrapup" || snapshot.mode === "manual-full-recomp")
|
|
17069
|
+
return true;
|
|
17070
|
+
const forceMaterializationPercentage = escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage;
|
|
17071
|
+
if (snapshot.usagePercentage >= forceMaterializationPercentage || snapshot.emergencyTailScale) {
|
|
17072
|
+
return snapshot.summaryRemovedEligibleTokens >= snapshot.contextLimit * 0.02;
|
|
17073
|
+
}
|
|
17074
|
+
return snapshot.eligibleEndOrdinal > snapshot.offset;
|
|
17075
|
+
}
|
|
17076
|
+
function boundarySnapshotIdChecks(snapshot) {
|
|
17077
|
+
const checks = [
|
|
17078
|
+
[snapshot.offset, snapshot.offsetMessageId, "offset"],
|
|
17079
|
+
[snapshot.rawMessageCountAtTrigger, snapshot.rawLastMessageIdAtTrigger, "last"]
|
|
17080
|
+
];
|
|
17081
|
+
if (snapshot.protectedTailStart <= snapshot.rawMessageCountAtTrigger) {
|
|
17082
|
+
checks.push([
|
|
17083
|
+
snapshot.protectedTailStart,
|
|
17084
|
+
snapshot.protectedTailStartMessageId,
|
|
17085
|
+
"protectedTailStart"
|
|
17086
|
+
]);
|
|
17087
|
+
}
|
|
17088
|
+
if (snapshot.eligibleEndOrdinal > snapshot.offset) {
|
|
17089
|
+
checks.push([
|
|
17090
|
+
snapshot.eligibleEndOrdinal - 1,
|
|
17091
|
+
snapshot.eligibleEndMessageId,
|
|
17092
|
+
"eligibleEnd"
|
|
17093
|
+
]);
|
|
17094
|
+
}
|
|
17095
|
+
return checks;
|
|
17096
|
+
}
|
|
17097
|
+
function validateBoundarySnapshot(args) {
|
|
17098
|
+
const { snapshot, exactIds } = args;
|
|
17099
|
+
if (args.currentContextLimit && args.currentContextLimit !== snapshot.contextLimit) {
|
|
17100
|
+
return {
|
|
17101
|
+
ok: false,
|
|
17102
|
+
reason: "model_or_limit_changed",
|
|
17103
|
+
detail: `context limit changed from ${snapshot.contextLimit} to ${args.currentContextLimit}`
|
|
17104
|
+
};
|
|
17105
|
+
}
|
|
17106
|
+
const currentRawMessageCount = getRawSessionMessageOrdinalCount2(snapshot.sessionId);
|
|
17107
|
+
if (snapshot.rawMessageCountAtTrigger > currentRawMessageCount) {
|
|
17108
|
+
return { ok: false, reason: "stale_snapshot", detail: "raw message count shrank" };
|
|
17109
|
+
}
|
|
17110
|
+
const idAt = (ordinal) => {
|
|
17111
|
+
if (!exactIds)
|
|
17112
|
+
return readRawSessionMessageIdOrdinalsForRange2(snapshot.sessionId, ordinal, ordinal).keys().next().value ?? null;
|
|
17113
|
+
const id = exactIds.get(ordinal);
|
|
17114
|
+
if (id === undefined)
|
|
17115
|
+
throw new Error(`boundary validation was given no exact id for ordinal ${ordinal}`);
|
|
17116
|
+
return id;
|
|
17117
|
+
};
|
|
17118
|
+
for (const [ordinal, expected, label] of boundarySnapshotIdChecks(snapshot)) {
|
|
17119
|
+
if (expected !== idAt(ordinal)) {
|
|
17120
|
+
return {
|
|
17121
|
+
ok: false,
|
|
17122
|
+
reason: "stale_snapshot",
|
|
17123
|
+
detail: `${label} ordinal ${ordinal} id changed`
|
|
17124
|
+
};
|
|
17125
|
+
}
|
|
17126
|
+
}
|
|
17127
|
+
const expectedOffset = Math.max(1, getLastCompartmentEndMessage(args.db, snapshot.sessionId) + 1);
|
|
17128
|
+
if (expectedOffset !== snapshot.offset) {
|
|
17129
|
+
return {
|
|
17130
|
+
ok: false,
|
|
17131
|
+
reason: "stale_snapshot",
|
|
17132
|
+
detail: `last compartment moved: offset ${snapshot.offset} -> ${expectedOffset}`
|
|
17133
|
+
};
|
|
17134
|
+
}
|
|
17135
|
+
const fingerprintMessages = readRawSessionMessageRange2(snapshot.sessionId, snapshot.offset, snapshot.eligibleEndOrdinal - 1);
|
|
17136
|
+
const fingerprint = computeRawRangeFingerprint(fingerprintMessages, snapshot.offset, snapshot.eligibleEndOrdinal);
|
|
17137
|
+
if (fingerprint !== snapshot.rawRangeFingerprint) {
|
|
17138
|
+
return { ok: false, reason: "stale_snapshot", detail: "raw range fingerprint changed" };
|
|
17139
|
+
}
|
|
17140
|
+
return { ok: true };
|
|
17141
|
+
}
|
|
17142
|
+
function recordHighPressureNoEligibleHead(db, snapshot) {
|
|
17143
|
+
const forceMaterializationPercentage = escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage;
|
|
17144
|
+
if (snapshot.usagePercentage < forceMaterializationPercentage && !snapshot.emergencyTailScale) {
|
|
17145
|
+
return 0;
|
|
17146
|
+
}
|
|
17147
|
+
return recordProtectedTailNoEligibleHead(db, snapshot.sessionId);
|
|
17148
|
+
}
|
|
17149
|
+
|
|
17150
|
+
// src/hooks/magic-context/historian-drain-gate.ts
|
|
17151
|
+
var loggedWindows = new WeakMap;
|
|
17152
|
+
function reportProviderRecoveryDrainSkip(sessionId) {
|
|
17153
|
+
let logged = false;
|
|
17154
|
+
return (skip) => {
|
|
17155
|
+
if (logged)
|
|
17156
|
+
return;
|
|
17157
|
+
logged = true;
|
|
17158
|
+
sessionLog2(sessionId, `historian skip during provider recovery: ${skip.reason}; next eligible at ${new Date(skip.nextEligibleAt).toISOString()}`);
|
|
17159
|
+
};
|
|
17160
|
+
}
|
|
17161
|
+
function resolveHistorianDrainBudgetGeometry(args) {
|
|
17162
|
+
const target = deriveProtectedTailTokenTarget(args);
|
|
17163
|
+
return { usable: target.usable, perRunCap: selectPerRunCap({ ...args, N: target.N }) };
|
|
17164
|
+
}
|
|
17165
|
+
function isHistorianDrainBudgetSpent(args) {
|
|
17166
|
+
const usagePercentage = args.recoveryUsagePercentage ?? args.usagePercentage;
|
|
17167
|
+
const state = getProtectedTailDrainBudgetSkip({
|
|
17168
|
+
...args,
|
|
17169
|
+
usagePercentage,
|
|
17170
|
+
providerRecovery: args.recoveryUsagePercentage !== undefined,
|
|
17171
|
+
...resolveHistorianDrainBudgetGeometry({ ...args, usagePercentage })
|
|
17172
|
+
});
|
|
17173
|
+
if (!state)
|
|
17174
|
+
return false;
|
|
17175
|
+
if (args.reportSkip) {
|
|
17176
|
+
args.reportSkip(state);
|
|
17177
|
+
return true;
|
|
17178
|
+
}
|
|
17179
|
+
let windows = loggedWindows.get(args.db);
|
|
17180
|
+
if (!windows) {
|
|
17181
|
+
windows = new Map;
|
|
17182
|
+
loggedWindows.set(args.db, windows);
|
|
17183
|
+
}
|
|
17184
|
+
if (windows.get(args.sessionId) !== state.resetsAt) {
|
|
17185
|
+
windows.set(args.sessionId, state.resetsAt);
|
|
17186
|
+
sessionLog2(args.sessionId, `historian skip: internal drain budget spent (${state.spentTokens}/${state.limitTokens} tokens); next eligible at ${new Date(state.nextEligibleAt).toISOString()}`);
|
|
17187
|
+
}
|
|
17188
|
+
return true;
|
|
17189
|
+
}
|
|
17190
|
+
|
|
17191
|
+
// src/hooks/magic-context/historian-failure-report.ts
|
|
17192
|
+
var REPEATED_HISTORIAN_FAILURE_WARNING_STEP = 3;
|
|
17193
|
+
var REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS = 30 * 60 * 1000;
|
|
17194
|
+
var ACTIONS = "What to do: run /ctx-status for detail; change the historian model or its fallback models in magic-context.jsonc (user or project config); or run /ctx-recomp to rebuild the history.";
|
|
17195
|
+
var REFUSAL_ERROR_MAX_CHARS = 500;
|
|
17196
|
+
var WARNING_ERROR_MAX_CHARS = 200;
|
|
17197
|
+
function readHistorianFailureStreak(db, sessionId, options = {}) {
|
|
17198
|
+
const state = getHistorianFailureState(db, sessionId);
|
|
17199
|
+
const count = state.failureCount;
|
|
17200
|
+
let since = null;
|
|
17201
|
+
if (count > 0) {
|
|
17202
|
+
const recorded = count - Math.max(0, options.unrecordedFailures ?? 0);
|
|
17203
|
+
if (recorded <= 0) {
|
|
17204
|
+
since = state.lastFailureAt;
|
|
17205
|
+
} else {
|
|
17206
|
+
const times = getRecentFailedHistorianRunTimes(db, sessionId, recorded);
|
|
17207
|
+
since = times.length === recorded ? times[recorded - 1] ?? null : null;
|
|
17208
|
+
}
|
|
17209
|
+
}
|
|
17210
|
+
return { count, lastError: state.lastError, lastFailureAt: state.lastFailureAt, since };
|
|
17211
|
+
}
|
|
17212
|
+
function formatHistorianClockTime(at, now = Date.now()) {
|
|
17213
|
+
const date = new Date(at);
|
|
17214
|
+
const pad = (value) => String(value).padStart(2, "0");
|
|
17215
|
+
const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
17216
|
+
const today = new Date(now);
|
|
17217
|
+
const sameDay = date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();
|
|
17218
|
+
return sameDay ? clock : `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${clock}`;
|
|
17219
|
+
}
|
|
17220
|
+
function formatHistorianSeconds(ms) {
|
|
17221
|
+
const seconds = Math.max(0, ms) / 1000;
|
|
17222
|
+
return String(Number(seconds.toFixed(seconds >= 10 ? 0 : 3)));
|
|
17223
|
+
}
|
|
17224
|
+
function singleLine(text) {
|
|
17225
|
+
return text.replace(/\s+/g, " ").trim();
|
|
17226
|
+
}
|
|
17227
|
+
function quoteError(error, maxChars) {
|
|
17228
|
+
const text = sanitizeDiagnosticText(singleLine(error));
|
|
17229
|
+
return text.length > maxChars ? `${text.slice(0, maxChars - 1).trimEnd()}…` : text;
|
|
17230
|
+
}
|
|
17231
|
+
function endSentence(text) {
|
|
17232
|
+
return /[.!?]$/.test(text) ? text : `${text}.`;
|
|
17233
|
+
}
|
|
17234
|
+
function usageClause(usagePercentage) {
|
|
17235
|
+
return typeof usagePercentage === "number" && Number.isFinite(usagePercentage) ? `context is at ${Math.round(usagePercentage)}% of the window` : "context is nearly full";
|
|
17236
|
+
}
|
|
17237
|
+
function capitalize(text) {
|
|
17238
|
+
return text.charAt(0).toUpperCase() + text.slice(1);
|
|
17239
|
+
}
|
|
17240
|
+
function chunkLabel(chunk) {
|
|
17241
|
+
return chunk ? `messages ${chunk.start}-${chunk.end}` : "";
|
|
17242
|
+
}
|
|
17243
|
+
function streakSentence(failures, now) {
|
|
17244
|
+
if (failures.count <= 0)
|
|
17245
|
+
return null;
|
|
17246
|
+
const since = failures.since !== null ? `, since ${formatHistorianClockTime(failures.since, now)}` : "";
|
|
17247
|
+
return `Summary runs failed in a row: ${failures.count}${since}.`;
|
|
17248
|
+
}
|
|
17249
|
+
function failureBelongsToRun(failures, run) {
|
|
17250
|
+
return failures.count > 0 && failures.lastFailureAt !== null && run?.startedAt !== undefined && failures.lastFailureAt >= run.startedAt;
|
|
17251
|
+
}
|
|
17252
|
+
function describeHistorianJoinRefusal(input) {
|
|
17253
|
+
const now = input.now ?? Date.now();
|
|
17254
|
+
const { run, failures } = input;
|
|
17255
|
+
const sentences = [
|
|
17256
|
+
`This turn was not sent: ${usageClause(input.usagePercentage)}, and Magic Context waited ${formatHistorianSeconds(input.waitedMs)} s for a history summary that did not finish in time.`
|
|
17257
|
+
];
|
|
17258
|
+
const subject = run?.chunk ? `The summary of ${chunkLabel(run.chunk)}` : "The summary run";
|
|
17259
|
+
const ownFailure = failureBelongsToRun(failures, run);
|
|
17260
|
+
const lastError = failures.lastError ? quoteError(failures.lastError, REFUSAL_ERROR_MAX_CHARS) : "";
|
|
17261
|
+
if (ownFailure) {
|
|
17262
|
+
sentences.push(endSentence(`${subject} failed: ${lastError || "no reason recorded"}`));
|
|
17263
|
+
} else if (run && run.endedAt === undefined) {
|
|
17264
|
+
sentences.push(run.startedAt !== undefined ? `${subject} is still running after ${formatHistorianSeconds(now - run.startedAt)} s.` : `${subject} is still running.`);
|
|
17265
|
+
} else if (run) {
|
|
17266
|
+
sentences.push(`${subject} finished after the wait ended.`);
|
|
17267
|
+
}
|
|
17268
|
+
if (!ownFailure && failures.count > 0 && lastError && failures.lastFailureAt !== null) {
|
|
17269
|
+
sentences.push(endSentence(`The previous run failed at ${formatHistorianClockTime(failures.lastFailureAt, now)}: ${lastError}`));
|
|
17270
|
+
}
|
|
17271
|
+
const streak = streakSentence(failures, now);
|
|
17272
|
+
if (streak)
|
|
17273
|
+
sentences.push(streak);
|
|
17274
|
+
sentences.push(ACTIONS);
|
|
17275
|
+
return sentences.join(" ");
|
|
17276
|
+
}
|
|
17277
|
+
function describeRepeatedHistorianFailures(input) {
|
|
17278
|
+
const now = input.now ?? Date.now();
|
|
17279
|
+
const { failures } = input;
|
|
17280
|
+
const facts = [
|
|
17281
|
+
streakSentence(failures, now) ?? "Summary runs are failing.",
|
|
17282
|
+
...input.chunk ? [`Last chunk: ${chunkLabel(input.chunk)}.`] : [],
|
|
17283
|
+
...failures.lastError ? [
|
|
17284
|
+
endSentence(`Last error: ${quoteError(failures.lastError, WARNING_ERROR_MAX_CHARS)}`)
|
|
17285
|
+
] : [],
|
|
17286
|
+
`${capitalize(usageClause(input.usagePercentage))}; at 95% a turn can be refused if no summary finishes in time.`
|
|
17287
|
+
];
|
|
17288
|
+
return [
|
|
17289
|
+
"## Magic Context — History summaries keep failing",
|
|
17290
|
+
"",
|
|
17291
|
+
facts.join(" "),
|
|
17292
|
+
"",
|
|
17293
|
+
ACTIONS
|
|
17294
|
+
].join(`
|
|
17295
|
+
`);
|
|
17296
|
+
}
|
|
17297
|
+
var repeatedFailureWarnings = new Map;
|
|
17298
|
+
function shouldWarnRepeatedHistorianFailures(sessionId, failureCount, now = Date.now()) {
|
|
17299
|
+
const step = REPEATED_HISTORIAN_FAILURE_WARNING_STEP;
|
|
17300
|
+
if (failureCount < step || failureCount % step !== 0)
|
|
17301
|
+
return false;
|
|
17302
|
+
const last = repeatedFailureWarnings.get(sessionId);
|
|
17303
|
+
if (last && failureCount > last.count && now - last.at < REPEATED_HISTORIAN_FAILURE_WARNING_INTERVAL_MS) {
|
|
17304
|
+
return false;
|
|
17305
|
+
}
|
|
17306
|
+
repeatedFailureWarnings.set(sessionId, { count: failureCount, at: now });
|
|
17307
|
+
return true;
|
|
17308
|
+
}
|
|
17309
|
+
function takeRepeatedHistorianFailureWarning(input) {
|
|
17310
|
+
const now = input.now ?? Date.now();
|
|
17311
|
+
if (!shouldWarnRepeatedHistorianFailures(input.sessionId, input.failureCount, now)) {
|
|
17312
|
+
return null;
|
|
17313
|
+
}
|
|
17314
|
+
const failures = readHistorianFailureStreak(input.db, input.sessionId, {
|
|
17315
|
+
unrecordedFailures: input.unrecordedFailures
|
|
17316
|
+
});
|
|
17317
|
+
return describeRepeatedHistorianFailures({
|
|
17318
|
+
chunk: input.chunk,
|
|
17319
|
+
failures: { ...failures, count: input.failureCount },
|
|
17320
|
+
usagePercentage: loadPersistedUsage(input.db, input.sessionId)?.usage.percentage,
|
|
17321
|
+
now
|
|
17322
|
+
});
|
|
17323
|
+
}
|
|
17324
|
+
|
|
17325
|
+
// src/hooks/magic-context/historian-history-wait.ts
|
|
17326
|
+
var historyWaits = new Map;
|
|
17327
|
+
function newestMessageId(snapshot) {
|
|
17328
|
+
try {
|
|
17329
|
+
const count = getRawSessionMessageOrdinalCount2(snapshot.sessionId);
|
|
17330
|
+
const ids = readRawSessionMessageIdOrdinalsForRange2(snapshot.sessionId, count, count);
|
|
17331
|
+
const newest = ids.keys().next().value;
|
|
17332
|
+
if (newest)
|
|
17333
|
+
return newest;
|
|
17334
|
+
} catch {}
|
|
17335
|
+
return snapshot.rawLastMessageIdAtTrigger;
|
|
17336
|
+
}
|
|
17337
|
+
function recoveryWindow(snapshot, percentage) {
|
|
17338
|
+
return percentage >= escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage || snapshot.emergencyTailScale !== undefined;
|
|
17339
|
+
}
|
|
17340
|
+
function clearHistorianHistoryWait(sessionId) {
|
|
17341
|
+
historyWaits.delete(sessionId);
|
|
17342
|
+
}
|
|
17343
|
+
function recordHistorianNoProgress(snapshot, emergency = false) {
|
|
17344
|
+
const newest = newestMessageId(snapshot);
|
|
17345
|
+
if (!newest)
|
|
17346
|
+
return;
|
|
17347
|
+
const previous = historyWaits.get(snapshot.sessionId);
|
|
17348
|
+
const sameHistory = previous?.newestMessageId === newest;
|
|
17349
|
+
historyWaits.set(snapshot.sessionId, {
|
|
17350
|
+
newestMessageId: newest,
|
|
17351
|
+
recoveryAttempted: sameHistory && previous.recoveryAttempted || emergency || recoveryWindow(snapshot, snapshot.usagePercentage),
|
|
17352
|
+
floorLiftAttempted: sameHistory && previous.floorLiftAttempted || snapshot.liftLivePromptFloor === true
|
|
17353
|
+
});
|
|
17354
|
+
}
|
|
17355
|
+
function shouldWaitForNewHistorianHistory(snapshot, options = {}) {
|
|
17356
|
+
const wait = historyWaits.get(snapshot.sessionId);
|
|
17357
|
+
if (!wait)
|
|
17358
|
+
return false;
|
|
17359
|
+
const newest = newestMessageId(snapshot);
|
|
17360
|
+
if (newest && newest !== wait.newestMessageId) {
|
|
17361
|
+
try {
|
|
17362
|
+
const order = compareRawSessionMessageOrder2(snapshot.sessionId, newest, wait.newestMessageId);
|
|
17363
|
+
if (order === null || order > 0)
|
|
17364
|
+
return false;
|
|
17365
|
+
} catch {}
|
|
17366
|
+
}
|
|
17367
|
+
const recovery = options.emergency || recoveryWindow(snapshot, options.usagePercentage ?? snapshot.usagePercentage);
|
|
17368
|
+
const floorLift = snapshot.liftLivePromptFloor === true;
|
|
17369
|
+
if (recovery && !wait.recoveryAttempted || floorLift && !wait.floorLiftAttempted) {
|
|
17370
|
+
if (options.claim) {
|
|
17371
|
+
wait.recoveryAttempted ||= recovery;
|
|
17372
|
+
wait.floorLiftAttempted ||= floorLift;
|
|
17373
|
+
}
|
|
17374
|
+
return false;
|
|
17375
|
+
}
|
|
17376
|
+
return true;
|
|
17377
|
+
}
|
|
17378
|
+
|
|
17379
|
+
// src/tools/ctx-note/render.ts
|
|
17380
|
+
var GLANCE_TITLE_MAX = 80;
|
|
17381
|
+
var NUDGE_TITLE_MAX = 60;
|
|
17382
|
+
var STALE_AFTER_MS = 30 * 24 * 60 * 60 * 1000;
|
|
17383
|
+
var EMPTY_READ_REPLY = `## Notes
|
|
17384
|
+
|
|
17385
|
+
No session notes or smart notes.`;
|
|
17386
|
+
function noteTouchedAt(note) {
|
|
17387
|
+
return note.updatedAt > 0 ? note.updatedAt : note.createdAt;
|
|
17388
|
+
}
|
|
17389
|
+
function formatNoteAge(touchedAt, nowMs) {
|
|
17390
|
+
const elapsed = Math.max(0, nowMs - touchedAt);
|
|
17391
|
+
const minutes = Math.floor(elapsed / 60000);
|
|
17392
|
+
if (minutes < 60)
|
|
17393
|
+
return `${minutes}m`;
|
|
17394
|
+
const hours = Math.floor(elapsed / 3600000);
|
|
17395
|
+
if (hours < 24)
|
|
17396
|
+
return `${hours}h`;
|
|
17397
|
+
const days = Math.floor(elapsed / 86400000);
|
|
17398
|
+
if (days < 7)
|
|
17399
|
+
return `${days}d`;
|
|
17400
|
+
return `${Math.floor(days / 7)}w`;
|
|
17401
|
+
}
|
|
17402
|
+
function clipNoteTitle(content, max) {
|
|
17403
|
+
const firstLine = (content.split(`
|
|
17404
|
+
`, 1)[0] ?? "").trim();
|
|
17405
|
+
const characters = [...firstLine];
|
|
17406
|
+
if (characters.length <= max)
|
|
17407
|
+
return firstLine;
|
|
17408
|
+
return `${characters.slice(0, max).join("")}…`;
|
|
17409
|
+
}
|
|
17410
|
+
function formatGlanceRow(note, nowMs) {
|
|
17411
|
+
const touchedAt = noteTouchedAt(note);
|
|
17412
|
+
const markers = [];
|
|
17413
|
+
if (note.status !== "active")
|
|
17414
|
+
markers.push(note.status);
|
|
17415
|
+
if (note.type === "smart" && note.status === "pending" && note.checkStatus === "parked") {
|
|
17416
|
+
markers.push(`parked: ${note.readyReason ?? "Condition can't be checked"}`);
|
|
17417
|
+
}
|
|
17418
|
+
if (nowMs - touchedAt >= STALE_AFTER_MS)
|
|
17419
|
+
markers.push("stale");
|
|
17420
|
+
const suffix = markers.length > 0 ? ` · ${markers.join(" · ")}` : "";
|
|
17421
|
+
const title = clipNoteTitle(note.content, GLANCE_TITLE_MAX);
|
|
17422
|
+
return `#${note.id} · ${formatNoteAge(touchedAt, nowMs)} · ${title}${suffix}`;
|
|
17423
|
+
}
|
|
17424
|
+
function newestFirst(left, right) {
|
|
17425
|
+
return right.updatedAt - left.updatedAt || right.id - left.id;
|
|
17426
|
+
}
|
|
17427
|
+
function orderGlanceNotes(notes) {
|
|
17428
|
+
const ready = notes.filter((note) => note.status === "ready").sort(newestFirst);
|
|
17429
|
+
const pending = notes.filter((note) => note.status === "pending").sort(newestFirst);
|
|
17430
|
+
const rest = notes.filter((note) => note.status !== "ready" && note.status !== "pending").sort(newestFirst);
|
|
17431
|
+
return [...ready, ...pending, ...rest];
|
|
17432
|
+
}
|
|
17433
|
+
function renderGlance(notes, options) {
|
|
17434
|
+
const ordered = orderGlanceNotes(notes);
|
|
17435
|
+
const page = ordered.slice(options.offset, options.offset + options.limit);
|
|
17436
|
+
if (page.length === 0)
|
|
17437
|
+
return EMPTY_READ_REPLY;
|
|
17438
|
+
const rows = page.map((note) => formatGlanceRow(note, options.nowMs)).join(`
|
|
17439
|
+
`);
|
|
17440
|
+
const remaining = ordered.length - options.offset - page.length;
|
|
17441
|
+
const footer = remaining > 0 ? `
|
|
17442
|
+
|
|
17443
|
+
Showing ${page.length} of ${ordered.length} — ${remaining} older: ctx_note(action="read", offset=${options.offset + page.length})` : "";
|
|
17444
|
+
return `## Notes
|
|
17445
|
+
|
|
17446
|
+
${rows}${footer}`;
|
|
17447
|
+
}
|
|
17448
|
+
function formatNoteBody(note, nowMs) {
|
|
17449
|
+
const touchedAt = noteTouchedAt(note);
|
|
17450
|
+
const anchor = note.anchorOrdinal !== null ? ` ↳ @msg ${note.anchorOrdinal}` : "";
|
|
17451
|
+
const head = `- **#${note.id}** · ${formatNoteAge(touchedAt, nowMs)} · ${note.status}: ${note.content}${anchor}`;
|
|
17452
|
+
if (note.type !== "smart")
|
|
17453
|
+
return head;
|
|
17454
|
+
const condition = note.status === "ready" ? note.readyReason ?? note.surfaceCondition ?? "Condition satisfied" : note.surfaceCondition ?? "No condition recorded";
|
|
17455
|
+
const label = note.status === "ready" ? "Condition met" : "Condition";
|
|
17456
|
+
const failure = note.status === "pending" && note.readyReason?.startsWith("Condition can't be checked:") ? `
|
|
17457
|
+
${note.readyReason}` : "";
|
|
17458
|
+
return `${head}
|
|
17459
|
+
${label}: ${condition}${failure}`;
|
|
17460
|
+
}
|
|
17461
|
+
function renderNotesById(entries, nowMs) {
|
|
17462
|
+
const lines = entries.map(({ noteId, note }) => note ? formatNoteBody(note, nowMs) : `- Note #${noteId}: not_found`);
|
|
17463
|
+
return `## Notes by ID
|
|
17464
|
+
|
|
17465
|
+
${lines.join(`
|
|
17466
|
+
|
|
17467
|
+
`)}`;
|
|
17468
|
+
}
|
|
17469
|
+
function formatTraySuffix(tray, nowMs) {
|
|
17470
|
+
if (tray.activeCount <= 0 || tray.oldestTouchedAt === null)
|
|
17471
|
+
return "";
|
|
17472
|
+
return ` ${tray.activeCount} active, oldest ${formatNoteAge(tray.oldestTouchedAt, nowMs)}.`;
|
|
17336
17473
|
}
|
|
17337
|
-
function
|
|
17338
|
-
|
|
17339
|
-
(SELECT end_message_id FROM compartments
|
|
17340
|
-
WHERE session_id = ? ORDER BY sequence DESC LIMIT 1) AS end_message_id
|
|
17341
|
-
FROM compartments WHERE session_id = ?`).get(sessionId, sessionId);
|
|
17342
|
-
const endMessageId = row?.end_message_id;
|
|
17343
|
-
return {
|
|
17344
|
-
endOrdinal: typeof row?.max_end === "number" ? row.max_end : -1,
|
|
17345
|
-
endMessageId: typeof endMessageId === "string" && endMessageId.length > 0 ? endMessageId : null
|
|
17346
|
-
};
|
|
17474
|
+
function formatWriteReply(noteId, tray, nowMs) {
|
|
17475
|
+
return `Saved session note #${noteId}.${formatTraySuffix(tray, nowMs)}`;
|
|
17347
17476
|
}
|
|
17348
|
-
function
|
|
17349
|
-
|
|
17350
|
-
|
|
17351
|
-
const
|
|
17352
|
-
let
|
|
17353
|
-
|
|
17354
|
-
|
|
17355
|
-
|
|
17356
|
-
try {
|
|
17357
|
-
legacyBoundary = getLegacyProtectedTailStartOrdinal2(args.sessionId);
|
|
17358
|
-
} catch (error) {
|
|
17359
|
-
sessionLog2(args.sessionId, "protected-tail migration seed fell back to ordinal 1:", error);
|
|
17360
|
-
}
|
|
17361
|
-
const seedResult = markProtectedTailPolicyV3Seeded(args.db, args.sessionId, Math.max(1, legacyBoundary));
|
|
17362
|
-
meta = seedResult;
|
|
17363
|
-
migrationFloorActive = seedResult.seeded;
|
|
17477
|
+
function noteNudgePickIndex(sessionId, counter, poolSize) {
|
|
17478
|
+
if (poolSize <= 0)
|
|
17479
|
+
return 0;
|
|
17480
|
+
const bytes = new TextEncoder().encode(`${sessionId}#${counter}`);
|
|
17481
|
+
let hash = 2166136261;
|
|
17482
|
+
for (const byte of bytes) {
|
|
17483
|
+
hash ^= byte;
|
|
17484
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
17364
17485
|
}
|
|
17365
|
-
|
|
17366
|
-
const storedTokenTotalsForMessages = (messageIds, messages = []) => {
|
|
17367
|
-
try {
|
|
17368
|
-
const weights = getAllStatusTagTokenTotalsFlat2(args.db, args.sessionId, args.taggerFloor ?? 0, calibration, messageIds);
|
|
17369
|
-
return {
|
|
17370
|
-
totals: omitIncompleteFileTokenTotals(args.db, args.sessionId, messages, weights.totals),
|
|
17371
|
-
summaryRemovedTotals: weights.summaryRemovedTotals
|
|
17372
|
-
};
|
|
17373
|
-
} catch (error) {
|
|
17374
|
-
sessionLog2(args.sessionId, "protected-tail stored-token map unavailable (live fallback):", error);
|
|
17375
|
-
return;
|
|
17376
|
-
}
|
|
17377
|
-
};
|
|
17378
|
-
return {
|
|
17379
|
-
sessionId: args.sessionId,
|
|
17380
|
-
mode: args.mode,
|
|
17381
|
-
contextLimit: args.contextLimit,
|
|
17382
|
-
executeThresholdPercentage: args.executeThresholdPercentage,
|
|
17383
|
-
triggerBudget,
|
|
17384
|
-
usage: args.usage ?? null,
|
|
17385
|
-
usageSource: args.usageSource ?? (args.usage ? "live" : "provisional-zero"),
|
|
17386
|
-
lastCompartmentEndOrdinal,
|
|
17387
|
-
lastCompartmentEndMessageId: lastCompartmentBoundary.endMessageId,
|
|
17388
|
-
priorBoundaryOrdinal: meta.priorBoundaryOrdinal,
|
|
17389
|
-
protectedTailPolicyVersion: meta.protectedTailPolicyVersion,
|
|
17390
|
-
migrationFloorActive,
|
|
17391
|
-
emergencyTailScale: args.emergencyTailScale,
|
|
17392
|
-
recovery: args.recovery,
|
|
17393
|
-
liftLivePromptFloor: args.liftLivePromptFloor,
|
|
17394
|
-
providerShapeVersion: args.providerShapeVersion ?? "opencode-v1",
|
|
17395
|
-
cacheNamespace: args.cacheNamespace ?? `opencode:${args.sessionId}`,
|
|
17396
|
-
storedTokenTotalsForMessages,
|
|
17397
|
-
calibration
|
|
17398
|
-
};
|
|
17486
|
+
return hash % poolSize;
|
|
17399
17487
|
}
|
|
17400
|
-
function
|
|
17401
|
-
|
|
17488
|
+
function formatNoteNudge(args) {
|
|
17489
|
+
const counts = `${args.readyCount} notes ready, ${args.activeCount} active`;
|
|
17490
|
+
const oldest = args.activeCount > 0 && args.oldestActiveTouchedAt !== null ? ` (oldest ${formatNoteAge(args.oldestActiveTouchedAt, args.nowMs)})` : "";
|
|
17491
|
+
const shown = args.shown ? `: #${args.shown.id} ${clipNoteTitle(args.shown.content, NUDGE_TITLE_MAX)}` : "";
|
|
17492
|
+
return `${counts}${oldest}${shown}`;
|
|
17402
17493
|
}
|
|
17403
|
-
|
|
17404
|
-
|
|
17405
|
-
|
|
17406
|
-
|
|
17407
|
-
|
|
17408
|
-
|
|
17409
|
-
|
|
17410
|
-
|
|
17411
|
-
const storedRemovedTotals = storedWeights?.summaryRemovedTotals ?? ctx.storedSummaryRemovedTokenTotals;
|
|
17412
|
-
const index = buildTrueRawTokenIndex(ctx.sessionId, messages, {
|
|
17413
|
-
providerShapeVersion: ctx.providerShapeVersion,
|
|
17414
|
-
cacheNamespace: ctx.cacheNamespace,
|
|
17415
|
-
calibration: ctx.calibration,
|
|
17416
|
-
absoluteMessageCount,
|
|
17417
|
-
storedTotalForMessage: storedTotals ? (m) => {
|
|
17418
|
-
const value = storedTotals?.get(m.id);
|
|
17419
|
-
return value === undefined ? null : value;
|
|
17420
|
-
} : undefined
|
|
17421
|
-
});
|
|
17422
|
-
const summaryRemovedIndex = buildTrueRawTokenIndex(ctx.sessionId, messages, {
|
|
17423
|
-
providerShapeVersion: ctx.providerShapeVersion,
|
|
17424
|
-
cacheNamespace: ctx.cacheNamespace,
|
|
17425
|
-
calibration: ctx.calibration,
|
|
17426
|
-
absoluteMessageCount,
|
|
17427
|
-
measure: "summary-removed",
|
|
17428
|
-
storedTotalForMessage: storedRemovedTotals ? (m) => storedRemovedTotals.get(m.id) ?? null : undefined
|
|
17429
|
-
});
|
|
17430
|
-
const rawMessageCount = index.rawMessageCount;
|
|
17431
|
-
const anchorRawMessageCount = Math.max(0, Math.min(rawMessageCount, Math.floor(args.anchorRawMessageCount ?? rawMessageCount)));
|
|
17432
|
-
const usagePercentage = clampPercentage(ctx.usage?.percentage ?? 0);
|
|
17433
|
-
const usageInputTokens = Math.max(0, Math.round(ctx.usage?.inputTokens ?? 0));
|
|
17434
|
-
const rawMessagesAboveLastCompartment = Math.max(0, anchorRawMessageCount - offset + 1);
|
|
17435
|
-
const keep = Math.max(1, Math.floor(args.messagesToKeep));
|
|
17436
|
-
let targetProtectedTailStart = offset;
|
|
17437
|
-
let boundaryReason = "manual-wrapup-empty";
|
|
17438
|
-
if (rawMessageCount === 0 || rawMessagesAboveLastCompartment <= keep) {
|
|
17439
|
-
targetProtectedTailStart = offset;
|
|
17440
|
-
boundaryReason = rawMessageCount === 0 ? "manual-wrapup-empty" : "manual-wrapup-within-keep";
|
|
17441
|
-
} else {
|
|
17442
|
-
targetProtectedTailStart = anchorRawMessageCount - keep + 1;
|
|
17443
|
-
boundaryReason = "manual-wrapup-keep-watermark";
|
|
17444
|
-
const arcs = buildToolArcs(messages);
|
|
17445
|
-
const fenced = fenceWrapupBoundaryForToolArcs({
|
|
17446
|
-
candidate: targetProtectedTailStart,
|
|
17447
|
-
arcs,
|
|
17448
|
-
lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
|
|
17449
|
-
});
|
|
17450
|
-
if (fenced !== targetProtectedTailStart)
|
|
17451
|
-
boundaryReason = "manual-wrapup-tool-arc";
|
|
17452
|
-
targetProtectedTailStart = fenced;
|
|
17453
|
-
const snapped = snapWrapupBoundaryToUser({
|
|
17454
|
-
messages,
|
|
17455
|
-
index,
|
|
17456
|
-
candidate: targetProtectedTailStart,
|
|
17457
|
-
offset,
|
|
17458
|
-
triggerBudget: ctx.triggerBudget
|
|
17459
|
-
});
|
|
17460
|
-
if (snapped !== targetProtectedTailStart)
|
|
17461
|
-
boundaryReason = "manual-wrapup-user-snap";
|
|
17462
|
-
targetProtectedTailStart = snapped;
|
|
17463
|
-
const refenced = fenceWrapupBoundaryForToolArcs({
|
|
17464
|
-
candidate: targetProtectedTailStart,
|
|
17465
|
-
arcs,
|
|
17466
|
-
lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal
|
|
17467
|
-
});
|
|
17468
|
-
if (refenced !== targetProtectedTailStart)
|
|
17469
|
-
boundaryReason = "manual-wrapup-tool-arc";
|
|
17470
|
-
targetProtectedTailStart = refenced;
|
|
17494
|
+
|
|
17495
|
+
// src/hooks/magic-context/note-nudger.ts
|
|
17496
|
+
var observedUsers = new WeakMap;
|
|
17497
|
+
function observeNoteNudgeServe(args) {
|
|
17498
|
+
let sessions = observedUsers.get(args.db);
|
|
17499
|
+
if (!sessions) {
|
|
17500
|
+
sessions = new Map;
|
|
17501
|
+
observedUsers.set(args.db, sessions);
|
|
17471
17502
|
}
|
|
17472
|
-
|
|
17473
|
-
|
|
17474
|
-
|
|
17475
|
-
|
|
17476
|
-
|
|
17477
|
-
|
|
17478
|
-
|
|
17479
|
-
|
|
17480
|
-
const perRunCap = selectPerRunCap({
|
|
17481
|
-
usagePercentage,
|
|
17482
|
-
N: target.N,
|
|
17483
|
-
contextLimit: ctx.contextLimit,
|
|
17484
|
-
executeThresholdPercentage: ctx.executeThresholdPercentage
|
|
17485
|
-
});
|
|
17486
|
-
let headDiagnostics;
|
|
17487
|
-
const head = applyHeadCap({
|
|
17488
|
-
observeDiagnostics: (value) => {
|
|
17489
|
-
headDiagnostics = value;
|
|
17490
|
-
},
|
|
17491
|
-
index: summaryRemovedIndex,
|
|
17492
|
-
protectedTailStart: targetProtectedTailStart,
|
|
17493
|
-
offset,
|
|
17494
|
-
arcs: buildToolArcs(messages),
|
|
17495
|
-
lastCompartmentEndOrdinal: ctx.lastCompartmentEndOrdinal,
|
|
17496
|
-
capTokens: perRunCap,
|
|
17497
|
-
recentOpenArcCutoff: targetProtectedTailStart
|
|
17498
|
-
});
|
|
17499
|
-
const eligibleEndOrdinal = retreatPastHostUnservedRows(messages, Math.min(head.eligibleEndOrdinal, targetProtectedTailStart), offset);
|
|
17500
|
-
const rawRangeFingerprint = computeRawRangeFingerprint(messages, offset, eligibleEndOrdinal);
|
|
17501
|
-
const snapshot = {
|
|
17502
|
-
sessionId: ctx.sessionId,
|
|
17503
|
-
mode: "manual-wrapup",
|
|
17504
|
-
offset,
|
|
17505
|
-
lastCompartmentEndMessageId: ctx.lastCompartmentEndMessageId,
|
|
17506
|
-
offsetMessageId: boundaryMessageId(index, offset),
|
|
17507
|
-
protectedTailStart: targetProtectedTailStart,
|
|
17508
|
-
protectedTailStartMessageId: boundaryMessageId(index, targetProtectedTailStart),
|
|
17509
|
-
eligibleEndOrdinal,
|
|
17510
|
-
eligibleEndMessageId: boundaryMessageId(index, eligibleEndOrdinal - 1),
|
|
17511
|
-
rawMessageCountAtTrigger: rawMessageCount,
|
|
17512
|
-
rawLastMessageIdAtTrigger: boundaryMessageId(index, rawMessageCount),
|
|
17513
|
-
N: keep,
|
|
17514
|
-
usagePercentage,
|
|
17515
|
-
usageInputTokens,
|
|
17516
|
-
usageSource: ctx.usageSource,
|
|
17517
|
-
contextLimit: ctx.contextLimit,
|
|
17518
|
-
executeThresholdPercentage: ctx.executeThresholdPercentage,
|
|
17519
|
-
triggerBudget: ctx.triggerBudget,
|
|
17520
|
-
priorBoundaryOrdinal: ctx.priorBoundaryOrdinal,
|
|
17521
|
-
migrationFloorActive: ctx.migrationFloorActive,
|
|
17522
|
-
emergencyTailScale: ctx.emergencyTailScale,
|
|
17523
|
-
providerShapeVersion: ctx.providerShapeVersion,
|
|
17524
|
-
cacheNamespace: ctx.cacheNamespace,
|
|
17525
|
-
createdAt,
|
|
17526
|
-
rawRangeFingerprint,
|
|
17527
|
-
trueRawEligibleTokens: index.rangeTokens(offset, targetProtectedTailStart),
|
|
17528
|
-
summaryRemovedEligibleTokens: summaryRemovedIndex.rangeTokens(offset, eligibleEndOrdinal),
|
|
17529
|
-
oversizeAtomicUnit: head.oversizeAtomicUnit,
|
|
17530
|
-
boundaryReason,
|
|
17531
|
-
diagnostics: boundaryDiagnostics({
|
|
17532
|
-
tailTarget: target,
|
|
17533
|
-
usable: target.usable,
|
|
17534
|
-
usagePercentage,
|
|
17535
|
-
N: target.N,
|
|
17536
|
-
triggerBudget: ctx.triggerBudget,
|
|
17537
|
-
capTokens: perRunCap,
|
|
17538
|
-
sizeWalkStart: Math.max(offset, anchorRawMessageCount - keep + 1),
|
|
17539
|
-
protectedTailStart: targetProtectedTailStart,
|
|
17540
|
-
livePromptFloor: {
|
|
17541
|
-
ordinal: null,
|
|
17542
|
-
from: targetProtectedTailStart,
|
|
17543
|
-
to: targetProtectedTailStart
|
|
17544
|
-
},
|
|
17545
|
-
head: headDiagnostics
|
|
17546
|
-
})
|
|
17547
|
-
};
|
|
17548
|
-
return {
|
|
17549
|
-
snapshot,
|
|
17550
|
-
rawMessagesAboveLastCompartment,
|
|
17551
|
-
anchorRawMessageCount,
|
|
17552
|
-
targetProtectedTailStart,
|
|
17553
|
-
targetEligibleEndOrdinal: targetProtectedTailStart
|
|
17554
|
-
};
|
|
17555
|
-
}
|
|
17556
|
-
function getRawHistoryEligibility(db, sessionId) {
|
|
17557
|
-
const lastCompartmentEnd = getLastCompartmentEndMessage(db, sessionId);
|
|
17558
|
-
const offset = Math.max(1, lastCompartmentEnd + 1);
|
|
17559
|
-
const absoluteCount = getCachedAbsoluteMessageCount2(sessionId);
|
|
17560
|
-
const rawMessageCount = absoluteCount ?? getRawSessionMessageOrdinalCount2(sessionId);
|
|
17503
|
+
let seen = sessions.get(args.sessionId);
|
|
17504
|
+
const warm = seen !== undefined && seen.size > 0;
|
|
17505
|
+
if (!seen)
|
|
17506
|
+
seen = new Set;
|
|
17507
|
+
const firstServe = args.anchorMessageId !== null && !seen.has(args.anchorMessageId);
|
|
17508
|
+
for (const id of args.userMessageIds)
|
|
17509
|
+
seen.add(id);
|
|
17510
|
+
sessions.set(args.sessionId, seen);
|
|
17561
17511
|
return {
|
|
17562
|
-
|
|
17563
|
-
|
|
17564
|
-
rawMessageCount,
|
|
17565
|
-
hasRawBeyondLastCompartment: rawMessageCount >= offset
|
|
17512
|
+
isFirstServe: warm && args.isLiveTail && firstServe,
|
|
17513
|
+
prefixRewriteCoversAnchor: args.anchorMessageId !== null && args.prefixRewriteCoversAnchor
|
|
17566
17514
|
};
|
|
17567
17515
|
}
|
|
17568
|
-
|
|
17569
|
-
|
|
17570
|
-
|
|
17571
|
-
|
|
17572
|
-
return false;
|
|
17573
|
-
if (snapshot.recovery || snapshot.usagePercentage >= 95 || snapshot.mode === "manual-wrapup" || snapshot.mode === "manual-full-recomp")
|
|
17574
|
-
return true;
|
|
17575
|
-
const forceMaterializationPercentage = escalationBands(snapshot.executeThresholdPercentage).forceMaterializationPercentage;
|
|
17576
|
-
if (snapshot.usagePercentage >= forceMaterializationPercentage || snapshot.emergencyTailScale) {
|
|
17577
|
-
return snapshot.summaryRemovedEligibleTokens >= snapshot.contextLimit * 0.02;
|
|
17578
|
-
}
|
|
17579
|
-
return snapshot.eligibleEndOrdinal > snapshot.offset;
|
|
17516
|
+
var NOTE_NUDGE_COOLDOWN_MS = 15 * 60 * 1000;
|
|
17517
|
+
var lastDeliveredAt = new Map;
|
|
17518
|
+
function isCoolingDown(deliveredAt, now) {
|
|
17519
|
+
return now - deliveredAt < NOTE_NUDGE_COOLDOWN_MS;
|
|
17580
17520
|
}
|
|
17581
|
-
function
|
|
17582
|
-
const
|
|
17583
|
-
|
|
17584
|
-
|
|
17585
|
-
|
|
17586
|
-
|
|
17587
|
-
|
|
17588
|
-
snapshot.protectedTailStart,
|
|
17589
|
-
snapshot.protectedTailStartMessageId,
|
|
17590
|
-
"protectedTailStart"
|
|
17591
|
-
]);
|
|
17521
|
+
function getNoteNudgeDeliveredAt(sessionId) {
|
|
17522
|
+
const deliveredAt = lastDeliveredAt.get(sessionId);
|
|
17523
|
+
if (deliveredAt === undefined)
|
|
17524
|
+
return 0;
|
|
17525
|
+
if (!isCoolingDown(deliveredAt, Date.now())) {
|
|
17526
|
+
lastDeliveredAt.delete(sessionId);
|
|
17527
|
+
return 0;
|
|
17592
17528
|
}
|
|
17593
|
-
|
|
17594
|
-
|
|
17595
|
-
|
|
17596
|
-
|
|
17597
|
-
|
|
17598
|
-
|
|
17529
|
+
return deliveredAt;
|
|
17530
|
+
}
|
|
17531
|
+
function recordNoteNudgeDeliveryTime(sessionId) {
|
|
17532
|
+
const now = Date.now();
|
|
17533
|
+
for (const [otherSessionId, deliveredAt] of lastDeliveredAt) {
|
|
17534
|
+
if (!isCoolingDown(deliveredAt, now))
|
|
17535
|
+
lastDeliveredAt.delete(otherSessionId);
|
|
17599
17536
|
}
|
|
17600
|
-
|
|
17537
|
+
lastDeliveredAt.set(sessionId, now);
|
|
17601
17538
|
}
|
|
17602
|
-
function
|
|
17603
|
-
|
|
17604
|
-
|
|
17605
|
-
|
|
17606
|
-
|
|
17607
|
-
|
|
17608
|
-
|
|
17609
|
-
|
|
17539
|
+
function onNoteTrigger(db, sessionId, trigger) {
|
|
17540
|
+
let transactionStartedAt = 0;
|
|
17541
|
+
db.transaction(() => {
|
|
17542
|
+
transactionStartedAt = performance.now();
|
|
17543
|
+
setPersistedNoteNudgeTrigger(db, sessionId);
|
|
17544
|
+
}).immediate();
|
|
17545
|
+
logSlowWriteTransaction("note_nudge_trigger", transactionStartedAt);
|
|
17546
|
+
sessionLog2(sessionId, `note-nudge: trigger fired (${trigger}), triggerPending=true`);
|
|
17547
|
+
}
|
|
17548
|
+
function peekNoteNudgeText(db, sessionId, currentUserMessageId, projectIdentity, noteReadStillVisible, eligibility) {
|
|
17549
|
+
const state = getPersistedNoteNudge(db, sessionId);
|
|
17550
|
+
if (!state.triggerPending)
|
|
17551
|
+
return null;
|
|
17552
|
+
if (eligibility && !eligibility.isFirstServe && !eligibility.prefixRewriteCoversAnchor) {
|
|
17553
|
+
sessionLog2(sessionId, "note-nudge: deferring — user already served or first serve unproven");
|
|
17554
|
+
return null;
|
|
17610
17555
|
}
|
|
17611
|
-
|
|
17612
|
-
|
|
17613
|
-
|
|
17556
|
+
if (!eligibility && !state.triggerMessageId && currentUserMessageId) {
|
|
17557
|
+
setPersistedNoteNudgeTriggerMessageId(db, sessionId, currentUserMessageId);
|
|
17558
|
+
state.triggerMessageId = currentUserMessageId;
|
|
17614
17559
|
}
|
|
17615
|
-
|
|
17616
|
-
|
|
17617
|
-
|
|
17618
|
-
|
|
17619
|
-
|
|
17620
|
-
|
|
17621
|
-
|
|
17622
|
-
|
|
17623
|
-
|
|
17624
|
-
|
|
17625
|
-
|
|
17626
|
-
|
|
17627
|
-
|
|
17628
|
-
|
|
17629
|
-
|
|
17560
|
+
if (!eligibility && state.triggerMessageId && currentUserMessageId && state.triggerMessageId === currentUserMessageId) {
|
|
17561
|
+
sessionLog2(sessionId, `note-nudge: deferring — current user message ${currentUserMessageId} is same as trigger-time message`);
|
|
17562
|
+
return null;
|
|
17563
|
+
}
|
|
17564
|
+
const deliveredAt = getNoteNudgeDeliveredAt(sessionId);
|
|
17565
|
+
if (deliveredAt > 0) {
|
|
17566
|
+
sessionLog2(sessionId, `note-nudge: suppressing — last delivered ${Math.round((Date.now() - deliveredAt) / 1000)}s ago (cooldown ${NOTE_NUDGE_COOLDOWN_MS / 60000}m)`);
|
|
17567
|
+
clearNoteNudgeTriggerOnly(db, sessionId);
|
|
17568
|
+
return null;
|
|
17569
|
+
}
|
|
17570
|
+
const notes = getSessionNotes(db, sessionId);
|
|
17571
|
+
const readySmartNotes = projectIdentity ? getReadySmartNotes(db, projectIdentity) : [];
|
|
17572
|
+
const totalCount = notes.length + readySmartNotes.length;
|
|
17573
|
+
if (totalCount === 0) {
|
|
17574
|
+
sessionLog2(sessionId, "note-nudge: triggerPending but no notes found, skipping");
|
|
17575
|
+
clearNoteNudgeTriggerOnly(db, sessionId);
|
|
17576
|
+
return null;
|
|
17577
|
+
}
|
|
17578
|
+
const lastReadAt = getNoteLastReadAt(db, sessionId);
|
|
17579
|
+
if (lastReadAt > 0 && noteReadStillVisible) {
|
|
17580
|
+
const mostRecentNoteActivity = maxNoteActivityTime([...notes, ...readySmartNotes]);
|
|
17581
|
+
if (mostRecentNoteActivity > 0 && lastReadAt > mostRecentNoteActivity) {
|
|
17582
|
+
sessionLog2(sessionId, `note-nudge: suppressing — agent ran ctx_note(read) at ${new Date(lastReadAt).toISOString()} and the read is still visible; no new notes since ${new Date(mostRecentNoteActivity).toISOString()}`);
|
|
17583
|
+
clearNoteNudgeTriggerOnly(db, sessionId);
|
|
17584
|
+
return null;
|
|
17630
17585
|
}
|
|
17631
17586
|
}
|
|
17632
|
-
const
|
|
17633
|
-
if (
|
|
17634
|
-
|
|
17635
|
-
|
|
17636
|
-
|
|
17637
|
-
|
|
17638
|
-
};
|
|
17587
|
+
const failureNotice = notes.find((note) => /^Smart note #\d+ cannot be checked\.\nCondition: /.test(note.content));
|
|
17588
|
+
if (failureNotice) {
|
|
17589
|
+
const reason = failureNotice.content.split(`
|
|
17590
|
+
Reason: `)[1]?.split(`
|
|
17591
|
+
`)[0] ?? "check unavailable";
|
|
17592
|
+
return `Smart note check unavailable: ${reason}. Read ctx_note #${failureNotice.id} for the condition and repair instructions; this is NOT evidence that the condition is met.`;
|
|
17639
17593
|
}
|
|
17640
|
-
const
|
|
17641
|
-
|
|
17642
|
-
|
|
17643
|
-
return { ok: false, reason: "stale_snapshot", detail: "raw range fingerprint changed" };
|
|
17594
|
+
const parts = [];
|
|
17595
|
+
if (notes.length > 0) {
|
|
17596
|
+
parts.push(`${notes.length} deferred note${notes.length === 1 ? "" : "s"}`);
|
|
17644
17597
|
}
|
|
17645
|
-
|
|
17598
|
+
if (readySmartNotes.length > 0) {
|
|
17599
|
+
parts.push(`${readySmartNotes.length} ready smart note${readySmartNotes.length === 1 ? "" : "s"}`);
|
|
17600
|
+
}
|
|
17601
|
+
sessionLog2(sessionId, `note-nudge: delivering nudge for ${parts.join(" and ")}`);
|
|
17602
|
+
return formatNoteNudge({
|
|
17603
|
+
readyCount: readySmartNotes.length,
|
|
17604
|
+
activeCount: notes.length,
|
|
17605
|
+
oldestActiveTouchedAt: oldestTouchedAt(notes),
|
|
17606
|
+
shown: pickNudgeNote({ db, sessionId, activeNotes: notes, readySmartNotes }),
|
|
17607
|
+
nowMs: Date.now()
|
|
17608
|
+
});
|
|
17646
17609
|
}
|
|
17647
|
-
function
|
|
17648
|
-
|
|
17649
|
-
|
|
17650
|
-
return
|
|
17610
|
+
function oldestTouchedAt(notes) {
|
|
17611
|
+
return notes.reduce((min, note) => {
|
|
17612
|
+
const touchedAt = noteTouchedAt(note);
|
|
17613
|
+
return min === null || touchedAt < min ? touchedAt : min;
|
|
17614
|
+
}, null);
|
|
17615
|
+
}
|
|
17616
|
+
function pickNudgeNote(args) {
|
|
17617
|
+
const pool = args.readySmartNotes.length > 0 ? [...args.readySmartNotes].sort((left, right) => left.id - right.id) : [...args.activeNotes].sort((left, right) => left.id - right.id);
|
|
17618
|
+
if (pool.length === 0)
|
|
17619
|
+
return null;
|
|
17620
|
+
const counter = getNoteNudgeAnchors(args.db, args.sessionId).length;
|
|
17621
|
+
return pool[noteNudgePickIndex(args.sessionId, counter, pool.length)] ?? null;
|
|
17622
|
+
}
|
|
17623
|
+
function maxNoteActivityTime(notes) {
|
|
17624
|
+
let max = 0;
|
|
17625
|
+
for (const note of notes) {
|
|
17626
|
+
if (note.updatedAt > max)
|
|
17627
|
+
max = note.updatedAt;
|
|
17628
|
+
if (note.readyAt !== null && note.readyAt > max)
|
|
17629
|
+
max = note.readyAt;
|
|
17651
17630
|
}
|
|
17652
|
-
return
|
|
17631
|
+
return max;
|
|
17632
|
+
}
|
|
17633
|
+
function markNoteNudgeDelivered(db, sessionId, text, messageId) {
|
|
17634
|
+
if (!messageId) {
|
|
17635
|
+
clearNoteNudgeTriggerAndCooldown(db, sessionId);
|
|
17636
|
+
sessionLog2(sessionId, "note-nudge: marked delivered without anchor");
|
|
17637
|
+
return { ok: true, kind: "already-present" };
|
|
17638
|
+
}
|
|
17639
|
+
const outcome = db.transaction(() => {
|
|
17640
|
+
const delivered = deliverNoteNudgeAtomic(db, sessionId, messageId, text);
|
|
17641
|
+
const nudgeText = text?.replace(/^\s*<instruction name="deferred_notes">/, "") ?? "";
|
|
17642
|
+
const noticeId = nudgeText.match(/^Smart note check unavailable: [\s\S]*Read ctx_note #(\d+) for the condition/);
|
|
17643
|
+
if (delivered.ok && noticeId) {
|
|
17644
|
+
db.prepare(`UPDATE notes SET status = 'dismissed', updated_at = ?
|
|
17645
|
+
WHERE id = ? AND type = 'session' AND session_id = ?
|
|
17646
|
+
AND content LIKE 'Smart note #% cannot be checked.%'`).run(Date.now(), Number(noticeId[1]), sessionId);
|
|
17647
|
+
}
|
|
17648
|
+
return delivered;
|
|
17649
|
+
}).immediate();
|
|
17650
|
+
if (outcome.ok) {
|
|
17651
|
+
recordNoteNudgeDeliveryTime(sessionId);
|
|
17652
|
+
}
|
|
17653
|
+
sessionLog2(sessionId, outcome.ok ? `note-nudge: marked delivered, sticky anchor=${messageId} (${outcome.kind})` : `note-nudge: delivery not persisted for anchor=${messageId} (${outcome.kind})`);
|
|
17654
|
+
return outcome;
|
|
17655
|
+
}
|
|
17656
|
+
function clearNoteNudgeTriggerAndCooldown(db, sessionId) {
|
|
17657
|
+
db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
|
|
17658
|
+
lastDeliveredAt.delete(sessionId);
|
|
17659
|
+
}
|
|
17660
|
+
function resetNoteNudgeCooldownOnly(sessionId) {
|
|
17661
|
+
lastDeliveredAt.delete(sessionId);
|
|
17662
|
+
}
|
|
17663
|
+
function clearNoteNudgeTriggerOnly(db, sessionId) {
|
|
17664
|
+
db.prepare("UPDATE session_meta SET note_nudge_trigger_pending = 0, note_nudge_trigger_message_id = '' WHERE session_id = ?").run(sessionId);
|
|
17665
|
+
}
|
|
17666
|
+
|
|
17667
|
+
// src/hooks/magic-context/persist-filtered-noise.ts
|
|
17668
|
+
function persistFilteredNoise(db, sessionId, chunk, eligibleEnd) {
|
|
17669
|
+
const rows = chunk.filteredNoiseLines ?? [];
|
|
17670
|
+
const start = chunk.startIndex;
|
|
17671
|
+
if (chunk.text || chunk.messageCount !== 0 || eligibleEnd <= start || rows.length !== eligibleEnd - start || rows.some((row, index) => row.ordinal !== start + index || !row.messageId))
|
|
17672
|
+
return false;
|
|
17673
|
+
const endId = rows[rows.length - 1].messageId;
|
|
17674
|
+
if (!hasRawSessionMessageById2(sessionId, endId)) {
|
|
17675
|
+
sessionLog2(sessionId, `historian skipped a filtered-noise marker for ordinals ${start}-${eligibleEnd - 1}: its end row ${endId} is no longer in the host store`);
|
|
17676
|
+
return false;
|
|
17677
|
+
}
|
|
17678
|
+
const saved = db.transaction(() => {
|
|
17679
|
+
const prior = getCompartments(db, sessionId);
|
|
17680
|
+
const last = prior.at(-1);
|
|
17681
|
+
if ((last?.endMessage ?? 0) + 1 !== start)
|
|
17682
|
+
return false;
|
|
17683
|
+
appendCompartments(db, sessionId, [
|
|
17684
|
+
{
|
|
17685
|
+
sequence: (last?.sequence ?? -1) + 1,
|
|
17686
|
+
startMessage: start,
|
|
17687
|
+
endMessage: eligibleEnd - 1,
|
|
17688
|
+
startMessageId: rows[0].messageId,
|
|
17689
|
+
endMessageId: rows[rows.length - 1].messageId,
|
|
17690
|
+
title: "",
|
|
17691
|
+
content: "",
|
|
17692
|
+
p1: "",
|
|
17693
|
+
p2: "",
|
|
17694
|
+
p3: "",
|
|
17695
|
+
p4: "",
|
|
17696
|
+
episodeType: "filtered-noise",
|
|
17697
|
+
importance: 1
|
|
17698
|
+
}
|
|
17699
|
+
]);
|
|
17700
|
+
return true;
|
|
17701
|
+
}).immediate();
|
|
17702
|
+
if (saved)
|
|
17703
|
+
sessionLog2(sessionId, `historian skipped ordinals ${start}-${eligibleEnd - 1}: all ${rows.length} raw rows excluded by chunk filters (no-content boundary marker)`);
|
|
17704
|
+
return saved;
|
|
17653
17705
|
}
|
|
17654
17706
|
|
|
17655
17707
|
// src/hooks/magic-context/raw-exact-ordinal-read.ts
|
|
@@ -18172,7 +18224,6 @@ async function runCompartmentAgent(deps) {
|
|
|
18172
18224
|
if (promptFit.trimmed || chunkTokens < historianChunkTokens) {
|
|
18173
18225
|
sessionLog2(sessionId, `historian prompt fit: sized to ${producerModel ?? "unknown"} (${describeHistorianPromptTrim(promptFit)}; requestedChunkTokens=${historianChunkTokens})`);
|
|
18174
18226
|
}
|
|
18175
|
-
const perRunCap = selectPerRunCap(boundarySnapshot);
|
|
18176
18227
|
if (!deps.forceDrainQuota && shouldWaitForNewHistorianHistory(boundarySnapshot, {
|
|
18177
18228
|
emergency: getOverflowState(db, sessionId).needsEmergencyRecovery
|
|
18178
18229
|
})) {
|
|
@@ -18181,19 +18232,27 @@ async function runCompartmentAgent(deps) {
|
|
|
18181
18232
|
sessionLog2(sessionId, "historian no-op: waiting for new history after no forward progress");
|
|
18182
18233
|
return;
|
|
18183
18234
|
}
|
|
18184
|
-
const
|
|
18235
|
+
const usagePercentage = deps.drainBudgetUsagePercentage ?? boundarySnapshot.usagePercentage;
|
|
18236
|
+
const { usable, perRunCap } = deps.drainBudgetUsagePercentage === undefined ? {
|
|
18237
|
+
usable: Math.max(1, Math.round(boundarySnapshot.contextLimit * boundarySnapshot.executeThresholdPercentage / 100)),
|
|
18238
|
+
perRunCap: selectPerRunCap(boundarySnapshot)
|
|
18239
|
+
} : resolveHistorianDrainBudgetGeometry({ ...boundarySnapshot, usagePercentage });
|
|
18185
18240
|
const reserve = deps.forceDrainQuota ? { ok: true, reservation: null } : reserveProtectedTailDrainTokens({
|
|
18186
18241
|
db,
|
|
18187
18242
|
sessionId,
|
|
18188
18243
|
runId: crypto.randomUUID(),
|
|
18189
18244
|
trueRawTokens: boundarySnapshot.summaryRemovedEligibleTokens,
|
|
18190
|
-
usagePercentage
|
|
18245
|
+
usagePercentage,
|
|
18246
|
+
providerRecovery: deps.drainBudgetUsagePercentage !== undefined,
|
|
18191
18247
|
usable,
|
|
18192
18248
|
perRunCap,
|
|
18193
18249
|
executeThresholdPercentage: boundarySnapshot.executeThresholdPercentage
|
|
18194
18250
|
});
|
|
18195
18251
|
if (!reserve.ok) {
|
|
18196
|
-
|
|
18252
|
+
if (deps.reportDrainSkip && reserve.drainSkip)
|
|
18253
|
+
deps.reportDrainSkip(reserve.drainSkip);
|
|
18254
|
+
else
|
|
18255
|
+
sessionLog2(sessionId, describeProtectedTailDrainBudgetSkip(reserve));
|
|
18197
18256
|
telemetry.status = "noop";
|
|
18198
18257
|
telemetry.failureReason = "internal protected-tail drain budget spent";
|
|
18199
18258
|
return;
|
|
@@ -18363,6 +18422,8 @@ ${chunkText}`,
|
|
|
18363
18422
|
const discardedLast = persistedCompartments.length < emittedCompartments.length;
|
|
18364
18423
|
const weakLookaheadFinalCompartment = forceKeepLastCompartmentForChunk;
|
|
18365
18424
|
const skipUnanchoredPromotion = discardedLast || weakLookaheadFinalCompartment;
|
|
18425
|
+
const facts = validatedPass.facts;
|
|
18426
|
+
const publishableFacts = !skipUnanchoredPromotion ? facts : retainAnchoredHistorianFacts(facts, weakLookaheadFinalCompartment ? Math.min(persistedCompartments.length, emittedCompartments.length - 1) : persistedCompartments.length);
|
|
18366
18427
|
const embeddingActive = !!promotionDirectory;
|
|
18367
18428
|
const promotionActive = embeddingActive && deps.memoryEnabled !== false && deps.autoPromote !== false;
|
|
18368
18429
|
const promotionProjectIdentity = promotionDirectory ? resolveProjectIdentity(promotionDirectory) : "";
|
|
@@ -18376,10 +18437,7 @@ ${chunkText}`,
|
|
|
18376
18437
|
}
|
|
18377
18438
|
return true;
|
|
18378
18439
|
});
|
|
18379
|
-
const
|
|
18380
|
-
if (unanchoredPromotionSkipReason) {
|
|
18381
|
-
sessionLog2(sessionId, `historian unanchored promotion skipped: reason=${unanchoredPromotionSkipReason} facts=${validatedPass.facts?.length ?? 0} user_observations=${validatedPass.userObservations?.length ?? 0} primers=${validatedPass.primerCandidates?.length ?? 0} events_publishable=${publishableEvents.length}/${validatedPass.events?.length ?? 0}`);
|
|
18382
|
-
}
|
|
18440
|
+
const weakTailReason = telemetry.discardedLast ? "discarded_last" : discardedLast ? "unserved_final_compartment" : weakLookaheadFinalCompartment ? "weak_lookahead_final_compartment" : null;
|
|
18383
18441
|
let promotedFactRefs = [];
|
|
18384
18442
|
let promotedFactCount = 0;
|
|
18385
18443
|
let publishedEventCount = 0;
|
|
@@ -18422,9 +18480,9 @@ ${chunkText}`,
|
|
|
18422
18480
|
}
|
|
18423
18481
|
appendCompartments(db, sessionId, persistedCompartments);
|
|
18424
18482
|
persistedIds = getNewestCompartmentIds(db, sessionId, persistedCompartments.length);
|
|
18425
|
-
if (promotionActive &&
|
|
18483
|
+
if (promotionActive && publishableFacts.length > 0) {
|
|
18426
18484
|
try {
|
|
18427
|
-
const promotion = promoteSessionFactsDurable(db, sessionId, promotionProjectIdentity,
|
|
18485
|
+
const promotion = promoteSessionFactsDurable(db, sessionId, promotionProjectIdentity, publishableFacts);
|
|
18428
18486
|
promotedFactRefs = promotion.newMemoryRefs;
|
|
18429
18487
|
promotedFactCount = promotion.factsPromoted;
|
|
18430
18488
|
} catch (error) {
|
|
@@ -18492,6 +18550,13 @@ ${chunkText}`,
|
|
|
18492
18550
|
}
|
|
18493
18551
|
updateSessionMeta(db, sessionId, { compartmentInProgress: false });
|
|
18494
18552
|
completedSuccessfully = true;
|
|
18553
|
+
if (weakTailReason) {
|
|
18554
|
+
logWeakTailFactPromotion(sessionId, {
|
|
18555
|
+
reason: weakTailReason,
|
|
18556
|
+
emitted: facts.length,
|
|
18557
|
+
stored: promotedFactCount
|
|
18558
|
+
});
|
|
18559
|
+
}
|
|
18495
18560
|
{
|
|
18496
18561
|
const facts = validatedPass.facts ?? [];
|
|
18497
18562
|
const validIds = persistedIds.filter((id) => typeof id === "number");
|
|
@@ -19773,4 +19838,4 @@ async function executeContextRecomp(deps, options = {}) {
|
|
|
19773
19838
|
return (await executeContextRecompWithResult(deps, options)).message;
|
|
19774
19839
|
}
|
|
19775
19840
|
|
|
19776
|
-
export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, isCommitRetentionPaused, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, supportsQuietHiddenChildren, matchesHiddenRunLocation, hiddenRunPlacement, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, noteTimedOutHiddenChild, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, isLatestAssistantLengthCapped, parseProviderModel, modelBodyField, toModelEntry, hiddenModelCooldowns, ModelProducedNoOutputError, promptTransportBudget, notePromptSetupTimeout, noteModelActivityMonitored, noteModelOutputReceived, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, annotateSubagentInvocationError, failedInvocationStatus, emptyTokenTotals, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, validateStoredCompartments, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, stripMemoryMuralBlock, servedHeadTexts, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, headMessagesForSizing, rawTailAfterNewestCompartment, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, pausedRecompReason, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync,
|
|
19841
|
+
export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, isCommitRetentionPaused, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, supportsQuietHiddenChildren, matchesHiddenRunLocation, hiddenRunPlacement, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, noteTimedOutHiddenChild, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, isLatestAssistantLengthCapped, parseProviderModel, modelBodyField, toModelEntry, hiddenModelCooldowns, ModelProducedNoOutputError, promptTransportBudget, notePromptSetupTimeout, noteModelActivityMonitored, noteModelOutputReceived, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, annotateSubagentInvocationError, failedInvocationStatus, emptyTokenTotals, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, validateStoredCompartments, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, stripMemoryMuralBlock, servedHeadTexts, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, headMessagesForSizing, rawTailAfterNewestCompartment, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, pausedRecompReason, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, reportProviderRecoveryDrainSkip, isHistorianDrainBudgetSpent, readHistorianFailureStreak, describeHistorianJoinRefusal, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, noteTransformPassForExactOrdinalReads, nonNarrativeStoredGapRanges, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };
|