@adamchanadam/agent-handoff-kit 0.3.66 → 0.4.0
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.en.md +230 -197
- package/README.md +222 -189
- package/bin/agent-handoff-kit.mjs +200 -59
- package/bin/commands.mjs +86 -0
- package/bin/handoff-read.mjs +88 -0
- package/bin/migration-baselines/official-origin-catalog.json +381 -1
- package/bin/progress/ICON-LICENSE.txt +21 -0
- package/bin/progress/agent-handoff-kit-logo2-256.png +0 -0
- package/bin/progress/dashboard-hero.png +0 -0
- package/bin/progress/dashboard.mjs +134 -0
- package/bin/progress/icons.svg +36 -0
- package/bin/progress/index.html +28 -0
- package/bin/progress/open.mjs +42 -0
- package/bin/progress/projection.mjs +144 -0
- package/bin/progress/renderer.js +151 -0
- package/bin/progress/server.mjs +76 -0
- package/bin/progress/styles.css +31 -0
- package/docs/commands.md +59 -0
- package/docs/progress.md +67 -0
- package/package.json +3 -1
- package/packs/closeout.md +72 -67
- package/runtime-core/AGENTS.core.md +124 -103
- package/runtime-core/PROJECT_INDEX.md +8 -1
- package/runtime-core/SESSION_HANDOFF.md +158 -148
- package/runtime-core/SESSION_LOG.md +2 -0
- package/runtime-core/START_NEXT_SESSION_PROMPT.txt +1 -1
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) Tailwind Labs, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// Deterministic, read-only dashboard. Existing Markdown remains authoritative.
|
|
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
|
+
import {readBounded,signature,markdown,safe,logEntry} from './projection.mjs';
|
|
6
|
+
import {parseProjectIndexTemplateVersion} from '../upgrade-inventory.mjs';
|
|
7
|
+
|
|
8
|
+
export const DASH_LIMITS=Object.freeze({document:1024*1024,metadata:512*1024,items:128,documents:160,historyBytes:256*1024,historyFiles:4,historyPage:20,entryBytes:64*1024,cursors:32});
|
|
9
|
+
const digest=s=>createHash('sha256').update(s).digest('hex');
|
|
10
|
+
const states=new Set(['planned','active','waiting','review','done','paused','dropped']);
|
|
11
|
+
const clean=s=>safe(String(s||'').replace(/\*\*/g,'').replace(/^\s*[-*]\s+/,'').trim());
|
|
12
|
+
const placeholder=s=>!s||s==='TBD'||/^<.*>$/.test(s)||s==='—'||s==='-';
|
|
13
|
+
const lines=s=>s.replace(/^\uFEFF/,'').split(/\r?\n/);
|
|
14
|
+
const key=s=>clean(s).toLowerCase();
|
|
15
|
+
const known=[
|
|
16
|
+
['handoff','dev/SESSION_HANDOFF.md','handoff','current'],['log','dev/SESSION_LOG.md','log','history'],
|
|
17
|
+
['archive','dev/SESSION_LOG_archive/INDEX.md','archive','history'],['index','dev/PROJECT_INDEX.md','index','reference'],
|
|
18
|
+
['rules','AGENTS.md','rules','rules'],['packs','dev/RULE_PACKS.md','packs','rules'],
|
|
19
|
+
['decisions','dev/PROJECT_DECISIONS.md','decisions','reference'],['sync','dev/DOC_SYNC_REGISTRY.md','sync','reference']
|
|
20
|
+
];
|
|
21
|
+
function section(text,title){return markdown(text).sections.find(s=>key(s.title)===title.toLowerCase());}
|
|
22
|
+
function table(section){
|
|
23
|
+
if(!section)return[];let headers=null,out=[];
|
|
24
|
+
for(const r of section.rows){if(!r.text.trim().startsWith('|'))continue;const cells=r.text.trim().replace(/^\||\|$/g,'').split(/(?<!\\)\|/).map(x=>clean(x.replace(/\\\|/g,'|')));
|
|
25
|
+
if(cells.every(x=>/^:?-+:?$/.test(x)))continue;
|
|
26
|
+
if(!headers){headers=cells.map(key);continue;}
|
|
27
|
+
out.push({...Object.fromEntries(headers.map((h,i)=>[h,cells[i]||''])),line:r.line});
|
|
28
|
+
}return out;
|
|
29
|
+
}
|
|
30
|
+
function fields(s){const out={};for(const r of s?.rows||[]){const m=clean(r.text).match(/^([^::]+)[::]\s*(.*)$/);if(m&&!placeholder(m[2]))out[key(m[1])]=m[2];}return out;}
|
|
31
|
+
function relativeFile(value){
|
|
32
|
+
const s=String(value||'').replace(/`/g,'').split('#')[0];
|
|
33
|
+
if(!s||s.includes('\\')||s.includes('\0')||path.isAbsolute(s)||/^[a-z]+:/i.test(s)||s.split('/').some(x=>!x||x==='.'||x==='..'||x.startsWith('.'))||/(?:^|\/)(?:node_modules|governance_migrations)(?:\/|$)/i.test(s)||/(?:credential|secret|\.env|private.key)/i.test(s))return null;
|
|
34
|
+
return s;
|
|
35
|
+
}
|
|
36
|
+
function checked(root,file){const rel=relativeFile(file);if(!rel)throw Error('boundary');const real=realpathSync(path.join(root,rel)),r=path.relative(root,real);if(r.startsWith('..')||path.isAbsolute(r))throw Error('boundary');if(!statSync(real).isFile())throw Error('not_file');return real;}
|
|
37
|
+
|
|
38
|
+
export function parseWork(text){
|
|
39
|
+
const sections=markdown(text).sections.filter(s=>key(s.title)==='work items');if(sections.length>1)throw Error('work_format');
|
|
40
|
+
const s=sections[0];if(!s)return {items:[],recorded:false};
|
|
41
|
+
if(!s.rows.some(r=>/^\|\s*ID\s*\|\s*Title\s*\|\s*Status\s*\|\s*Parent\s*\|\s*Summary\s*\|\s*Source\s*\|/i.test(r.text.trim())))throw Error('work_format');
|
|
42
|
+
const rows=table(s).filter(r=>!placeholder(r.id));if(rows.length>DASH_LIMITS.items)throw Error('work_capacity');
|
|
43
|
+
const ids=new Set();const items=rows.map(r=>{
|
|
44
|
+
if(!/^[a-z0-9][a-z0-9_-]{0,63}$/i.test(r.id)||ids.has(r.id)||!states.has(r.status)||placeholder(r.title))throw Error('work_format');ids.add(r.id);
|
|
45
|
+
const source=placeholder(r.source)?null:relativeFile(r.source);if(!placeholder(r.source)&&!source)throw Error('work_source');
|
|
46
|
+
return {id:r.id,title:r.title,titleZh:r['title zh-hant']||null,status:r.status,parent:placeholder(r.parent)?null:r.parent,summary:r.summary||'',summaryZh:r['summary zh-hant']||null,artifact:source,source:{file:'dev/SESSION_HANDOFF.md',line:r.line}};
|
|
47
|
+
});
|
|
48
|
+
for(const item of items){let at=item,seen=new Set();while(at.parent){if(seen.has(at.id))throw Error('work_cycle');seen.add(at.id);at=items.find(x=>x.id===at.parent);if(!at)throw Error('work_parent');}}
|
|
49
|
+
return {items,recorded:true};
|
|
50
|
+
}
|
|
51
|
+
export function parseProfile(text){const f=fields(section(text,'Project'));return {name:f.name||null,nameZh:f['name zh-hant']||null,goal:f.goal||null,goalZh:f['goal zh-hant']||null};}
|
|
52
|
+
|
|
53
|
+
function logEntries(text,file,startLine=1){
|
|
54
|
+
return markdown(text).sections.map(s=>logEntry(s,file,startLine)).filter(Boolean);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function createDashboard(root,source){
|
|
58
|
+
root=realpathSync(root);const cache=new Map(),cursors=new Map(),watched=new Map();let acceptedIndex=null,projectKitVersion=null,historyRevision=0,revision=0,work={items:[],recorded:false},profile={},docs=[],links=[],errors={},last='';
|
|
59
|
+
function read(file,limit=DASH_LIMITS.metadata){const sig=signature(root,file),old=cache.get(file);if(old?.sig===sig)return old;try{const r=readBounded(root,file,limit);const v={...r,sig};cache.set(file,v);return v;}catch(e){const v={sig,error:e.message,previous:old?.error?old.previous:old};cache.set(file,v);return v;}}
|
|
60
|
+
function refresh(){if(existsSync(path.join(root,'dev/governance_migrations/.upgrade.lock')))return false;
|
|
61
|
+
errors={};const h=source?.state?{text:source.state.acceptedHandoff,error:source.state.errors.handoff||(!source.state.acceptedHandoff?'unavailable':null)}:read('dev/SESSION_HANDOFF.md',DASH_LIMITS.document);let i=read('dev/PROJECT_INDEX.md');
|
|
62
|
+
projectKitVersion=i.error?null:parseProjectIndexTemplateVersion(i.text);
|
|
63
|
+
if(!h.error){try{work=parseWork(h.text);}catch(e){errors.work=e.message;}}else errors.work=h.error;
|
|
64
|
+
if(!i.error){try{const next=parseProfile(i.text);const block=section(i.text,'Project');if((profile.name||profile.goal)&&!block||block&&!block.rows.some(r=>/^(?:-\s*)?Name:\s*\S/.test(r.text)))throw Error('index_format');profile=next;acceptedIndex=i;}catch{errors.index='format';i=acceptedIndex||{error:'format'};}}else{if(i.sig!=='missing'||acceptedIndex)errors.index=i.error;if(acceptedIndex)i=acceptedIndex;}
|
|
65
|
+
const all=known.map(([id,file,role,group])=>({id,file,role,group,title:null,registered:true}));
|
|
66
|
+
if(!i.error){for(const r of table(section(i.text,'Directory Map'))){const file=relativeFile(r.path);if(file&&!all.some(x=>x.file===file)&&/\.(md|txt|html|pdf|csv|json)$/i.test(file))all.push({id:digest(file).slice(0,16),file,role:'document',group:'reference',title:r.role||file,registered:true,source:{file:'dev/PROJECT_INDEX.md',line:r.line}});}}
|
|
67
|
+
for(const item of work.items)if(item.artifact&&!all.some(x=>x.file===item.artifact))all.push({id:digest(item.artifact).slice(0,16),file:item.artifact,role:'artifact',group:'results',title:item.title,titleZh:item.titleZh,registered:true,source:item.source});
|
|
68
|
+
if(all.length>DASH_LIMITS.documents)errors.documents='capacity';
|
|
69
|
+
docs=all.slice(0,DASH_LIMITS.documents).map(d=>{try{const st=statSync(checked(root,d.file));return {...d,available:true,updated:new Date(st.mtimeMs).toISOString(),bytes:st.size};}catch{return {...d,available:false};}});
|
|
70
|
+
links=[['index','handoff','routes'],['rules','handoff','governs'],['packs','rules','routes'],['log','archive','archives']].filter(([a,b])=>docs.some(x=>x.id===a&&x.available)&&docs.some(x=>x.id===b&&x.available)).map(([from,to,type])=>({from,to,type,basis:'kit-contract'}));
|
|
71
|
+
// Project-specific links must be explicit, never inferred from prose or filenames.
|
|
72
|
+
if(!i.error)for(const r of table(section(i.text,'Document Relations'))){const a=docs.find(x=>x.file===relativeFile(r.from)),b=docs.find(x=>x.file===relativeFile(r.to));if(a&&b&&['references','routes','mirrors','checks'].includes(r.relation))links.push({from:a.id,to:b.id,type:r.relation,basis:'dev/PROJECT_INDEX.md',line:r.line});}
|
|
73
|
+
for(const file of ['dev/SESSION_LOG.md','dev/SESSION_LOG_archive/INDEX.md',...watched.keys()]){const sig=signature(root,file);if(watched.has(file)&&watched.get(file)!==sig)historyRevision++;watched.set(file,sig);}
|
|
74
|
+
const value=JSON.stringify({work,profile,projectKitVersion,docs,links,errors,historyRevision});if(value===last)return false;last=value;revision++;return true;
|
|
75
|
+
}
|
|
76
|
+
function snapshot(){return{revision,historyRevision,work,profile,projectKitVersion,documents:docs,links,errors,limits:DASH_LIMITS};}
|
|
77
|
+
function document(id){if(existsSync(path.join(root,'dev/governance_migrations/.upgrade.lock')))throw Error('upgrade');const doc=docs.find(x=>x.id===id);if(!doc)throw Error('unknown_document');checked(root,doc.file);if(!/\.(md|txt|csv|json)$/i.test(doc.file))return{...doc,text:null,reason:'preview_unavailable'};const r=readBounded(root,doc.file,DASH_LIMITS.document);return{...doc,text:safe(r.text),updated:r.mtime,hash:r.hash};}
|
|
78
|
+
function history({from='',to='',search='',work:workId='',cursor=''}={}){
|
|
79
|
+
if(existsSync(path.join(root,'dev/governance_migrations/.upgrade.lock')))throw Error('upgrade');
|
|
80
|
+
for(const d of [from,to])if(d&&(!/^\d{4}-\d{2}-\d{2}$/.test(d)||Number.isNaN(Date.parse(d))||new Date(d+'T00:00:00Z').toISOString().slice(0,10)!==d))throw Error('date');if(from&&to&&from>to)throw Error('date');if(search.length>100||workId.length>64)throw Error('query');
|
|
81
|
+
const query={from,to,search,workId},q=digest(JSON.stringify(query));let job;
|
|
82
|
+
if(cursor){job=cursors.get(cursor);if(!job||job.q!==q||Date.now()-job.created>15*60_000)throw Error('expired');cursors.delete(cursor);for(const [file,sig]of Object.entries(job.signatures))if(signature(root,file)!==sig)throw Error('history_changed');}
|
|
83
|
+
else{
|
|
84
|
+
const files=['dev/SESSION_LOG.md'],warnings=[];const idx=read('dev/SESSION_LOG_archive/INDEX.md');
|
|
85
|
+
if(!idx.error){const block=section(idx.text,'Batch 清單')||section(idx.text,'Batches')||markdown(idx.text).sections.find(s=>s.rows.some(x=>/\|.*(?:File path|Path).*\|/i.test(x.text)));const rows=table(block);
|
|
86
|
+
if(!block||!block.rows.some(r=>/\|.*Date range.*\|.*(?:File path|Path).*\|/i.test(r.text)))warnings.push('archive_index');
|
|
87
|
+
for(const r of rows){const file=String(r['file path']||r.path||'').replace(/`/g,'');const rel=relativeFile('dev/SESSION_LOG_archive/'+file);if(!rel||!/^archive_[\w.-]+\.md$/.test(file)){warnings.push('archive_index');continue;}
|
|
88
|
+
const dates=String(r['date range']||'').match(/\d{4}-\d{2}-\d{2}/g);if(!dates||dates.length!==2||dates[0]>dates[1]||dates.some(d=>Number.isNaN(Date.parse(d))||new Date(d+'T00:00:00Z').toISOString().slice(0,10)!==d)){warnings.push('archive_range');files.push(rel);continue;}
|
|
89
|
+
if((!from||dates[1]>=from)&&(!to||dates[0]<=to))files.push(rel);
|
|
90
|
+
}
|
|
91
|
+
}else if(idx.sig!=='missing')warnings.push('archive_index');
|
|
92
|
+
else if(existsSync(path.join(root,'dev/SESSION_LOG_archive')))warnings.push('archive_index');
|
|
93
|
+
job={q,query,files:[...new Set(files)],index:0,offset:0,line:1,buffer:'',entry:'',entryLine:1,fence:null,seen:{},queue:[],warnings:[...new Set(warnings)],created:Date.now(),signatures:{'dev/SESSION_LOG_archive/INDEX.md':signature(root,'dev/SESSION_LOG_archive/INDEX.md')},bytes:0};
|
|
94
|
+
}
|
|
95
|
+
// Bound every request independently of total history. Resume byte offsets using an opaque cursor.
|
|
96
|
+
let budget=DASH_LIMITS.historyBytes,fileBudget=DASH_LIMITS.historyFiles;
|
|
97
|
+
const emit=(text,file,line)=>{try{if(text.includes('<!-- ack:log-entry:start -->')&&!text.includes('<!-- ack:log-entry:end -->'))job.warnings.push('incomplete_entry');for(const item of logEntries(text,file,line)){
|
|
98
|
+
if(from&&item.date<from||to&&item.date>to||workId&&item.work!==workId||search&&!`${item.title}\n${item.body}`.toLocaleLowerCase().includes(search.toLocaleLowerCase()))continue;
|
|
99
|
+
if(job.seen[item.id]){if(job.seen[item.id]!==item.fingerprint)job.warnings.push('event_conflict');continue;}job.seen[item.id]=item.fingerprint;job.queue.push(item);
|
|
100
|
+
}}catch{job.warnings.push('incomplete_entry');}};
|
|
101
|
+
while(job.queue.length<DASH_LIMITS.historyPage&&job.index<job.files.length&&budget>0&&fileBudget>0){
|
|
102
|
+
const file=job.files[job.index];let fd;
|
|
103
|
+
try{
|
|
104
|
+
const real=checked(root,file),sig=signature(root,file);if(job.signatures[file]&&job.signatures[file]!==sig)throw Error('history_changed');job.signatures[file]=sig;
|
|
105
|
+
if(watched.size>=130&&!watched.has(file)){const victim=[...watched.keys()].find(x=>x.includes('/archive_'));if(victim)watched.delete(victim);}watched.set(file,sig);
|
|
106
|
+
fd=openSync(real,'r');const st=fstatSync(fd);if(st.size<job.offset)throw Error('history_changed');
|
|
107
|
+
const len=Math.min(32768,budget,st.size-job.offset),buf=Buffer.alloc(len);const n=readSync(fd,buf,0,len,job.offset);job.offset+=n;budget-=n;job.bytes+=n;
|
|
108
|
+
// Buffer bytes between chunks so a multi-byte UTF-8 character is never split.
|
|
109
|
+
const pending=Buffer.concat([Buffer.from(job.buffer,'base64'),buf.subarray(0,n)]);const end=job.offset===st.size?pending.length:pending.lastIndexOf(10)+1;
|
|
110
|
+
job.buffer=pending.subarray(end).toString('base64');if(pending.length>DASH_LIMITS.entryBytes&&end===0)throw Error('entry_capacity');
|
|
111
|
+
const text=new TextDecoder('utf-8',{fatal:true}).decode(pending.subarray(0,end));
|
|
112
|
+
for(const raw of text?text.split('\n').slice(0,text.endsWith('\n')?-1:undefined):[]){
|
|
113
|
+
const line=raw.replace(/\r$/,'');let visible=line;
|
|
114
|
+
if(!job.fence&&!/^\s*<!-- ack:log-entry:(?:start|end) -->\s*$/.test(line)){if(job.inComment){const end=visible.indexOf('-->');if(end<0)visible='';else{visible=visible.slice(end+3);job.inComment=false;}}while(visible.includes('<!--')){const start=visible.indexOf('<!--'),end=visible.indexOf('-->',start+4);if(end<0){visible=visible.slice(0,start);job.inComment=true;break;}visible=visible.slice(0,start)+visible.slice(end+3);}}
|
|
115
|
+
const f=visible.match(/^\s*(`{3,}|~{3,})(.*)$/);if(f){if(!job.fence)job.fence=f[1];else if(job.fence[0]===f[1][0]&&f[1].length>=job.fence.length&&!f[2].trim())job.fence=null;}
|
|
116
|
+
if(!job.fence&&!job.inComment&&/^\s*<!-- ack:log-entry:start -->\s*$/.test(line)){if(job.entry)emit(job.entry,file,job.entryLine);job.entry='';job.marked=true;job.line++;continue;}
|
|
117
|
+
const heading=!job.fence&&/^## \d{4}-\d{2}-\d{2}\s*[—–-]/.test(visible);
|
|
118
|
+
if(heading){if(job.entry)emit(job.entry,file,job.entryLine);job.entry=(job.marked?'<!-- ack:log-entry:start -->\n':'')+line+'\n';job.entryLine=job.line-(job.marked?1:0);job.marked=false;}
|
|
119
|
+
else if(job.entry)job.entry+=line+'\n';
|
|
120
|
+
if(Buffer.byteLength(job.entry)>DASH_LIMITS.entryBytes){job.entry='';job.warnings.push('entry_capacity');}job.line++;
|
|
121
|
+
}
|
|
122
|
+
if(signature(root,file)!==sig||fstatSync(fd).mtimeMs!==st.mtimeMs)throw Error('history_changed');
|
|
123
|
+
if(job.offset===st.size){if(job.entry)emit(job.entry,file,job.entryLine);if(job.marked||job.fence||job.inComment)job.warnings.push('incomplete_entry');job.index++;job.offset=0;job.line=1;job.entry='';job.buffer='';job.fence=null;job.marked=false;job.inComment=false;fileBudget--;}
|
|
124
|
+
}catch(e){if(e.message==='history_changed')throw e;job.warnings.push(e.message==='boundary'?'boundary':'history_unreadable');job.index++;job.offset=0;job.line=1;job.entry='';job.buffer='';job.fence=null;job.marked=false;fileBudget--;}
|
|
125
|
+
finally{if(fd!==undefined)closeSync(fd);}
|
|
126
|
+
}
|
|
127
|
+
job.queue.sort((a,b)=>b.date.localeCompare(a.date));const items=job.queue.splice(0,DASH_LIMITS.historyPage);const complete=job.index>=job.files.length&&!job.queue.length;
|
|
128
|
+
// Cap remembered deduplication identities; explicit coverage warning instead of silent unbounded growth.
|
|
129
|
+
if(Object.keys(job.seen).length>10000){job.warnings.push('history_capacity');job.index=job.files.length;job.queue=[];}
|
|
130
|
+
let next=null;if(!complete&&Object.keys(job.seen).length<=10000){next=digest(q+Date.now()+Math.random());job.created=Date.now();if(cursors.size>=DASH_LIMITS.cursors)cursors.delete(cursors.keys().next().value);cursors.set(next,job);}
|
|
131
|
+
return{items,next,complete:complete&&!job.warnings.length,warnings:[...new Set(job.warnings)],bytesRead:DASH_LIMITS.historyBytes-budget,filesChecked:job.index,totalFiles:job.files.length,range:{from,to},revision};
|
|
132
|
+
}
|
|
133
|
+
return{refresh,snapshot,document,history};
|
|
134
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg"><symbol id="document" viewBox="0 0 24 24">
|
|
2
|
+
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"/>
|
|
3
|
+
</symbol>
|
|
4
|
+
<symbol id="clock" viewBox="0 0 24 24">
|
|
5
|
+
<path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/>
|
|
6
|
+
</symbol>
|
|
7
|
+
<symbol id="check" viewBox="0 0 24 24">
|
|
8
|
+
<path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12c0 1.268-.63 2.39-1.593 3.068a3.745 3.745 0 0 1-1.043 3.296 3.745 3.745 0 0 1-3.296 1.043A3.745 3.745 0 0 1 12 21c-1.268 0-2.39-.63-3.068-1.593a3.746 3.746 0 0 1-3.296-1.043 3.745 3.745 0 0 1-1.043-3.296A3.745 3.745 0 0 1 3 12c0-1.268.63-2.39 1.593-3.068a3.745 3.745 0 0 1 1.043-3.296 3.746 3.746 0 0 1 3.296-1.043A3.746 3.746 0 0 1 12 3c1.268 0 2.39.63 3.068 1.593a3.746 3.746 0 0 1 3.296 1.043 3.746 3.746 0 0 1 1.043 3.296A3.745 3.745 0 0 1 21 12Z"/>
|
|
9
|
+
</symbol>
|
|
10
|
+
<symbol id="search" viewBox="0 0 24 24">
|
|
11
|
+
<path stroke-linecap="round" stroke-linejoin="round" d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"/>
|
|
12
|
+
</symbol>
|
|
13
|
+
<symbol id="close" viewBox="0 0 24 24">
|
|
14
|
+
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/>
|
|
15
|
+
</symbol>
|
|
16
|
+
<symbol id="arrow" viewBox="0 0 24 24">
|
|
17
|
+
<path stroke-linecap="round" stroke-linejoin="round" d="M13.5 4.5 21 12m0 0-7.5 7.5M21 12H3"/>
|
|
18
|
+
</symbol>
|
|
19
|
+
<symbol id="grid" viewBox="0 0 24 24">
|
|
20
|
+
<path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z"/>
|
|
21
|
+
</symbol>
|
|
22
|
+
<symbol id="archive" viewBox="0 0 24 24">
|
|
23
|
+
<path stroke-linecap="round" stroke-linejoin="round" d="m20.25 7.5-.625 10.632a2.25 2.25 0 0 1-2.247 2.118H6.622a2.25 2.25 0 0 1-2.247-2.118L3.75 7.5M10 11.25h4M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125Z"/>
|
|
24
|
+
</symbol>
|
|
25
|
+
<symbol id="map" viewBox="0 0 24 24">
|
|
26
|
+
<path stroke-linecap="round" stroke-linejoin="round" d="M9 6.75V15m6-6v8.25m.503 3.498 4.875-2.437c.381-.19.622-.58.622-1.006V4.82c0-.836-.88-1.38-1.628-1.006l-3.869 1.934c-.317.159-.69.159-1.006 0L9.503 3.252a1.125 1.125 0 0 0-1.006 0L3.622 5.689C3.24 5.88 3 6.27 3 6.695V19.18c0 .836.88 1.38 1.628 1.006l3.869-1.934c.317-.159.69-.159 1.006 0l4.994 2.497c.317.158.69.158 1.006 0Z"/>
|
|
27
|
+
</symbol>
|
|
28
|
+
<symbol id="calendar" viewBox="0 0 24 24">
|
|
29
|
+
<path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 0 1 2.25-2.25h13.5A2.25 2.25 0 0 1 21 7.5v11.25m-18 0A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75m-18 0v-7.5A2.25 2.25 0 0 1 5.25 9h13.5A2.25 2.25 0 0 1 21 11.25v7.5m-9-6h.008v.008H12v-.008ZM12 15h.008v.008H12V15Zm0 2.25h.008v.008H12v-.008ZM9.75 15h.008v.008H9.75V15Zm0 2.25h.008v.008H9.75v-.008ZM7.5 15h.008v.008H7.5V15Zm0 2.25h.008v.008H7.5v-.008Zm6.75-4.5h.008v.008h-.008v-.008Zm0 2.25h.008v.008h-.008V15Zm0 2.25h.008v.008h-.008v-.008Zm2.25-4.5h.008v.008H16.5v-.008Zm0 2.25h.008v.008H16.5V15Z"/>
|
|
30
|
+
</symbol>
|
|
31
|
+
<symbol id="link" viewBox="0 0 24 24">
|
|
32
|
+
<path stroke-linecap="round" stroke-linejoin="round" d="M13.19 8.688a4.5 4.5 0 0 1 1.242 7.244l-4.5 4.5a4.5 4.5 0 0 1-6.364-6.364l1.757-1.757m13.35-.622 1.757-1.757a4.5 4.5 0 0 0-6.364-6.364l-4.5 4.5a4.5 4.5 0 0 0 1.242 7.244"/>
|
|
33
|
+
</symbol>
|
|
34
|
+
<symbol id="copy" viewBox="0 0 24 24">
|
|
35
|
+
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 0 1-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 0 1 1.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 0 0-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 0 1-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 0 0-3.375-3.375h-1.5a1.125 1.125 0 0 1-1.125-1.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H9.75"/>
|
|
36
|
+
</symbol></svg>
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="zh-Hant">
|
|
3
|
+
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>專案總覽 · Agent Handoff Kit</title><link rel="icon" href="agent-handoff-kit-logo2-256.png"><link rel="stylesheet" href="styles.css"><script src="renderer.js" defer></script></head>
|
|
4
|
+
<body>
|
|
5
|
+
<a class="skip" href="#main" data-i18n="skip">跳到內容</a>
|
|
6
|
+
<header class="brandbar"><a class="brand" href="#overview"><img src="agent-handoff-kit-logo2-256.png" alt="" width="48" height="48"><span class="brand-label"><span>Agent Handoff Kit</span><small id="kit-version" class="kit-version"></small></span></a><nav aria-label="主要頁面 / Main navigation"><a href="#overview" data-view="overview" data-i18n="overview">總覽</a><a href="#history" data-view="history" data-i18n="history">歷程</a><a href="#documents" data-view="documents" data-i18n="documents">文件地圖</a></nav><div class="tools"><span id="sync" role="status"></span><select id="language" aria-label="介面語言 / Interface language"><option value="zh-Hant">繁中</option><option value="en">English</option></select></div></header>
|
|
7
|
+
<main id="main">
|
|
8
|
+
<p id="warning" class="warning" hidden role="status"></p>
|
|
9
|
+
<section id="overview-view" class="view" aria-labelledby="project-title">
|
|
10
|
+
<header class="project"><div class="project-copy"><p class="eyebrow" data-i18n="project">專案工作總覽</p><h1 id="project-title"></h1></div><img class="project-art" src="dashboard-hero.png" width="1536" height="1024" alt="" decoding="async"><div class="project-meta"><button id="freshness" class="quiet" data-action="sources"></button><button id="recorded-current" class="recorded-current quiet" data-document="handoff"></button></div></header>
|
|
11
|
+
<p id="empty" class="empty" hidden data-i18n="empty"></p>
|
|
12
|
+
<section class="journey" aria-labelledby="journey-title"><h2 id="journey-title" class="journey-label" data-i18n="workstreams">工作主線</h2><p id="work-scope" class="scope-note" hidden></p><div id="work-route" class="work-route"></div><button id="more-work" class="text-link" hidden data-action="all-work"></button><div id="focus" class="focus-panel"></div></section>
|
|
13
|
+
<div class="overview-grid">
|
|
14
|
+
<section class="panel recent-panel"><header class="section-heading"><h2><svg aria-hidden="true"><use href="icons.svg#clock"></use></svg><span data-i18n="recent">最近變更</span></h2><a href="#history" class="text-link" data-i18n="viewHistory">查看歷程</a></header><div id="recent-list" class="recent-list"></div></section>
|
|
15
|
+
<section class="panel outstanding-panel"><header class="section-heading"><h2><svg aria-hidden="true"><use href="icons.svg#check"></use></svg><span data-i18n="outstanding">待辦事項</span></h2><button data-action="all-work" class="text-link" data-i18n="allWork">全部工作</button></header><div class="pending-columns"><div id="pending-list"></div><div class="results"><h3 data-i18n="results">成果與參考</h3><div id="result-list"></div></div></div></section>
|
|
16
|
+
</div>
|
|
17
|
+
<section class="document-strip panel"><div class="strip-intro"><h2 data-i18n="documentRelations">文件關係</h2><p data-i18n="documentIntro">從目前交接,找回紀錄與依據。</p></div><div id="document-strip"></div><a href="#documents" class="text-link" data-i18n="viewMap">查看地圖</a></section>
|
|
18
|
+
</section>
|
|
19
|
+
<section id="history-view" class="view" hidden aria-labelledby="history-title"><header class="view-header"><div><p class="eyebrow" id="history-project"></p><h1 id="history-title" data-i18n="projectHistory">專案歷程</h1><p data-i18n="historyIntro">找回每次改變與交接的脈絡。</p></div></header>
|
|
20
|
+
<form id="history-filter" class="filterbar"><div class="segmented"><button type="button" data-days="7" data-i18n="last7">近7日</button><button type="button" data-days="30" data-i18n="last30">近30日</button><button type="button" data-days="all" data-i18n="allDates">全部日期</button></div><label><span data-i18n="from">由</span><input id="from" type="date"></label><label><span data-i18n="to">至</span><input id="to" type="date"></label><label><select id="history-work" aria-label="工作線 / Workstream"></select></label><label class="search-label"><svg aria-hidden="true"><use href="icons.svg#search"></use></svg><input id="search" type="search" maxlength="100" data-placeholder="search" aria-label="查找紀錄 / Search records"></label><button class="primary" type="submit" data-i18n="apply">查看</button></form>
|
|
21
|
+
<p class="scope-note" data-i18n="dateBoundary">日期只篩選歷程,目前未完事項不受影響。</p><div id="history-status" class="scope-note" role="status"></div><div id="history-list" class="timeline"></div><button id="history-more" class="secondary" hidden data-i18n="loadMore">載入更多紀錄</button>
|
|
22
|
+
</section>
|
|
23
|
+
<section id="documents-view" class="view" hidden aria-labelledby="documents-title"><header class="view-header"><div><p class="eyebrow" id="documents-project"></p><h1 id="documents-title" data-i18n="documentsHeading">文件各司其職</h1><p data-i18n="documentsIntro">點選文件,查看用途、來源與相關紀錄。</p></div><div class="segmented"><button id="map-mode" aria-pressed="true" data-i18n="map">地圖</button><button id="list-mode" aria-pressed="false" data-i18n="list">清單</button></div></header><p id="document-status" class="scope-note"></p><div id="document-map" class="document-map"></div><div id="map-detail" class="map-detail panel"></div><div id="document-list" class="document-list" hidden></div><p class="scope-note" data-i18n="mapBoundary">連線表示已記錄的文件角色或關係;不代表已驗收。</p></section>
|
|
24
|
+
<footer><p data-i18n="boundary">依已保存紀錄更新;未保存的工作不會出現在這裏。</p><button class="quiet" data-action="sources" data-i18n="sources">資料依據</button></footer>
|
|
25
|
+
<noscript><p class="warning">請啟用 JavaScript 以讀取紀錄。 / Please enable JavaScript to load records.</p></noscript>
|
|
26
|
+
</main>
|
|
27
|
+
<dialog id="drawer" aria-labelledby="drawer-title"><header><div><p id="drawer-kicker" class="eyebrow"></p><h2 id="drawer-title"></h2></div><button id="close" class="icon-button" aria-label="關閉 / Close"><svg aria-hidden="true"><use href="icons.svg#close"></use></svg></button></header><div id="drawer-content"></div></dialog><div id="announcement" class="sr-only" role="status" aria-live="polite"></div>
|
|
28
|
+
</body></html>
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
import {spawn} from 'node:child_process';
|
|
5
|
+
import {progressIdentity,openProgressBrowser} from './server.mjs';
|
|
6
|
+
import {createSource} from './projection.mjs';
|
|
7
|
+
const cli=fileURLToPath(new URL('../agent-handoff-kit.mjs',import.meta.url));
|
|
8
|
+
const sleep=ms=>new Promise(r=>setTimeout(r,ms));
|
|
9
|
+
export function probeProgress(port,{reopen=false}={}){
|
|
10
|
+
return new Promise(resolve=>{
|
|
11
|
+
let done=false,request,response,deadline;
|
|
12
|
+
const end=value=>{if(done)return;done=true;clearTimeout(deadline);response?.destroy();request?.destroy();resolve(value);};
|
|
13
|
+
// Inactivity timeouts alone can be kept alive by a foreign slow-trickle server.
|
|
14
|
+
deadline=setTimeout(()=>end(null),350);
|
|
15
|
+
request=http.get({hostname:'127.0.0.1',port,path:'/api/identity'+(reopen?'?reopen=1':'')},res=>{
|
|
16
|
+
response=res;let text='';if(res.statusCode!==200){end(null);return;}
|
|
17
|
+
res.on('data',chunk=>{text+=chunk;if(text.length>2048)end(null);});
|
|
18
|
+
res.on('end',()=>{try{end(JSON.parse(text));}catch{end(null);}});
|
|
19
|
+
res.on('error',()=>end(null));res.on('aborted',()=>end(null));
|
|
20
|
+
});
|
|
21
|
+
request.on('error',()=>end(null));
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
export async function openProgress({root,version,port=0,openBrowser=true}){
|
|
25
|
+
if(!Number.isInteger(port)||port<0||port>65535)throw Error('progress --port must be an integer from 0 to 65535');
|
|
26
|
+
root=path.resolve(root);const identity=progressIdentity(root,version);
|
|
27
|
+
const source=createSource(root);source.refresh({immediate:true});
|
|
28
|
+
if(source.state.errors.lock)throw Error('Upgrade lock exists; recover the Kit upgrade before opening progress.');
|
|
29
|
+
if(source.state.errors.handoff==='missing')throw Error('No dev/SESSION_HANDOFF.md found. Select an installed Kit project with --root.');
|
|
30
|
+
const ports=port?[port]:Array.from({length:12},(_,i)=>42000+((parseInt(identity.rootId.slice(0,8),16)+i)%18000));
|
|
31
|
+
const same=other=>other&&Object.keys(identity).every(key=>other[key]===identity[key]);
|
|
32
|
+
for(const candidate of ports){const existing=await probeProgress(candidate);if(same(existing)&&same(await probeProgress(candidate,{reopen:true}))){const url=`http://127.0.0.1:${candidate}`;if(openBrowser)openProgressBrowser(url);return{url,reused:true};}}
|
|
33
|
+
for(const candidate of ports){let error=null,ended=false;const child=spawn(process.execPath,[cli,'progress','--root',root,'--port',String(candidate),'--no-open'],{detached:true,windowsHide:true,stdio:'ignore'});
|
|
34
|
+
child.once('error',e=>{error=e;ended=true;});child.once('exit',()=>{ended=true;});
|
|
35
|
+
const deadline=Date.now()+6000;
|
|
36
|
+
while(Date.now()<deadline&&!ended){if(same(await probeProgress(candidate))){child.unref();const url=`http://127.0.0.1:${candidate}`;if(openBrowser)openProgressBrowser(url);return{url,reused:false,pid:child.pid};}await sleep(80);}
|
|
37
|
+
if(!ended)child.kill();if(error)throw Error('Could not start the local progress process.');
|
|
38
|
+
// Another invocation may have won the same port while our child exited.
|
|
39
|
+
if(same(await probeProgress(candidate))&&same(await probeProgress(candidate,{reopen:true}))){const url=`http://127.0.0.1:${candidate}`;if(openBrowser)openProgressBrowser(url);return{url,reused:true};}
|
|
40
|
+
}
|
|
41
|
+
throw Error('Could not open project progress. Check the project files and available loopback ports.');
|
|
42
|
+
}
|
|
@@ -0,0 +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
|
+
}
|