dsh-bufeng 0.0.0-stage → 0.64.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/LICENSE +21 -0
- package/README.md +68 -2
- package/bufeng.patch.yml +3 -0
- package/client/build-client.mjs +159 -0
- package/client/client.js +4038 -0
- package/client/src/board.js +133 -0
- package/client/src/capabilities.js +787 -0
- package/client/src/cards.js +263 -0
- package/client/src/data.js +43 -0
- package/client/src/graph.js +558 -0
- package/client/src/icons.js +88 -0
- package/client/src/projects.js +467 -0
- package/client/src/prompt.js +55 -0
- package/client/src/react.js +7 -0
- package/client/src/settings.js +407 -0
- package/client/src/styles.js +611 -0
- package/client/src/taskboard.js +321 -0
- package/client/src/taskgraph.js +145 -0
- package/client/src/ui.js +72 -0
- package/lib/acceptance-subject.js +71 -0
- package/lib/board/server.js +546 -0
- package/lib/board/snapshot.js +133 -0
- package/lib/board/taskview.js +151 -0
- package/lib/bootstrap.js +77 -0
- package/lib/catalog.js +385 -0
- package/lib/core.js +478 -0
- package/lib/data/capability-alias-catalog.json +301 -0
- package/lib/data/capability-alias.json +25 -0
- package/lib/domain.js +1342 -0
- package/lib/host-probe.js +176 -0
- package/lib/identity-hook.js +490 -0
- package/lib/index.js +119 -0
- package/lib/lessons.js +134 -0
- package/lib/metering.js +109 -0
- package/lib/scope.js +389 -0
- package/lib/session/child-watch.js +86 -0
- package/lib/session/evidence.js +118 -0
- package/lib/session/node-session.js +335 -0
- package/lib/session/queue.js +307 -0
- package/lib/session/reconcile.js +500 -0
- package/lib/tools/capabilities.js +1461 -0
- package/lib/tools/governance.js +579 -0
- package/lib/tools/index.js +33 -0
- package/lib/tools/project.js +500 -0
- package/lib/tools/readonly.js +566 -0
- package/lib/tools/recover.js +402 -0
- package/lib/tools/run.js +1609 -0
- package/lib/tools/skills.js +162 -0
- package/lib/tools/trees.js +637 -0
- package/lib/workspace-rmw.js +365 -0
- package/package.json +42 -4
package/lib/lessons.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/lessons.js — 教训册(lessons)叶子模块:校验 / 读取自愈视图 / 两级匹配 / 提示词行渲染 / improve 素材段。
|
|
3
|
+
* 教训管线批次1(ADR docs/决策/2026-10-21-教训管线lessons作用域projectId第一轴.md):
|
|
4
|
+
* · 账本顶层惰性字段 lessons(emptyLedger 挂 undefined 不落 JSON,normalizeLedger 零迁移,读取侧 ?? 兜底);
|
|
5
|
+
* · 条目 {id, text≤120字, scope:{projectId 必填=已登记项目 id, files?, nodeId?}, status:'active'|'pending'|'retired',
|
|
6
|
+
* source:{taskId, proposedBy, approvedBy?}, createdAt/updatedAt};
|
|
7
|
+
* · 两级匹配(L1 projectId 全等硬门——派单无 projectId 时零注入=按项目双向隔离;L2 同项目内 files glob 求交
|
|
8
|
+
* +nodeId 全等逐条收窄,声明了就须满足);K=3 条上限、单条 ≤120 字;
|
|
9
|
+
* · v1 三轴 OR 匹配废弃(无 projectId 的 files/nodeId 轴教训可跨项目命中=污染面),工坊级共享层删除——详见 ADR。
|
|
10
|
+
* 纯函数模块:只依赖 lib/scope.js(叶子→叶子),不读账本不落盘,写面在 bufeng_lesson(lib/tools/governance.js)。
|
|
11
|
+
*/
|
|
12
|
+
import { validateFiles, expandScope, intersectScopes, declaredLiteralPaths } from './scope.js';
|
|
13
|
+
|
|
14
|
+
export const LESSON_TEXT_MAX = 120; // 单条教训文本上限(字)——写入侧硬拒,注入侧双保险截断
|
|
15
|
+
export const LESSON_INJECT_K = 3; // 单次派单注入条数上限
|
|
16
|
+
export const LESSON_STATUSES = ['active', 'pending', 'retired'];
|
|
17
|
+
|
|
18
|
+
/** 单条教训结构校验(写侧单一权威:propose/approve 共用)。
|
|
19
|
+
* 入参用宽松形态(字段可缺省),返回 {ok:true} 或 {ok:false,error}——error 文案给下一步指引。 */
|
|
20
|
+
export function validateLessonDraft({ text, files, nodeId, status } = {}) {
|
|
21
|
+
const t = typeof text === 'string' ? text.trim() : '';
|
|
22
|
+
if (!t) return { ok: false, error: '教训 text 必填(不能为空)' };
|
|
23
|
+
if (t.length > LESSON_TEXT_MAX) return { ok: false, error: `教训 text 超长:最多 ${LESSON_TEXT_MAX} 字(现 ${t.length} 字)——请提炼后再提,细节留在任务回报里` };
|
|
24
|
+
if (files !== undefined && files !== null) {
|
|
25
|
+
const v = validateFiles(files);
|
|
26
|
+
if (!v.ok) return { ok: false, error: `教训 scope.files 非法(${v.error}):只收仓库相对路径/glob(如 ['lib/**'])` };
|
|
27
|
+
}
|
|
28
|
+
if (nodeId !== undefined && nodeId !== null) {
|
|
29
|
+
const n = typeof nodeId === 'string' ? nodeId.trim() : '';
|
|
30
|
+
if (!n) return { ok: false, error: '教训 scope.nodeId 须为非空节点 id(收窄到具体岗位;不收窄请不要传该键)' };
|
|
31
|
+
}
|
|
32
|
+
if (status !== undefined && !LESSON_STATUSES.includes(status)) {
|
|
33
|
+
return { ok: false, error: `教训 status 只能是 ${LESSON_STATUSES.join('/')}(收到:${String(status)})——状态流转由 action 驱动(propose→pending、approve→active、retire→retired),不接受手工指定` };
|
|
34
|
+
}
|
|
35
|
+
return { ok: true };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 读取侧自愈视图:条目结构性不可用(非对象/id/text/scope.projectId/status 非法)→ null(丢弃出视图,磁盘原样保留——
|
|
39
|
+
* 红线:账本数据零丢失);缺 updatedAt 回填 createdAt、缺 approvedBy 容忍(pending 期天然无)。 */
|
|
40
|
+
export function lessonEntryView(entry) {
|
|
41
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return null;
|
|
42
|
+
const id = typeof entry.id === 'string' ? entry.id.trim() : '';
|
|
43
|
+
const text = typeof entry.text === 'string' ? entry.text.trim() : '';
|
|
44
|
+
const scope = entry.scope && typeof entry.scope === 'object' && !Array.isArray(entry.scope) ? entry.scope : null;
|
|
45
|
+
const projectId = scope && typeof scope.projectId === 'string' ? scope.projectId.trim() : '';
|
|
46
|
+
if (!id || !text || !projectId) return null;
|
|
47
|
+
if (!LESSON_STATUSES.includes(entry.status)) return null;
|
|
48
|
+
const source = entry.source && typeof entry.source === 'object' && !Array.isArray(entry.source) ? entry.source : {};
|
|
49
|
+
const createdAt = typeof entry.createdAt === 'string' && entry.createdAt ? entry.createdAt : '';
|
|
50
|
+
if (!createdAt) return null;
|
|
51
|
+
const view = {
|
|
52
|
+
id,
|
|
53
|
+
text,
|
|
54
|
+
scope: { projectId }, // 无事键缺省纪律:files/nodeId/approvedBy 仅在在场时挂键(pending 期天然无 approvedBy)
|
|
55
|
+
status: entry.status,
|
|
56
|
+
source: {
|
|
57
|
+
taskId: typeof source.taskId === 'string' ? source.taskId : '',
|
|
58
|
+
proposedBy: typeof source.proposedBy === 'string' ? source.proposedBy : ''
|
|
59
|
+
},
|
|
60
|
+
createdAt,
|
|
61
|
+
updatedAt: typeof entry.updatedAt === 'string' && entry.updatedAt ? entry.updatedAt : createdAt // 自愈:缺 updatedAt 回填 createdAt(仅视图)
|
|
62
|
+
};
|
|
63
|
+
if (Array.isArray(scope.files) && scope.files.length) view.scope.files = scope.files;
|
|
64
|
+
if (typeof scope.nodeId === 'string' && scope.nodeId.trim()) view.scope.nodeId = scope.nodeId.trim();
|
|
65
|
+
if (typeof source.approvedBy === 'string' && source.approvedBy) view.source.approvedBy = source.approvedBy;
|
|
66
|
+
return view;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** lessons 原始数据 → 可用视图数组(账本任意形态安全:undefined/非数组/畸形条目全部兜底)。 */
|
|
70
|
+
export function normalizeLessons(raw) {
|
|
71
|
+
if (!Array.isArray(raw)) return [];
|
|
72
|
+
return raw.map(lessonEntryView).filter(Boolean);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** L2 files 轴命中:教训声明的 files 与派单 files glob 求交(复用文件域闸同源 expandScope/intersectScopes)。
|
|
76
|
+
* 语料=两侧字面路径并集(glob 串当语料字面串可自匹配——scope.js 既有技巧);未声明 files 的教训视为项目级(恒过本轴)。 */
|
|
77
|
+
export function lessonFilesHit(lessonFiles, taskFiles) {
|
|
78
|
+
if (!Array.isArray(lessonFiles) || !lessonFiles.length) return true; // 未声明=项目级,不收窄
|
|
79
|
+
const raw = [...new Set([...(Array.isArray(taskFiles) ? taskFiles : []), ...(Array.isArray(lessonFiles) ? lessonFiles : [])])];
|
|
80
|
+
const corpus = [...new Set([...raw, ...declaredLiteralPaths(taskFiles), ...declaredLiteralPaths(lessonFiles)])]; // glob 串本身也入语料(自匹配+互匹配):双纯 glob 求交(如 ['lib/**']×['lib/**'])不落空
|
|
81
|
+
const overlap = intersectScopes(expandScope(lessonFiles, corpus), expandScope(taskFiles, corpus));
|
|
82
|
+
return overlap.length > 0;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 两级匹配(注入面单一权威;queue.spawnForTask 与 run.dispatchCore 估算共用同一函数=投递与计费同源):
|
|
86
|
+
* L1 projectId 全等硬门——task 无 projectId 一律 [](无项目单零注入=按项目双向隔离,ADR §决策);
|
|
87
|
+
* L2 同项目内逐条收窄:scope.files glob 相交 + scope.nodeId 全等(声明了就须满足);
|
|
88
|
+
* 只取 status='active'(pending 未批准/retired 已退役都不注入);排序=双轴>单轴>项目级、同级 createdAt 倒序;K=LESSON_INJECT_K 截断。 */
|
|
89
|
+
export function matchLessonsForDispatch(lessons, task) {
|
|
90
|
+
const pid = typeof task?.projectId === 'string' && task.projectId.trim() ? task.projectId : null;
|
|
91
|
+
if (!pid) return [];
|
|
92
|
+
return normalizeLessons(lessons)
|
|
93
|
+
.filter((l) => l.status === 'active' && l.scope.projectId === pid)
|
|
94
|
+
.filter((l) => lessonFilesHit(l.scope.files, task?.files))
|
|
95
|
+
.filter((l) => !l.scope.nodeId || l.scope.nodeId === (typeof task?.nodeId === 'string' ? task.nodeId : null))
|
|
96
|
+
.sort((a, b) => {
|
|
97
|
+
const ax = (a.scope.files?.length ? 1 : 0) + (a.scope.nodeId ? 1 : 0);
|
|
98
|
+
const bx = (b.scope.files?.length ? 1 : 0) + (b.scope.nodeId ? 1 : 0);
|
|
99
|
+
return bx - ax || (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : a.id < b.id ? -1 : 1); // createdAt 倒序=新教训优先
|
|
100
|
+
})
|
|
101
|
+
.slice(0, LESSON_INJECT_K);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** 教训段渲染(domain.renderPromptParts lessonsNote 段内容,SEGMENTS 第 4 位):matched=matchLessonsForDispatch 输出
|
|
105
|
+
* (已是自愈视图;再过一遍 normalizeLessons 兜底手工构造的调用形态,畸形条目零渲染)。 */
|
|
106
|
+
export function lessonLinesForPrompt(matched) {
|
|
107
|
+
const list = normalizeLessons(matched);
|
|
108
|
+
if (!list.length) return [];
|
|
109
|
+
return [
|
|
110
|
+
'【本项目教训】(账本 lessons 册,总管已审核;与本任务提示词冲突时,以本任务提示词为准)',
|
|
111
|
+
...list.map((l, i) => `${i + 1}. ${l.text.slice(0, LESSON_TEXT_MAX)}(出处任务 ${l.source.taskId || '未知'})`)
|
|
112
|
+
];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** improve 执行手册素材段(acceptance #6):active lessons 按树关联项目过滤(树内项目=该树任务挂过的项目去重集合),
|
|
116
|
+
* 逐条「id+所属项目+text」;零条目明示「无在册教训」。 */
|
|
117
|
+
export function improveLessonsBlock(ledger, tree) {
|
|
118
|
+
const treeId = tree?.id ?? null;
|
|
119
|
+
const projectIds = new Set(
|
|
120
|
+
(Array.isArray(ledger?.tasks) ? ledger.tasks : [])
|
|
121
|
+
.filter((k) => k && k.treeId === treeId && typeof k.projectId === 'string' && k.projectId)
|
|
122
|
+
.map((k) => k.projectId)
|
|
123
|
+
);
|
|
124
|
+
const nameOf = (pid) => {
|
|
125
|
+
const p = (Array.isArray(ledger?.projects) ? ledger.projects : []).find((x) => x && x.id === pid);
|
|
126
|
+
return p?.name ? `${p.name}(${pid})` : pid;
|
|
127
|
+
};
|
|
128
|
+
const active = normalizeLessons(ledger?.lessons).filter((l) => l.status === 'active' && projectIds.has(l.scope.projectId));
|
|
129
|
+
const lines = active.map((l) => `- ${l.id}(项目 ${nameOf(l.scope.projectId)}):${l.text.slice(0, LESSON_TEXT_MAX)}`);
|
|
130
|
+
return [
|
|
131
|
+
'【在册教训】(账本 lessons 册·active,按本树关联项目过滤;自省与提案须逐条对照,完成后的新教训经 bufeng_lesson propose 提炼入册)',
|
|
132
|
+
...(lines.length ? lines : ['无在册教训'])
|
|
133
|
+
].join('\n');
|
|
134
|
+
}
|
package/lib/metering.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/metering.js — v0.53.0 B1 真实计量=转录解析(叶子模块)。
|
|
3
|
+
* ADR docs/决策/2026-10-28-成本护栏A档-v0.53.0.md §3.4:宿主无累计用量 API(§1.2 证据 1),
|
|
4
|
+
* 真值口径=解析会话转录 ~/.dsh/sessions/<token>/<sessionId>/session.v4.jsonl.zstd
|
|
5
|
+
* (多帧 zstd,帧头 magic 28 b5 2f fd,逐帧 node:zlib zstdDecompressSync 全解——整文件一次解只返首帧的陷阱勿踩)。
|
|
6
|
+
* 本模块是叶子——只依赖 node 内建(同 lib/scope.js 先例):tools/、session/、board/ 都可 import,
|
|
7
|
+
* 自己绝不反向 import 它们。
|
|
8
|
+
* 全链容错铁律(B2 收尾回写依赖):任一步缺失/失败=返回 null,绝不抛错。
|
|
9
|
+
* 测试隔离红线(m9 B1 判据):真实 ~/.dsh/sessions 零读——测试一律以 env BUFENG_DSH_SESSIONS_ROOT 指向夹具根。
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
12
|
+
import { homedir } from 'node:os';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { zstdDecompressSync } from 'node:zlib';
|
|
15
|
+
|
|
16
|
+
const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]); // 帧头 magic(0xfd2fb528 小端字节序)
|
|
17
|
+
const TRANSCRIPT_NAME = 'session.v4.jsonl.zstd';
|
|
18
|
+
|
|
19
|
+
/** 读转录文件→按 magic 扫帧→逐帧解压(单帧失败跳过)→拼接→逐行 JSON.parse(坏行跳过)。
|
|
20
|
+
* 非 zstd 内容(零 magic 命中)/读失败/宿主无 zstd 面=返回 null;正常返回 records[]。 */
|
|
21
|
+
export function decodeSessionTranscript(absPath) {
|
|
22
|
+
try {
|
|
23
|
+
if (typeof absPath !== 'string' || !absPath) return null;
|
|
24
|
+
const buf = readFileSync(absPath);
|
|
25
|
+
const frameStarts = [];
|
|
26
|
+
for (let i = 0; i + 4 <= buf.length; i++) {
|
|
27
|
+
if (buf[i] === 0x28 && buf[i + 1] === 0xb5 && buf[i + 2] === 0x2f && buf[i + 3] === 0xfd) frameStarts.push(i);
|
|
28
|
+
}
|
|
29
|
+
if (!frameStarts.length) return null;
|
|
30
|
+
if (typeof zstdDecompressSync !== 'function') return null;
|
|
31
|
+
const chunks = [];
|
|
32
|
+
for (let f = 0; f < frameStarts.length; f++) {
|
|
33
|
+
const start = frameStarts[f];
|
|
34
|
+
const end = f + 1 < frameStarts.length ? frameStarts[f + 1] : buf.length;
|
|
35
|
+
try { chunks.push(zstdDecompressSync(buf.subarray(start, end))); } catch { /* 单帧解压失败容错跳过 */ }
|
|
36
|
+
}
|
|
37
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
38
|
+
const records = [];
|
|
39
|
+
for (const line of text.split(/\r?\n/)) {
|
|
40
|
+
const s = line.trim();
|
|
41
|
+
if (!s) continue;
|
|
42
|
+
try { records.push(JSON.parse(s)); } catch { /* 坏 JSON 行跳过 */ }
|
|
43
|
+
}
|
|
44
|
+
return records;
|
|
45
|
+
} catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 会话根(缺省 ~/.dsh/sessions;env BUFENG_DSH_SESSIONS_ROOT 可覆盖供测试隔离)下
|
|
51
|
+
* 两层扫描 <root>/<token>/<sessionId>/session.v4.jsonl.zstd,命中即返绝对路径,未命中 null。
|
|
52
|
+
* 不解析 workspace-token 命名规则(免疫命名漂移;实测目录深度恒 3 层)。 */
|
|
53
|
+
export function findTranscriptPath(sessionId, sessionsRoot) {
|
|
54
|
+
try {
|
|
55
|
+
if (typeof sessionId !== 'string' || !sessionId.trim()) return null;
|
|
56
|
+
let root = null;
|
|
57
|
+
if (typeof sessionsRoot === 'string' && sessionsRoot.trim()) root = sessionsRoot;
|
|
58
|
+
else if (typeof process.env.BUFENG_DSH_SESSIONS_ROOT === 'string' && process.env.BUFENG_DSH_SESSIONS_ROOT.trim()) root = process.env.BUFENG_DSH_SESSIONS_ROOT;
|
|
59
|
+
else root = join(homedir(), '.dsh', 'sessions');
|
|
60
|
+
const entries = readdirSync(root, { withFileTypes: true });
|
|
61
|
+
for (const ent of entries) {
|
|
62
|
+
if (!ent.isDirectory()) continue;
|
|
63
|
+
const p = join(root, ent.name, sessionId, TRANSCRIPT_NAME);
|
|
64
|
+
if (existsSync(p)) return p;
|
|
65
|
+
}
|
|
66
|
+
return null;
|
|
67
|
+
} catch {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** records[]→用量汇总:Σ assistant/message 的 data.usage(cacheReadTokens 缺省 0);
|
|
73
|
+
* requests=assistant/message 条数;contextPeakTokens=max(单条 inputTokens);
|
|
74
|
+
* compactions=compaction/start 条数。 */
|
|
75
|
+
export function usageOf(records) {
|
|
76
|
+
const out = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, totalTokens: 0, requests: 0, contextPeakTokens: 0, compactions: 0 };
|
|
77
|
+
for (const r of Array.isArray(records) ? records : []) {
|
|
78
|
+
if (!r || typeof r !== 'object') continue;
|
|
79
|
+
if (r.type === 'assistant/message') {
|
|
80
|
+
out.requests += 1;
|
|
81
|
+
const u = r.data && typeof r.data === 'object' && r.data.usage && typeof r.data.usage === 'object' ? r.data.usage : null;
|
|
82
|
+
if (u) {
|
|
83
|
+
const inp = Number(u.inputTokens) || 0;
|
|
84
|
+
out.inputTokens += inp;
|
|
85
|
+
out.outputTokens += Number(u.outputTokens) || 0;
|
|
86
|
+
out.cacheReadTokens += Number(u.cacheReadTokens) || 0;
|
|
87
|
+
if (inp > out.contextPeakTokens) out.contextPeakTokens = inp;
|
|
88
|
+
out.totalTokens += Number(u.totalTokens) || 0;
|
|
89
|
+
}
|
|
90
|
+
} else if (r.type === 'compaction/start') {
|
|
91
|
+
out.compactions += 1;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** sessionId→usageOf 形状对象|null:findTranscriptPath→decodeSessionTranscript→usageOf 链;
|
|
98
|
+
* 任一步缺失/失败(含转录不存在、非 zstd、解码失败)=null,绝不抛错(B2 收尾回写依赖此契约)。 */
|
|
99
|
+
export function costTokensForSession(sessionId) {
|
|
100
|
+
try {
|
|
101
|
+
const p = findTranscriptPath(sessionId);
|
|
102
|
+
if (!p) return null;
|
|
103
|
+
const records = decodeSessionTranscript(p);
|
|
104
|
+
if (!records || !records.length) return null;
|
|
105
|
+
return usageOf(records);
|
|
106
|
+
} catch {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
}
|
package/lib/scope.js
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/scope.js — v0.34.0 派单期文件域闸 + 收尾越界审计的纯工具层。
|
|
3
|
+
*
|
|
4
|
+
* 语义(客户 2026-10-20 拍板「扩展版 A」;取代 v0.25 批2-T2 项目级排队闸):
|
|
5
|
+
* · files 声明 = 本单允许触碰的仓库相对路径(字面路径或 glob,`**` 跨目录、`*` 不跨 `/`、`?` 单字符);
|
|
6
|
+
* `['**']` = 全域哨兵;`[]` = 空集(只读单,与任何在跑单都不冲突);缺省/旧账本无 files 的单按全域处理。
|
|
7
|
+
* · 闸只在「解析出的工作目录是 git 工作树」时生效(git rev-parse --show-toplevel 成功);非 git 不生效。
|
|
8
|
+
* · 只与「同 cwd(realpath 归一)的 running/pending 单」求交;不同 cwd 互不干扰。
|
|
9
|
+
* · 交集判定走「声明→路径集合」展开:语料 = git ls-files -z + 双方声明中的字面路径
|
|
10
|
+
* (后者覆盖未跟踪新文件——两单都声明同一个还没 git add 的新文件时仍能互相命中)。
|
|
11
|
+
* · Windows 大小写不敏感(路径折叠比较)、`\` 一律归一为 `/`。
|
|
12
|
+
*
|
|
13
|
+
* 依赖方向(AGENTS §2):本模块是叶子——只依赖 node 内建,tools/ 与 session/ 都可 import,自己绝不反向 import 它们。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { execFile } from 'node:child_process';
|
|
17
|
+
import { realpath } from 'node:fs/promises';
|
|
18
|
+
import { isAbsolute, normalize } from 'node:path';
|
|
19
|
+
import { promisify } from 'node:util';
|
|
20
|
+
|
|
21
|
+
const execFileAsync = promisify(execFile);
|
|
22
|
+
const IS_WIN = process.platform === 'win32';
|
|
23
|
+
const GIT_TIMEOUT_MS = 15000;
|
|
24
|
+
|
|
25
|
+
export const SCOPE_MAX_FILES = 200; // files 条数硬顶(防一次声明上千条把语料展开搞爆)
|
|
26
|
+
export const WHOLE_SCOPE = '**'; // 全域哨兵
|
|
27
|
+
|
|
28
|
+
/** `\` → `/`(Windows 调用方可能传反斜杠;账本与 git 一律用正斜杠)。 */
|
|
29
|
+
function toPosix(p) {
|
|
30
|
+
return String(p ?? '').replace(/\\/g, '/');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 比较键:posix + Windows 折叠小写(其它平台保持大小写敏感)。 */
|
|
34
|
+
export function foldPath(p) {
|
|
35
|
+
const s = toPosix(p);
|
|
36
|
+
return IS_WIN ? s.toLowerCase() : s;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 去掉开头的 `./`(`./lib/a.js` 与 `lib/a.js` 是同一路径)。 */
|
|
40
|
+
function trimDotSlash(s) {
|
|
41
|
+
return toPosix(s).replace(/^(?:\.\/)+/, '');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 含路径段 `..`(不是文件名里的两个点)——越出工作目录的声明一律拒。 */
|
|
45
|
+
function hasDotDot(p) {
|
|
46
|
+
return toPosix(p).split('/').some((seg) => seg === '..');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 绝对路径(POSIX `/x`、Windows `C:\x` / `\\server\share`)。 */
|
|
50
|
+
function looksAbsolute(p) {
|
|
51
|
+
const s = String(p ?? '');
|
|
52
|
+
return isAbsolute(s) || /^[A-Za-z]:/.test(s);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** glob 判定(v0.34.0 契约只认 `*` 与 `?`;`[` 当普通字符,避免误伤含方括号的合法文件名)。 */
|
|
56
|
+
function isGlobEntry(s) {
|
|
57
|
+
return s.includes('*') || s.includes('?');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* files 参数校验(B2):非数组/元素非串/空串/绝对路径/含 `..` 段/超 200 条 → 拒(文案给下一步指路)。
|
|
62
|
+
* 返回 { ok:true, files: null|string[] }(null=未声明/继承语义)或 { ok:false, reason }。
|
|
63
|
+
* 一律归一为 posix、去重(Windows 折叠判重)——合法声明原样保留大小写供展示。
|
|
64
|
+
*/
|
|
65
|
+
export function validateFiles(files) {
|
|
66
|
+
if (files === undefined || files === null) return { ok: true, files: null };
|
|
67
|
+
if (!Array.isArray(files)) {
|
|
68
|
+
return { ok: false, reason: `files 必须是字符串数组(本单允许触碰的仓库相对路径或 glob;只读单显式传 [],不声明视为全域)——收到 ${typeof files}` };
|
|
69
|
+
}
|
|
70
|
+
if (files.length > SCOPE_MAX_FILES) {
|
|
71
|
+
return { ok: false, reason: `files 最多 ${SCOPE_MAX_FILES} 条(当前 ${files.length} 条):把同目录文件收成一条 glob(如 lib/tools/*.js)再派` };
|
|
72
|
+
}
|
|
73
|
+
const out = [];
|
|
74
|
+
const seen = new Set();
|
|
75
|
+
for (let i = 0; i < files.length; i += 1) {
|
|
76
|
+
const raw = files[i];
|
|
77
|
+
if (typeof raw !== 'string') {
|
|
78
|
+
return { ok: false, reason: `files 第 ${i + 1} 项不是字符串(收到 ${typeof raw}):逐项写仓库相对路径或 glob,如 lib/tools/run.js` };
|
|
79
|
+
}
|
|
80
|
+
const s = trimDotSlash(raw.trim());
|
|
81
|
+
if (!s) {
|
|
82
|
+
return { ok: false, reason: `files 第 ${i + 1} 项是空串:删掉该条;只读单请显式传 []([]=空集,不与任何在跑单冲突)` };
|
|
83
|
+
}
|
|
84
|
+
if (looksAbsolute(s)) {
|
|
85
|
+
return { ok: false, reason: `files 第 ${i + 1} 项是绝对路径(${raw}):files 只收工作目录内的仓库相对路径(如 lib/tools/run.js)` };
|
|
86
|
+
}
|
|
87
|
+
if (hasDotDot(s)) {
|
|
88
|
+
return { ok: false, reason: `files 第 ${i + 1} 项含 '..' 路径段(${raw}):文件域必须落在工作目录内,越界请先缩小到仓内路径` };
|
|
89
|
+
}
|
|
90
|
+
const key = foldPath(s);
|
|
91
|
+
if (seen.has(key)) continue;
|
|
92
|
+
seen.add(key);
|
|
93
|
+
out.push(s);
|
|
94
|
+
}
|
|
95
|
+
return { ok: true, files: out };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* glob → RegExp:`**` 跨目录(`a/**` 含 a 下全部层级;`**` 单独形态=全域,由 expandScope 先判),
|
|
100
|
+
* `*` 不跨 `/`,`?` 匹配单个非 `/` 字符;其余字符转义;Windows 加 `i`(大小写不敏感)。
|
|
101
|
+
*/
|
|
102
|
+
export function globToRegex(glob) {
|
|
103
|
+
const s = trimDotSlash(glob);
|
|
104
|
+
let re = '';
|
|
105
|
+
for (let i = 0; i < s.length; i += 1) {
|
|
106
|
+
const c = s[i];
|
|
107
|
+
if (c === '*') {
|
|
108
|
+
if (s[i + 1] === '*') {
|
|
109
|
+
i += 1;
|
|
110
|
+
if (s[i + 1] === '/') { i += 1; re += '(?:.*/)?'; } else { re += '.*'; }
|
|
111
|
+
} else {
|
|
112
|
+
re += '[^/]*';
|
|
113
|
+
}
|
|
114
|
+
} else if (c === '?') {
|
|
115
|
+
re += '[^/]';
|
|
116
|
+
} else {
|
|
117
|
+
re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return new RegExp(`^${re}$`, IS_WIN ? 'i' : '');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function addPath(map, rawPath) {
|
|
124
|
+
const key = foldPath(trimDotSlash(rawPath));
|
|
125
|
+
if (key && !map.has(key)) map.set(key, trimDotSlash(toPosix(rawPath)));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** 声明里的字面路径(不含 glob 哨兵)——语料补充用(覆盖未跟踪新文件互命中)。 */
|
|
129
|
+
export function declaredLiteralPaths(files) {
|
|
130
|
+
const out = [];
|
|
131
|
+
for (const raw of files ?? []) {
|
|
132
|
+
const s = trimDotSlash(String(raw ?? ''));
|
|
133
|
+
if (!s || s === WHOLE_SCOPE || isGlobEntry(s)) continue;
|
|
134
|
+
out.push(s);
|
|
135
|
+
}
|
|
136
|
+
return out;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* 声明 → 路径集合(B3)。返回 { whole:boolean, map:Map<folded, display> }:
|
|
141
|
+
* · files 缺省/null → whole=true(legacy / 未声明=全域);
|
|
142
|
+
* · [] → whole=false、空 map(只读单);
|
|
143
|
+
* · 含 `**` → whole=true;其余按 glob 对语料匹配、字面路径直接入集。
|
|
144
|
+
*/
|
|
145
|
+
export function expandScope(files, corpus) {
|
|
146
|
+
if (files === undefined || files === null) return { whole: true, map: new Map() };
|
|
147
|
+
const list = Array.isArray(files) ? files : [];
|
|
148
|
+
if (!list.length) return { whole: false, map: new Map() };
|
|
149
|
+
if (list.some((f) => trimDotSlash(String(f ?? '')) === WHOLE_SCOPE)) return { whole: true, map: new Map() };
|
|
150
|
+
const corpusArr = corpus instanceof Set ? [...corpus] : (corpus ?? []);
|
|
151
|
+
const corpusFolded = corpusArr.map((p) => ({ key: foldPath(p), display: toPosix(p) }));
|
|
152
|
+
const map = new Map();
|
|
153
|
+
for (const raw of list) {
|
|
154
|
+
const pat = trimDotSlash(String(raw ?? ''));
|
|
155
|
+
if (!pat) continue;
|
|
156
|
+
if (isGlobEntry(pat)) {
|
|
157
|
+
let re;
|
|
158
|
+
try { re = globToRegex(pat); } catch { continue; }
|
|
159
|
+
for (const c of corpusFolded) {
|
|
160
|
+
if (re.test(c.key)) addPath(map, c.display);
|
|
161
|
+
}
|
|
162
|
+
} else {
|
|
163
|
+
addPath(map, pat);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return { whole: false, map };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** 两个作用域求交(B4):返回冲突路径展示串数组;空数组=不相交。全域 ∩ 空集=不相交(只读单放行)。 */
|
|
170
|
+
export function intersectScopes(a, b) {
|
|
171
|
+
if (!a || !b) return [];
|
|
172
|
+
if (a.whole && b.whole) return [WHOLE_SCOPE];
|
|
173
|
+
if (a.whole) return [...b.map.values()];
|
|
174
|
+
if (b.whole) return [...a.map.values()];
|
|
175
|
+
const out = [];
|
|
176
|
+
const [small, big] = a.map.size <= b.map.size ? [a.map, b.map] : [b.map, a.map];
|
|
177
|
+
for (const [key, display] of small) {
|
|
178
|
+
if (big.has(key)) out.push(display);
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** cwd 归一(realpath 优先;失败回退 path.normalize;Windows 折叠小写、去尾部分隔符)。 */
|
|
184
|
+
export async function normCwd(cwd) {
|
|
185
|
+
const raw = typeof cwd === 'string' && cwd.trim() ? cwd.trim() : null;
|
|
186
|
+
if (!raw) return null;
|
|
187
|
+
let p = raw;
|
|
188
|
+
try { p = await realpath(raw); } catch { try { p = normalize(raw); } catch { p = raw; } }
|
|
189
|
+
p = toPosix(p).replace(/\/+$/, '');
|
|
190
|
+
return IS_WIN ? p.toLowerCase() : p;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** 两个工作目录是否同一目录(realpath 归一 + Windows 大小写折叠)。 */
|
|
194
|
+
export async function sameCwd(a, b) {
|
|
195
|
+
const na = await normCwd(a);
|
|
196
|
+
const nb = await normCwd(b);
|
|
197
|
+
return !!na && !!nb && na === nb;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function runGit(cwd, args) {
|
|
201
|
+
try {
|
|
202
|
+
const { stdout } = await execFileAsync('git', args, { cwd, timeout: GIT_TIMEOUT_MS, windowsHide: true, maxBuffer: 32 * 1024 * 1024 });
|
|
203
|
+
return { ok: true, out: String(stdout ?? '') };
|
|
204
|
+
} catch (error) {
|
|
205
|
+
return { ok: false, error: String(error?.message || error) };
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** git rev-parse --show-toplevel(B1:闸是否生效的判据)。 */
|
|
210
|
+
export async function gitTopLevel(cwd) {
|
|
211
|
+
if (!cwd) return { ok: false, error: 'no-cwd' };
|
|
212
|
+
const r = await runGit(cwd, ['rev-parse', '--show-toplevel']);
|
|
213
|
+
if (!r.ok) return { ok: false, error: r.error };
|
|
214
|
+
const top = r.out.trim();
|
|
215
|
+
return top ? { ok: true, top } : { ok: false, error: 'empty-toplevel' };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** git rev-parse HEAD(C:baseHead 收尾审计锚点;非 git/无提交 → null)。 */
|
|
219
|
+
export async function gitHead(cwd) {
|
|
220
|
+
if (!cwd) return { ok: false, error: 'no-cwd' };
|
|
221
|
+
const r = await runGit(cwd, ['rev-parse', 'HEAD']);
|
|
222
|
+
const head = r.out?.trim();
|
|
223
|
+
return r.ok && head ? { ok: true, head } : { ok: false, error: r.error ?? 'empty-head' };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* v0.53.0 C2(ADR docs/决策/2026-10-28-成本护栏A档-v0.53.0.md §3.8)stalled 披露的 git 探针:
|
|
228
|
+
* baseHead..HEAD 范围内是否存在本单 Task-Id trailer 提交。返回三态:true=有匹配提交(在推进,不标);
|
|
229
|
+
* false=确证无匹配(可披露);null=无法核验(非 git 工作目录/探针失败——调用方按静默跳过处理,绝不武断判无)。
|
|
230
|
+
* trailer 逐 commit 匹配 /^Task-Id:[ \t]*<taskId>\s*$/m(git log --format=%H 等号连写先例形态);
|
|
231
|
+
* range 空(HEAD==baseHead)时补核 baseHead 自身消息——trailer 提交恰为 baseHead 位的形态不误标(m14 W1C-10 反例)。
|
|
232
|
+
*/
|
|
233
|
+
export async function hasTaskIdCommit(cwd, baseHead, taskId) {
|
|
234
|
+
try {
|
|
235
|
+
if (!cwd || !baseHead || !taskId) return null;
|
|
236
|
+
const esc = String(taskId).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
237
|
+
const re = new RegExp(`^Task-Id:[ \\t]*${esc}\\s*$`, 'm');
|
|
238
|
+
const range = await runGit(cwd, ['log', '--format=%H', `${baseHead}..HEAD`]);
|
|
239
|
+
if (!range.ok) return null;
|
|
240
|
+
const shas = range.out.split('\n').map((s) => s.trim()).filter(Boolean);
|
|
241
|
+
if (!shas.length) {
|
|
242
|
+
// range 空:HEAD==baseHead——补核 baseHead 自身消息(本单 trailer 提交可能恰为 baseHead 位)
|
|
243
|
+
const self = await runGit(cwd, ['log', '-n', '1', '--format=%B', baseHead]);
|
|
244
|
+
return self.ok ? re.test(self.out) : null;
|
|
245
|
+
}
|
|
246
|
+
for (const sha of shas) {
|
|
247
|
+
const msg = await runGit(cwd, ['log', '-n', '1', '--format=%B', sha]);
|
|
248
|
+
if (!msg.ok) return null; // 逐条核验失败=无法核验(fail-safe,不武断判无)
|
|
249
|
+
if (re.test(msg.out)) return true;
|
|
250
|
+
}
|
|
251
|
+
return false;
|
|
252
|
+
} catch {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** git ls-files -z(B3 语料主干:已跟踪文件;未跟踪新文件靠 declaredLiteralPaths 补)。 */
|
|
258
|
+
export async function gitListFiles(cwd) {
|
|
259
|
+
if (!cwd) return { ok: false, error: 'no-cwd' };
|
|
260
|
+
const r = await runGit(cwd, ['ls-files', '-z']);
|
|
261
|
+
if (!r.ok) return { ok: false, error: r.error };
|
|
262
|
+
const files = r.out.split('\0').map((s) => toPosix(s.trim())).filter(Boolean);
|
|
263
|
+
return { ok: true, files };
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* 同 cwd 的 running/pending 单(B4 冲突面 + B6 并行披露共用;排除自身 id)。
|
|
268
|
+
* v0.50.0 P2 披露·C5 超龄停算(ADR docs/决策/2026-10-28-投递链路加固-P2披露-v0.50.0.md §2.3):第 4 参 opts={staleMs}——
|
|
269
|
+
* staleMs>0 时「pending 且无 childId 且 age>staleMs」的行不计入冲突面(边界严格 >;有 childId 的 pending=finalize 进行中
|
|
270
|
+
* 正常窗口,保守照常计入);不传 opts/不传 staleMs/非正数/非有限数=现行为回旧(0=关闭停算;缺省 ?? 120000 读取兜底在
|
|
271
|
+
* 调用方 run.js,本函数只认入参)。既有 3 参调用点(queue.js 投递期并行披露、run.js 冲突判定)零漂移;
|
|
272
|
+
* 保守边界:createdAt 缺失/不可解析→超龄判定不成立→照常计入(宁可多算冲突不静默放行)。
|
|
273
|
+
*/
|
|
274
|
+
export async function activePeers(tasks, cwd, excludeId = null, opts = {}) {
|
|
275
|
+
const target = await normCwd(cwd);
|
|
276
|
+
const out = [];
|
|
277
|
+
if (!target) return out;
|
|
278
|
+
const o = (opts && typeof opts === 'object' && !Array.isArray(opts)) ? opts : {};
|
|
279
|
+
const rawStale = o.staleMs;
|
|
280
|
+
const staleMs = (typeof rawStale === 'number' && Number.isFinite(rawStale) && rawStale > 0) ? rawStale : null;
|
|
281
|
+
const now = Date.now();
|
|
282
|
+
for (const t of tasks ?? []) {
|
|
283
|
+
if (!t || (excludeId && t.id === excludeId)) continue;
|
|
284
|
+
if (t.status !== 'running' && t.status !== 'pending') continue;
|
|
285
|
+
if (staleMs !== null && t.status === 'pending' && !t.childId) {
|
|
286
|
+
const created = Date.parse(t.createdAt ?? '');
|
|
287
|
+
if (Number.isFinite(created) && now - created > staleMs) continue; // 超龄未落定单停算:不进冲突面
|
|
288
|
+
}
|
|
289
|
+
const c = await normCwd(t.workspace);
|
|
290
|
+
if (c && c === target) out.push(t);
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* 派单期文件域判定(B1/B3/B4/B5):
|
|
297
|
+
* · 非 git → { gated:false, conflicts:[], note }(闸不生效 + note 说明);
|
|
298
|
+
* · git → 组语料(ls-files + 双方字面声明)→ 与每个 peer 求交 → { gated:true, conflicts:[{taskId,nodeId,title,paths}], note }。
|
|
299
|
+
* 语料/展开异常 → 本单保守按全域处理 + note 告警(fail-closed,宁可拒一次也不静默放行越界写)。
|
|
300
|
+
*/
|
|
301
|
+
export async function findScopeConflicts({ cwd, files, peers }) {
|
|
302
|
+
const list = peers ?? [];
|
|
303
|
+
const top = await gitTopLevel(cwd);
|
|
304
|
+
if (!top.ok) {
|
|
305
|
+
return {
|
|
306
|
+
gated: false,
|
|
307
|
+
conflicts: [],
|
|
308
|
+
note: '工作目录不是 git 工作树(git rev-parse --show-toplevel 失败):文件域闸不生效,本单按全域处理;要启用闸请在 git 仓内派单(可在 detail 写明文件范围)'
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
const warnings = [];
|
|
312
|
+
const ls = await gitListFiles(cwd);
|
|
313
|
+
const corpus = [];
|
|
314
|
+
if (ls.ok) {
|
|
315
|
+
for (const p of ls.files) corpus.push(p);
|
|
316
|
+
} else {
|
|
317
|
+
warnings.push(`文件域语料解析失败(git ls-files 不可用:${String(ls.error).slice(0, 120)}):未跟踪新文件无法核对,本单保守按全域处理`);
|
|
318
|
+
}
|
|
319
|
+
for (const p of declaredLiteralPaths(files)) corpus.push(p);
|
|
320
|
+
for (const peer of list) {
|
|
321
|
+
for (const p of declaredLiteralPaths(peer.files)) corpus.push(p);
|
|
322
|
+
}
|
|
323
|
+
let mine;
|
|
324
|
+
if (!ls.ok) {
|
|
325
|
+
mine = { whole: true, map: new Map() };
|
|
326
|
+
} else {
|
|
327
|
+
try {
|
|
328
|
+
mine = expandScope(files, corpus);
|
|
329
|
+
} catch (error) {
|
|
330
|
+
mine = { whole: true, map: new Map() };
|
|
331
|
+
warnings.push(`文件域展开异常(${String(error?.message || error).slice(0, 120)}):本单保守按全域处理`);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
const conflicts = [];
|
|
335
|
+
for (const peer of list) {
|
|
336
|
+
let theirs;
|
|
337
|
+
try {
|
|
338
|
+
theirs = expandScope(peer.files, corpus);
|
|
339
|
+
} catch {
|
|
340
|
+
theirs = { whole: true, map: new Map() };
|
|
341
|
+
}
|
|
342
|
+
const paths = intersectScopes(mine, theirs);
|
|
343
|
+
if (paths.length) {
|
|
344
|
+
conflicts.push({ taskId: peer.id, nodeId: peer.nodeId ?? null, title: peer.title ?? null, paths });
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return { gated: true, conflicts, note: warnings.length ? warnings.join(';') : null };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* 收尾越界审计(D1/D2/D3):baseHead..HEAD 里带 `Task-Id: <taskId>` trailer 的提交,
|
|
352
|
+
* 逐 commit 取 --name-only,路径不在本单 files 域内即列为越界。
|
|
353
|
+
* 全 try/catch 包裹(绝不抛):无提交/非 git/git 失败 → status='skipped'(静默);
|
|
354
|
+
* 有提交但无 Task-Id → status='no-trailer'(调用方 note 提示)。files 缺省=全域(不判越界)。
|
|
355
|
+
*/
|
|
356
|
+
export async function auditTaskScope({ cwd, baseHead, files, taskId }) {
|
|
357
|
+
const silent = { status: 'skipped', commits: [], outOfScope: [] };
|
|
358
|
+
try {
|
|
359
|
+
if (!cwd || !baseHead || !taskId) return silent;
|
|
360
|
+
const range = `${baseHead}..HEAD`;
|
|
361
|
+
const logAll = await runGit(cwd, ['log', '--format=%H', range]);
|
|
362
|
+
if (!logAll.ok) return silent;
|
|
363
|
+
const all = logAll.out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
|
364
|
+
if (!all.length) return { ...silent, status: 'no-commits' };
|
|
365
|
+
const grep = await runGit(cwd, ['log', '--format=%H', range, `--grep=Task-Id: ${taskId}`]);
|
|
366
|
+
if (!grep.ok) return silent;
|
|
367
|
+
const hits = grep.out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
|
368
|
+
if (!hits.length) return { ...silent, status: 'no-trailer' };
|
|
369
|
+
const ls = await gitListFiles(cwd);
|
|
370
|
+
if (!ls.ok) return { ...silent, status: 'skipped', commits: hits }; // 语料不可用 → 静默(不误报越界)
|
|
371
|
+
const corpus = [...ls.files, ...declaredLiteralPaths(files)];
|
|
372
|
+
let scope;
|
|
373
|
+
try { scope = expandScope(files, corpus); } catch { scope = { whole: true, map: new Map() }; }
|
|
374
|
+
const outOfScope = [];
|
|
375
|
+
for (const sha of hits) {
|
|
376
|
+
const show = await runGit(cwd, ['show', '--name-only', '--format=', '-z', sha]);
|
|
377
|
+
if (!show.ok) continue;
|
|
378
|
+
for (const raw of show.out.split('\0')) {
|
|
379
|
+
const p = toPosix(raw.trim());
|
|
380
|
+
if (!p) continue;
|
|
381
|
+
if (scope.whole) continue;
|
|
382
|
+
if (!scope.map.has(foldPath(p))) outOfScope.push({ path: p, commit: sha });
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
return { status: 'checked', commits: hits, outOfScope };
|
|
386
|
+
} catch {
|
|
387
|
+
return silent;
|
|
388
|
+
}
|
|
389
|
+
}
|