@adamchanadam/agent-handoff-kit 0.4.2 → 0.4.4

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 (46) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +1 -1
  3. package/README.md +1 -1
  4. package/bin/agent-handoff-kit.mjs +7146 -7047
  5. package/bin/commands.mjs +134 -134
  6. package/bin/handoff-read.mjs +88 -88
  7. package/bin/installed-file-contract.mjs +154 -90
  8. package/bin/migration-baselines/official-origin-catalog.json +534 -1
  9. package/bin/official-origin-catalog.mjs +294 -294
  10. package/bin/progress/ICON-LICENSE.txt +21 -21
  11. package/bin/progress/assets.mjs +6 -6
  12. package/bin/progress/dashboard.mjs +134 -134
  13. package/bin/progress/icons.svg +36 -36
  14. package/bin/progress/index.html +31 -31
  15. package/bin/progress/launch.mjs +40 -40
  16. package/bin/progress/open.mjs +43 -43
  17. package/bin/progress/project-version.mjs +121 -121
  18. package/bin/progress/projection.mjs +144 -144
  19. package/bin/progress/renderer.js +152 -152
  20. package/bin/progress/server.mjs +78 -78
  21. package/bin/progress/styles.css +31 -31
  22. package/bin/prompt-mirror-core.mjs +84 -84
  23. package/bin/upgrade-inventory.mjs +243 -243
  24. package/bin/user-rules-router.mjs +4 -4
  25. package/docs/commands.md +2 -2
  26. package/docs/progress.md +73 -73
  27. package/package.json +22 -22
  28. package/packs/agent-governance.md +120 -120
  29. package/packs/closeout.md +91 -91
  30. package/packs/coding.md +28 -28
  31. package/packs/integrations.md +19 -19
  32. package/packs/knowledge.md +3 -3
  33. package/packs/onboarding.md +45 -45
  34. package/packs/research.md +30 -30
  35. package/packs/safety.md +2 -2
  36. package/runtime-core/AGENTS.core.md +161 -161
  37. package/runtime-core/CLAUDE.md +13 -13
  38. package/runtime-core/DOC_SYNC_REGISTRY.md +24 -24
  39. package/runtime-core/GEMINI.md +17 -17
  40. package/runtime-core/PROJECT_DECISIONS.md +43 -43
  41. package/runtime-core/PROJECT_INDEX.md +16 -16
  42. package/runtime-core/RULE_PACKS.md +1 -1
  43. package/runtime-core/SESSION_HANDOFF.md +180 -180
  44. package/runtime-core/SESSION_LOG.md +37 -37
  45. package/runtime-core/START_NEXT_SESSION_PROMPT.txt +1 -1
  46. package/runtime-core/USER_RULES_ENTRY.md +5 -5
