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.
Files changed (85) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/CHANGELOG.zh.md +9 -0
  3. package/README.de.md +1 -1
  4. package/assets/dshfind-card.svg +33 -0
  5. package/docs/shallow-teaching-preset-template.md +46 -0
  6. package/package.json +6 -6
  7. package/packages/selector/dsh.plugin.json +2 -2
  8. package/packages/selector/lib/client.d.ts +8 -0
  9. package/packages/selector/lib/client.js +212 -3
  10. package/packages/selector/lib/index.js +1 -1
  11. package/packages/selector/lib/profiles.d.ts +34 -0
  12. package/packages/selector/lib/pruner.d.ts +55 -0
  13. package/packages/selector/lib/pruner.js +1925 -303
  14. package/packages/selector/lib/savings-integral.js +126 -3
  15. package/packages/selector/lib/tool-result.js +9 -1
  16. package/packages/selector/package.json +21 -21
  17. package/packages/selector/src/client/CompressionProfileControls.tsx +33 -0
  18. package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
  19. package/packages/selector/src/client/decode.ts +5 -1
  20. package/packages/selector/src/client/index.ts +4 -0
  21. package/packages/selector/src/client/locales/de.ts +7 -0
  22. package/packages/selector/src/client/locales/es.ts +7 -0
  23. package/packages/selector/src/client/locales/fr.ts +7 -0
  24. package/packages/selector/src/client/locales/it.ts +7 -0
  25. package/packages/selector/src/client/locales/ja.ts +7 -0
  26. package/packages/selector/src/client/locales/ko.ts +7 -0
  27. package/packages/selector/src/client/locales/ru.ts +7 -0
  28. package/packages/selector/src/client/locales.ts +14 -0
  29. package/packages/selector/src/client/monitor-fab.ts +14 -0
  30. package/packages/selector/src/client/settings-section.tsx +9 -2
  31. package/packages/selector/src/profiles.ts +103 -0
  32. package/packages/selector/src/pruner.ts +310 -4
  33. package/packages/selector/src/runtime/audit.ts +1 -0
  34. package/packages/selector/src/runtime/config.ts +88 -1
  35. package/packages/selector/src/runtime/fold-router.ts +143 -0
  36. package/packages/selector/src/runtime/monitor.ts +31 -0
  37. package/packages/selector/src/runtime/reducers.ts +1 -1
  38. package/packages/selector/src/runtime/sediment-card.ts +126 -0
  39. package/packages/selector/src/runtime/sediment-clock.ts +87 -0
  40. package/packages/selector/src/runtime/sediment-guard.ts +136 -0
  41. package/packages/selector/src/runtime/sediment-publish.ts +144 -0
  42. package/packages/selector/src/runtime/sediment-span.ts +170 -0
  43. package/packages/selector/src/runtime/sediment.ts +209 -0
  44. package/packages/selector/src/runtime/shallow-tools.ts +342 -0
  45. package/packages/selector/src/runtime/tool-names.ts +6 -0
  46. package/packages/selector/src/runtime/triage/masks.ts +128 -0
  47. package/packages/selector/src/runtime/triage/shallow.ts +132 -0
  48. package/packages/selector/src/runtime/triage/signals.ts +167 -0
  49. package/packages/selector/src/runtime/triage/types.ts +125 -0
  50. package/packages/selector/src/runtime/types.ts +28 -0
  51. package/packages/selector/tests/fixtures/sediment-pool/52adc205-cloud-5.orig.txt +231 -0
  52. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-25.orig.txt +236 -0
  53. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-38.orig.txt +220 -0
  54. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-42.orig.txt +140 -0
  55. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-53.orig.txt +117 -0
  56. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-local-10.orig.txt +67 -0
  57. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-45.orig.txt +119 -0
  58. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-49.orig.txt +119 -0
  59. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-63.orig.txt +131 -0
  60. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-75.orig.txt +196 -0
  61. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-76.orig.txt +71 -0
  62. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-85.orig.txt +126 -0
  63. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-86.orig.txt +86 -0
  64. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-87.orig.txt +50 -0
  65. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-96.orig.txt +102 -0
  66. package/packages/selector/tests/public/package-contract.client.spec.ts +7 -4
  67. package/packages/selector/tests/runtime/fold-router.spec.ts +140 -0
  68. package/packages/selector/tests/runtime/sediment-card.spec.ts +111 -0
  69. package/packages/selector/tests/runtime/sediment-config.spec.ts +56 -0
  70. package/packages/selector/tests/runtime/sediment-guard.spec.ts +71 -0
  71. package/packages/selector/tests/runtime/sediment-masks.spec.ts +95 -0
  72. package/packages/selector/tests/runtime/sediment-orchestrator.spec.ts +166 -0
  73. package/packages/selector/tests/runtime/sediment-pool-share.spec.ts +65 -0
  74. package/packages/selector/tests/runtime/sediment-publish.spec.ts +142 -0
  75. package/packages/selector/tests/runtime/sediment-real-shapes.spec.ts +158 -0
  76. package/packages/selector/tests/runtime/sediment-settings.spec.ts +73 -0
  77. package/packages/selector/tests/runtime/sediment-signals.spec.ts +124 -0
  78. package/packages/selector/tests/runtime/sediment-span.spec.ts +92 -0
  79. package/packages/selector/tests/runtime/shallow-primitives.spec.ts +135 -0
  80. package/packages/selector/tests/settings-seat.client.spec.ts +1 -1
  81. package/scripts/hosts.d.mts +3 -0
  82. package/scripts/hosts.mjs +3 -1
  83. package/scripts/sediment-latency-report.mjs +63 -0
  84. package/scripts/verify-release.mjs +7 -2
  85. package/$null +0 -1
