dsh-context-compression-improved 0.10.5 → 0.11.1
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/CHANGELOG.md +8 -0
- package/CHANGELOG.zh.md +9 -0
- package/README.de.md +1 -1
- package/assets/dshfind-card.svg +33 -0
- package/docs/shallow-teaching-preset-template.md +46 -0
- package/package.json +6 -6
- package/packages/selector/dsh.plugin.json +2 -2
- package/packages/selector/lib/client.d.ts +8 -0
- package/packages/selector/lib/client.js +212 -3
- package/packages/selector/lib/index.js +1 -1
- package/packages/selector/lib/profiles.d.ts +34 -0
- package/packages/selector/lib/pruner.d.ts +55 -0
- package/packages/selector/lib/pruner.js +1925 -303
- package/packages/selector/lib/savings-integral.js +126 -3
- package/packages/selector/lib/tool-result.js +9 -1
- package/packages/selector/package.json +21 -21
- package/packages/selector/src/client/CompressionProfileControls.tsx +33 -0
- package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
- package/packages/selector/src/client/decode.ts +5 -1
- package/packages/selector/src/client/index.ts +4 -0
- package/packages/selector/src/client/locales/de.ts +7 -0
- package/packages/selector/src/client/locales/es.ts +7 -0
- package/packages/selector/src/client/locales/fr.ts +7 -0
- package/packages/selector/src/client/locales/it.ts +7 -0
- package/packages/selector/src/client/locales/ja.ts +7 -0
- package/packages/selector/src/client/locales/ko.ts +7 -0
- package/packages/selector/src/client/locales/ru.ts +7 -0
- package/packages/selector/src/client/locales.ts +14 -0
- package/packages/selector/src/client/monitor-fab.ts +14 -0
- package/packages/selector/src/client/settings-section.tsx +9 -2
- package/packages/selector/src/profiles.ts +103 -0
- package/packages/selector/src/pruner.ts +310 -4
- package/packages/selector/src/runtime/audit.ts +1 -0
- package/packages/selector/src/runtime/config.ts +88 -1
- package/packages/selector/src/runtime/fold-router.ts +143 -0
- package/packages/selector/src/runtime/monitor.ts +31 -0
- package/packages/selector/src/runtime/reducers.ts +1 -1
- package/packages/selector/src/runtime/sediment-card.ts +126 -0
- package/packages/selector/src/runtime/sediment-clock.ts +87 -0
- package/packages/selector/src/runtime/sediment-guard.ts +136 -0
- package/packages/selector/src/runtime/sediment-publish.ts +144 -0
- package/packages/selector/src/runtime/sediment-span.ts +170 -0
- package/packages/selector/src/runtime/sediment.ts +209 -0
- package/packages/selector/src/runtime/shallow-tools.ts +342 -0
- package/packages/selector/src/runtime/tool-names.ts +6 -0
- package/packages/selector/src/runtime/triage/masks.ts +128 -0
- package/packages/selector/src/runtime/triage/shallow.ts +132 -0
- package/packages/selector/src/runtime/triage/signals.ts +167 -0
- package/packages/selector/src/runtime/triage/types.ts +125 -0
- package/packages/selector/src/runtime/types.ts +28 -0
- package/packages/selector/tests/fixtures/sediment-pool/52adc205-cloud-5.orig.txt +231 -0
- package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-25.orig.txt +236 -0
- package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-38.orig.txt +220 -0
- package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-42.orig.txt +140 -0
- package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-53.orig.txt +117 -0
- package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-local-10.orig.txt +67 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-45.orig.txt +119 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-49.orig.txt +119 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-63.orig.txt +131 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-75.orig.txt +196 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-76.orig.txt +71 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-85.orig.txt +126 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-86.orig.txt +86 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-87.orig.txt +50 -0
- package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-96.orig.txt +102 -0
- package/packages/selector/tests/public/package-contract.client.spec.ts +7 -4
- package/packages/selector/tests/runtime/fold-router.spec.ts +140 -0
- package/packages/selector/tests/runtime/sediment-card.spec.ts +111 -0
- package/packages/selector/tests/runtime/sediment-config.spec.ts +56 -0
- package/packages/selector/tests/runtime/sediment-guard.spec.ts +71 -0
- package/packages/selector/tests/runtime/sediment-masks.spec.ts +95 -0
- package/packages/selector/tests/runtime/sediment-orchestrator.spec.ts +166 -0
- package/packages/selector/tests/runtime/sediment-pool-share.spec.ts +65 -0
- package/packages/selector/tests/runtime/sediment-publish.spec.ts +142 -0
- package/packages/selector/tests/runtime/sediment-real-shapes.spec.ts +158 -0
- package/packages/selector/tests/runtime/sediment-settings.spec.ts +73 -0
- package/packages/selector/tests/runtime/sediment-signals.spec.ts +124 -0
- package/packages/selector/tests/runtime/sediment-span.spec.ts +92 -0
- package/packages/selector/tests/runtime/shallow-primitives.spec.ts +135 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
- package/scripts/hosts.d.mts +3 -0
- package/scripts/hosts.mjs +3 -1
- package/scripts/sediment-latency-report.mjs +63 -0
- package/scripts/verify-release.mjs +7 -2
- package/$null +0 -1
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PTC downgrade guard (plan cci-sedimentation-triage, Phase 3, T3.10/T3.11).
|
|
3
|
+
*
|
|
4
|
+
* Two decisions live here as pure functions, unit-tested before any wiring:
|
|
5
|
+
* 1. PTC-mode detection — registration truth via the omnibus tool names
|
|
6
|
+
* (`run_code` on 0.1.x, `code_run` on 0.2.x), never wire literal guessing;
|
|
7
|
+
* 2. the negative-feedback loop — when net savings stay negative across K
|
|
8
|
+
* request boundaries (the community 1:15 / HUD -24,035 shape), fall back
|
|
9
|
+
* to conservative mode: aging decisions OFF, only fresh large-block cuts.
|
|
10
|
+
*
|
|
11
|
+
* The WRITE_TOOLS blindness probe encodes the root cause directly: in PTC,
|
|
12
|
+
* write operations fold into run_code bodies, so the regex-based read-state
|
|
13
|
+
* predicate sees zero hits and its "superseded" verdicts are untrustworthy.
|
|
14
|
+
*/
|
|
15
|
+
import type { SedimentSettings } from './types.ts'
|
|
16
|
+
|
|
17
|
+
/** Omnibus tool names that mark a PTC/code-mode session (both host lines). */
|
|
18
|
+
export const OMNIBUS_TOOL_NAMES: readonly string[] = Object.freeze(['run_code', 'code_run'])
|
|
19
|
+
|
|
20
|
+
/** Conservative fallback mode: aging-style decisions disabled. */
|
|
21
|
+
export interface ConservativeMode {
|
|
22
|
+
readonly conservative: boolean
|
|
23
|
+
readonly reason: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** True when the registered tool surface contains an omnibus runner. */
|
|
27
|
+
export function detectPtcMode(hasTool: (name: string) => boolean): boolean {
|
|
28
|
+
return OMNIBUS_TOOL_NAMES.some(name => hasTool(name))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* read-state blindness probe: with PTC active and ZERO write-tool regex hits
|
|
33
|
+
* across the observed calls, the superseded predicate cannot see real write
|
|
34
|
+
* targets — aging decisions must be considered untrustworthy.
|
|
35
|
+
*/
|
|
36
|
+
export function readStateBlind(ptcActive: boolean, writeRegexHits: number, observedCalls: number): boolean {
|
|
37
|
+
if (!ptcActive) return false
|
|
38
|
+
return observedCalls > 0 && writeRegexHits === 0
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface NetSample {
|
|
42
|
+
readonly grossSaved: number
|
|
43
|
+
readonly recallOffset: number
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Feedback loop state: consumes request-boundary samples and decides whether
|
|
48
|
+
* sediment/aging operation should run in conservative mode. K consecutive
|
|
49
|
+
* negative-net samples arm it; a positive net sample disarms immediately.
|
|
50
|
+
*/
|
|
51
|
+
export class FeedbackLoop {
|
|
52
|
+
private negativeStreak = 0
|
|
53
|
+
private armed = false
|
|
54
|
+
|
|
55
|
+
constructor(private readonly k: number = 5) {}
|
|
56
|
+
|
|
57
|
+
get conservative(): boolean {
|
|
58
|
+
return this.armed
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
observe(sample: NetSample): ConservativeMode {
|
|
62
|
+
const net = sample.grossSaved - sample.recallOffset
|
|
63
|
+
if (net < 0) {
|
|
64
|
+
this.negativeStreak += 1
|
|
65
|
+
if (this.negativeStreak >= this.k) this.armed = true
|
|
66
|
+
} else if (net > 0) {
|
|
67
|
+
this.negativeStreak = 0
|
|
68
|
+
this.armed = false
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
conservative: this.armed,
|
|
72
|
+
reason: this.armed ? `net-negative-x${this.negativeStreak}` : 'ok',
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Watcher adapter (T3.11 consumption point): the savings ledger reports
|
|
79
|
+
* CUMULATIVE gross/offsets; the feedback loop needs per-boundary NET deltas.
|
|
80
|
+
* This wrapper remembers the last reading and feeds the loop the difference.
|
|
81
|
+
*/
|
|
82
|
+
export class SedimentFeedbackWatcher {
|
|
83
|
+
private last: { gross: number; offsets: number } = { gross: 0, offsets: 0 }
|
|
84
|
+
|
|
85
|
+
constructor(private readonly loop: FeedbackLoop = new FeedbackLoop(5)) {}
|
|
86
|
+
|
|
87
|
+
observe(totals: { gross: { exact: number, estimated: number }, offsets: { exact: number, estimated: number } }): ConservativeMode {
|
|
88
|
+
const gross = totals.gross.exact + totals.gross.estimated
|
|
89
|
+
const offsets = totals.offsets.exact + totals.offsets.estimated
|
|
90
|
+
const sample = {
|
|
91
|
+
grossSaved: gross - this.last.gross,
|
|
92
|
+
recallOffset: offsets - this.last.offsets,
|
|
93
|
+
}
|
|
94
|
+
this.last = { gross, offsets }
|
|
95
|
+
return this.loop.observe(sample)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
get conservative(): boolean {
|
|
99
|
+
return this.loop.conservative
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Effective sediment behavior for one session after the PTC guard is folded
|
|
105
|
+
* in: in PTC mode, aging-style decisions short-circuit and the rewrite guard
|
|
106
|
+
* ratio tightens; the card pipeline itself (mask/pool/pointer) is unaffected.
|
|
107
|
+
*/
|
|
108
|
+
export function effectiveSedimentMode(
|
|
109
|
+
settings: SedimentSettings,
|
|
110
|
+
ptcActive: boolean,
|
|
111
|
+
blindReadState: boolean,
|
|
112
|
+
feedback: ConservativeMode,
|
|
113
|
+
): {
|
|
114
|
+
readonly enabled: boolean
|
|
115
|
+
readonly agingAllowed: boolean
|
|
116
|
+
readonly rewriteGuardRatio: number
|
|
117
|
+
readonly reason: string
|
|
118
|
+
} {
|
|
119
|
+
if (!settings.enabled) {
|
|
120
|
+
return { enabled: false, agingAllowed: false, rewriteGuardRatio: settings.rewriteGuardRatio, reason: 'disabled' }
|
|
121
|
+
}
|
|
122
|
+
const agingAllowed = !(ptcActive && blindReadState) && !feedback.conservative
|
|
123
|
+
const rewriteGuardRatio = ptcActive || feedback.conservative
|
|
124
|
+
? Math.max(settings.rewriteGuardRatio, 5)
|
|
125
|
+
: settings.rewriteGuardRatio
|
|
126
|
+
return {
|
|
127
|
+
enabled: true,
|
|
128
|
+
agingAllowed,
|
|
129
|
+
rewriteGuardRatio,
|
|
130
|
+
reason: feedback.conservative
|
|
131
|
+
? `conservative:${feedback.reason}`
|
|
132
|
+
: ptcActive && blindReadState
|
|
133
|
+
? 'ptc-blind-aging-off'
|
|
134
|
+
: 'normal',
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sediment publication (plan cci-sedimentation-triage, Phase 3, T3.5/T3.6).
|
|
3
|
+
*
|
|
4
|
+
* The commit transaction mirrors the proven TailTrim publication shape
|
|
5
|
+
* (pruner.ts L2386-2406): a `compaction/prune` manifest event, then ONE
|
|
6
|
+
* `user/message` replacement carrying `surfaceOp: replace` and
|
|
7
|
+
* `sourceEventSeqs`, through the generation-gated message builder so 0.1.x
|
|
8
|
+
* and 0.2.x hosts accept the same code path. The shortening proof (M7) runs
|
|
9
|
+
* BEFORE any append — a card that does not shrink the span is refused, and
|
|
10
|
+
* nothing half-committed can exist.
|
|
11
|
+
*
|
|
12
|
+
* The session is injected as a minimal interface so the transaction is
|
|
13
|
+
* unit-testable without a host; the wiring site passes the real session.
|
|
14
|
+
*/
|
|
15
|
+
import { tailTrimMessage } from './tail-trim.ts'
|
|
16
|
+
import { renderTurnCard } from './sediment-card.ts'
|
|
17
|
+
import type { TurnCardDraft } from './triage/types.ts'
|
|
18
|
+
|
|
19
|
+
export interface PublishTarget {
|
|
20
|
+
append(type: 'compaction/prune', data: Record<string, unknown>): { seq: number }
|
|
21
|
+
append(type: 'user/message', message: unknown, options?: Record<string, unknown>): { seq: number }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface PublishResult {
|
|
25
|
+
readonly ok: boolean
|
|
26
|
+
readonly reason: string
|
|
27
|
+
readonly manifestSeq?: number
|
|
28
|
+
readonly replacementSeq?: number
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface PublishSpan {
|
|
32
|
+
readonly startSeq: number
|
|
33
|
+
readonly endSeq: number
|
|
34
|
+
readonly shadowedSeqs: readonly number[]
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Commit one card over the span. Never throws; every failure is a reason code. */
|
|
38
|
+
export function publishSettledCard(
|
|
39
|
+
session: PublishTarget,
|
|
40
|
+
draft: TurnCardDraft,
|
|
41
|
+
span: PublishSpan,
|
|
42
|
+
): PublishResult {
|
|
43
|
+
if (draft.retainedTokens >= draft.sourceTokens) {
|
|
44
|
+
return { ok: false, reason: `shortening-proof-failed:${draft.retainedTokens}>=${draft.sourceTokens}` }
|
|
45
|
+
}
|
|
46
|
+
if (span.shadowedSeqs.length === 0) {
|
|
47
|
+
return { ok: false, reason: 'empty-span' }
|
|
48
|
+
}
|
|
49
|
+
const manifest = session.append('compaction/prune', {
|
|
50
|
+
shadowedRange: { start: span.startSeq, end: span.endSeq },
|
|
51
|
+
shadowedSeqs: [...span.shadowedSeqs],
|
|
52
|
+
shadowedTokenCount: draft.sourceTokens,
|
|
53
|
+
})
|
|
54
|
+
let replacementSeq: number
|
|
55
|
+
try {
|
|
56
|
+
const message = tailTrimMessage(renderTurnCard(draft))
|
|
57
|
+
replacementSeq = session.append('user/message', message, {
|
|
58
|
+
surfaceOp: { op: 'replace', startSeq: span.startSeq, endSeq: span.endSeq },
|
|
59
|
+
sourceEventSeqs: [manifest.seq, ...span.shadowedSeqs],
|
|
60
|
+
}).seq
|
|
61
|
+
} catch (error) {
|
|
62
|
+
// The manifest stands alone (same tolerated state as TailTrim publication
|
|
63
|
+
// failure: an append without replacement is inert on the surface).
|
|
64
|
+
return { ok: false, reason: `publication-failed:${error instanceof Error ? error.message : String(error)}`, manifestSeq: manifest.seq }
|
|
65
|
+
}
|
|
66
|
+
return { ok: true, reason: 'landed', manifestSeq: manifest.seq, replacementSeq }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Rewrite guard (T3.3 accounting, findings F2 community 1:15 evidence):
|
|
71
|
+
* a cut may only land when its saving clears the estimated cached-tail
|
|
72
|
+
* rewrite cost by the configured ratio. Pure function over token counts.
|
|
73
|
+
*/
|
|
74
|
+
export function passesRewriteGuard(
|
|
75
|
+
draft: TurnCardDraft,
|
|
76
|
+
rewriteTailTokens: number,
|
|
77
|
+
ratio: number,
|
|
78
|
+
): boolean {
|
|
79
|
+
const saving = draft.sourceTokens - draft.retainedTokens
|
|
80
|
+
return saving > 0 && saving >= rewriteTailTokens * ratio
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Project a host session event into the minimal `SurfaceEvent` the span
|
|
85
|
+
* planner consumes. Kept separate from the planner so the planner stays
|
|
86
|
+
* host-type-free; the wiring site supplies the call-id → name/args map.
|
|
87
|
+
*/
|
|
88
|
+
export function projectSurfaceEvent(
|
|
89
|
+
seq: number,
|
|
90
|
+
event: {
|
|
91
|
+
type: string
|
|
92
|
+
data?: {
|
|
93
|
+
message?: { content?: unknown; toolCallId?: string; isError?: boolean }
|
|
94
|
+
content?: unknown
|
|
95
|
+
reason?: { kind?: string }
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
callInfo: { name: string; argsJson: string } | undefined,
|
|
99
|
+
): import('./sediment-span.ts').SurfaceEvent | null {
|
|
100
|
+
const text = flattenText(event.data?.message?.content ?? event.data?.content)
|
|
101
|
+
switch (event.type) {
|
|
102
|
+
case 'user/message':
|
|
103
|
+
return { seq, type: 'user/message', text }
|
|
104
|
+
case 'assistant/message': {
|
|
105
|
+
const toolCalls = countToolCallBlocks(event.data?.message?.content)
|
|
106
|
+
return { seq, type: 'assistant/message', text: stripToolCallBlocks(text), toolCalls }
|
|
107
|
+
}
|
|
108
|
+
case 'tool/result':
|
|
109
|
+
return {
|
|
110
|
+
seq,
|
|
111
|
+
type: 'tool/result',
|
|
112
|
+
text,
|
|
113
|
+
...(callInfo === undefined ? {} : { toolName: callInfo.name, argsJson: callInfo.argsJson }),
|
|
114
|
+
isError: event.data?.message?.isError === true,
|
|
115
|
+
}
|
|
116
|
+
case 'turn/end': {
|
|
117
|
+
const reasonKind = event.data?.reason?.kind
|
|
118
|
+
return { seq, type: 'turn/end', text: '', ...(reasonKind === undefined ? {} : { reasonKind }) }
|
|
119
|
+
}
|
|
120
|
+
default:
|
|
121
|
+
return null
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function blockText(block: unknown): string {
|
|
126
|
+
if (block === null || typeof block !== 'object') return ''
|
|
127
|
+
const record = block as Record<string, unknown>
|
|
128
|
+
return typeof record.text === 'string' ? record.text : ''
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function flattenText(content: unknown): string {
|
|
132
|
+
if (typeof content === 'string') return content
|
|
133
|
+
if (Array.isArray(content)) return content.map(blockText).filter(entry => entry !== '').join('\n')
|
|
134
|
+
return ''
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function countToolCallBlocks(content: unknown): number {
|
|
138
|
+
if (!Array.isArray(content)) return 0
|
|
139
|
+
return content.filter(block => (block as Record<string, unknown> | null)?.type === 'tool-call').length
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function stripToolCallBlocks(text: string): string {
|
|
143
|
+
return text // blocks already filtered by blockText (tool-call blocks carry no .text)
|
|
144
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whole-turn span planning (plan cci-sedimentation-triage, Phase 3, T3.3).
|
|
3
|
+
*
|
|
4
|
+
* Pure function over a minimal projected event list (the wiring site adapts
|
|
5
|
+
* real session events to `SurfaceEvent`). Decisions made here:
|
|
6
|
+
* - reason gate (R13①): only turns that ended `completed` are replaceable;
|
|
7
|
+
* - tail-kept region (R13③): the last `tailRoundsKept` tool rounds stay
|
|
8
|
+
* verbatim on the surface — the replacement span ends before them;
|
|
9
|
+
* - closing extraction: the last tool-call-free assistant text is the
|
|
10
|
+
* candidate closing body for the qualification gate;
|
|
11
|
+
* - the span covers contiguous assistant/tool events after the turn's user
|
|
12
|
+
* message; a span with no maskable/replaceable block returns null.
|
|
13
|
+
*
|
|
14
|
+
* Turn boundaries make cross-turn pairing checks unnecessary (rounds close
|
|
15
|
+
* inside their turn), which is the whole-turn granularity's main simplification.
|
|
16
|
+
*/
|
|
17
|
+
import type { TriageResult } from './triage/types.ts'
|
|
18
|
+
import { blockFailureVerdict, linePool, type LineRule } from './triage/signals.ts'
|
|
19
|
+
import { manifestFromCall, skeletonFromRead } from './triage/masks.ts'
|
|
20
|
+
import { estimateTokens } from './sediment-card.ts'
|
|
21
|
+
|
|
22
|
+
/** Minimal projected event the wiring site must provide per surface node. */
|
|
23
|
+
export interface SurfaceEvent {
|
|
24
|
+
readonly seq: number
|
|
25
|
+
readonly type: 'user/message' | 'assistant/message' | 'tool/result' | 'turn/end'
|
|
26
|
+
readonly text: string
|
|
27
|
+
/** tool-call block count on an assistant message (0 otherwise). */
|
|
28
|
+
readonly toolCalls?: number
|
|
29
|
+
/** Resolved tool name for a tool/result (call-id lookup done by the wiring site). */
|
|
30
|
+
readonly toolName?: string
|
|
31
|
+
/** Raw arguments JSON for the call owning a tool/result. */
|
|
32
|
+
readonly argsJson?: string
|
|
33
|
+
readonly isError?: boolean
|
|
34
|
+
/** `turn/end` reason kind, e.g. 'completed' | 'interrupted'. */
|
|
35
|
+
readonly reasonKind?: string
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface TurnSpanPlan {
|
|
39
|
+
readonly completed: boolean
|
|
40
|
+
/** Inclusive replacement span; null when nothing is replaceable. */
|
|
41
|
+
readonly startSeq: number | null
|
|
42
|
+
readonly endSeq: number | null
|
|
43
|
+
/** Events inside the span (assistant/tool), in order. */
|
|
44
|
+
readonly blocks: readonly SurfaceEvent[]
|
|
45
|
+
/** The turn's closing body (last tool-call-free assistant text after the span). */
|
|
46
|
+
readonly closingText: string
|
|
47
|
+
/** Kept-verbatim seqs: user messages, tail rounds, closing — never in the span. */
|
|
48
|
+
readonly keptSeqs: readonly number[]
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface TurnSpanOptions {
|
|
52
|
+
readonly tailRoundsKept?: number
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface Round { readonly start: number; readonly end: number }
|
|
56
|
+
|
|
57
|
+
/** Close tool rounds over the projected events (open-stack, same shape as the replay harness). */
|
|
58
|
+
function closeRounds(events: readonly SurfaceEvent[]): Round[] {
|
|
59
|
+
const rounds: Round[] = []
|
|
60
|
+
let open = 0
|
|
61
|
+
let start = -1
|
|
62
|
+
for (const event of events) {
|
|
63
|
+
const calls = event.type === 'assistant/message' ? event.toolCalls ?? 0 : 0
|
|
64
|
+
if (calls > 0) {
|
|
65
|
+
if (open === 0) start = events.indexOf(event)
|
|
66
|
+
open += calls
|
|
67
|
+
continue
|
|
68
|
+
}
|
|
69
|
+
if (event.type !== 'tool/result') continue
|
|
70
|
+
if (open <= 0) continue
|
|
71
|
+
open -= 1
|
|
72
|
+
if (open === 0 && start >= 0) {
|
|
73
|
+
rounds.push({ start, end: events.indexOf(event) })
|
|
74
|
+
start = -1
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return rounds
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Plan the replacement span for one turn's projected events. */
|
|
81
|
+
export function planTurnSpan(events: readonly SurfaceEvent[], options: TurnSpanOptions = {}): TurnSpanPlan {
|
|
82
|
+
const tailRoundsKept = options.tailRoundsKept ?? 1
|
|
83
|
+
const turnEnd = events.find(event => event.type === 'turn/end')
|
|
84
|
+
const completed = turnEnd?.reasonKind === 'completed'
|
|
85
|
+
const body = events.filter(event => event.type !== 'turn/end')
|
|
86
|
+
const keptSeqs: number[] = body.filter(event => event.type === 'user/message').map(event => event.seq)
|
|
87
|
+
|
|
88
|
+
const rounds = closeRounds(body)
|
|
89
|
+
// Closing body: last assistant text without tool-calls, after the last closed round.
|
|
90
|
+
const lastRoundEnd = rounds.length > 0 ? (rounds[rounds.length - 1] as Round).end : -1
|
|
91
|
+
let closingText = ''
|
|
92
|
+
let closingIndex = -1
|
|
93
|
+
for (let index = body.length - 1; index > lastRoundEnd; index -= 1) {
|
|
94
|
+
const event = body[index]
|
|
95
|
+
if (event === undefined) continue
|
|
96
|
+
if (event.type === 'assistant/message' && (event.toolCalls ?? 0) === 0 && event.text.trim() !== '') {
|
|
97
|
+
closingText = event.text.trim()
|
|
98
|
+
closingIndex = index
|
|
99
|
+
keptSeqs.push(event.seq)
|
|
100
|
+
break
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Tail-kept rounds: last `tailRoundsKept` rounds stay verbatim.
|
|
105
|
+
const keptRounds = tailRoundsKept > 0 ? rounds.slice(Math.max(0, rounds.length - tailRoundsKept)) : []
|
|
106
|
+
for (const round of keptRounds) {
|
|
107
|
+
for (let index = round.start; index <= round.end; index += 1) {
|
|
108
|
+
const event = body[index]
|
|
109
|
+
if (event !== undefined) keptSeqs.push(event.seq)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Replacement span: from the first replaceable event up to the kept boundary.
|
|
114
|
+
// The closing body is never inside the span (it stays verbatim on the surface).
|
|
115
|
+
const firstIndex = body.findIndex(event => event.type === 'assistant/message' || event.type === 'tool/result')
|
|
116
|
+
const keptStartIndex = keptRounds.length > 0
|
|
117
|
+
? (keptRounds[0] as Round).start
|
|
118
|
+
: closingIndex >= 0 ? closingIndex : body.length
|
|
119
|
+
const spanEndIndex = Math.max(firstIndex, keptStartIndex) - 1
|
|
120
|
+
const replaceable = firstIndex >= 0 && spanEndIndex >= firstIndex
|
|
121
|
+
const blocks = replaceable ? body.slice(firstIndex, spanEndIndex + 1) : []
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
completed,
|
|
125
|
+
startSeq: replaceable ? (blocks[0] as SurfaceEvent).seq : null,
|
|
126
|
+
endSeq: replaceable ? (blocks[blocks.length - 1] as SurfaceEvent).seq : null,
|
|
127
|
+
blocks,
|
|
128
|
+
closingText,
|
|
129
|
+
keptSeqs,
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Triage every block of a planned span into the frozen TriageResult shape. */
|
|
134
|
+
export function triageSpanBlocks(
|
|
135
|
+
plan: TurnSpanPlan,
|
|
136
|
+
rules: readonly LineRule[],
|
|
137
|
+
): TriageResult[] {
|
|
138
|
+
return plan.blocks.map(event => {
|
|
139
|
+
const sourceTokens = estimateTokens(event.text)
|
|
140
|
+
if (event.type === 'tool/result') {
|
|
141
|
+
const verdict = blockFailureVerdict(event.text, event.isError === true)
|
|
142
|
+
const poolLines = linePool(event.text, {
|
|
143
|
+
seq: event.seq,
|
|
144
|
+
role: 'tool',
|
|
145
|
+
hardFailure: verdict.hard,
|
|
146
|
+
extraPatterns: rules,
|
|
147
|
+
})
|
|
148
|
+
const mask = manifestFromCall(event.toolName ?? '', event.argsJson ?? '', event.text, event.seq)
|
|
149
|
+
?? (event.toolName !== undefined && /^(read|read_file|view)$/i.test(event.toolName)
|
|
150
|
+
? skeletonFromRead(event.text, event.seq)
|
|
151
|
+
: null)
|
|
152
|
+
const residualNarrative = poolLines.length === 0 && mask === null && event.text.trim() !== ''
|
|
153
|
+
? [{ seq: event.seq, role: 'tool' as const, tokens: sourceTokens, text: event.text }]
|
|
154
|
+
: []
|
|
155
|
+
return { poolLines, ...(mask === null ? {} : { mask }), residualNarrative, sourceTokens }
|
|
156
|
+
}
|
|
157
|
+
// Assistant text inside the span: pool-check it (assertion lines occur here too).
|
|
158
|
+
const verdict = blockFailureVerdict(event.text, false)
|
|
159
|
+
const poolLines = linePool(event.text, {
|
|
160
|
+
seq: event.seq,
|
|
161
|
+
role: 'assistant',
|
|
162
|
+
hardFailure: verdict.hard,
|
|
163
|
+
extraPatterns: rules,
|
|
164
|
+
})
|
|
165
|
+
const residualNarrative = poolLines.length === 0
|
|
166
|
+
? [{ seq: event.seq, role: 'assistant' as const, tokens: sourceTokens, text: event.text }]
|
|
167
|
+
: []
|
|
168
|
+
return { poolLines, residualNarrative, sourceTokens }
|
|
169
|
+
})
|
|
170
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sediment orchestrator (plan cci-sedimentation-triage, Phase 3, T3.6).
|
|
3
|
+
*
|
|
4
|
+
* Host-agnostic by injection: the wiring site (pruner) supplies the settings
|
|
5
|
+
* snapshot reader, the event reader, and the call-id map; this module owns
|
|
6
|
+
* the per-session clock and the turn-end decision pipeline:
|
|
7
|
+
*
|
|
8
|
+
* settings gate → clock predicate → span plan (reason gate)
|
|
9
|
+
* → triage → card build (tier gates) → rewrite guard → publish.
|
|
10
|
+
*
|
|
11
|
+
* With `sediment.enabled=false` (the default) the FIRST check short-circuits
|
|
12
|
+
* and nothing else in this module runs — the M1 zero-drift guarantee holds by
|
|
13
|
+
* construction: no event accumulation, no card, no append.
|
|
14
|
+
*/
|
|
15
|
+
import { planTurnSpan, triageSpanBlocks, type SurfaceEvent } from './sediment-span.ts'
|
|
16
|
+
import { buildTurnCard, estimateTokens } from './sediment-card.ts'
|
|
17
|
+
import { passesRewriteGuard, projectSurfaceEvent, publishSettledCard, type PublishResult } from './sediment-publish.ts'
|
|
18
|
+
import { SedimentClock, type CommitDecision } from './sediment-clock.ts'
|
|
19
|
+
import { mergeExtraPatterns, type LineRule } from './triage/signals.ts'
|
|
20
|
+
import { buildFoldPrompt, type FoldPrompt } from './fold-router.ts'
|
|
21
|
+
import type { MaskVerdict } from './triage/types.ts'
|
|
22
|
+
import type { SedimentSettings } from './types.ts'
|
|
23
|
+
|
|
24
|
+
/** Minimal append-capable session face (real Session satisfies it). */
|
|
25
|
+
export interface SedimentSession {
|
|
26
|
+
readonly id: string | number
|
|
27
|
+
append(type: never, data: never, options?: never): { seq: number }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface OrchestratorOptions {
|
|
31
|
+
/** Frozen per-session settings snapshot reader; undefined = not yet observed. */
|
|
32
|
+
readonly settingsFor: (sessionId: string) => SedimentSettings | undefined
|
|
33
|
+
/** Raw host events for one turn (including the trailing turn/end). */
|
|
34
|
+
readonly eventsFor: (session: SedimentSession, turn: number) => ReadonlyArray<{
|
|
35
|
+
seq: number
|
|
36
|
+
type: string
|
|
37
|
+
data?: Record<string, unknown>
|
|
38
|
+
}>
|
|
39
|
+
/** call-id → tool name/args map built by the wiring site. */
|
|
40
|
+
readonly callInfoFor: (sessionId: string) => (callId: string | undefined) => { name: string; argsJson: string } | undefined
|
|
41
|
+
/** Tokens on the surface AFTER the span (rewrite tail estimate). */
|
|
42
|
+
readonly tailTokensFor: (session: SedimentSession, endSeq: number) => number
|
|
43
|
+
readonly onLanded?: (sessionId: string, savedTokens: number, tier: string, result: PublishResult) => void
|
|
44
|
+
readonly onSkip?: (sessionId: string, reason: string) => void
|
|
45
|
+
/** Narrative tier 2 channel (T4.5): present only when a fold endpoint is configured. */
|
|
46
|
+
readonly fold?: {
|
|
47
|
+
readonly run: (sessionId: string, prompt: FoldPrompt, signal: AbortSignal) => Promise<string | undefined>
|
|
48
|
+
}
|
|
49
|
+
/** Feedback-loop state (T3.11): conservative arms the tightened rewrite guard. */
|
|
50
|
+
readonly feedback?: () => { readonly conservative: boolean; readonly reason: string }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface TurnOutcome {
|
|
54
|
+
readonly committed: boolean
|
|
55
|
+
readonly reason: string
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Compiled extra-pattern rules per session settings identity (cheap cache). */
|
|
59
|
+
const ruleCache = new WeakMap<SedimentSettings, readonly LineRule[]>()
|
|
60
|
+
|
|
61
|
+
function rulesFor(settings: SedimentSettings): readonly LineRule[] {
|
|
62
|
+
let rules = ruleCache.get(settings)
|
|
63
|
+
if (rules === undefined) {
|
|
64
|
+
rules = mergeExtraPatterns(settings.extraSignalPatterns ?? [])
|
|
65
|
+
ruleCache.set(settings, rules)
|
|
66
|
+
}
|
|
67
|
+
return rules
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export class SedimentOrchestrator {
|
|
71
|
+
private readonly clocks = new Map<string, SedimentClock>()
|
|
72
|
+
|
|
73
|
+
constructor(private readonly options: OrchestratorOptions) {}
|
|
74
|
+
|
|
75
|
+
clockFor(sessionId: string): SedimentClock {
|
|
76
|
+
let clock = this.clocks.get(sessionId)
|
|
77
|
+
if (clock === undefined) {
|
|
78
|
+
clock = new SedimentClock()
|
|
79
|
+
this.clocks.set(sessionId, clock)
|
|
80
|
+
}
|
|
81
|
+
return clock
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Entry point called by the wiring site on `turn/end`. Returns immediately
|
|
86
|
+
* with reason 'disabled' when the gate is off — nothing downstream runs.
|
|
87
|
+
*/
|
|
88
|
+
async handleTurnEnd(session: SedimentSession, turn: number, context: {
|
|
89
|
+
readonly lastEventType: string | undefined
|
|
90
|
+
readonly inFlightRequest: boolean
|
|
91
|
+
readonly compactionOpen: boolean
|
|
92
|
+
readonly officialCheckpointSeq: number | undefined
|
|
93
|
+
readonly resumeFirstBatch: boolean
|
|
94
|
+
}): Promise<TurnOutcome> {
|
|
95
|
+
const sessionId = String(session.id)
|
|
96
|
+
const settings = this.options.settingsFor(sessionId)
|
|
97
|
+
if (settings === undefined || !settings.enabled) {
|
|
98
|
+
return { committed: false, reason: 'disabled' }
|
|
99
|
+
}
|
|
100
|
+
const clock = this.clockFor(sessionId)
|
|
101
|
+
const decision: CommitDecision = clock.decide({
|
|
102
|
+
lastEventType: context.lastEventType,
|
|
103
|
+
inFlightRequest: context.inFlightRequest,
|
|
104
|
+
compactionOpen: context.compactionOpen,
|
|
105
|
+
officialCheckpointSeq: context.officialCheckpointSeq,
|
|
106
|
+
resumeFirstBatch: context.resumeFirstBatch,
|
|
107
|
+
})
|
|
108
|
+
if (!decision.ok) {
|
|
109
|
+
// Consuming the yield is the clock's job: once skipped for an official
|
|
110
|
+
// checkpoint, the next seam may proceed.
|
|
111
|
+
if (context.officialCheckpointSeq !== undefined && decision.reason.startsWith('yield-official')) {
|
|
112
|
+
clock.noteOfficialConsumed(context.officialCheckpointSeq)
|
|
113
|
+
}
|
|
114
|
+
this.options.onSkip?.(sessionId, decision.reason)
|
|
115
|
+
return { committed: false, reason: decision.reason }
|
|
116
|
+
}
|
|
117
|
+
if (!clock.begin()) {
|
|
118
|
+
return { committed: false, reason: 'already-committing' }
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
return await this.commitTurn(session, turn, settings)
|
|
122
|
+
} finally {
|
|
123
|
+
clock.end()
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
private async commitTurn(
|
|
128
|
+
session: SedimentSession,
|
|
129
|
+
turn: number,
|
|
130
|
+
settings: SedimentSettings,
|
|
131
|
+
): Promise<TurnOutcome> {
|
|
132
|
+
const sessionId = String(session.id)
|
|
133
|
+
const rawEvents = this.options.eventsFor(session, turn)
|
|
134
|
+
const projected: SurfaceEvent[] = []
|
|
135
|
+
for (const event of rawEvents) {
|
|
136
|
+
const message = event.data?.message as Record<string, unknown> | undefined
|
|
137
|
+
const callId = message?.toolCallId as string | undefined
|
|
138
|
+
const surface = projectSurfaceEvent(event.seq, {
|
|
139
|
+
type: event.type,
|
|
140
|
+
data: event.data as never,
|
|
141
|
+
}, this.options.callInfoFor(sessionId)(callId))
|
|
142
|
+
if (surface !== null) projected.push(surface)
|
|
143
|
+
}
|
|
144
|
+
const plan = planTurnSpan(projected)
|
|
145
|
+
if (!plan.completed) {
|
|
146
|
+
this.options.onSkip?.(sessionId, 'reason-gate')
|
|
147
|
+
return { committed: false, reason: 'reason-gate' }
|
|
148
|
+
}
|
|
149
|
+
if (plan.startSeq === null || plan.endSeq === null) {
|
|
150
|
+
this.options.onSkip?.(sessionId, 'empty-span')
|
|
151
|
+
return { committed: false, reason: 'empty-span' }
|
|
152
|
+
}
|
|
153
|
+
const triage = triageSpanBlocks(plan, rulesFor(settings))
|
|
154
|
+
const foldAvailable = this.options.fold !== undefined
|
|
155
|
+
// Narrative tier 2 (T4.5): when the closing body fails the qualification
|
|
156
|
+
// gate and a fold channel is configured, request the connective narrative
|
|
157
|
+
// over the residual spans ONLY (protected/skeleton material is excluded
|
|
158
|
+
// by buildFoldPrompt construction, S4). Timeout and failure are the
|
|
159
|
+
// FoldRouter's fail-open contract; undefined drops the card to tier 3.
|
|
160
|
+
let foldText: string | undefined
|
|
161
|
+
if (this.options.fold !== undefined && estimateTokens(plan.closingText) < (settings.minClosingTokens ?? 120)) {
|
|
162
|
+
const spans = triage.flatMap(result => result.residualNarrative)
|
|
163
|
+
const protectedLines = triage.flatMap(result => result.poolLines)
|
|
164
|
+
const masks = triage.map(result => result.mask).filter((mask): mask is MaskVerdict => mask !== undefined)
|
|
165
|
+
const prompt = buildFoldPrompt(spans, protectedLines, masks)
|
|
166
|
+
if (prompt !== null) {
|
|
167
|
+
foldText = await this.options.fold.run(sessionId, prompt, AbortSignal.timeout(20_000))
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const draft = buildTurnCard({
|
|
171
|
+
startSeq: plan.startSeq,
|
|
172
|
+
endSeq: plan.endSeq,
|
|
173
|
+
triage,
|
|
174
|
+
closingText: plan.closingText,
|
|
175
|
+
foldAvailable,
|
|
176
|
+
...(foldText === undefined ? {} : { foldText }),
|
|
177
|
+
minClosingTokens: settings.minClosingTokens,
|
|
178
|
+
})
|
|
179
|
+
if (draft === null) {
|
|
180
|
+
this.options.onSkip?.(sessionId, 'tier-skip')
|
|
181
|
+
return { committed: false, reason: 'tier-skip' }
|
|
182
|
+
}
|
|
183
|
+
const tailTokens = this.options.tailTokensFor(session, plan.endSeq)
|
|
184
|
+
// T3.11: a conservative gate (net-negative streak) tightens the rewrite
|
|
185
|
+
// guard to ≥5x — cuts must clearly pay for the tail they invalidate.
|
|
186
|
+
const feedback = this.options.feedback?.() ?? { conservative: false, reason: 'ok' }
|
|
187
|
+
const guardRatio = feedback.conservative
|
|
188
|
+
? Math.max(settings.rewriteGuardRatio, 5)
|
|
189
|
+
: settings.rewriteGuardRatio
|
|
190
|
+
if (!passesRewriteGuard(draft, tailTokens, guardRatio)) {
|
|
191
|
+
this.options.onSkip?.(sessionId, feedback.conservative ? `rewrite-guard-conservative:${feedback.reason}` : 'rewrite-guard')
|
|
192
|
+
return { committed: false, reason: 'rewrite-guard' }
|
|
193
|
+
}
|
|
194
|
+
const result = publishSettledCard(session as never, draft, {
|
|
195
|
+
startSeq: plan.startSeq,
|
|
196
|
+
endSeq: plan.endSeq,
|
|
197
|
+
shadowedSeqs: plan.blocks.map(block => block.seq),
|
|
198
|
+
})
|
|
199
|
+
if (result.ok) {
|
|
200
|
+
this.options.onLanded?.(sessionId, draft.sourceTokens - draft.retainedTokens, draft.narrativeTier, result)
|
|
201
|
+
} else {
|
|
202
|
+
this.options.onSkip?.(sessionId, result.reason)
|
|
203
|
+
}
|
|
204
|
+
return { committed: result.ok, reason: result.reason }
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Re-exported for the wiring site's tail estimate fallback (kept single-sourced). */
|
|
209
|
+
export { estimateTokens }
|