@@ -1,144 +1,144 @@
1
- // Read-only projection of existing Kit records. No AI calls, generated summaries or source writes.
2
- import {openSync,closeSync,readSync,fstatSync,statSync,realpathSync,existsSync} from 'node:fs';
3
- import path from 'node:path';
4
- import {createHash} from 'node:crypto';
5
- export const LIMITS={handoff:1024*1024,log:64*1024,recent:10,page:6,item:12000};
6
- const names={
7
- 'task-understanding-summary':'understanding','active-objective':'current','completed-this-session':'done',
8
- 'next-priorities':'pending','risks-blockers':'risks','confirmed-decisions':'decisions'
9
- };
10
- const headings={
11
- 'task understanding summary':'understanding','任務理解摘要':'understanding','active objective':'current','目前目標':'current',
12
- 'completed this session':'done','本次完成':'done','本次已完成':'done','next priorities':'pending','下一步':'pending','下一步優先事項':'pending',
13
- 'risks / blockers':'risks','風險與阻礙':'risks','風險 / 阻礙':'risks','confirmed decisions':'decisions','已確認決策':'decisions'
14
- };
15
- export const hash=v=>createHash('sha256').update(v).digest('hex');
16
- const clean=s=>s.replace(/<!--.*?-->/g,'').replace(/^\s*(?:[-*+] |\d+[.)] )/,'').replace(/\*\*/g,'').trim();
17
- const missing=s=>!s||/^(?:TBD|待填|尚未記錄|未提供)(?:\b|\s|$)/i.test(s)||/^<[^>]+>$/.test(s)||/^[^::]{1,90}[::]\s*(?:TBD|待填)(?:\b|\s|$)/i.test(s)||/^Record only work actually completed in the current session\./.test(s);
18
- // Defensive display redaction. Source files remain untouched.
19
- export const safe=s=>s.replace(/\b(?:sk-(?:ant-)?|gh[pousr]_|github_pat_|xox[baprs]-|AIza|AKIA)[A-Za-z0-9_-]{16,}/g,'<REDACTED>');
20
- function item(text,file,line){text=safe(clean(text));return{id:hash(file+':'+line+':'+text).slice(0,16),text:text.slice(0,LIMITS.item),clipped:text.length>LIMITS.item,source:{file,line}};}
21
-
22
- export function markdown(text,{prefix=false}={}){
23
- const lines=text.replace(/^\uFEFF/,'').split(/\r?\n/),sections=[];let fence=null,current=null,marker=null,title='',inComment=false,entryMarked=false,listContext=false;
24
- for(let i=0;i<lines.length;i++){
25
- let raw=lines[i];if(inComment){const end=raw.indexOf('-->');if(end<0)continue;raw=raw.slice(end+3);inComment=false;}
26
- const f=raw.match(/^\s{0,3}(`{3,}|~{3,})(.*)$/);
27
- if(f){if(!fence)fence=f[1];else if(f[1][0]===fence[0]&&f[1].length>=fence.length&&!f[2].trim())fence=null;continue;}if(fence)continue;
28
- if(/^(?: {4}|\t)/.test(raw)&&!listContext)continue;
29
- if(/^\s*<!-- ack:log-entry:start -->\s*$/.test(raw)){entryMarked=true;continue;}
30
- if(/^\s*<!-- ack:log-entry:end -->\s*$/.test(raw)){if(current)current.entryClosed=true;continue;}
31
- const m=raw.match(/^\s*<!-- ack:section:([a-z-]+) -->\s*$/);if(m){marker=m[1];continue;}
32
- while(raw.includes('<!--')){const start=raw.indexOf('<!--'),end=raw.indexOf('-->',start+4);if(end<0){raw=raw.slice(0,start);inComment=true;break;}raw=raw.slice(0,start)+raw.slice(end+3);}
33
- if(/^# [^#]/.test(raw)&&!title)title=raw.slice(2).trim();
34
- const h=raw.match(/^## (?!#)(.+?)\s*#*$/);
35
- if(h){if(current)current.end=i;current={title:h[1],key:names[marker]||headings[h[1].toLowerCase()]||null,line:i+1,rows:[],end:null,entryMarked,entryClosed:false};sections.push(current);marker=null;entryMarked=false;listContext=false;continue;}
36
- if(raw.trim()&&marker)marker=null;
37
- if(/^(?:[-*+] |\d+[.)] )/.test(raw))listContext=true;else if(raw.trim()&&!/^\s/.test(raw))listContext=false;
38
- if(current)current.rows.push({text:raw,line:i+1});
39
- }
40
- if((fence||inComment)&&!prefix)throw Error('incomplete');
41
- if(current&&!prefix)current.end=lines.length;
42
- return{title,sections};
43
- }
44
- function blocks(section,file){
45
- if(!section)return[];const out=[];let buffer=[],line=0;
46
- const following=new Array(section.rows.length);let nextRow=null;
47
- for(let i=section.rows.length-1;i>=0;i--){following[i]=nextRow;if(section.rows[i].text.trim())nextRow=section.rows[i];}
48
- const flush=()=>{const text=buffer.join(' ').trim();if(text&&!missing(clean(text)))out.push(item(text,file,line));buffer=[];};
49
- for(let i=0;i<section.rows.length;i++){
50
- const row=section.rows[i];
51
- if(!row.text.trim()){const next=following[i];if(buffer.length&&/^(?:[-*+] |\d+[.)] )/.test(buffer[0])&&next&&/^\s+\S/.test(next.text))continue;flush();continue;}
52
- if(/^#{3,}\s/.test(row.text)){flush();continue;}
53
- if(/^(?:[-*+] |\d+[.)] )/.test(row.text)){flush();line=row.line;buffer=[row.text];}
54
- else{if(!buffer.length)line=row.line;buffer.push(row.text);}
55
- }flush();return out;
56
- }
57
- const fieldNames=['Parent outcome / consumer','Current step','Task position','User intent','Task essence','User value','Resume point','Remaining acceptance','Completed within this task','Remaining acceptance / resume point','Recommended next step','專案目標','最終目標','目前階段','目前工作','任務位置','用戶意圖'];
58
- const fieldPattern=new RegExp('(?:^|[.。]\\s+|\\s+(?=(?:Current step|目前階段)[::]))('+fieldNames.map(s=>s.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')).join('|')+')[::]\\s*','gi');
59
- function field(items,keys){for(const row of items){const matches=[...row.text.matchAll(fieldPattern)];for(let i=0;i<matches.length;i++){if(!keys.includes(matches[i][1].toLowerCase()))continue;const start=matches[i].index+matches[i][0].length,end=matches[i+1]?.index??row.text.length,value=row.text.slice(start,end).trim();if(!missing(value))return{...row,text:value};}}return null;}
60
-
61
- export function parseHandoff(text,rootName='Project'){
62
- const parsed=markdown(text),groups={};
63
- for(const s of parsed.sections)if(s.key){if(groups[s.key])throw Error('duplicate');groups[s.key]=s;}
64
- if(!groups.current||!groups.pending||!groups.risks)throw Error('structure');
65
- const file='dev/SESSION_HANDOFF.md',all=Object.fromEntries(Object.entries(groups).map(([k,v])=>[k,blocks(v,file)]));
66
- const understanding=all.understanding||[],active=all.current||[];
67
- const goal=field([...understanding,...active],['parent outcome / consumer','專案目標','最終目標'])||field(understanding,['user intent','用戶意圖']);
68
- const current=field(active,['current step','目前階段','目前工作'])||active.find(x=>!fieldNames.some(label=>x.text.toLowerCase().startsWith(label.toLowerCase()+':')||x.text.toLowerCase().startsWith(label.toLowerCase()+':')))||null;
69
- const position=field(understanding,['task position','任務位置']);
70
- const title=parsed.title.replace(/\s+(?:Session\s+)?Handoff$/i,'').replace(/\s*交接(?:包|紀錄)?$/,'').trim();
71
- const name=!title||/^(?:Session|Handoff|Session Handoff)$/i.test(parsed.title)?rootName:title;
72
- const updated=text.match(/^Last Updated:\s*(.+)$/mi)?.[1]||text.match(/^最後更新[::]\s*(.+)$/m)?.[1]||null;
73
- const collections={};for(const k of ['done','pending','risks','decisions'])collections[k]=all[k]||[];
74
- // Preserve source wording. Never infer that a child result completes the parent.
75
- return{name,goal,current,position,updated:missing(updated)?null:updated,collections,missingSections:['done','decisions'].filter(k=>!groups[k])};
76
- }
77
- // One event reader for both the bounded home prefix and paged history.
78
- export function logEntry(s,file,startLine=1){
79
- if(!/^\d{4}-\d{2}-\d{2}\s*[—–-]/.test(s.title)||s.entryMarked&&!s.entryClosed)return null;
80
- const date=s.title.slice(0,10);if(Number.isNaN(Date.parse(date))||new Date(date+'T00:00:00Z').toISOString().slice(0,10)!==date)return null;
81
- const fields={};let active=null;const prose=[];
82
- for(const row of s.rows){
83
- const text=safe(clean(row.text)),nested=/^(?: {2,}|\t)/.test(row.text);
84
- const m=!nested&&text.match(/^([A-Za-z][A-Za-z0-9 _/-]{0,80})[::]\s*(.*)$/);
85
- if(m){active=m[1].toLowerCase();fields[active]=missing(m[2])||/^[—-]$/.test(m[2])?'':m[2];}
86
- else if(nested&&active&&text)fields[active]+=(fields[active]?'\n':'')+text;
87
- else if(text){active=null;prose.push(text);}
88
- }
89
- for(const key of Object.keys(fields))if(!fields[key])delete fields[key];
90
- const body=safe(s.rows.map(x=>x.text).join('\n').trim()),explicit=fields['event id'];
91
- return{id:hash(explicit?'id:'+explicit:s.title+'\n'+body).slice(0,24),fingerprint:hash(s.title+'\n'+body),date,title:safe(s.title.slice(10).replace(/^\s*[—–-]\s*/,'')),titleZh:fields['title zh-hant']||null,summary:fields.summary||fields.done||prose[0]||'',summaryZh:fields['summary zh-hant']||null,work:fields.work||null,fields,body,source:{file,line:startLine+s.line-1}};
92
- }
93
- export function parseLog(text,limited=false){
94
- const {sections}=markdown(text,{prefix:limited}),entries=[];
95
- for(const s of sections){
96
- if(!/^\d{4}-\d{2}-\d{2}\s*[—–-]/.test(s.title))continue;
97
- if((limited&&s.end===null&&!s.entryClosed)||(s.entryMarked&&!s.entryClosed))continue; // Never display an unclosed or chopped entry as complete.
98
- const entry=logEntry(s,'dev/SESSION_LOG.md');if(!entry)continue;
99
- entries.push({...entry,title:safe(s.title),summary:entry.summary?item(entry.summary,entry.source.file,s.line):null,body:entry.body.slice(0,LIMITS.item)});
100
- if(entries.length===LIMITS.recent)break;
101
- }
102
- return{entries,limited:limited||sections.filter(s=>/^\d{4}-\d{2}-\d{2}\s*[—–-]/.test(s.title)).length>LIMITS.recent};
103
- }
104
- export function readBounded(root,file,limit,{prefix=false}={}){
105
- const target=path.join(root,file),real=realpathSync(target),relative=path.relative(root,real);
106
- if(relative.startsWith('..')||path.isAbsolute(relative))throw Error('boundary');
107
- const fd=openSync(real,'r');try{
108
- const before=fstatSync(fd);if(!before.isFile()||(!prefix&&before.size>limit))throw Error('capacity');
109
- const checked=realpathSync(target),relativeNow=path.relative(root,checked);
110
- if(checked!==real||relativeNow.startsWith('..')||path.isAbsolute(relativeNow)||statSync(checked).ino!==before.ino)throw Error('boundary');
111
- const count=Math.min(before.size,limit),buffer=Buffer.alloc(count);let offset=0;
112
- while(offset<count){const n=readSync(fd,buffer,offset,count-offset,offset);if(!n)throw Error('unstable');offset+=n;}
113
- const after=fstatSync(fd),now=statSync(target);
114
- if(before.size!==after.size||before.mtimeMs!==after.mtimeMs||now.ino!==before.ino||now.size!==before.size||now.mtimeMs!==before.mtimeMs)throw Error('unstable');
115
- const limited=before.size>limit;let content=new TextDecoder('utf-8',{fatal:true}).decode(limited?buffer.subarray(0,Math.max(0,buffer.lastIndexOf(10)+1)):buffer);
116
- return{text:content,hash:hash(content),bytesRead:offset,limited,mtime:new Date(before.mtimeMs).toISOString()};
117
- }finally{closeSync(fd);}
118
- }
119
- export function signature(root,file){try{const target=path.join(root,file),real=realpathSync(target),r=path.relative(root,real);if(r.startsWith('..')||path.isAbsolute(r))return'boundary';const s=statSync(target);return[s.ino,s.size,s.mtimeMs,s.ctimeMs].join(':');}catch(e){return e.code==='ENOENT'?'missing':'unreadable';}}
120
- export function createSource(projectRoot){
121
- const root=realpathSync(path.resolve(projectRoot)),files=['dev/SESSION_HANDOFF.md','dev/SESSION_LOG.md'];
122
- const state={handoff:null,log:null,errors:{},metrics:{reads:0,bytes:0,handoffBytes:0,logBytes:0},rootName:path.basename(root)};
123
- const seen=new Map(),pending=new Map();let previous='',version=0;
124
- function refresh({immediate=false}={}){
125
- if(existsSync(path.join(root,'dev/governance_migrations/.upgrade.lock'))){state.errors.lock='upgrade';}
126
- else{
127
- delete state.errors.lock;
128
- for(const file of files){const key=file.includes('HANDOFF')?'handoff':'log',sig=signature(root,file);
129
- if(seen.get(file)===sig&&!['unreadable','unstable'].includes(state.errors[key]))continue;
130
- if(!immediate&&pending.get(file)!==sig){pending.set(file,sig);continue;}
131
- try{
132
- const read=readBounded(root,file,LIMITS[key],{prefix:key==='log'});state.metrics.reads++;state.metrics.bytes+=read.bytesRead;state.metrics[key+'Bytes']=read.bytesRead;
133
- const parsed=key==='handoff'?parseHandoff(read.text,state.rootName):parseLog(read.text,read.limited);
134
- state[key]={...parsed,meta:{file,updated:read.mtime,hash:read.hash,bytesRead:read.bytesRead,limited:read.limited}};if(key==='handoff')state.acceptedHandoff=read.text;delete state.errors[key];
135
- }catch(e){state.errors[key]=['capacity','boundary','structure','incomplete','duplicate','unstable'].includes(e.message)?e.message:sig==='missing'?'missing':'unreadable';}
136
- seen.set(file,sig);pending.delete(file);
137
- }
138
- }
139
- const value=JSON.stringify({handoff:state.handoff,log:state.log,errors:state.errors});if(value===previous)return false;previous=value;version++;return true;
140
- }
141
- function snapshot(){const h=state.handoff;return{schemaVersion:2,version,project:{name:h?.name||state.rootName,goal:h?.goal||null,current:h?.current||null,position:h?.position||null},recordDate:h?.updated||null,available:!!h,sections:Object.fromEntries(['done','pending','risks','decisions'].map(k=>[k,{items:(h?.collections[k]||[]).slice(0,k==='risks'?2:3),total:h?.collections[k]?.length||null}])),recent:{items:(state.log?.entries||[]).slice(0,3),total:state.log?.entries.length??null,limited:state.log?.limited||false},sources:[h?.meta,state.log?.meta].filter(Boolean),errors:{...state.errors},limits:LIMITS};}
142
- function page(kind,offset=0){if(!['done','pending','risks','decisions','recent'].includes(kind)||!Number.isSafeInteger(offset)||offset<0)throw Error('query');const items=kind==='recent'?state.log?.entries||[]:state.handoff?.collections[kind]||[];if(offset>items.length)throw Error('query');return{version,kind,offset,total:items.length,items:items.slice(offset,offset+LIMITS.page),next:offset+LIMITS.page<items.length?offset+LIMITS.page:null,previous:offset?Math.max(0,offset-LIMITS.page):null};}
143
- return{root,state,refresh,snapshot,page};
144
- }
1
+ // Read-only projection of existing Kit records. No AI calls, generated summaries or source writes.
2
+ import {openSync,closeSync,readSync,fstatSync,statSync,realpathSync,existsSync} from 'node:fs';
3
+ import path from 'node:path';
4
+ import {createHash} from 'node:crypto';
5
+ export const LIMITS={handoff:1024*1024,log:64*1024,recent:10,page:6,item:12000};
6
+ const names={
7
+ 'task-understanding-summary':'understanding','active-objective':'current','completed-this-session':'done',
8
+ 'next-priorities':'pending','risks-blockers':'risks','confirmed-decisions':'decisions'
9
+ };
10
+ const headings={
11
+ 'task understanding summary':'understanding','任務理解摘要':'understanding','active objective':'current','目前目標':'current',
12
+ 'completed this session':'done','本次完成':'done','本次已完成':'done','next priorities':'pending','下一步':'pending','下一步優先事項':'pending',
13
+ 'risks / blockers':'risks','風險與阻礙':'risks','風險 / 阻礙':'risks','confirmed decisions':'decisions','已確認決策':'decisions'
14
+ };
15
+ export const hash=v=>createHash('sha256').update(v).digest('hex');
16
+ const clean=s=>s.replace(/<!--.*?-->/g,'').replace(/^\s*(?:[-*+] |\d+[.)] )/,'').replace(/\*\*/g,'').trim();
17
+ const missing=s=>!s||/^(?:TBD|待填|尚未記錄|未提供)(?:\b|\s|$)/i.test(s)||/^<[^>]+>$/.test(s)||/^[^::]{1,90}[::]\s*(?:TBD|待填)(?:\b|\s|$)/i.test(s)||/^Record only work actually completed in the current session\./.test(s);
18
+ // Defensive display redaction. Source files remain untouched.
19
+ export const safe=s=>s.replace(/\b(?:sk-(?:ant-)?|gh[pousr]_|github_pat_|xox[baprs]-|AIza|AKIA)[A-Za-z0-9_-]{16,}/g,'<REDACTED>');
20
+ function item(text,file,line){text=safe(clean(text));return{id:hash(file+':'+line+':'+text).slice(0,16),text:text.slice(0,LIMITS.item),clipped:text.length>LIMITS.item,source:{file,line}};}
21
+
22
+ export function markdown(text,{prefix=false}={}){
23
+ const lines=text.replace(/^\uFEFF/,'').split(/\r?\n/),sections=[];let fence=null,current=null,marker=null,title='',inComment=false,entryMarked=false,listContext=false;
24
+ for(let i=0;i<lines.length;i++){
25
+ let raw=lines[i];if(inComment){const end=raw.indexOf('-->');if(end<0)continue;raw=raw.slice(end+3);inComment=false;}
26
+ const f=raw.match(/^\s{0,3}(`{3,}|~{3,})(.*)$/);
27
+ if(f){if(!fence)fence=f[1];else if(f[1][0]===fence[0]&&f[1].length>=fence.length&&!f[2].trim())fence=null;continue;}if(fence)continue;
28
+ if(/^(?: {4}|\t)/.test(raw)&&!listContext)continue;
29
+ if(/^\s*<!-- ack:log-entry:start -->\s*$/.test(raw)){entryMarked=true;continue;}
30
+ if(/^\s*<!-- ack:log-entry:end -->\s*$/.test(raw)){if(current)current.entryClosed=true;continue;}
31
+ const m=raw.match(/^\s*<!-- ack:section:([a-z-]+) -->\s*$/);if(m){marker=m[1];continue;}
32
+ while(raw.includes('<!--')){const start=raw.indexOf('<!--'),end=raw.indexOf('-->',start+4);if(end<0){raw=raw.slice(0,start);inComment=true;break;}raw=raw.slice(0,start)+raw.slice(end+3);}
33
+ if(/^# [^#]/.test(raw)&&!title)title=raw.slice(2).trim();
34
+ const h=raw.match(/^## (?!#)(.+?)\s*#*$/);
35
+ if(h){if(current)current.end=i;current={title:h[1],key:names[marker]||headings[h[1].toLowerCase()]||null,line:i+1,rows:[],end:null,entryMarked,entryClosed:false};sections.push(current);marker=null;entryMarked=false;listContext=false;continue;}
36
+ if(raw.trim()&&marker)marker=null;
37
+ if(/^(?:[-*+] |\d+[.)] )/.test(raw))listContext=true;else if(raw.trim()&&!/^\s/.test(raw))listContext=false;
38
+ if(current)current.rows.push({text:raw,line:i+1});
39
+ }
40
+ if((fence||inComment)&&!prefix)throw Error('incomplete');
41
+ if(current&&!prefix)current.end=lines.length;
42
+ return{title,sections};
43
+ }
44
+ function blocks(section,file){
45
+ if(!section)return[];const out=[];let buffer=[],line=0;
46
+ const following=new Array(section.rows.length);let nextRow=null;
47
+ for(let i=section.rows.length-1;i>=0;i--){following[i]=nextRow;if(section.rows[i].text.trim())nextRow=section.rows[i];}
48
+ const flush=()=>{const text=buffer.join(' ').trim();if(text&&!missing(clean(text)))out.push(item(text,file,line));buffer=[];};
49
+ for(let i=0;i<section.rows.length;i++){
50
+ const row=section.rows[i];
51
+ if(!row.text.trim()){const next=following[i];if(buffer.length&&/^(?:[-*+] |\d+[.)] )/.test(buffer[0])&&next&&/^\s+\S/.test(next.text))continue;flush();continue;}
52
+ if(/^#{3,}\s/.test(row.text)){flush();continue;}
53
+ if(/^(?:[-*+] |\d+[.)] )/.test(row.text)){flush();line=row.line;buffer=[row.text];}
54
+ else{if(!buffer.length)line=row.line;buffer.push(row.text);}
55
+ }flush();return out;
56
+ }
57
+ const fieldNames=['Parent outcome / consumer','Current step','Task position','User intent','Task essence','User value','Resume point','Remaining acceptance','Completed within this task','Remaining acceptance / resume point','Recommended next step','專案目標','最終目標','目前階段','目前工作','任務位置','用戶意圖'];
58
+ const fieldPattern=new RegExp('(?:^|[.。]\\s+|\\s+(?=(?:Current step|目前階段)[::]))('+fieldNames.map(s=>s.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')).join('|')+')[::]\\s*','gi');
59
+ function field(items,keys){for(const row of items){const matches=[...row.text.matchAll(fieldPattern)];for(let i=0;i<matches.length;i++){if(!keys.includes(matches[i][1].toLowerCase()))continue;const start=matches[i].index+matches[i][0].length,end=matches[i+1]?.index??row.text.length,value=row.text.slice(start,end).trim();if(!missing(value))return{...row,text:value};}}return null;}
60
+
61
+ export function parseHandoff(text,rootName='Project'){
62
+ const parsed=markdown(text),groups={};
63
+ for(const s of parsed.sections)if(s.key){if(groups[s.key])throw Error('duplicate');groups[s.key]=s;}
64
+ if(!groups.current||!groups.pending||!groups.risks)throw Error('structure');
65
+ const file='dev/SESSION_HANDOFF.md',all=Object.fromEntries(Object.entries(groups).map(([k,v])=>[k,blocks(v,file)]));
66
+ const understanding=all.understanding||[],active=all.current||[];
67
+ const goal=field([...understanding,...active],['parent outcome / consumer','專案目標','最終目標'])||field(understanding,['user intent','用戶意圖']);
68
+ const current=field(active,['current step','目前階段','目前工作'])||active.find(x=>!fieldNames.some(label=>x.text.toLowerCase().startsWith(label.toLowerCase()+':')||x.text.toLowerCase().startsWith(label.toLowerCase()+':')))||null;
69
+ const position=field(understanding,['task position','任務位置']);
70
+ const title=parsed.title.replace(/\s+(?:Session\s+)?Handoff$/i,'').replace(/\s*交接(?:包|紀錄)?$/,'').trim();
71
+ const name=!title||/^(?:Session|Handoff|Session Handoff)$/i.test(parsed.title)?rootName:title;
72
+ const updated=text.match(/^Last Updated:\s*(.+)$/mi)?.[1]||text.match(/^最後更新[::]\s*(.+)$/m)?.[1]||null;
73
+ const collections={};for(const k of ['done','pending','risks','decisions'])collections[k]=all[k]||[];
74
+ // Preserve source wording. Never infer that a child result completes the parent.
75
+ return{name,goal,current,position,updated:missing(updated)?null:updated,collections,missingSections:['done','decisions'].filter(k=>!groups[k])};
76
+ }
77
+ // One event reader for both the bounded home prefix and paged history.
78
+ export function logEntry(s,file,startLine=1){
79
+ if(!/^\d{4}-\d{2}-\d{2}\s*[—–-]/.test(s.title)||s.entryMarked&&!s.entryClosed)return null;
80
+ const date=s.title.slice(0,10);if(Number.isNaN(Date.parse(date))||new Date(date+'T00:00:00Z').toISOString().slice(0,10)!==date)return null;
81
+ const fields={};let active=null;const prose=[];
82
+ for(const row of s.rows){
83
+ const text=safe(clean(row.text)),nested=/^(?: {2,}|\t)/.test(row.text);
84
+ const m=!nested&&text.match(/^([A-Za-z][A-Za-z0-9 _/-]{0,80})[::]\s*(.*)$/);
85
+ if(m){active=m[1].toLowerCase();fields[active]=missing(m[2])||/^[—-]$/.test(m[2])?'':m[2];}
86
+ else if(nested&&active&&text)fields[active]+=(fields[active]?'\n':'')+text;
87
+ else if(text){active=null;prose.push(text);}
88
+ }
89
+ for(const key of Object.keys(fields))if(!fields[key])delete fields[key];
90
+ const body=safe(s.rows.map(x=>x.text).join('\n').trim()),explicit=fields['event id'];
91
+ return{id:hash(explicit?'id:'+explicit:s.title+'\n'+body).slice(0,24),fingerprint:hash(s.title+'\n'+body),date,title:safe(s.title.slice(10).replace(/^\s*[—–-]\s*/,'')),titleZh:fields['title zh-hant']||null,summary:fields.summary||fields.done||prose[0]||'',summaryZh:fields['summary zh-hant']||null,work:fields.work||null,fields,body,source:{file,line:startLine+s.line-1}};
92
+ }
93
+ export function parseLog(text,limited=false){
94
+ const {sections}=markdown(text,{prefix:limited}),entries=[];
95
+ for(const s of sections){
96
+ if(!/^\d{4}-\d{2}-\d{2}\s*[—–-]/.test(s.title))continue;
97
+ if((limited&&s.end===null&&!s.entryClosed)||(s.entryMarked&&!s.entryClosed))continue; // Never display an unclosed or chopped entry as complete.
98
+ const entry=logEntry(s,'dev/SESSION_LOG.md');if(!entry)continue;
99
+ entries.push({...entry,title:safe(s.title),summary:entry.summary?item(entry.summary,entry.source.file,s.line):null,body:entry.body.slice(0,LIMITS.item)});
100
+ if(entries.length===LIMITS.recent)break;
101
+ }
102
+ return{entries,limited:limited||sections.filter(s=>/^\d{4}-\d{2}-\d{2}\s*[—–-]/.test(s.title)).length>LIMITS.recent};
103
+ }
104
+ export function readBounded(root,file,limit,{prefix=false}={}){
105
+ const target=path.join(root,file),real=realpathSync(target),relative=path.relative(root,real);
106
+ if(relative.startsWith('..')||path.isAbsolute(relative))throw Error('boundary');
107
+ const fd=openSync(real,'r');try{
108
+ const before=fstatSync(fd);if(!before.isFile()||(!prefix&&before.size>limit))throw Error('capacity');
109
+ const checked=realpathSync(target),relativeNow=path.relative(root,checked);
110
+ if(checked!==real||relativeNow.startsWith('..')||path.isAbsolute(relativeNow)||statSync(checked).ino!==before.ino)throw Error('boundary');
111
+ const count=Math.min(before.size,limit),buffer=Buffer.alloc(count);let offset=0;
112
+ while(offset<count){const n=readSync(fd,buffer,offset,count-offset,offset);if(!n)throw Error('unstable');offset+=n;}
113
+ const after=fstatSync(fd),now=statSync(target);
114
+ if(before.size!==after.size||before.mtimeMs!==after.mtimeMs||now.ino!==before.ino||now.size!==before.size||now.mtimeMs!==before.mtimeMs)throw Error('unstable');
115
+ const limited=before.size>limit;let content=new TextDecoder('utf-8',{fatal:true}).decode(limited?buffer.subarray(0,Math.max(0,buffer.lastIndexOf(10)+1)):buffer);
116
+ return{text:content,hash:hash(content),bytesRead:offset,limited,mtime:new Date(before.mtimeMs).toISOString()};
117
+ }finally{closeSync(fd);}
118
+ }
119
+ export function signature(root,file){try{const target=path.join(root,file),real=realpathSync(target),r=path.relative(root,real);if(r.startsWith('..')||path.isAbsolute(r))return'boundary';const s=statSync(target);return[s.ino,s.size,s.mtimeMs,s.ctimeMs].join(':');}catch(e){return e.code==='ENOENT'?'missing':'unreadable';}}
120
+ export function createSource(projectRoot){
121
+ const root=realpathSync(path.resolve(projectRoot)),files=['dev/SESSION_HANDOFF.md','dev/SESSION_LOG.md'];
122
+ const state={handoff:null,log:null,errors:{},metrics:{reads:0,bytes:0,handoffBytes:0,logBytes:0},rootName:path.basename(root)};
123
+ const seen=new Map(),pending=new Map();let previous='',version=0;
124
+ function refresh({immediate=false}={}){
125
+ if(existsSync(path.join(root,'dev/governance_migrations/.upgrade.lock'))){state.errors.lock='upgrade';}
126
+ else{
127
+ delete state.errors.lock;
128
+ for(const file of files){const key=file.includes('HANDOFF')?'handoff':'log',sig=signature(root,file);
129
+ if(seen.get(file)===sig&&!['unreadable','unstable'].includes(state.errors[key]))continue;
130
+ if(!immediate&&pending.get(file)!==sig){pending.set(file,sig);continue;}
131
+ try{
132
+ const read=readBounded(root,file,LIMITS[key],{prefix:key==='log'});state.metrics.reads++;state.metrics.bytes+=read.bytesRead;state.metrics[key+'Bytes']=read.bytesRead;
133
+ const parsed=key==='handoff'?parseHandoff(read.text,state.rootName):parseLog(read.text,read.limited);
134
+ state[key]={...parsed,meta:{file,updated:read.mtime,hash:read.hash,bytesRead:read.bytesRead,limited:read.limited}};if(key==='handoff')state.acceptedHandoff=read.text;delete state.errors[key];
135
+ }catch(e){state.errors[key]=['capacity','boundary','structure','incomplete','duplicate','unstable'].includes(e.message)?e.message:sig==='missing'?'missing':'unreadable';}
136
+ seen.set(file,sig);pending.delete(file);
137
+ }
138
+ }
139
+ const value=JSON.stringify({handoff:state.handoff,log:state.log,errors:state.errors});if(value===previous)return false;previous=value;version++;return true;
140
+ }
141
+ function snapshot(){const h=state.handoff;return{schemaVersion:2,version,project:{name:h?.name||state.rootName,goal:h?.goal||null,current:h?.current||null,position:h?.position||null},recordDate:h?.updated||null,available:!!h,sections:Object.fromEntries(['done','pending','risks','decisions'].map(k=>[k,{items:(h?.collections[k]||[]).slice(0,k==='risks'?2:3),total:h?.collections[k]?.length||null}])),recent:{items:(state.log?.entries||[]).slice(0,3),total:state.log?.entries.length??null,limited:state.log?.limited||false},sources:[h?.meta,state.log?.meta].filter(Boolean),errors:{...state.errors},limits:LIMITS};}
142
+ function page(kind,offset=0){if(!['done','pending','risks','decisions','recent'].includes(kind)||!Number.isSafeInteger(offset)||offset<0)throw Error('query');const items=kind==='recent'?state.log?.entries||[]:state.handoff?.collections[kind]||[];if(offset>items.length)throw Error('query');return{version,kind,offset,total:items.length,items:items.slice(offset,offset+LIMITS.page),next:offset+LIMITS.page<items.length?offset+LIMITS.page:null,previous:offset?Math.max(0,offset-LIMITS.page):null};}
143
+ return{root,state,refresh,snapshot,page};
144
+ }