dsh-vscode-mode 0.20.0 → 0.20.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/README.md +24 -15
- package/lib/client.js +589 -54
- package/lib/client.js.map +1 -1
- package/lib/index.js +417 -15
- package/lib/index.js.map +1 -1
- package/package.json +1 -1
- package/src/client/monaco/diffRender.ts +2 -2
- package/src/client/reviewBatch.ts +64 -0
- package/src/client/state/reviewFeed.ts +8 -4
- package/src/client/styles/editor.css +39 -0
- package/src/client/ui/DiffBox.ts +2 -17
- package/src/client/ui/EditorView.ts +149 -11
- package/src/client/ui/OfficialDiffBar.tsx +112 -0
- package/src/client-primitives.d.ts +22 -0
- package/src/index.ts +4 -1
- package/src/officialCapture.ts +7 -3
- package/src/reviewCapture.ts +112 -0
- package/src/reviewDb.ts +77 -6
- package/src/reviewEvidence.ts +70 -0
- package/src/reviewRpc.ts +10 -1
- package/src/reviewUndo.ts +104 -0
- package/src/shared/review.ts +5 -1
- package/src/shared/reviewRegions.ts +74 -0
package/src/index.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { registerRoutes } from './routes.js'
|
|
3
3
|
import { captureToolResult } from './capture.js'
|
|
4
4
|
import { installCapture } from './officialCapture.js'
|
|
5
|
+
import { installEvidence } from './reviewCapture.js'
|
|
5
6
|
import { closeArchiveDbs } from './archiveDb.js'
|
|
6
7
|
import { handleRpc, integrationBaseUrlOf } from './rpc.js'
|
|
7
8
|
import { newSearcher } from './search/orchestrator.js'
|
|
@@ -68,7 +69,8 @@ function createRuntime(ctx: Ctx, config: unknown) {
|
|
|
68
69
|
* @param runtime Managers created by this instance.
|
|
69
70
|
*/
|
|
70
71
|
function attachRuntime(ctx: Ctx, runtime: Runtime): void {
|
|
71
|
-
const
|
|
72
|
+
const evidence = installEvidence(ctx)
|
|
73
|
+
const stopCapture = installCapture(ctx, (cwd, snapshot) => { evidence.persist(cwd, snapshot); return true })
|
|
72
74
|
/** @author ddj 2026年09月28号 @param exec Tool execution. @param result Tool result. */
|
|
73
75
|
function onResult(exec: unknown, result: unknown): void {
|
|
74
76
|
void captureToolResult(ctx, runtime.registry, exec, result)
|
|
@@ -87,6 +89,7 @@ function attachRuntime(ctx: Ctx, runtime: Runtime): void {
|
|
|
87
89
|
/** @author ddj 2026年09月28号 Release every manager even if another cleanup rejects. */
|
|
88
90
|
async function cleanup(): Promise<void> {
|
|
89
91
|
await stopCapture()
|
|
92
|
+
evidence.dispose()
|
|
90
93
|
runtime.fileVersions.dispose()
|
|
91
94
|
closeArchiveDbs()
|
|
92
95
|
disposeAllServers()
|
package/src/officialCapture.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Deferred official-event collection; no private snapshot access. @author ddj 2026年10月26号 */
|
|
2
2
|
import { captureState, repairPaths, saveSnapshot } from './reviewDb.js'
|
|
3
|
-
import type { OfficialDiff, OfficialSummary } from './shared/review.js'
|
|
3
|
+
import type { OfficialDiff, OfficialSummary, ReviewSnapshot } from './shared/review.js'
|
|
4
4
|
import type { Ctx } from './store.js'
|
|
5
5
|
import { loadBucket } from './store.js'
|
|
6
6
|
import { log } from './log.js'
|
|
@@ -148,12 +148,16 @@ async function readDiff(source: SourceService, task: CaptureTask, index: number,
|
|
|
148
148
|
}
|
|
149
149
|
|
|
150
150
|
/** @public @author ddj 2026年10月26号 @param ctx Host lifecycle owner; services remain optional for older Hosts. */
|
|
151
|
-
export function installCapture(ctx: Ctx): () => Promise<void> {
|
|
151
|
+
export function installCapture(ctx: Ctx, onSnapshot?: (cwd: string, snapshot: ReviewSnapshot) => void): () => Promise<void> {
|
|
152
152
|
const collector = createCollector({
|
|
153
153
|
source: () => ctx.get('workspaceChanges'),
|
|
154
154
|
prepare: async (cwd) => { await loadBucket(ctx, cwd); await repairPaths(cwd, resolvePath) },
|
|
155
155
|
identity: resolvePath,
|
|
156
|
-
persist:
|
|
156
|
+
persist: (cwd, snapshot) => {
|
|
157
|
+
const saved = saveSnapshot(cwd, snapshot)
|
|
158
|
+
onSnapshot?.(cwd, snapshot)
|
|
159
|
+
return saved
|
|
160
|
+
}, state: captureState, report: (message) => log.warn(message),
|
|
157
161
|
})
|
|
158
162
|
// Subscribe first: seed reads must not create a live-event race window.
|
|
159
163
|
ctx.on('session/event', collector.enqueue)
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/** Independent byte evidence; official diff remains the only display authority. @author ddj 2026年10月27号 */
|
|
2
|
+
import { rawReviewFile, evidenceBlocks } from './reviewEvidence.js'
|
|
3
|
+
import type { RawReviewFile } from './reviewEvidence.js'
|
|
4
|
+
import type { ReviewSnapshot } from './shared/review.js'
|
|
5
|
+
import { reviewDb } from './reviewDb.js'
|
|
6
|
+
import { resolveTarget } from './store.js'
|
|
7
|
+
import type { Ctx } from './store.js'
|
|
8
|
+
import { log } from './log.js'
|
|
9
|
+
|
|
10
|
+
interface ByteChain { before: RawReviewFile; after: RawReviewFile; busy: boolean; invalid: boolean }
|
|
11
|
+
interface EvidenceCapture {
|
|
12
|
+
persist(cwd: string, snapshot: ReviewSnapshot): void
|
|
13
|
+
dispose(): void
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** @public @author ddj 2026年10月27号 @param ctx Host lifecycle owner. @returns Scoped byte recorder; failures disable undo evidence only, never tool execution. */
|
|
17
|
+
export function installEvidence(ctx: Ctx): EvidenceCapture {
|
|
18
|
+
const chains = new Map<string, Map<string, ByteChain>>()
|
|
19
|
+
const staged = new Map<string, Map<string, ByteChain>>()
|
|
20
|
+
let stopped = false
|
|
21
|
+
ctx.on('tools/execute', aroundTool)
|
|
22
|
+
ctx.on('session/event', onEvent)
|
|
23
|
+
ctx.on('session/disposed', onDisposed)
|
|
24
|
+
|
|
25
|
+
/** @private @author ddj 2026年10月27号 @param session Disposed owner. Drops optional in-memory evidence, never persisted official facts. */
|
|
26
|
+
function onDisposed(session: { id: string }): void { chains.delete(session.id) }
|
|
27
|
+
|
|
28
|
+
/** @private @author ddj 2026年10月27号 @returns Current bounded capture footprint, excluding transient filesystem reads. */
|
|
29
|
+
function footprint(): number {
|
|
30
|
+
let bytes = 0
|
|
31
|
+
for (const group of [chains, staged]) {
|
|
32
|
+
for (const files of group.values()) {
|
|
33
|
+
for (const chain of files.values()) bytes += chain.before.bytes.length + chain.after.bytes.length
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return bytes
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** @private @author ddj 2026年10月27号 @param exec Allowed tool dispatch. @param next Original dispatch. @returns Original result unchanged, regardless of capture failure. */
|
|
40
|
+
async function aroundTool(exec: any, next: () => Promise<any>): Promise<any> {
|
|
41
|
+
const session = exec.agent?.session
|
|
42
|
+
const path = exec.arguments?.file_path
|
|
43
|
+
if (stopped || !session?.id || !['edit', 'write'].includes(exec.name) || typeof path !== 'string') return next()
|
|
44
|
+
let fs: any
|
|
45
|
+
let chain: ByteChain | undefined
|
|
46
|
+
let target: any
|
|
47
|
+
try {
|
|
48
|
+
if ((chains.size >= 16 && !chains.has(session.id)) || footprint() >= 32 * 1024 * 1024) return next()
|
|
49
|
+
fs = ctx.get('fs')
|
|
50
|
+
target = await resolveTarget(ctx, session, path)
|
|
51
|
+
const identity = fs.processPath(target)
|
|
52
|
+
const before = await readRaw(fs, target, exec.signal)
|
|
53
|
+
let files = chains.get(session.id)
|
|
54
|
+
if (!files) { files = new Map(); chains.set(session.id, files) }
|
|
55
|
+
if (files.size >= 64 && !files.has(identity)) return next()
|
|
56
|
+
chain = files.get(identity)
|
|
57
|
+
if (!chain) { chain = { before, after: before, busy: false, invalid: false }; files.set(identity, chain) }
|
|
58
|
+
if (chain.busy || chain.after.hash !== before.hash) chain.invalid = true
|
|
59
|
+
chain.busy = true
|
|
60
|
+
} catch { /* No trustworthy read means no undo evidence, not a failed user tool. */ }
|
|
61
|
+
try { return await next() }
|
|
62
|
+
finally {
|
|
63
|
+
if (chain) {
|
|
64
|
+
try { chain.after = await readRaw(fs, target, exec.signal) } catch { chain.invalid = true }
|
|
65
|
+
chain.busy = false
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** @private @author ddj 2026年10月27号 @param session Source session. @param event Published official turn. Freezes the chain before the next turn can mutate it. */
|
|
71
|
+
function onEvent(session: any, event: any): void {
|
|
72
|
+
if (stopped || event.type !== 'workspace/changes') return
|
|
73
|
+
const files = chains.get(session.id)
|
|
74
|
+
chains.delete(session.id)
|
|
75
|
+
if (!files || staged.size >= 128) return
|
|
76
|
+
staged.set(JSON.stringify([session.id, event.seq]), structuredClone(files))
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** @public @author ddj 2026年10月27号 @param cwd Official workspace. @param snapshot Committed official facts. Persists only independently validated, exact-correspondence byte chains. */
|
|
80
|
+
function persist(cwd: string, snapshot: ReviewSnapshot): void {
|
|
81
|
+
const key = JSON.stringify([snapshot.sessionId, snapshot.seq])
|
|
82
|
+
const files = staged.get(key)
|
|
83
|
+
staged.delete(key)
|
|
84
|
+
if (!files || stopped) return
|
|
85
|
+
const db = reviewDb(cwd)
|
|
86
|
+
for (const file of snapshot.files) {
|
|
87
|
+
const chain = files.get(file.identity)
|
|
88
|
+
if (!chain || chain.invalid || chain.busy) continue
|
|
89
|
+
try {
|
|
90
|
+
const evidence = { before: chain.before, after: chain.after }
|
|
91
|
+
evidenceBlocks(file.diff, evidence)
|
|
92
|
+
db.prepare(`INSERT OR IGNORE INTO review_evidence(file_id,payload)
|
|
93
|
+
SELECT id,? FROM review_files WHERE session_id=? AND turn=? AND seq=? AND identity=?`)
|
|
94
|
+
.run(JSON.stringify(evidence), snapshot.sessionId, snapshot.turn, snapshot.seq, file.identity)
|
|
95
|
+
} catch (error) { log.warn('官方回滚证据不可用:' + String(error)) }
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** @public @author ddj 2026年10月27号 Release bounded in-memory images after capture has drained. */
|
|
100
|
+
function dispose(): void { stopped = true; chains.clear(); staged.clear() }
|
|
101
|
+
return { persist, dispose }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** @private @author ddj 2026年10月27号 @param fs Public filesystem. @param target Backend identity. @returns Raw bounded file or confirmed missing. @throws Any non-missing read error. */
|
|
105
|
+
async function readRaw(fs: any, target: any, signal?: AbortSignal): Promise<RawReviewFile> {
|
|
106
|
+
try { return rawReviewFile(await fs.readBytes(target, signal, 1024 * 1024)) }
|
|
107
|
+
catch (error) {
|
|
108
|
+
const code = (error as { code?: string }).code
|
|
109
|
+
if (code === 'ENOENT' || code === 'FS_NOT_FOUND') return rawReviewFile(null)
|
|
110
|
+
throw error
|
|
111
|
+
}
|
|
112
|
+
}
|
package/src/reviewDb.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
/** Official history shares the archive connection, but never the legacy callId namespace. @author ddj 2026年10月26号 */
|
|
2
2
|
import { createHash } from 'node:crypto'
|
|
3
|
+
import { existsSync } from 'node:fs'
|
|
4
|
+
import { archiveDbFile } from './paths.js'
|
|
5
|
+
import { reviewBlocks } from './shared/reviewRegions.js'
|
|
6
|
+
import type { ReviewBlockState } from './shared/reviewRegions.js'
|
|
3
7
|
import type { DatabaseSync } from 'node:sqlite'
|
|
4
8
|
import { activeReady, dbFor } from './archiveDb.js'
|
|
5
9
|
import type { CaptureGap, DecideReview, OfficialDiff, ReviewDetail, ReviewItem, ReviewPage, ReviewSnapshot } from './shared/review.js'
|
|
@@ -11,7 +15,7 @@ export function reviewDb(cwd: string): DatabaseSync {
|
|
|
11
15
|
if (!activeReady(cwd)) throw new Error('官方审查要求先完成活跃库迁移')
|
|
12
16
|
const db = dbFor(cwd)
|
|
13
17
|
const version = db.prepare("SELECT value FROM metadata WHERE name='schema'").get() as Row
|
|
14
|
-
if (version.value === '4') return db
|
|
18
|
+
if (version.value === '4') { migrateBlocks(cwd, db); return db }
|
|
15
19
|
db.exec('BEGIN IMMEDIATE')
|
|
16
20
|
try {
|
|
17
21
|
db.exec(`CREATE TABLE review_snapshots (
|
|
@@ -37,9 +41,37 @@ export function reviewDb(cwd: string): DatabaseSync {
|
|
|
37
41
|
if (db.isTransaction) db.exec('ROLLBACK')
|
|
38
42
|
throw error
|
|
39
43
|
}
|
|
44
|
+
migrateBlocks(cwd, db)
|
|
40
45
|
return db
|
|
41
46
|
}
|
|
42
47
|
|
|
48
|
+
/** @private @author ddj 2026年10月27号 @param cwd Workspace backup identity. @param db Open schema4 database. Extends the official-review sub-schema without changing legacy archive schema. @throws Migration failure, leaving prior decisions intact. */
|
|
49
|
+
function migrateBlocks(cwd: string, db: DatabaseSync): void {
|
|
50
|
+
if (db.prepare("SELECT value FROM metadata WHERE name='review_schema'").get()) return
|
|
51
|
+
const backup = archiveDbFile(cwd) + '.before-review-blocks.bak'
|
|
52
|
+
if (!existsSync(backup)) db.exec(`VACUUM INTO '${backup.replace(/'/g, "''")}'`)
|
|
53
|
+
|
|
54
|
+
db.exec('BEGIN IMMEDIATE')
|
|
55
|
+
try {
|
|
56
|
+
db.exec(`CREATE TABLE review_blocks (file_id TEXT NOT NULL, block_id TEXT NOT NULL,
|
|
57
|
+
decision TEXT NOT NULL, PRIMARY KEY(file_id,block_id));
|
|
58
|
+
CREATE TABLE review_evidence (file_id TEXT PRIMARY KEY, payload TEXT NOT NULL);
|
|
59
|
+
INSERT INTO metadata(name,value) VALUES('review_schema','2');`)
|
|
60
|
+
const files = db.prepare('SELECT id,diff,decision FROM review_files').all() as Row[]
|
|
61
|
+
for (const file of files) seedBlocks(db, String(file.id), JSON.parse(String(file.diff)), String(file.decision))
|
|
62
|
+
db.exec('COMMIT')
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (db.isTransaction) db.exec('ROLLBACK')
|
|
65
|
+
throw error
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** @private @author ddj 2026年10月27号 @param db Transaction connection. @param id File record. @param diff Immutable official source. @param decision Prior file decision. Seeds deterministic blocks without changing source facts. */
|
|
70
|
+
function seedBlocks(db: DatabaseSync, id: string, diff: OfficialDiff, decision: string): void {
|
|
71
|
+
const insert = db.prepare('INSERT INTO review_blocks VALUES(?,?,?)')
|
|
72
|
+
for (const block of reviewBlocks(diff)) insert.run(id, block.id, decision)
|
|
73
|
+
}
|
|
74
|
+
|
|
43
75
|
/** @private @author ddj 2026年10月26号 @param text Canonical serialized input. @returns Collision-resistant identity. */
|
|
44
76
|
function digest(text: string): string { return createHash('sha256').update(text).digest('hex') }
|
|
45
77
|
|
|
@@ -107,7 +139,7 @@ export async function repairPaths(cwd: string, resolvePath: (cwd: string, path:
|
|
|
107
139
|
/** @private @author ddj 2026年10月26号 @param db Transaction. @param snapshot Source payload. @param hash Source digest. */
|
|
108
140
|
function insertSnapshot(db: DatabaseSync, snapshot: ReviewSnapshot, hash: string): void {
|
|
109
141
|
const { sessionId, turn, seq } = snapshot
|
|
110
|
-
const previous = db.prepare('SELECT identity,diff,decision FROM review_files WHERE session_id=? AND turn=? AND current=1').all(sessionId, turn) as Row[]
|
|
142
|
+
const previous = db.prepare('SELECT id,identity,diff,decision FROM review_files WHERE session_id=? AND turn=? AND current=1').all(sessionId, turn) as Row[]
|
|
111
143
|
db.prepare('UPDATE review_snapshots SET current=0 WHERE session_id=? AND turn=?').run(sessionId, turn)
|
|
112
144
|
db.prepare('UPDATE review_files SET current=0 WHERE session_id=? AND turn=?').run(sessionId, turn)
|
|
113
145
|
db.prepare('INSERT INTO review_snapshots VALUES(?,?,?,?,?,1)').run(sessionId, turn, seq, JSON.stringify(snapshot), hash)
|
|
@@ -116,7 +148,17 @@ function insertSnapshot(db: DatabaseSync, snapshot: ReviewSnapshot, hash: string
|
|
|
116
148
|
const encoded = JSON.stringify(file.diff)
|
|
117
149
|
const unchanged = previous.find((item) => item.identity === file.identity && item.diff === encoded)
|
|
118
150
|
const id = digest(JSON.stringify([sessionId, turn, seq, file.identity]))
|
|
119
|
-
|
|
151
|
+
const decision = String(unchanged?.decision ?? 'pending')
|
|
152
|
+
insert.run(id, sessionId, turn, seq, file.identity, JSON.stringify(snapshot.summary.files[index]), encoded, decision)
|
|
153
|
+
seedBlocks(db, id, file.diff, decision)
|
|
154
|
+
if (unchanged) {
|
|
155
|
+
// A same-turn republish must preserve mixed per-block decisions, not seed all blocks as mixed.
|
|
156
|
+
db.prepare(`UPDATE review_blocks SET decision=(SELECT p.decision FROM review_blocks p
|
|
157
|
+
WHERE p.file_id=? AND p.block_id=review_blocks.block_id)
|
|
158
|
+
WHERE file_id=? AND EXISTS(SELECT 1 FROM review_blocks p WHERE p.file_id=? AND p.block_id=review_blocks.block_id)`)
|
|
159
|
+
.run(unchanged.id, id, unchanged.id)
|
|
160
|
+
db.prepare('INSERT INTO review_evidence SELECT ?,payload FROM review_evidence WHERE file_id=?').run(id, unchanged.id)
|
|
161
|
+
}
|
|
120
162
|
}
|
|
121
163
|
}
|
|
122
164
|
|
|
@@ -181,9 +223,33 @@ export function reviewDetail(cwd: string, id: string): ReviewDetail | null {
|
|
|
181
223
|
const row = db.prepare(`SELECT f.*,json_extract(s.payload,'$.capturedAt') AS captured_at FROM review_files f JOIN review_snapshots s
|
|
182
224
|
USING(session_id,turn,seq) WHERE f.id=?`).get(id) as Row | undefined
|
|
183
225
|
if (!row) return null
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
226
|
+
const blocks = db.prepare('SELECT block_id AS id,decision FROM review_blocks WHERE file_id=? ORDER BY rowid').all(id) as unknown as ReviewBlockState[]
|
|
227
|
+
const diff = JSON.parse(String(row.diff)) as OfficialDiff
|
|
228
|
+
const evidence = db.prepare('SELECT 1 FROM review_evidence WHERE file_id=?').get(id)
|
|
229
|
+
const pending = row.current === 1 && row.decision === 'pending'
|
|
230
|
+
const undo = pending && !!evidence && diff.kind === 'text' && diff.before && diff.after && !diff.coarse
|
|
231
|
+
return { item: itemOf(row), diff, capturedAt: String(row.captured_at), blocks,
|
|
232
|
+
capability: { keep: pending, undo,
|
|
233
|
+
reason: undo ? 'Undo 将校验原始字节、当前文件版本及已处理差异块;文件变化会安全拒绝。'
|
|
234
|
+
: '该记录缺少可验证的原始字节或受控写回能力;仍可显示差异和 Keep,不能猜测历史全文执行 Undo。' } }
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** @public @author ddj 2026年10月27号 @param db Active decision transaction. @param request File or block action. Updates aggregate without losing mixed decisions. @throws Invalid or already-decided block. */
|
|
238
|
+
export function changeBlocks(db: DatabaseSync, request: DecideReview): void {
|
|
239
|
+
if (request.scope === 'hunk') {
|
|
240
|
+
const changed = db.prepare("UPDATE review_blocks SET decision=? WHERE file_id=? AND block_id=? AND decision='pending'")
|
|
241
|
+
.run(request.decision, request.id, request.blockId ?? '')
|
|
242
|
+
if (changed.changes !== 1) throw new Error('差异块不存在或已处理')
|
|
243
|
+
} else {
|
|
244
|
+
db.prepare("UPDATE review_blocks SET decision=? WHERE file_id=? AND decision='pending'").run(request.decision, request.id)
|
|
245
|
+
}
|
|
246
|
+
const states = db.prepare('SELECT DISTINCT decision FROM review_blocks WHERE file_id=?').all(request.id) as Row[]
|
|
247
|
+
const decisions = states.map((row) => String(row.decision))
|
|
248
|
+
let aggregate = request.decision as string
|
|
249
|
+
if (decisions.includes('pending')) aggregate = 'pending'
|
|
250
|
+
else if (decisions.length > 1) aggregate = 'mixed'
|
|
251
|
+
else if (decisions.length === 1) aggregate = decisions[0]
|
|
252
|
+
db.prepare('UPDATE review_files SET decision=? WHERE id=?').run(aggregate, request.id)
|
|
187
253
|
}
|
|
188
254
|
|
|
189
255
|
/** @public @author ddj 2026年10月26号 @param cwd Workspace. @param request Frozen identity/revision. @returns Idempotent decision; rejection never guesses a target. */
|
|
@@ -196,13 +262,18 @@ export function decideReview(cwd: string, request: DecideReview): { revision: nu
|
|
|
196
262
|
const previous = db.prepare('SELECT request,result FROM review_ops WHERE operation_id=?').get(request.operationId) as Row | undefined
|
|
197
263
|
if (previous) {
|
|
198
264
|
if (previous.request !== encoded) throw new Error('operationId 已用于其他请求')
|
|
265
|
+
if (!previous.result) throw new Error('Undo 尚待写后核对,请重试原操作')
|
|
199
266
|
db.exec('COMMIT')
|
|
200
267
|
return JSON.parse(String(previous.result))
|
|
201
268
|
}
|
|
269
|
+
if (db.prepare("SELECT 1 FROM review_ops WHERE state='prepared' AND json_extract(request,'$.id')=?").get(request.id)) {
|
|
270
|
+
throw new Error('该文件有尚待核对的 Undo,暂不能 Keep')
|
|
271
|
+
}
|
|
202
272
|
if (request.decision !== 'accepted') throw new Error('缺少可信全文证据,禁止拒绝写回')
|
|
203
273
|
const change = db.prepare(`UPDATE review_files SET decision='accepted',revision=revision+1
|
|
204
274
|
WHERE id=? AND seq=? AND revision=? AND current=1 AND decision='pending'`).run(request.id, request.seq, request.revision)
|
|
205
275
|
if (change.changes !== 1) throw new Error('审查版本冲突,请刷新后重试')
|
|
276
|
+
changeBlocks(db, request)
|
|
206
277
|
const result = { revision: request.revision + 1 }
|
|
207
278
|
db.prepare("INSERT INTO review_ops VALUES(?,?,'committed',?,NULL)").run(request.operationId, encoded, JSON.stringify(result))
|
|
208
279
|
db.exec('COMMIT')
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/** Raw UTF-8 evidence and patch correspondence; never reconstructs a historical file from disk. @author ddj 2026年10月27号 */
|
|
2
|
+
import { createHash } from 'node:crypto'
|
|
3
|
+
import { reviewBlocks } from './shared/reviewRegions.js'
|
|
4
|
+
import type { OfficialDiff } from './shared/review.js'
|
|
5
|
+
|
|
6
|
+
export interface RawReviewFile { present: boolean; bytes: string; hash: string }
|
|
7
|
+
export interface ReviewEvidence { before: RawReviewFile; after: RawReviewFile }
|
|
8
|
+
export interface RawReviewBlock { id: string; before: string; after: string; offset: number }
|
|
9
|
+
|
|
10
|
+
/** @public @author ddj 2026年10月27号 @param bytes File bytes, or null for confirmed absence. @returns Existence-sensitive immutable digest and base64. */
|
|
11
|
+
export function rawReviewFile(bytes: Uint8Array | null): RawReviewFile {
|
|
12
|
+
const payload = bytes === null ? Buffer.alloc(0) : Buffer.from(bytes)
|
|
13
|
+
return { present: bytes !== null, bytes: payload.toString('base64'), hash: createHash('sha256')
|
|
14
|
+
.update(bytes === null ? 'absent:' : 'present:').update(payload).digest('hex') }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** @private @author ddj 2026年10月27号 @param file Persisted raw image. @returns UTF-8 storage text preserving BOM and terminators. @throws Binary, invalid encoding or corrupt hash. */
|
|
18
|
+
function rawText(file: RawReviewFile): string {
|
|
19
|
+
const bytes = Buffer.from(file.bytes, 'base64')
|
|
20
|
+
if (bytes.length > 8 * 1024 * 1024 || bytes.includes(0)) throw new Error('回滚证据不是受支持的 UTF-8 文本')
|
|
21
|
+
if (rawReviewFile(file.present ? bytes : null).hash !== file.hash) throw new Error('回滚证据哈希不匹配')
|
|
22
|
+
// ignoreBOM=true retains the BOM codepoint, allowing byte-identical writeText.
|
|
23
|
+
const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes)
|
|
24
|
+
if (!Buffer.from(text, 'utf8').equals(bytes)) throw new Error('回滚证据无法字节往返')
|
|
25
|
+
return text
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** @private @author ddj 2026年10月27号 @param text Storage text. @returns Physical lines, retaining each original line ending and excluding BOM. */
|
|
29
|
+
function rawLines(text: string): string[] {
|
|
30
|
+
const body = text.replace(/^\uFEFF/, '')
|
|
31
|
+
return body.match(/[^\r\n]*(?:\r\n|\n|\r|$)/g)?.filter((line, index, lines) => line !== '' || index !== lines.length - 1) ?? []
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @private @author ddj 2026年10月27号 @param lines Physical storage lines. @returns Official logical-line comparison basis. */
|
|
35
|
+
function logical(lines: string[]): string[] { return lines.map((line) => line.replace(/(?:\r\n|\r|\n)$/, '')) }
|
|
36
|
+
|
|
37
|
+
/** @public @author ddj 2026年10月27号 @param diff Official source. @param evidence Independent raw captures. @returns Exact raw segments only when every official hunk reproduces the entire captured result. @throws Incomplete chain, coarse patch or mismatched context/content. */
|
|
38
|
+
export function evidenceBlocks(diff: OfficialDiff, evidence: ReviewEvidence): RawReviewBlock[] {
|
|
39
|
+
if (diff.kind !== 'text' || diff.coarse) throw new Error('该官方差异没有可靠文本基线')
|
|
40
|
+
if (diff.before !== evidence.before.present || diff.after !== evidence.after.present) throw new Error('文件存在性证据不一致')
|
|
41
|
+
const beforeText = rawText(evidence.before), afterText = rawText(evidence.after)
|
|
42
|
+
const before = rawLines(beforeText), after = rawLines(afterText)
|
|
43
|
+
const expected = logical(before)
|
|
44
|
+
let delta = 0
|
|
45
|
+
for (const hunk of diff.hunks) {
|
|
46
|
+
const old = hunk.lines.filter((line) => line[0] === ' ' || line[0] === '-').map((line) => line.slice(1))
|
|
47
|
+
const next = hunk.lines.filter((line) => line[0] === ' ' || line[0] === '+').map((line) => line.slice(1))
|
|
48
|
+
if (old.length !== hunk.oldLines || next.length !== hunk.newLines) throw new Error('官方差异行数不一致')
|
|
49
|
+
const position = Math.max(0, hunk.oldStart - 1) + delta
|
|
50
|
+
if (JSON.stringify(expected.slice(position, position + old.length)) !== JSON.stringify(old)) throw new Error('原始基线与官方上下文不一致')
|
|
51
|
+
expected.splice(position, old.length, ...next)
|
|
52
|
+
delta += next.length - old.length
|
|
53
|
+
}
|
|
54
|
+
if (JSON.stringify(expected) !== JSON.stringify(logical(after))) throw new Error('采集链未覆盖全部官方变更')
|
|
55
|
+
if (!diff.hunks.length && beforeText !== afterText) throw new Error('官方没有提供可撤销的变更块')
|
|
56
|
+
const blocks = reviewBlocks(diff)
|
|
57
|
+
const segments = blocks.map((block) => ({ id: block.id,
|
|
58
|
+
before: before.slice(block.oldStart - 1, block.oldStart - 1 + block.oldLines.length).join(''),
|
|
59
|
+
after: after.slice(block.newStart - 1, block.newStart - 1 + block.newLines.length).join(''),
|
|
60
|
+
offset: (afterText.startsWith('\uFEFF') ? 1 : 0) + after.slice(0, block.newStart - 1).join('').length }))
|
|
61
|
+
let reversed = afterText
|
|
62
|
+
for (const segment of [...segments].reverse()) reversed = reversed.slice(0, segment.offset) + segment.before + reversed.slice(segment.offset + segment.after.length)
|
|
63
|
+
if (reversed !== beforeText) throw new Error('官方变更外的 BOM、行尾或末尾换行发生变化,证据不足')
|
|
64
|
+
return segments
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** @public @author ddj 2026年10月27号 @param evidence Raw original images. @returns Exact before and after UTF-8 storage text for guarded writes. */
|
|
68
|
+
export function evidenceText(evidence: ReviewEvidence): { before: string; after: string } {
|
|
69
|
+
return { before: rawText(evidence.before), after: rawText(evidence.after) }
|
|
70
|
+
}
|
package/src/reviewRpc.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/** Session-scoped official review RPC. @author ddj 2026年10月26号 */
|
|
2
2
|
import type { RpcHandlerMap } from './shared/rpc.js'
|
|
3
3
|
import { decideReview, reviewDetail, reviewPage } from './reviewDb.js'
|
|
4
|
+
import { undoReview } from './reviewUndo.js'
|
|
4
5
|
import { bucketOf, cwdOfSession, sessionOf } from './registry.js'
|
|
5
6
|
import type { Registry } from './registry.js'
|
|
6
7
|
import type { Ctx } from './store.js'
|
|
@@ -27,7 +28,15 @@ export function reviewHandlers(ctx: Ctx, registry: Registry): Partial<RpcHandler
|
|
|
27
28
|
},
|
|
28
29
|
'edrv.review.decide': async (args) => {
|
|
29
30
|
const cwd = await workspace(args.sessionId)
|
|
30
|
-
|
|
31
|
+
try {
|
|
32
|
+
const result = args.decision === 'rejected'
|
|
33
|
+
? await undoReview(ctx, sessionOf(ctx, args.sessionId), cwd, args)
|
|
34
|
+
: decideReview(cwd, args)
|
|
35
|
+
return { ok: true, ...result }
|
|
36
|
+
} catch (error) {
|
|
37
|
+
// Guard failures are review results, not transport failures: preserve their reason.
|
|
38
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) }
|
|
39
|
+
}
|
|
31
40
|
},
|
|
32
41
|
}
|
|
33
42
|
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/** Guarded official undo with a durable write-intent journal. @author ddj 2026年10月27号 */
|
|
2
|
+
import { changeBlocks, reviewDb, reviewDetail } from './reviewDb.js'
|
|
3
|
+
import { evidenceBlocks, evidenceText, rawReviewFile } from './reviewEvidence.js'
|
|
4
|
+
import type { ReviewEvidence } from './reviewEvidence.js'
|
|
5
|
+
import type { DecideReview } from './shared/review.js'
|
|
6
|
+
import type { Ctx, Session } from './store.js'
|
|
7
|
+
import { policyOf, resolveTarget } from './store.js'
|
|
8
|
+
|
|
9
|
+
type OperationRow = { request: string; state: string; result: string | null; evidence: string }
|
|
10
|
+
interface UndoJournal { before: string; after: string }
|
|
11
|
+
const writes = new Map<string, Promise<unknown>>()
|
|
12
|
+
|
|
13
|
+
/** @public @author ddj 2026年10月27号 @param ctx Host capability. @param session Authenticated caller. @param cwd Workspace. @param request Frozen file/block version. @returns Durable decision; retries reconcile disk hashes and never blindly repeat a write. @throws Missing evidence, stale state, policy or uncertain write failure. */
|
|
14
|
+
export async function undoReview(ctx: Ctx, session: Session, cwd: string, request: DecideReview): Promise<{ revision: number }> {
|
|
15
|
+
const detail = reviewDetail(cwd, request.id)
|
|
16
|
+
const key = JSON.stringify([cwd, detail?.item.currentPath ?? request.id])
|
|
17
|
+
const prior = writes.get(key) ?? Promise.resolve()
|
|
18
|
+
const operation = prior.catch(() => undefined).then(() => runUndo(ctx, session, cwd, request))
|
|
19
|
+
writes.set(key, operation)
|
|
20
|
+
try { return await operation }
|
|
21
|
+
finally { if (writes.get(key) === operation) writes.delete(key) }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** @private @author ddj 2026年10月27号 @param ctx Host. @param session Caller. @param cwd Workspace. @param request Frozen decision. @returns Serialized guarded mutation and journal reconciliation. @throws Conflicting bytes or decisions. */
|
|
25
|
+
async function runUndo(ctx: Ctx, session: Session, cwd: string, request: DecideReview): Promise<{ revision: number }> {
|
|
26
|
+
const db = reviewDb(cwd)
|
|
27
|
+
const encoded = JSON.stringify(request)
|
|
28
|
+
if (!request.operationId || request.operationId.length > 128) throw new Error('operationId 无效')
|
|
29
|
+
const prior = db.prepare('SELECT * FROM review_ops WHERE operation_id=?').get(request.operationId) as OperationRow | undefined
|
|
30
|
+
if (prior && prior.request !== encoded) throw new Error('operationId 已用于其他请求')
|
|
31
|
+
if (prior?.state === 'committed') return JSON.parse(prior.result!)
|
|
32
|
+
const detail = reviewDetail(cwd, request.id)
|
|
33
|
+
if (!detail || !detail.item.current || detail.item.seq !== request.seq || detail.item.revision !== request.revision
|
|
34
|
+
|| detail.item.decision !== 'pending') throw new Error('审查版本冲突,请刷新后重试')
|
|
35
|
+
const fs = ctx.get('fs')
|
|
36
|
+
if (!fs?.readBytes || !fs?.writeText || !fs?.stat) throw new Error('后端缺少受控回滚能力')
|
|
37
|
+
const target = await resolveTarget(ctx, session, detail.item.currentPath)
|
|
38
|
+
const info = await fs.stat(target)
|
|
39
|
+
if (!info || info.type !== 'file' || !info.version) throw new Error('文件不存在或缺少版本守卫,不能安全 Undo')
|
|
40
|
+
const bytes = await fs.readBytes(target, undefined, 8 * 1024 * 1024)
|
|
41
|
+
const current = rawReviewFile(bytes)
|
|
42
|
+
const observed = await fs.stat(target)
|
|
43
|
+
if (observed?.version !== info.version) throw new Error('文件在回滚读取期间变化,未修改文件')
|
|
44
|
+
if (prior) {
|
|
45
|
+
const journal = JSON.parse(prior.evidence) as UndoJournal
|
|
46
|
+
if (current.hash === journal.after) return finishUndo(cwd, request)
|
|
47
|
+
if (current.hash !== journal.before) throw new Error('上次 Undo 状态不确定:磁盘既非写前也非写后,禁止重复执行')
|
|
48
|
+
}
|
|
49
|
+
const unresolved = db.prepare("SELECT operation_id FROM review_ops WHERE state='prepared' AND json_extract(request,'$.id')=? AND operation_id<>?")
|
|
50
|
+
.get(request.id, request.operationId)
|
|
51
|
+
if (unresolved) throw new Error('存在未核对的 Undo,请使用原操作重试,不能创建另一项写入')
|
|
52
|
+
const row = db.prepare('SELECT payload FROM review_evidence WHERE file_id=?').get(request.id) as { payload: string } | undefined
|
|
53
|
+
if (!row) throw new Error('该历史记录缺少可信原始字节证据,不能 Undo;差异仍可展示和 Keep')
|
|
54
|
+
const evidence = JSON.parse(row.payload) as ReviewEvidence
|
|
55
|
+
const segments = evidenceBlocks(detail.diff, evidence)
|
|
56
|
+
const texts = evidenceText(evidence)
|
|
57
|
+
if (!evidence.before.present || !evidence.after.present) throw new Error('当前后端未提供受控原子删除/重建能力')
|
|
58
|
+
const selected = detail.blocks.filter((block) => block.decision === 'pending' && (request.scope !== 'hunk' || block.id === request.blockId))
|
|
59
|
+
if (!selected.length) throw new Error('差异块不存在或已处理')
|
|
60
|
+
// Build the expected disk version by removing only previously rejected blocks.
|
|
61
|
+
const rejected = new Set(detail.blocks.filter((block) => block.decision === 'rejected').map((block) => block.id))
|
|
62
|
+
const expected = reverseBlocks(texts.after, segments, rejected)
|
|
63
|
+
if (rawReviewFile(Buffer.from(expected)).hash !== current.hash) throw new Error('当前文件已被后续编辑,版本与回滚证据冲突,未修改文件')
|
|
64
|
+
const undo = new Set([...rejected, ...selected.map((block) => block.id)])
|
|
65
|
+
const next = reverseBlocks(texts.after, segments, undo)
|
|
66
|
+
const journal = { before: current.hash, after: rawReviewFile(Buffer.from(next)).hash }
|
|
67
|
+
const latest = reviewDetail(cwd, request.id)
|
|
68
|
+
if (!latest?.item.current || latest.item.revision !== request.revision || latest.item.decision !== 'pending') {
|
|
69
|
+
throw new Error('审查版本在回滚校验期间变化,未修改文件')
|
|
70
|
+
}
|
|
71
|
+
db.prepare("INSERT INTO review_ops VALUES(?,?,'prepared',NULL,?) ON CONFLICT(operation_id) DO NOTHING")
|
|
72
|
+
.run(request.operationId, encoded, JSON.stringify(journal))
|
|
73
|
+
// Provider checks the exact observation inside its atomic mutation critical section.
|
|
74
|
+
await fs.writeText(target, next, { kind: 'replaceIfVersion', version: info.version }, undefined, policyOf(ctx, session))
|
|
75
|
+
const written = rawReviewFile(await fs.readBytes(target, undefined, 8 * 1024 * 1024))
|
|
76
|
+
if (written.hash !== journal.after) throw new Error('Undo 写后内容不确定,请保留原操作重试核对')
|
|
77
|
+
return finishUndo(cwd, request)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** @private @author ddj 2026年10月27号 @param text Captured result. @param segments Validated raw ranges. @param rejected Blocks to reverse. @returns Raw storage text preserving unselected blocks. */
|
|
81
|
+
function reverseBlocks(text: string, segments: ReturnType<typeof evidenceBlocks>, rejected: Set<string>): string {
|
|
82
|
+
let result = text
|
|
83
|
+
for (const segment of [...segments].reverse()) {
|
|
84
|
+
if (!rejected.has(segment.id)) continue
|
|
85
|
+
result = result.slice(0, segment.offset) + segment.before + result.slice(segment.offset + segment.after.length)
|
|
86
|
+
}
|
|
87
|
+
return result
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** @private @author ddj 2026年10月27号 @param cwd Workspace. @param request Frozen action. @returns Transactionally committed status, or a retryable prepared journal if the database fails. */
|
|
91
|
+
function finishUndo(cwd: string, request: DecideReview): { revision: number } {
|
|
92
|
+
const db = reviewDb(cwd)
|
|
93
|
+
db.exec('BEGIN IMMEDIATE')
|
|
94
|
+
try {
|
|
95
|
+
const updated = db.prepare("UPDATE review_files SET revision=revision+1 WHERE id=? AND seq=? AND revision=? AND current=1 AND decision='pending'")
|
|
96
|
+
.run(request.id, request.seq, request.revision)
|
|
97
|
+
if (updated.changes !== 1) throw new Error('审查版本冲突,请核对已执行 Undo')
|
|
98
|
+
changeBlocks(db, request)
|
|
99
|
+
const result = { revision: request.revision + 1 }
|
|
100
|
+
db.prepare("UPDATE review_ops SET state='committed',result=? WHERE operation_id=?").run(JSON.stringify(result), request.operationId)
|
|
101
|
+
db.exec('COMMIT')
|
|
102
|
+
return result
|
|
103
|
+
} catch (error) { if (db.isTransaction) db.exec('ROLLBACK'); throw error }
|
|
104
|
+
}
|
package/src/shared/review.ts
CHANGED
|
@@ -35,6 +35,7 @@ export interface ReviewSnapshot {
|
|
|
35
35
|
files: { identity: string; diff: OfficialDiff }[]
|
|
36
36
|
}
|
|
37
37
|
export type ReviewDecision = 'pending' | 'accepted' | 'rejected'
|
|
38
|
+
export type ReviewFileDecision = ReviewDecision | 'mixed'
|
|
38
39
|
export interface ReviewItem {
|
|
39
40
|
id: string
|
|
40
41
|
sessionId: string
|
|
@@ -46,7 +47,7 @@ export interface ReviewItem {
|
|
|
46
47
|
added: number
|
|
47
48
|
deleted: number
|
|
48
49
|
kind: OfficialDiff['kind']
|
|
49
|
-
decision:
|
|
50
|
+
decision: ReviewFileDecision
|
|
50
51
|
revision: number
|
|
51
52
|
current: boolean
|
|
52
53
|
}
|
|
@@ -54,6 +55,7 @@ export interface ReviewDetail {
|
|
|
54
55
|
item: ReviewItem
|
|
55
56
|
diff: OfficialDiff
|
|
56
57
|
capturedAt: string
|
|
58
|
+
blocks: import('./reviewRegions.js').ReviewBlockState[]
|
|
57
59
|
capability: { keep: boolean; undo: boolean; reason: string }
|
|
58
60
|
}
|
|
59
61
|
export interface CaptureGap {
|
|
@@ -86,6 +88,8 @@ export interface DecideReview extends ReviewRequest {
|
|
|
86
88
|
seq: number
|
|
87
89
|
revision: number
|
|
88
90
|
operationId: string
|
|
91
|
+
scope?: 'file' | 'hunk'
|
|
92
|
+
blockId?: string
|
|
89
93
|
decision: 'accepted' | 'rejected'
|
|
90
94
|
}
|
|
91
95
|
export type ReviewResult<T> = ({ ok: true } & T) | { ok: false; error: string }
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/** Official patch parsing shared by review decisions and editor display. @author ddj 2026年10月27号 */
|
|
2
|
+
import type { OfficialDiff, ReviewDecision } from './review.js'
|
|
3
|
+
|
|
4
|
+
export interface ReviewBlock {
|
|
5
|
+
id: string
|
|
6
|
+
hunkIndex: number
|
|
7
|
+
oldStart: number
|
|
8
|
+
newStart: number
|
|
9
|
+
oldLines: string[]
|
|
10
|
+
newLines: string[]
|
|
11
|
+
contextBefore: string[]
|
|
12
|
+
contextAfter: string[]
|
|
13
|
+
}
|
|
14
|
+
export interface ReviewBlockState { id: string; decision: ReviewDecision }
|
|
15
|
+
export interface ReviewRegion extends ReviewBlock {
|
|
16
|
+
sourceKind: 'official'
|
|
17
|
+
recordId: string
|
|
18
|
+
idx: number
|
|
19
|
+
status: ReviewDecision
|
|
20
|
+
stale: boolean
|
|
21
|
+
start?: number
|
|
22
|
+
end?: number
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** @public @author ddj 2026年10月27号 @param diff Immutable official patch. @returns Contiguous change runs with stable source-coordinate identities. */
|
|
26
|
+
export function reviewBlocks(diff: OfficialDiff): ReviewBlock[] {
|
|
27
|
+
if (diff.kind !== 'text') return []
|
|
28
|
+
const blocks: ReviewBlock[] = []
|
|
29
|
+
for (const [hunkIndex, hunk] of diff.hunks.entries()) {
|
|
30
|
+
let oldLine = hunk.oldStart, newLine = hunk.newStart
|
|
31
|
+
let before: string[] = []
|
|
32
|
+
let current: ReviewBlock | undefined
|
|
33
|
+
for (const line of hunk.lines) {
|
|
34
|
+
const marker = line[0], text = line.slice(1)
|
|
35
|
+
if (marker === ' ') {
|
|
36
|
+
if (current) { current.contextAfter.push(text); current = undefined }
|
|
37
|
+
else if (blocks.at(-1)?.hunkIndex === hunkIndex) blocks.at(-1)!.contextAfter.push(text)
|
|
38
|
+
before.push(text); oldLine++; newLine++
|
|
39
|
+
continue
|
|
40
|
+
}
|
|
41
|
+
if (marker !== '+' && marker !== '-') continue
|
|
42
|
+
if (!current) {
|
|
43
|
+
current = { id: `${hunkIndex}:${oldLine}:${newLine}`, hunkIndex, oldStart: oldLine, newStart: newLine,
|
|
44
|
+
oldLines: [], newLines: [], contextBefore: before.slice(-3), contextAfter: [] }
|
|
45
|
+
blocks.push(current); before = []
|
|
46
|
+
}
|
|
47
|
+
if (marker === '-') { current.oldLines.push(text); oldLine++ }
|
|
48
|
+
else { current.newLines.push(text); newLine++ }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return blocks
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** @public @author ddj 2026年10月27号 @param diff Source patch. @param recordId Official record, not a tool call. @param states Persisted per-block decisions. @param content Current editor text; null has no current-file location. @returns Regions only located by unique full contextual matches, never by guessed history line numbers. */
|
|
55
|
+
export function reviewRegions(diff: OfficialDiff, recordId: string, states: ReviewBlockState[], content: string | null): ReviewRegion[] {
|
|
56
|
+
const lines = content === null ? null : content.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n').split('\n')
|
|
57
|
+
return reviewBlocks(diff).map((block, idx) => {
|
|
58
|
+
const status = states.find((state) => state.id === block.id)?.decision ?? 'pending'
|
|
59
|
+
const region: ReviewRegion = { ...block, sourceKind: 'official', recordId, idx, status, stale: true }
|
|
60
|
+
if (!lines) return region
|
|
61
|
+
const pattern = [...block.contextBefore, ...block.newLines, ...block.contextAfter]
|
|
62
|
+
if (!pattern.length) return region
|
|
63
|
+
const matches: number[] = []
|
|
64
|
+
for (let offset = 0; offset + pattern.length <= lines.length; offset++) {
|
|
65
|
+
if (pattern.every((text, index) => lines[offset + index] === text)) matches.push(offset)
|
|
66
|
+
if (matches.length > 1) break
|
|
67
|
+
}
|
|
68
|
+
if (matches.length !== 1) return region
|
|
69
|
+
region.start = matches[0] + block.contextBefore.length + 1
|
|
70
|
+
region.end = region.start + block.newLines.length
|
|
71
|
+
region.stale = false
|
|
72
|
+
return region
|
|
73
|
+
})
|
|
74
|
+
}
|