@lynn123411/dsh-matt-plus 0.0.0-stage → 0.13.7

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.
@@ -0,0 +1,193 @@
1
+ import { lstat, realpath } from 'node:fs/promises'
2
+ import { createRequire } from 'node:module'
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path'
4
+ import { pathToFileURL } from 'node:url'
5
+ import { parseArgs } from 'node:util'
6
+
7
+ const sessionIdPattern = /^(?:session-)?[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/
8
+ const taskIdPattern = /^task-[0-9]{1,8}$/
9
+ const taskStatuses = new Set(['pending', 'in_progress', 'completed', 'deleted'])
10
+ const turnFailures = new Set(['error', 'blocked', 'max-tokens', 'interrupted'])
11
+ const namedTools = new Set([
12
+ 'apply_patch', 'ask_user_question', 'bash', 'edit', 'glob', 'grep', 'job_output', 'pwsh',
13
+ 'read', 'read_image', 'run_code', 'send_message', 'session_event_read', 'session_event_search',
14
+ 'session_search', 'session_trace', 'skill', 'subagent', 'subagent_fork', 'team_task_update',
15
+ 'terminal_send', 'web_fetch', 'web_search', 'write',
16
+ ])
17
+ const usage = 'Usage: node session-index.mjs --project-dir PATH --workspace PATH [--compression zstd|none] ROOT_ID [DESCENDANT_ID ...]'
18
+
19
+ class IndexError extends Error {}
20
+
21
+ function assertHeader(header, workspace, id, parentId) {
22
+ if (header.id !== id || header.cwd !== workspace) throw new IndexError('header-scope-mismatch')
23
+ if (parentId && header.parentSession !== parentId) throw new IndexError('header-parent-mismatch')
24
+ }
25
+
26
+ async function readLog(backend, projectDir, workspace, compression, id, parentId) {
27
+ const dir = join(projectDir, id)
28
+ const path = join(dir, compression === 'zstd' ? 'session.v4.jsonl.zstd' : 'session.v4.jsonl')
29
+ if (!(await lstat(dir)).isDirectory() || !(await lstat(path)).isFile()) throw new IndexError('invalid-log-path')
30
+ const meta = await backend.stat(id)
31
+ if (meta?.formatStatus !== 'current' || meta.location?.path !== path) throw new IndexError('missing-or-unsupported-log')
32
+ assertHeader(meta.header, workspace, id, parentId)
33
+ const handle = await backend.open(id, 'read')
34
+ try {
35
+ assertHeader(handle.header, workspace, id, parentId)
36
+ const { events } = await handle.read()
37
+ return { header: handle.header, events, inheritedEventCount: handle.inheritedEventCount }
38
+ } finally {
39
+ await handle.close()
40
+ }
41
+ }
42
+
43
+ function shellExit(name, blocks) {
44
+ if (name !== 'bash' && name !== 'pwsh') return undefined
45
+ const lastText = blocks?.findLast(block => block.type === 'text')?.text
46
+ if (typeof lastText !== 'string') return undefined
47
+ const text = lastText.trimEnd()
48
+ const line = text.slice(text.lastIndexOf(String.fromCharCode(10)) + 1)
49
+ return Number(/^[[]exit code: (-?[0-9]{1,10})\]$/.exec(line)?.[1]) || undefined
50
+ }
51
+
52
+ export function indexLog(log, parentId, requested) {
53
+ const { header, events, inheritedEventCount } = log
54
+ const evidence = []
55
+ const children = []
56
+ const nativeTools = new Map()
57
+ const lastAssistant = new Map()
58
+ let directMessages = 0
59
+ for (const { seq, type, data } of events.slice(inheritedEventCount)) {
60
+ const add = (kind, fields = {}) => evidence.push({ seq, kind, ...fields })
61
+ const toolFailure = (reason, name, fields = {}) => add(reason, { tool: namedTools.has(name) ? name : 'other', ...fields })
62
+ switch (type) {
63
+ case 'subagent/catalog':
64
+ if (requested.has(data.childId)) {
65
+ children.push(data.childId)
66
+ add('child-dispatch', { childSessionId: data.childId })
67
+ }
68
+ break
69
+ case 'team/task': {
70
+ const { id, status } = data.task ?? {}
71
+ if (typeof id === 'string' && taskIdPattern.test(id) && taskStatuses.has(status)) add('team-task', { taskId: id, status })
72
+ break
73
+ }
74
+ case 'user/message': {
75
+ const { kind, senderSessionId } = data.source ?? {}
76
+ if (kind === 'user') add(directMessages++ === 0 ? 'initial-user-message' : 'user-message')
77
+ if (kind === 'agent-message' && senderSessionId && requested.has(senderSessionId)) {
78
+ add(senderSessionId === parentId ? 'parent-message' : 'agent-message', { senderSessionId })
79
+ }
80
+ if (kind === 'subagent-settled' && requested.has(senderSessionId)) add('child-settled', { senderSessionId })
81
+ break
82
+ }
83
+ case 'assistant/message': {
84
+ const content = data.message?.content ?? []
85
+ const standalone = content.some(block => block.type === 'text' && block.text?.trim())
86
+ && !content.some(block => block.type === 'tool-call')
87
+ lastAssistant.set(data.turn, standalone ? seq : undefined)
88
+ break
89
+ }
90
+ case 'turn/end': {
91
+ const finalSeq = lastAssistant.get(data.turn)
92
+ if (data.reason?.kind === 'completed' && finalSeq !== undefined) {
93
+ evidence.push({ seq: finalSeq, kind: 'final-report', endSeq: seq })
94
+ }
95
+ if (turnFailures.has(data.reason?.kind)) add('turn-failure', { reason: data.reason.kind })
96
+ lastAssistant.delete(data.turn)
97
+ break
98
+ }
99
+ case 'tool/call':
100
+ nativeTools.set(data.callId, data.name)
101
+ break
102
+ case 'tool/result': {
103
+ const name = nativeTools.get(data.message?.toolCallId)
104
+ const exitCode = shellExit(name, data.message?.content)
105
+ if (data.message?.isError) toolFailure('tool-error', name)
106
+ else if (exitCode) toolFailure('nonzero-exit', name, { exitCode })
107
+ if (name === 'send_message' && !data.message?.isError) add('outbound-agent-message')
108
+ break
109
+ }
110
+ case 'tool/ptc-dispatch': {
111
+ const exitCode = shellExit(data.name, data.content)
112
+ if (data.isError) toolFailure('tool-error', data.name)
113
+ else if (exitCode) toolFailure('nonzero-exit', data.name, { exitCode })
114
+ if (data.name === 'send_message' && !data.isError) add('outbound-agent-message')
115
+ break
116
+ }
117
+ case 'job/settled': {
118
+ const commandJob = data.kind === 'bash' || data.kind === 'pwsh'
119
+ const exitCode = commandJob && typeof data.detail === 'string'
120
+ ? Number(/^exit code: (-?[0-9]{1,10})(?:;|$)/.exec(data.detail)?.[1]) : 0
121
+ if (data.status === 'failed') add('job-failure')
122
+ else if (data.status === 'completed' && exitCode) add('job-nonzero-exit', { exitCode })
123
+ break
124
+ }
125
+ case 'llm/retry':
126
+ add('model-retry')
127
+ break
128
+ }
129
+ }
130
+ evidence.sort((a, b) => a.seq - b.seq)
131
+ return { id: header.id, parentId: parentId ?? null, inheritedEventCount, events: events.length,
132
+ lastSeq: events.at(-1)?.seq ?? null, children, evidence }
133
+ }
134
+
135
+ async function loadBackend(root, compression) {
136
+ if (!process.env.DSH_INSTALL_DIR) throw new IndexError('missing-dsh-install-dir')
137
+ const require = createRequire(join(process.env.DSH_INSTALL_DIR, 'package.json'))
138
+ const load = name => import(pathToFileURL(require.resolve(name)).href)
139
+ const { sessionFormatCatalog } = await load('@deepseek-ai/dsh-session-format-catalog')
140
+ if (sessionFormatCatalog.currentVersion !== 4) throw new IndexError('unsupported-installed-format')
141
+ const { Context } = await load('@deepseek-ai/cordis')
142
+ const { JsonlSessionPersistence } = await load('@deepseek-ai/dsh-session-persistence-jsonl')
143
+ return new JsonlSessionPersistence(new Context(), { root, compression })
144
+ }
145
+
146
+ async function main() {
147
+ const { values, positionals: ids } = parseArgs({
148
+ options: { 'project-dir': { type: 'string' }, workspace: { type: 'string' },
149
+ compression: { type: 'string', default: 'zstd' }, help: { type: 'boolean' } },
150
+ allowPositionals: true,
151
+ })
152
+ if (values.help) {
153
+ process.stdout.write(usage + String.fromCharCode(10))
154
+ return
155
+ }
156
+ if (!ids.length || !ids.every(id => sessionIdPattern.test(id)) || new Set(ids).size !== ids.length
157
+ || !values['project-dir'] || !isAbsolute(values['project-dir']) || !values.workspace || !isAbsolute(values.workspace)
158
+ || !['zstd', 'none'].includes(values.compression)) {
159
+ throw new IndexError('invalid-arguments')
160
+ }
161
+ const [rootSessionId] = ids
162
+ const requested = new Set(ids)
163
+ const pending = new Map([[rootSessionId, undefined]])
164
+ const sessions = []
165
+ const unavailable = []
166
+ const projectDir = await realpath(values['project-dir'])
167
+ const backend = await loadBackend(dirname(projectDir), values.compression)
168
+ for (const [id, parentId] of pending) {
169
+ try {
170
+ const log = await readLog(backend, projectDir, values.workspace, values.compression, id, parentId)
171
+ const { children, ...session } = indexLog(log, parentId, requested)
172
+ for (const child of children) if (!pending.has(child)) pending.set(child, id)
173
+ sessions.push(session)
174
+ } catch (error) {
175
+ unavailable.push({ id, reason: error instanceof IndexError ? error.message : 'unreadable-or-invalid-log' })
176
+ }
177
+ }
178
+ for (const id of requested) {
179
+ if (!pending.has(id)) unavailable.push({ id, reason: 'not-linked-by-indexed-parent' })
180
+ }
181
+ process.stdout.write(JSON.stringify({ schemaVersion: 1, rootSessionId, requestedSessions: ids.length, sessions, unavailable }, null, 2) + String.fromCharCode(10))
182
+ if (unavailable.length) process.exitCode = 1
183
+ }
184
+
185
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
186
+ main().catch(error => {
187
+ const reason = error instanceof IndexError ? error.message : 'invalid-arguments-or-unavailable-runtime'
188
+ process.stderr.write(`session-index: ${reason}
189
+ ${usage}
190
+ `)
191
+ process.exitCode = 2
192
+ })
193
+ }
@@ -0,0 +1,80 @@
1
+ import assert from 'node:assert/strict'
2
+ import { spawnSync } from 'node:child_process'
3
+ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
4
+ import { join, resolve } from 'node:path'
5
+ import { test } from 'node:test'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { indexLog } from './session-index.mjs'
8
+
9
+ const root = 'session-00000000-0000-4000-8000-000000000001'
10
+ const child = '00000000-0000-4000-8000-000000000002'
11
+ const unrelated = '00000000-0000-4000-8000-000000000003'
12
+ const canary = 'synthetic-secret-that-must-never-leave-the-log'
13
+ const text = value => ({ type: 'text', text: value })
14
+ const record = (type, data, seq) => ({ type, data, seq, time: 1 })
15
+
16
+ test('indexes only stable evidence and skips fork-inherited events', () => {
17
+ const events = [
18
+ record('user/message', { source: { kind: 'user' }, content: [text(canary)] }, 0),
19
+ record('user/message', { source: { kind: 'agent-message', senderSessionId: root }, content: [text(canary)] }, 1),
20
+ record('user/message', { source: { kind: 'agent-message', senderSessionId: unrelated }, content: [text(canary)] }, 2),
21
+ record('user/message', { source: { kind: 'user' }, content: [text(canary)] }, 3),
22
+ record('tool/ptc-dispatch', { name: canary, isError: true, arguments: { token: canary } }, 4),
23
+ record('tool/ptc-dispatch', { name: 'bash', content: [text('[exit code: 3]' + String.fromCharCode(10) + canary)] }, 5),
24
+ record('tool/ptc-dispatch', { name: 'bash', content: [text(canary + String.fromCharCode(10) + '[exit code: 2]')] }, 6),
25
+ record('job/settled', { status: 'completed', kind: 'bash', detail: 'exit code: 9; ' + canary }, 7),
26
+ record('job/settled', { status: 'completed', kind: 'other', detail: 'exit code: 9; ' + canary }, 8),
27
+ record('assistant/message', { turn: 1, message: { content: [text(canary)] } }, 9),
28
+ record('turn/end', { turn: 1, reason: { kind: 'completed' } }, 10),
29
+ record('assistant/message', { turn: 2, message: { content: [text(canary), { type: 'tool-call' }] } }, 11),
30
+ record('turn/end', { turn: 2, reason: { kind: 'aborted' } }, 12),
31
+ ]
32
+ const indexed = indexLog({ header: { id: child }, inheritedEventCount: 1, events }, root, new Set([root, child]))
33
+ assert.deepEqual(indexed.evidence, [
34
+ { seq: 1, kind: 'parent-message', senderSessionId: root },
35
+ { seq: 3, kind: 'initial-user-message' },
36
+ { seq: 4, kind: 'tool-error', tool: 'other' },
37
+ { seq: 6, kind: 'nonzero-exit', tool: 'bash', exitCode: 2 },
38
+ { seq: 7, kind: 'job-nonzero-exit', exitCode: 9 },
39
+ { seq: 9, kind: 'final-report', endSeq: 10 },
40
+ ])
41
+ assert.equal(JSON.stringify(indexed).includes(canary), false)
42
+ })
43
+
44
+ test('opens only the requested lineage and checks persisted parent identity', { skip: !process.env.DSH_INSTALL_DIR }, async t => {
45
+ const temp = resolve('tmp/evolution/retro-index')
46
+ await mkdir(temp, { recursive: true })
47
+ const logs = await mkdtemp(join(temp, 'fixture-'))
48
+ t.after(() => rm(logs, { recursive: true }))
49
+ const workspace = '/retro-fixture'
50
+ const project = join(logs, '--retro-fixture--')
51
+ async function save(id, parentSession, events) {
52
+ const dir = join(project, id)
53
+ await mkdir(dir, { recursive: true })
54
+ const header = { type: 'session', version: 4, id, cwd: workspace, createdAt: 1, isSeeded: false,
55
+ parentSession, delegationDepth: parentSession ? 1 : 0, origin: parentSession ? 'subagent' : undefined }
56
+ const newline = String.fromCharCode(10)
57
+ await writeFile(join(dir, 'session.v4.jsonl'), [header, ...events].map(value => JSON.stringify(value)).join(newline) + newline)
58
+ }
59
+ const dispatch = record('subagent/catalog', { version: 1, childId: child, childCreatedAt: 1, mode: 'continuable', label: canary }, 0)
60
+ await save(root, undefined, [dispatch])
61
+ await save(child, root, [])
62
+ await save(unrelated, undefined, [canary])
63
+ const script = fileURLToPath(new URL('./session-index.mjs', import.meta.url))
64
+ const run = ids => spawnSync(process.execPath, [script, '--project-dir', project, '--workspace', workspace,
65
+ '--compression', 'none', ...ids], { encoding: 'utf8' })
66
+ const accepted = run([root, child])
67
+ assert.equal(accepted.status, 0, accepted.stderr || accepted.stdout)
68
+ const acceptedIndex = JSON.parse(accepted.stdout)
69
+ assert.deepEqual(acceptedIndex.sessions.map(s => [s.id, s.parentId]), [[root, null], [child, root]])
70
+ assert.deepEqual(acceptedIndex.sessions[0].evidence, [{ seq: 0, kind: 'child-dispatch', childSessionId: child }])
71
+ assert.equal(accepted.stdout.includes(canary), false)
72
+ const extra = run([root, child, unrelated])
73
+ assert.equal(extra.status, 1, extra.stderr)
74
+ assert.deepEqual(JSON.parse(extra.stdout).unavailable, [{ id: unrelated, reason: 'not-linked-by-indexed-parent' }])
75
+ await save(child, unrelated, [canary])
76
+ const wrongParent = run([root, child])
77
+ assert.equal(wrongParent.status, 1, wrongParent.stderr)
78
+ assert.deepEqual(JSON.parse(wrongParent.stdout).unavailable, [{ id: child, reason: 'header-parent-mismatch' }])
79
+ assert.equal((wrongParent.stdout + wrongParent.stderr).includes(canary), false)
80
+ })