@@ -0,0 +1,166 @@
1
+ /**
2
+ * T3.6 red tests: orchestrator pipeline and the disabled short-circuit.
3
+ * The M1 guarantee is asserted structurally: with `enabled=false` the
4
+ * event reader is NEVER invoked — no accumulation, no card, no append.
5
+ */
6
+ import { describe, expect, it } from 'vitest'
7
+ import { SedimentOrchestrator, type OrchestratorOptions, type SedimentSession } from '../../src/runtime/sediment.ts'
8
+ import { DEFAULT_SEDIMENT_SETTINGS } from '../../src/runtime/config.ts'
9
+ import type { SedimentSettings } from '../../src/runtime/types.ts'
10
+
11
+ interface Recorded extends SedimentSession {
12
+ appends: Array<{ type: string; data: unknown; options?: unknown }>
13
+ }
14
+
15
+ function recordedSession(): Recorded {
16
+ const session: Recorded = {
17
+ id: 's1',
18
+ appends: [],
19
+ append(type: never, data: never, options?: never): { seq: number } {
20
+ session.appends.push({ type, data, options })
21
+ return { seq: session.appends.length + 100 }
22
+ },
23
+ }
24
+ return session
25
+ }
26
+
27
+ const bigRead = `import fs from "node:fs"\n${' const x = compute(i)\n'.repeat(300)}`
28
+
29
+ function turnEvents(completed = true): OrchestratorOptions['eventsFor'] {
30
+ return () => [
31
+ { seq: 1, type: 'user/message', data: { content: [{ type: 'text', text: 'do it' }] } },
32
+ { seq: 2, type: 'assistant/message', data: { message: { content: [{ type: 'tool-call', id: 'c1' }] } } },
33
+ { seq: 3, type: 'tool/result', data: { message: { toolCallId: 'c1', content: [{ type: 'text', text: bigRead }] } } },
34
+ { seq: 4, type: 'assistant/message', data: { message: { content: [{ type: 'tool-call', id: 'c2' }] } } },
35
+ { seq: 5, type: 'tool/result', data: { message: { toolCallId: 'c2', content: [{ type: 'text', text: 'Error: TS2345 failed\n[exit code: 2]' }] } } },
36
+ { seq: 6, type: 'assistant/message', data: { message: { content: [{ type: 'tool-call', id: 'c3' }] } } },
37
+ { seq: 7, type: 'tool/result', data: { message: { toolCallId: 'c3', content: [{ type: 'text', text: 'fixed now' }] } } },
38
+ { seq: 8, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: `收尾:读过大文件并修复 TS2345,构建现在通过。${'总结。'.repeat(40)}` }] } } },
39
+ { seq: 9, type: 'turn/end', data: { reason: { kind: completed ? 'completed' : 'interrupted' } } },
40
+ ]
41
+ }
42
+
43
+ function harnessOptions(
44
+ settings: SedimentSettings | undefined,
45
+ tailTokens = 10,
46
+ eventsFor = turnEvents(),
47
+ counters?: { events: () => void },
48
+ ): OrchestratorOptions {
49
+ return {
50
+ settingsFor: () => settings,
51
+ eventsFor: (s, turn) => {
52
+ counters?.events()
53
+ return eventsFor(s, turn)
54
+ },
55
+ callInfoFor: () => callId => callId === 'c1'
56
+ ? { name: 'read', argsJson: JSON.stringify({ file_path: 'src/big.ts' }) }
57
+ : callId === 'c2' || callId === 'c3'
58
+ ? { name: 'pwsh', argsJson: '{"command":"tsc"}' }
59
+ : undefined,
60
+ tailTokensFor: () => tailTokens,
61
+ }
62
+ }
63
+
64
+ function harness(settings: SedimentSettings | undefined, tailTokens = 10, eventsFor = turnEvents()) {
65
+ const session = recordedSession()
66
+ let eventsCalled = 0
67
+ const orchestrator = new SedimentOrchestrator(harnessOptions(settings, tailTokens, eventsFor, { events: () => { eventsCalled += 1 } }))
68
+ const context = {
69
+ lastEventType: 'turn/end',
70
+ inFlightRequest: false,
71
+ compactionOpen: false,
72
+ officialCheckpointSeq: undefined,
73
+ resumeFirstBatch: false,
74
+ }
75
+ return { session, orchestrator, context, eventsCalled: () => eventsCalled }
76
+ }
77
+
78
+ const ON: SedimentSettings = { ...DEFAULT_SEDIMENT_SETTINGS, enabled: true, minClosingTokens: 40 }
79
+
80
+ describe('SedimentOrchestrator (T3.6)', () => {
81
+ it('disabled settings short-circuit BEFORE touching events (M1 structural)', async () => {
82
+ const { session, orchestrator, context, eventsCalled } = harness({ ...DEFAULT_SEDIMENT_SETTINGS })
83
+ const outcome = await orchestrator.handleTurnEnd(session, 1, context)
84
+ expect(outcome).toEqual({ committed: false, reason: 'disabled' })
85
+ expect(eventsCalled()).toBe(0)
86
+ expect(session.appends).toHaveLength(0)
87
+ })
88
+
89
+ it('undefined settings (session not yet snapped) behaves like disabled', async () => {
90
+ const { orchestrator, context, eventsCalled, session } = harness(undefined)
91
+ expect((await orchestrator.handleTurnEnd(session, 1, context)).reason).toBe('disabled')
92
+ expect(eventsCalled()).toBe(0)
93
+ })
94
+
95
+ it('enabled completed turn lands manifest + replacement', async () => {
96
+ const { session, orchestrator, context } = harness(ON)
97
+ const outcome = await orchestrator.handleTurnEnd(session, 1, context)
98
+ expect(outcome.committed).toBe(true)
99
+ expect(session.appends.map(entry => entry.type)).toEqual(['compaction/prune', 'user/message'])
100
+ const second = session.appends[1]
101
+ if (second === undefined) throw new Error('missing replacement append')
102
+ const options = second.options as { surfaceOp: { op: string; startSeq: number; endSeq: number } }
103
+ expect(options.surfaceOp.op).toBe('replace')
104
+ expect(options.surfaceOp.startSeq).toBe(2)
105
+ // tail round (6,7) kept: span ends at seq 5
106
+ expect(options.surfaceOp.endSeq).toBe(5)
107
+ })
108
+
109
+ it('reason gate: interrupted turns never publish', async () => {
110
+ const { session, orchestrator, context } = harness(ON, 10, turnEvents(false))
111
+ const outcome = await orchestrator.handleTurnEnd(session, 1, context)
112
+ expect(outcome).toEqual({ committed: false, reason: 'reason-gate' })
113
+ expect(session.appends).toHaveLength(0)
114
+ })
115
+
116
+ it('rewrite guard: a fat cached tail refuses the cut (1:15 defense)', async () => {
117
+ const { session, orchestrator, context } = harness(ON, 500_000)
118
+ const outcome = await orchestrator.handleTurnEnd(session, 1, context)
119
+ expect(outcome).toEqual({ committed: false, reason: 'rewrite-guard' })
120
+ expect(session.appends).toHaveLength(0)
121
+ })
122
+
123
+ it('official checkpoint yield: skip once, consume, proceed next seam', async () => {
124
+ const { session, orchestrator, context } = harness(ON)
125
+ const first = await orchestrator.handleTurnEnd(session, 1, { ...context, officialCheckpointSeq: 60 })
126
+ expect(first.committed).toBe(false)
127
+ expect(first.reason).toContain('yield-official-checkpoint-60')
128
+ const second = await orchestrator.handleTurnEnd(session, 2, { ...context, officialCheckpointSeq: 60 })
129
+ expect(second.committed).toBe(true)
130
+ })
131
+
132
+ it('narrative tier 2 (T4.5): failing closing with a live fold channel lands the fold text', async () => {
133
+ const session = recordedSession()
134
+ // short closing (below minClosingTokens=40) + fold channel that answers
135
+ const foldCalls: Array<{ prompt: unknown }> = []
136
+ const shortClosing: OrchestratorOptions['eventsFor'] = () => [
137
+ { seq: 1, type: 'user/message', data: { content: [{ type: 'text', text: 'go' }] } },
138
+ { seq: 2, type: 'assistant/message', data: { message: { content: [{ type: 'tool-call', id: 'c1' }] } } },
139
+ { seq: 3, type: 'tool/result', data: { message: { toolCallId: 'c1', content: [{ type: 'text', text: bigRead }] } } },
140
+ { seq: 4, type: 'assistant/message', data: { message: { content: [{ type: 'tool-call', id: 'c2' }] } } },
141
+ { seq: 5, type: 'tool/result', data: { message: { toolCallId: 'c2', content: [{ type: 'text', text: 'Error: TS2345 failed\n[exit code: 2]' }] } } },
142
+ { seq: 6, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: 'narrative residue for folding: refactored the loader boundary first' }] } } },
143
+ { seq: 7, type: 'assistant/message', data: { message: { content: [{ type: 'tool-call', id: 'c3' }] } } },
144
+ { seq: 8, type: 'tool/result', data: { message: { toolCallId: 'c3', content: [{ type: 'text', text: 'fixed' }] } } },
145
+ { seq: 9, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: 'done' }] } } },
146
+ { seq: 10, type: 'turn/end', data: { reason: { kind: 'completed' } } },
147
+ ]
148
+ const orchestrator = new SedimentOrchestrator({
149
+ ...harnessOptions(ON, 10, shortClosing),
150
+ fold: {
151
+ run: async (_sid, prompt) => {
152
+ foldCalls.push({ prompt })
153
+ return '- folded: loader refactor, TS2345 fixed'
154
+ },
155
+ },
156
+ })
157
+ const outcome = await orchestrator.handleTurnEnd(session, 1, {
158
+ lastEventType: 'turn/end', inFlightRequest: false, compactionOpen: false,
159
+ officialCheckpointSeq: undefined, resumeFirstBatch: false,
160
+ })
161
+ expect(outcome.committed).toBe(true)
162
+ expect(foldCalls).toHaveLength(1)
163
+ const stub = session.appends[1]?.data as { content?: Array<{ text?: string }> }
164
+ expect(JSON.stringify(stub)).toContain('folded: loader refactor')
165
+ })
166
+ })
@@ -0,0 +1,65 @@
1
+ /**
2
+ * T1.6 pool-share guard: over a sampled fixture corpus copied from the real
3
+ * replay cuts (trial-3 source data), the verbatim pool must stay a tiny
4
+ * fraction of total bytes — the "0.4% of tokens buys 100% error recall"
5
+ * property. Sampled subset uses a generous 2% ceiling; the full-corpus 0.5%
6
+ * gate lives in the S5 script run at Phase 5.
7
+ */
8
+ import { readFileSync, readdirSync } from 'node:fs'
9
+ import { fileURLToPath } from 'node:url'
10
+ import { describe, expect, it } from 'vitest'
11
+ import { linePool } from '../../src/runtime/triage/signals.ts'
12
+ import type { TriageRole } from '../../src/runtime/triage/types.ts'
13
+
14
+ const FIXTURE_DIR = fileURLToPath(new URL('../fixtures/sediment-pool', import.meta.url))
15
+
16
+ /** Split a cut fixture into `[role] body` segments (replay dump format). */
17
+ function segments(text: string): Array<{ role: TriageRole; body: string }> {
18
+ return text.split('\n===\n').map(chunk => {
19
+ const match = /^\[(\w+)\] ([\s\S]*)$/.exec(chunk)
20
+ if (match === null) return { role: 'tool' as const, body: chunk }
21
+ const role = match[1]
22
+ return {
23
+ role: role === 'user' || role === 'assistant' || role === 'tool' ? role : 'tool',
24
+ body: match[2] ?? '',
25
+ }
26
+ })
27
+ }
28
+
29
+ describe('pool share over real-cut fixtures (T1.6)', () => {
30
+ const files = readdirSync(FIXTURE_DIR).filter(name => name.endsWith('.orig.txt'))
31
+
32
+ it('fixture corpus is present and non-trivial', () => {
33
+ expect(files.length).toBeGreaterThanOrEqual(10)
34
+ })
35
+
36
+ it('verbatim pool stays under 2% of corpus bytes (sampled ceiling; S5 guards 0.5% full)', () => {
37
+ let totalChars = 0
38
+ let poolChars = 0
39
+ let poolLines = 0
40
+ for (const name of files) {
41
+ const raw = readFileSync(`${FIXTURE_DIR}/${name}`, 'utf8')
42
+ for (const [index, seg] of segments(raw).entries()) {
43
+ totalChars += seg.body.length
44
+ const pool = linePool(seg.body, { seq: index, role: seg.role, hardFailure: false })
45
+ poolLines += pool.length
46
+ poolChars += pool.reduce((sum, line) => sum + line.text.length, 0)
47
+ }
48
+ }
49
+ // Every pool line must be a substring of its source segment (copy, never paraphrase).
50
+ expect(poolChars / Math.max(1, totalChars)).toBeLessThanOrEqual(0.02)
51
+ expect(poolLines).toBeGreaterThan(0) // corpus does contain failure signals
52
+ })
53
+
54
+ it('every pooled line is verbatim-contained in its source segment', () => {
55
+ for (const name of files) {
56
+ const raw = readFileSync(`${FIXTURE_DIR}/${name}`, 'utf8')
57
+ for (const [index, seg] of segments(raw).entries()) {
58
+ for (const line of linePool(seg.body, { seq: index, role: seg.role, hardFailure: false })) {
59
+ const body = line.text.replace(/ …$/, '')
60
+ expect(seg.body.includes(body)).toBe(true)
61
+ }
62
+ }
63
+ }
64
+ })
65
+ })
@@ -0,0 +1,142 @@
1
+ /**
2
+ * T3.4/T3.5 red tests: commit clock and publication transaction
3
+ * (plan cci-sedimentation-triage Phase 3).
4
+ */
5
+ import { describe, expect, it } from 'vitest'
6
+ import { SedimentClock, canCommitNow } from '../../src/runtime/sediment-clock.ts'
7
+ import { passesRewriteGuard, projectSurfaceEvent, publishSettledCard, type PublishTarget } from '../../src/runtime/sediment-publish.ts'
8
+ import type { TurnCardDraft } from '../../src/runtime/triage/types.ts'
9
+
10
+ function draft(retained: number, source: number): TurnCardDraft {
11
+ return {
12
+ head: 'h',
13
+ pool: [],
14
+ masks: [],
15
+ omissionStats: 's',
16
+ narrativeTier: 'closing',
17
+ retainedTokens: retained,
18
+ sourceTokens: source,
19
+ }
20
+ }
21
+
22
+ describe('canCommitNow (T3.4 predicate)', () => {
23
+ const open = {
24
+ lastEventType: 'turn/end',
25
+ inFlightRequest: false,
26
+ compactionOpen: false,
27
+ officialCheckpointSeq: undefined,
28
+ seenOfficialCheckpointSeq: undefined,
29
+ resumeFirstBatch: false,
30
+ }
31
+
32
+ it('passes in a clean quiet seam', () => {
33
+ expect(canCommitNow(open)).toEqual({ ok: true, reason: 'quiet-seam' })
34
+ })
35
+ it('blocks outside the seam, in-flight, compaction, resume', () => {
36
+ expect(canCommitNow({ ...open, lastEventType: 'step/start', }).reason).toBe('not-in-quiet-seam')
37
+ expect(canCommitNow({ ...open, inFlightRequest: true }).reason).toBe('request-in-flight')
38
+ expect(canCommitNow({ ...open, compactionOpen: true }).reason).toBe('compaction-in-progress')
39
+ expect(canCommitNow({ ...open, resumeFirstBatch: true }).reason).toBe('resume-first-batch')
40
+ })
41
+ it('yields exactly once to a fresh official checkpoint (seen-seq cooldown)', () => {
42
+ const withOfficial = { ...open, officialCheckpointSeq: 55 }
43
+ expect(canCommitNow(withOfficial).reason).toBe('yield-official-checkpoint-55')
44
+ expect(canCommitNow({ ...withOfficial, seenOfficialCheckpointSeq: 55 }).ok).toBe(true)
45
+ })
46
+
47
+ it('SedimentClock: re-entrance guard and one-time consumption', () => {
48
+ const clock = new SedimentClock()
49
+ expect(clock.begin()).toBe(true)
50
+ expect(clock.begin()).toBe(false) // M11 single queue
51
+ clock.end()
52
+ expect(clock.begin()).toBe(true)
53
+ clock.end()
54
+ const base = { lastEventType: 'turn/end', inFlightRequest: false, compactionOpen: false, officialCheckpointSeq: 77, resumeFirstBatch: false }
55
+ expect(clock.decide(base).reason).toBe('yield-official-checkpoint-77')
56
+ clock.noteOfficialConsumed(77)
57
+ expect(clock.decide(base).ok).toBe(true)
58
+ // A newer checkpoint re-arms the yield.
59
+ expect(clock.decide({ ...base, officialCheckpointSeq: 88 }).ok).toBe(false)
60
+ })
61
+ })
62
+
63
+ interface RecordingSession extends PublishTarget {
64
+ calls: Array<{ type: string; data: unknown; options?: unknown }>
65
+ }
66
+
67
+ function recordingSession(failSecond = false): RecordingSession {
68
+ const session: RecordingSession = {
69
+ calls: [],
70
+ append(type: 'compaction/prune' | 'user/message', data: unknown, options?: unknown): { seq: number } {
71
+ if (failSecond && type === 'user/message') throw new Error('disk locked')
72
+ session.calls.push({ type, data, options })
73
+ return { seq: session.calls.length + 10 }
74
+ },
75
+ }
76
+ return session
77
+ }
78
+
79
+ describe('publishSettledCard (T3.5 transaction)', () => {
80
+ it('shortening proof runs BEFORE any append — a non-shrinking card writes nothing (M7)', () => {
81
+ const session = recordingSession()
82
+ const result = publishSettledCard(session, draft(5_000, 4_000), { startSeq: 2, endSeq: 9, shadowedSeqs: [2, 3, 9] })
83
+ expect(result.ok).toBe(false)
84
+ expect(result.reason).toContain('shortening-proof-failed')
85
+ expect(session.calls).toHaveLength(0)
86
+ })
87
+
88
+ it('lands manifest then replacement with replace surfaceOp and source seqs', () => {
89
+ const session = recordingSession()
90
+ const result = publishSettledCard(session, draft(1_000, 4_000), { startSeq: 2, endSeq: 9, shadowedSeqs: [2, 3, 9] })
91
+ expect(result.ok).toBe(true)
92
+ expect(session.calls.map(call => call.type)).toEqual(['compaction/prune', 'user/message'])
93
+ const second = session.calls[1]
94
+ if (second === undefined) throw new Error('missing replacement call')
95
+ const options = second.options as { surfaceOp?: unknown, sourceEventSeqs?: unknown }
96
+ expect(options.surfaceOp).toEqual({ op: 'replace', startSeq: 2, endSeq: 9 })
97
+ expect(options.sourceEventSeqs).toEqual([11, 2, 3, 9])
98
+ const first = session.calls[0]
99
+ if (first === undefined) throw new Error('missing manifest call')
100
+ const manifest = first.data as Record<string, unknown>
101
+ expect(manifest.shadowedTokenCount).toBe(4_000)
102
+ })
103
+
104
+ it('replacement failure surfaces as a reason with the manifest seq, never throws', () => {
105
+ const session = recordingSession(true)
106
+ const result = publishSettledCard(session, draft(1_000, 4_000), { startSeq: 2, endSeq: 9, shadowedSeqs: [2] })
107
+ expect(result.ok).toBe(false)
108
+ expect(result.reason).toContain('publication-failed')
109
+ expect(result.manifestSeq).toBeDefined()
110
+ })
111
+
112
+ it('empty span refuses', () => {
113
+ const session = recordingSession()
114
+ expect(publishSettledCard(session, draft(10, 100), { startSeq: 1, endSeq: 1, shadowedSeqs: [] }).reason).toBe('empty-span')
115
+ })
116
+ })
117
+
118
+ describe('passesRewriteGuard (community 1:15 defense)', () => {
119
+ it('rejects a cut whose saving drowns in tail rewrite', () => {
120
+ // saving 5k vs tail rewrite 30k × ratio 3 → refuse (the 1:15 shape)
121
+ expect(passesRewriteGuard(draft(5_000, 10_000), 30_000, 3)).toBe(false)
122
+ // saving 5k vs tail 1k × ratio 3 → pass
123
+ expect(passesRewriteGuard(draft(5_000, 10_000), 1_000, 3)).toBe(true)
124
+ // zero saving never passes
125
+ expect(passesRewriteGuard(draft(10_000, 10_000), 0, 1)).toBe(false)
126
+ })
127
+ })
128
+
129
+ describe('projectSurfaceEvent', () => {
130
+ it('maps the four event shapes and drops the rest', () => {
131
+ const assistant = projectSurfaceEvent(5, {
132
+ type: 'assistant/message',
133
+ data: { message: { content: [{ type: 'text', text: 'running' }, { type: 'tool-call', id: 'c1' }, { type: 'tool-call', id: 'c2' }] } },
134
+ }, undefined)
135
+ expect(assistant).toMatchObject({ seq: 5, type: 'assistant/message', toolCalls: 2, text: 'running' })
136
+ const result = projectSurfaceEvent(6, { type: 'tool/result', data: { message: { content: [{ type: 'text', text: 'out' }], isError: true } } }, { name: 'pwsh', argsJson: '{}' })
137
+ expect(result).toMatchObject({ type: 'tool/result', toolName: 'pwsh', isError: true })
138
+ const end = projectSurfaceEvent(7, { type: 'turn/end', data: { reason: { kind: 'completed' } } }, undefined)
139
+ expect(end).toMatchObject({ type: 'turn/end', reasonKind: 'completed' })
140
+ expect(projectSurfaceEvent(8, { type: 'workspace/changes', data: {} }, undefined)).toBeNull()
141
+ })
142
+ })
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Real-host event-shape landing guard (T3.8 evidence, plan cci-sedimentation-triage).
3
+ *
4
+ * The unit harness in sediment-orchestrator.spec.ts uses a minimal event shape.
5
+ * This spec pins landing against the EXACT durable envelope captured from a real
6
+ * `dsh --profile headless` LAN-Qwen session (verified field set: tool/result rides
7
+ * `data.{turn,step,message,meta}` with `message.content[]` + `message.toolCallId` +
8
+ * `message.isError`; the turn closes with `data.reason.kind === 'completed'`).
9
+ * It is the contract proof that the looseData/looseContent accessors and the span
10
+ * planner consume genuine host events, so a real-machine run only has to flip the
11
+ * settings gate — no shape surprises.
12
+ */
13
+ import { describe, expect, it } from 'vitest'
14
+ import { SedimentOrchestrator, type OrchestratorOptions, type SedimentSession } from '../../src/runtime/sediment.ts'
15
+ import { DEFAULT_SEDIMENT_SETTINGS } from '../../src/runtime/config.ts'
16
+ import type { SedimentSettings } from '../../src/runtime/types.ts'
17
+
18
+ interface Recorded extends SedimentSession {
19
+ appends: Array<{ type: string; data: unknown; options?: unknown }>
20
+ }
21
+
22
+ function recordedSession(): Recorded {
23
+ const session: Recorded = {
24
+ id: 'real-shapes',
25
+ appends: [],
26
+ append(type: never, data: never, options?: never): { seq: number } {
27
+ session.appends.push({ type, data, options })
28
+ return { seq: session.appends.length + 100 }
29
+ },
30
+ }
31
+ return session
32
+ }
33
+
34
+ // A read large enough to clear the mask threshold so the whole tool round is
35
+ // shadow-able (real durable reads run 25-60K chars; a few hundred lines suffices).
36
+ const largeRead = Array.from(
37
+ { length: 400 },
38
+ (_, i) => `${i + 1} const settled = commit(i) // sediment span probe line ${i + 1}`,
39
+ ).join('\n')
40
+
41
+ const CALL1 = 'call_1206d7a550f54ec1bfbd5701'
42
+ const CALL2 = 'call_e6ecf1b89a3d436284c1399a'
43
+
44
+ /** Events cloned from the observed real envelope — same nesting, same field names. */
45
+ function realShapedEvents(): OrchestratorOptions['eventsFor'] {
46
+ return () => [
47
+ {
48
+ seq: 12,
49
+ type: 'user/message',
50
+ data: {
51
+ turn: 1,
52
+ step: 1,
53
+ message: { role: 'user', content: [{ type: 'text', text: 'do exactly two sequential tool calls then answer' }], id: 'u1' },
54
+ },
55
+ },
56
+ {
57
+ seq: 16,
58
+ type: 'assistant/message',
59
+ data: {
60
+ turn: 1,
61
+ step: 2,
62
+ message: {
63
+ role: 'assistant',
64
+ content: [{ type: 'tool-call', id: CALL1, name: 'read', arguments: JSON.stringify({ file_path: 'src/big.ts', offset: 1, limit: 1000 }) }],
65
+ id: 'a1',
66
+ },
67
+ },
68
+ },
69
+ {
70
+ seq: 18,
71
+ type: 'tool/result',
72
+ data: {
73
+ turn: 1,
74
+ step: 2,
75
+ message: { role: 'tool', source: { kind: 'tool-result' }, toolCallId: CALL1, content: [{ type: 'text', text: largeRead }], isError: false, id: 'r1' },
76
+ meta: { duration: 12 },
77
+ },
78
+ },
79
+ {
80
+ seq: 22,
81
+ type: 'assistant/message',
82
+ data: {
83
+ turn: 1,
84
+ step: 3,
85
+ message: {
86
+ role: 'assistant',
87
+ content: [{ type: 'tool-call', id: CALL2, name: 'read', arguments: JSON.stringify({ file_path: 'src/big.ts', offset: 1001, limit: 5 }) }],
88
+ id: 'a2',
89
+ },
90
+ },
91
+ },
92
+ {
93
+ seq: 23,
94
+ type: 'tool/result',
95
+ data: {
96
+ turn: 1,
97
+ step: 3,
98
+ message: { role: 'tool', source: { kind: 'tool-result' }, toolCallId: CALL2, content: [{ type: 'text', text: '1001 tail line one\n1002 tail line two' }], isError: false, id: 'r2' },
99
+ meta: { duration: 3 },
100
+ },
101
+ },
102
+ {
103
+ seq: 26,
104
+ type: 'assistant/message',
105
+ data: {
106
+ turn: 1,
107
+ step: 4,
108
+ message: { role: 'assistant', content: [{ type: 'text', text: `收尾:两次顺序读取完成,第一块大块内容已沉降,尾部只保留了最后五行的验证行。${'结论。'.repeat(30)}` }], id: 'a3' },
109
+ },
110
+ },
111
+ { seq: 28, type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } },
112
+ ]
113
+ }
114
+
115
+ function harness(settings: SedimentSettings): { session: Recorded; orchestrator: SedimentOrchestrator } {
116
+ const session = recordedSession()
117
+ const options: OrchestratorOptions = {
118
+ settingsFor: () => settings,
119
+ eventsFor: realShapedEvents(),
120
+ callInfoFor: () => (callId: string | undefined) => {
121
+ if (callId === CALL1) return { name: 'read', argsJson: JSON.stringify({ file_path: 'src/big.ts', offset: 1, limit: 1000 }) }
122
+ if (callId === CALL2) return { name: 'read', argsJson: JSON.stringify({ file_path: 'src/big.ts', offset: 1001, limit: 5 }) }
123
+ return undefined
124
+ },
125
+ // The tail after the cut (tiny second read + closing) stays small in tokens,
126
+ // mirroring the big-then-small real session that motivated this fixture.
127
+ tailTokensFor: () => 60,
128
+ }
129
+ return { session, orchestrator: new SedimentOrchestrator(options) }
130
+ }
131
+
132
+ const ON: SedimentSettings = { ...DEFAULT_SEDIMENT_SETTINGS, enabled: true, minClosingTokens: 40 }
133
+
134
+ describe('SedimentOrchestrator real-host event shapes (T3.8)', () => {
135
+ it('lands manifest + replace over the captured durable envelope', async () => {
136
+ const { session, orchestrator } = harness(ON)
137
+ const outcome = await orchestrator.handleTurnEnd(session, 1, {
138
+ lastEventType: 'turn/end',
139
+ inFlightRequest: false,
140
+ compactionOpen: false,
141
+ officialCheckpointSeq: undefined,
142
+ resumeFirstBatch: false,
143
+ })
144
+ expect(outcome.committed).toBe(true)
145
+ const types = session.appends.map(entry => entry.type)
146
+ expect(types).toEqual(['compaction/prune', 'user/message'])
147
+ const manifest = session.appends[0]
148
+ const manifestData = manifest?.data as { shadowedSeqs: number[]; shadowedRange: { start: number; end: number } }
149
+ // The first big read round (16,18) must be shadowed; the tail round (22,23) kept.
150
+ expect(manifestData.shadowedSeqs).toContain(18)
151
+ expect(manifestData.shadowedSeqs).not.toContain(23)
152
+ expect(manifestData.shadowedRange.start).toBeLessThanOrEqual(16)
153
+ expect(manifestData.shadowedRange.end).toBeLessThan(22)
154
+ const replacement = session.appends[1]
155
+ const surfaceOp = (replacement?.options as { surfaceOp: { op: string } }).surfaceOp
156
+ expect(surfaceOp.op).toBe('replace')
157
+ })
158
+ })
@@ -0,0 +1,73 @@
1
+ /**
2
+ * T0.2/T0.3 red tests: the sediment settings section must decode with exactly
3
+ * the runtime schema's strictness — absent inherits off defaults, unknown keys
4
+ * or bad types invalidate the whole section, and an unparseable extra pattern
5
+ * is rejected rather than silently dropped.
6
+ */
7
+ import { describe, expect, it } from 'vitest'
8
+ import {
9
+ DEFAULT_SEDIMENT_SETTINGS,
10
+ decodeSedimentSettings,
11
+ } from '../../src/profiles.ts'
12
+
13
+ describe('decodeSedimentSettings (plan cci-sedimentation-triage T0.2/T0.3)', () => {
14
+ it('absent decodes to the off defaults', () => {
15
+ expect(decodeSedimentSettings(undefined)).toEqual(DEFAULT_SEDIMENT_SETTINGS)
16
+ expect(DEFAULT_SEDIMENT_SETTINGS.enabled).toBe(false)
17
+ expect(DEFAULT_SEDIMENT_SETTINGS.granularity).toBe('turn')
18
+ })
19
+
20
+ it('accepts a complete valid document and round-trips every field', () => {
21
+ const input = {
22
+ enabled: true,
23
+ granularity: 'span',
24
+ minClosingTokens: 200,
25
+ rewriteGuardRatio: 4,
26
+ maxTurnSpanTokens: 40_000,
27
+ extraSignalPatterns: ['TOOL_TIMEOUT', 'npm ERR!'],
28
+ }
29
+ expect(decodeSedimentSettings(input)).toEqual(input)
30
+ })
31
+
32
+ it('partial documents inherit per-field defaults', () => {
33
+ const decoded = decodeSedimentSettings({ enabled: true })
34
+ expect(decoded).toEqual({ ...DEFAULT_SEDIMENT_SETTINGS, enabled: true })
35
+ })
36
+
37
+ it('rejects unknown keys — never silently ignored', () => {
38
+ expect(decodeSedimentSettings({ enabled: true, keepRounds: 3 })).toBeUndefined()
39
+ })
40
+
41
+ it('rejects wrong types and out-of-range bounds', () => {
42
+ expect(decodeSedimentSettings({ enabled: 'yes' })).toBeUndefined()
43
+ expect(decodeSedimentSettings({ granularity: 'turnish' })).toBeUndefined()
44
+ expect(decodeSedimentSettings({ minClosingTokens: 0 })).toBeUndefined()
45
+ expect(decodeSedimentSettings({ minClosingTokens: 2001 })).toBeUndefined()
46
+ expect(decodeSedimentSettings({ rewriteGuardRatio: 0 })).toBeUndefined()
47
+ expect(decodeSedimentSettings({ rewriteGuardRatio: 11 })).toBeUndefined()
48
+ expect(decodeSedimentSettings({ maxTurnSpanTokens: 3_000 })).toBeUndefined()
49
+ expect(decodeSedimentSettings({ maxTurnSpanTokens: 1.5 })).toBeUndefined()
50
+ })
51
+
52
+ it('rejects non-plain records (arrays, class instances, null)', () => {
53
+ expect(decodeSedimentSettings(null)).toBeUndefined()
54
+ expect(decodeSedimentSettings([])).toBeUndefined()
55
+ expect(decodeSedimentSettings(new Date())).toBeUndefined()
56
+ })
57
+
58
+ it('extraSignalPatterns: invalid entries reject the whole section', () => {
59
+ expect(decodeSedimentSettings({ extraSignalPatterns: ['(unclosed'] })).toBeUndefined()
60
+ expect(decodeSedimentSettings({ extraSignalPatterns: [''] })).toBeUndefined()
61
+ expect(decodeSedimentSettings({ extraSignalPatterns: 'TOOL_TIMEOUT' })).toBeUndefined()
62
+ expect(decodeSedimentSettings({ extraSignalPatterns: ['x'.repeat(201)] })).toBeUndefined()
63
+ })
64
+
65
+ it('extraSignalPatterns is copied out, not aliased', () => {
66
+ const patterns = ['TOOL_TIMEOUT']
67
+ const decoded = decodeSedimentSettings({ extraSignalPatterns: patterns })
68
+ expect(decoded?.extraSignalPatterns).toEqual(patterns)
69
+ if (decoded?.extraSignalPatterns !== undefined) {
70
+ expect(decoded.extraSignalPatterns).not.toBe(patterns)
71
+ }
72
+ })
73
+ })