dsh-collab-workbench 0.0.0-stage → 0.1.2

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.

Potentially problematic release.


This version of dsh-collab-workbench might be problematic. Click here for more details.

@@ -0,0 +1,101 @@
1
+ import * as fs from 'node:fs/promises'
2
+ import {join, resolve, isAbsolute} from 'node:path'
3
+ import {randomUUID} from 'node:crypto'
4
+
5
+ const START='<!-- dsh-workbench:managed:start -->'
6
+ const END='<!-- dsh-workbench:managed:end -->'
7
+ const generation=(task,runs)=>Math.max(1,task.generation??1,...runs.filter(r=>r.taskId===task.id).map(r=>r.generation??1))
8
+ export function snapshotSignature(tasks, runs=[]) {
9
+ return JSON.stringify(tasks.map(t=>({id:t.id,revision:t.revision??1,status:t.status,generation:generation(t,runs)})).sort((a,b)=>a.id<b.id?-1:a.id>b.id?1:0))
10
+ }
11
+ const pick=(value,keys)=>Object.fromEntries(keys.filter(k=>value[k]!==undefined).map(k=>[k,value[k]]))
12
+ function projection(group,tasks,runs) {
13
+ const current=tasks.flatMap(t=>{
14
+ const latest=new Map()
15
+ for(const r of runs.filter(r=>r.taskId===t.id && (r.generation??1)===generation(t,runs) && (!t.assignees || t.assignees.includes(r.roleId)))) latest.set(r.roleId,r)
16
+ return [...latest.values()]
17
+ })
18
+ const signature=snapshotSignature(tasks,runs)
19
+ const blocked=!!group.pendingDecision || current.some(r=>['failed','blocked','paused','cancelled'].includes(r.status)||r.attention||r.error)
20
+ const done=tasks.length>0 && tasks.every(t=>t.status==='已完成')
21
+ const delivered=done && group.delivery?.status==='delivered' && group.delivery.signature===signature
22
+ return {version:1,groupId:group.id,signature,state:blocked?'BLOCKED':done?(delivered?'COMPLETE':'DELIVERY'):'IMPLEMENTATION',
23
+ tasks:tasks.slice().sort((a,b)=>a.id.localeCompare(b.id)).map(t=>({...pick(t,['id','title','revision','status','executionSummary']),generation:generation(t,runs)})),
24
+ runs:current.map(r=>pick(r,['id','taskId','roleId','generation','status','summary','error','attention','evidence'])).sort((a,b)=>a.id.localeCompare(b.id)),
25
+ evidence:current.filter(r=>r.evidence?.length).map(r=>({runId:r.id,taskId:r.taskId,evidence:r.evidence})),
26
+ handoffs:current.filter(r=>r.summary).map(r=>({runId:r.id,taskId:r.taskId,status:r.status,summary:r.summary})),
27
+ delivery:group.delivery?pick(group.delivery,['signature','status','notifiedAt','summary']):null}
28
+ }
29
+ function homepage(raw,item,p) {
30
+ const block=`${START}\n## 工作台派生状态\n\n状态:${p.state}\n\n${p.tasks.map(t=>`- ${t.id}:${t.status} — ${String(t.title??'').replace(/\n/g,' ')}`).join('\n')}\n\n证据与执行摘要:见 [work_item.json](./work_item.json) 的 workbench_projection。\n${END}`
31
+ const start=raw.indexOf(START),end=raw.indexOf(END)
32
+ if(start!==-1 || end!==-1) {
33
+ if(start===-1 || end<start || raw.indexOf(START,start+START.length)!==-1 || raw.indexOf(END,end+END.length)!==-1) throw new Error('首页 managed 标记损坏,拒绝覆盖')
34
+ return raw.slice(0,start)+block+raw.slice(end+END.length)
35
+ }
36
+ const initial=`# ${item.work_item_id} / ${item.title}\n\n状态:接收中,尚无角色调用或业务批准。\n\n协调员请在实际执行后更新:重要变化、待决入口、未验证、已完成、可以继续与证据。\n`
37
+ // Only the exact known initializer is disposable; other prose is human-owned.
38
+ const base=raw===initial?`# ${item.work_item_id} / ${item.title}\n`:raw
39
+ return base+(base.endsWith('\n')?'\n':'\n\n')+block+'\n'
40
+ }
41
+
42
+ export function install(rt) {
43
+ const io={...fs,...rt.config?.workItemSyncIO}
44
+ const retryAt=new Map()
45
+ let tail=Promise.resolve()
46
+ async function read(path,optional=false) {
47
+ try { if((await io.lstat(path)).isSymbolicLink()) throw new Error(`拒绝符号链接:${path}`);return await io.readFile(path,'utf8') }
48
+ catch(error) {if(optional && error.code==='ENOENT') return '';throw error}
49
+ }
50
+ async function atomic(path,before,after,optional=false) {
51
+ if(before===after) return
52
+ const tmp=`${path}.${process.pid}.${randomUUID()}.tmp`
53
+ try {
54
+ await io.writeFile(tmp,after,{encoding:'utf8',flag:'wx'})
55
+ if(await read(path,optional)!==before) throw new Error(`并发修改冲突:${path}`)
56
+ await io.rename(tmp,path)
57
+ } finally {await io.unlink(tmp).catch(()=>{})}
58
+ }
59
+ async function status(group,next) {
60
+ if(JSON.stringify(group.workItemSync)===JSON.stringify(next)) return
61
+ group.workItemSync=next
62
+ rt.touch?.()
63
+ await rt.saveAll?.()
64
+ }
65
+ async function sync() {
66
+ for(const group of rt.listGroups()) {
67
+ if(!group.dir || !isAbsolute(group.dir) || (retryAt.get(group.id)??0)>Date.now()) continue
68
+ try {
69
+ const root=join(group.dir,'.sopai','runs')
70
+ let dirs
71
+ try {dirs=await io.readdir(root,{withFileTypes:true})} catch(error) {if(error.code==='ENOENT') continue;throw error}
72
+ if((await io.realpath(root))!==join(await io.realpath(group.dir),'.sopai','runs')) throw new Error('SOPAI运行目录含符号链接')
73
+ const candidates=[]
74
+ for(const dir of dirs) {
75
+ if(!dir.isDirectory()) continue
76
+ const path=join(root,dir.name,'work_item.json')
77
+ let raw
78
+ try {raw=await read(path)} catch(error) {if(error.code==='ENOENT') continue;throw error}
79
+ const item=JSON.parse(raw)
80
+ if(typeof item.project==='string' && isAbsolute(item.project) && resolve(item.project)===resolve(group.dir) && item.work_item_id===dir.name) candidates.push({path,raw,item,dir:join(root,dir.name)})
81
+ }
82
+ if(candidates.length>1) throw new Error(`多个匹配SOPAI工作项(${candidates.length}),拒绝猜测`)
83
+ if(!candidates.length) {await status(group,{status:'unmatched'});continue}
84
+ const c=candidates[0], tasks=rt.listTasks().filter(t=>t.groupId===group.id),runs=rt.state.execution?.runs??[]
85
+ const p=projection(group,tasks,runs)
86
+ const page=join(c.dir,'复核首页.md'),oldPage=await read(page,true),newPage=homepage(oldPage,c.item,p)
87
+ const next=JSON.stringify({...c.item,state:p.state,workbench_projection:p},null,2)+'\n'
88
+ // Preflight both inputs before either write; each rename repeats its own check.
89
+ if(await read(c.path)!==c.raw || await read(page,true)!==oldPage) throw new Error('并发修改冲突:SOPAI投影输入已变化')
90
+ await atomic(c.path,c.raw,next)
91
+ await atomic(page,oldPage,newPage,true)
92
+ retryAt.delete(group.id)
93
+ await status(group,{status:'synced',workItemId:c.item.work_item_id,path:c.path,signature:p.signature})
94
+ } catch(error) {
95
+ retryAt.set(group.id,Date.now()+(rt.config?.workItemSyncRetryMs??30000))
96
+ await status(group,{status:'error',error:String(error?.message??error)})
97
+ }
98
+ }
99
+ }
100
+ rt.syncWorkItems=()=>{const result=tail.then(sync);tail=result.catch(()=>{});return result}
101
+ }