@rowansenne/workflow-run 0.26.1 → 0.28.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.
Files changed (71) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +68 -38
  3. package/bin/lib/artifact-context.mjs +46 -0
  4. package/bin/lib/docnexus.mjs +4 -4
  5. package/bin/lib/doctor.mjs +1 -2
  6. package/bin/lib/install.mjs +1 -1
  7. package/bin/lib/uninstall.mjs +3 -0
  8. package/bin/workflow-run.mjs +20 -29
  9. package/code-graph/SKILL.md.tpl +2 -7
  10. package/create-release-md-doc/SKILL.md.tpl +12 -13
  11. package/create-tech-md-doc/SKILL.md.tpl +12 -13
  12. package/database-query/SKILL.md.tpl +2 -0
  13. package/database-query/skill.json +2 -2
  14. package/dev/SKILL.md.tpl +42 -116
  15. package/dev/references/bug.md +32 -0
  16. package/dev/references/delivery-template.md +6 -6
  17. package/dev/references/delivery.md +50 -0
  18. package/dev/references/implementation.md +23 -0
  19. package/dev/references/plan-template.md +5 -3
  20. package/dev/references/planning.md +45 -0
  21. package/dev/references/preflight.md +35 -0
  22. package/dev/skill.json +2 -2
  23. package/md-to-wiki/SKILL.md.tpl +5 -1
  24. package/md-to-wiki/skill.json +2 -2
  25. package/package.json +2 -2
  26. package/project-review/SKILL.md.tpl +46 -72
  27. package/project-review/references/report.md.tpl +4 -4
  28. package/project-review/references/reporting.md +48 -0
  29. package/project-review/references/review-method.md +56 -0
  30. package/project-review/references/verification.md +30 -0
  31. package/shared/prd-fetch.md +1 -1
  32. package/workflow/SKILL.md.tpl +16 -16
  33. package/workflow/lib/artifact-finalize.mjs +144 -0
  34. package/workflow/lib/artifact-model.mjs +83 -0
  35. package/workflow/lib/capabilities.mjs +80 -0
  36. package/workflow/lib/code-snapshot.mjs +55 -0
  37. package/workflow/lib/document-model.mjs +86 -0
  38. package/workflow/lib/meta-store.mjs +114 -0
  39. package/workflow/lib/path-match.mjs +21 -0
  40. package/workflow/lib/project.mjs +218 -0
  41. package/workflow/lib/requirement-read.mjs +68 -0
  42. package/workflow/lib/requirements.mjs +224 -0
  43. package/workflow/lib/run-gates.mjs +136 -0
  44. package/workflow/lib/runs.mjs +188 -0
  45. package/workflow/lib/workspace-read.mjs +122 -0
  46. package/workflow/references/architecture.md +53 -0
  47. package/workflow/references/capabilities.md +39 -0
  48. package/workflow/references/codegraph.md +3 -3
  49. package/workflow/references/docnexus.md +1 -1
  50. package/workflow/references/execution.md +95 -0
  51. package/workflow/references/requirements.md +36 -25
  52. package/workflow/references/runs.md +100 -0
  53. package/workflow/references/status.md +7 -3
  54. package/workflow/references/templates.md +11 -14
  55. package/workflow/scripts/artifact.mjs +39 -0
  56. package/workflow/scripts/artifacts.mjs +21 -80
  57. package/workflow/scripts/doc-sections.mjs +2 -55
  58. package/workflow/scripts/docnexus-layout.mjs +2 -24
  59. package/workflow/scripts/knowledge.mjs +4 -2
  60. package/workflow/scripts/lint-doc.mjs +2 -35
  61. package/workflow/scripts/meta-store.mjs +2 -0
  62. package/workflow/scripts/pr-desc.mjs +8 -6
  63. package/workflow/scripts/report.mjs +20 -68
  64. package/workflow/scripts/requirement.mjs +9 -402
  65. package/workflow/scripts/resolve.mjs +22 -190
  66. package/workflow/scripts/review-handoff.mjs +59 -0
  67. package/workflow/scripts/review-scope.mjs +4 -22
  68. package/workflow/scripts/run.mjs +35 -0
  69. package/workflow/scripts/tables.mjs +1 -1
  70. package/workflow/scripts/template.mjs +2 -6
  71. package/workflow/scripts/view.mjs +41 -21
@@ -0,0 +1,86 @@
1
+ // Markdown 纯文本模型:标题、章节、表格和元信息;不依赖文件、模板或命令入口。
2
+
3
+ // 去掉代码块后返回 [{ line, text }],行号从 1 开始
4
+ export function proseLines(md) {
5
+ const out = [];
6
+ let fence = null;
7
+ md.replace(/\r/g, '').split('\n').forEach((text, i) => {
8
+ const m = text.match(/^\s*(```+|~~~+)/);
9
+ if (m) { if (!fence) fence = m[1][0]; else if (m[1][0] === fence) fence = null; return; }
10
+ if (!fence) out.push({ line: i + 1, text });
11
+ });
12
+ return out;
13
+ }
14
+
15
+ // 章节标题归一化:去掉编号(1. / 4.1 / 一、/ 第一部分)、必填标记 *、可选标记(如有),用于模板与文档比对
16
+ export function headingKey(text) {
17
+ return text
18
+ .replace(/\*+\s*$/, '')
19
+ .replace(/[((]\s*如有[^))]*[))]/g, '')
20
+ .replace(/^\s*(?:第?[一二三四五六七八九十]+[、..]|[0-9]+(?:\.(?:[0-9]+|x))*[.、.]?)\s*/, '')
21
+ .replace(/\s+/g, '')
22
+ .trim();
23
+ }
24
+
25
+ export function headings(md) {
26
+ return proseLines(md)
27
+ .map(({ line, text }) => ({ line, m: text.match(/^(#{1,6})\s+(.+?)\s*#*\s*$/) }))
28
+ .filter((h) => h.m)
29
+ .map(({ line, m }) => ({
30
+ line, level: m[1].length, text: m[2],
31
+ key: headingKey(m[2]),
32
+ required: /\*\s*$/.test(m[2]),
33
+ optional: /[((]\s*如有/.test(m[2]),
34
+ placeholder: /\{\{|<[^>]*填写[^>]*>/.test(m[2]),
35
+ }));
36
+ }
37
+
38
+ const stripComments = (s) => s.replace(/<!--[\s\S]*?-->/g, '');
39
+
40
+ // 二级标题(归一化后的 key)→ 正文(去掉 HTML 注释与首尾空行)
41
+ export function sections(text) {
42
+ const lines = text.split(/\r?\n/);
43
+ const hs = headings(text);
44
+ const out = new Map();
45
+ hs.forEach((h, i) => {
46
+ if (h.level !== 2) return;
47
+ const next = hs.slice(i + 1).find((x) => x.level <= 2);
48
+ const body = lines.slice(h.line, next ? next.line - 1 : lines.length).join('\n');
49
+ if (!out.has(h.key)) out.set(h.key, stripComments(body).trim());
50
+ });
51
+ return out;
52
+ }
53
+
54
+ // 按标题前缀取一节(「严重问题」匹配「严重问题(CRITICAL / HIGH)」),前缀同样归一化
55
+ export function section(secs, prefix) {
56
+ const key = headingKey(prefix);
57
+ for (const [k, v] of secs) if (k.startsWith(key)) return v;
58
+ return null;
59
+ }
60
+
61
+ // 「无」「无。」或只剩占位符的节当作空
62
+ export const isEmpty = (body) => !body || /^(无|无。|none|n\/a)$/i.test(body.trim()) || /^\{\{[^}]*\}\}$/.test(body.trim());
63
+
64
+ // 表格数据行(跳过表头、分隔行、全空行和带 {{占位符}} 的模板行),返回单元格数组
65
+ export function tableRows(body) {
66
+ if (!body) return [];
67
+ const lines = body.split('\n').filter((l) => /^\s*\|/.test(l));
68
+ return lines.slice(1)
69
+ .filter((l) => !/^\s*\|[\s:|-]+\|\s*$/.test(l))
70
+ .map((l) => l.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim()))
71
+ .filter((cells) => cells.some((c) => c) && !cells.some((c) => /\{\{/.test(c)));
72
+ }
73
+
74
+ // 列表项(- / * / 1.),跳过「无」与占位符
75
+ export function listItems(body) {
76
+ if (!body) return [];
77
+ return body.split('\n').map((l) => /^\s*(?:[-*]|\d+[.)])\s+(.*)$/.exec(l)?.[1]?.trim()).filter((x) => x && !isEmpty(x) && !/\{\{/.test(x));
78
+ }
79
+
80
+ // 开头引用块里的元信息:「> DocNexus:xxx」取 xxx(遇到「|」截断)
81
+ export function meta(text, key) {
82
+ const head = text.split(/\r?\n/).slice(0, 20).join('\n');
83
+ const m = new RegExp(`${key}[::]\\s*([^|\\n]*)`).exec(head);
84
+ const v = m?.[1]?.trim();
85
+ return v && !/^\{\{/.test(v) ? v : null;
86
+ }
@@ -0,0 +1,114 @@
1
+ // 需求索引和运行状态共用同一把短时写锁;原子替换,避免读到半份 JSON。
2
+ // 锁和临时文件都放在 workflow-run/tmp/ 下(不放需求目录),崩溃残留不会混进 git;
3
+ // 锁目录里的唯一进程标记记录 pid 和时间;只回收已退出进程的旧标记,非空目录不能删除。
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { createHash, randomUUID } from 'node:crypto';
7
+
8
+ const STALE_MS = 30_000;
9
+ const LOCK_DIR = 'workflow-run/tmp/locks'; // 与 requirement.mjs 的 HOME / TMP_DIR 一致;不 import 以免循环依赖
10
+
11
+ export function readMeta(file) {
12
+ if (!fs.existsSync(file)) return {};
13
+ const text = fs.readFileSync(file, 'utf8');
14
+ let value;
15
+ try { value = JSON.parse(text); }
16
+ catch { throw new Error(`需求元信息不是合法 JSON,已停止写入以免覆盖:${file}(修复或删除该文件后重试)`); }
17
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`无效的需求元信息:${file}`);
18
+ return value;
19
+ }
20
+
21
+ // 固定长度,避免中文需求名与项目名拼接后超过文件名限制,也避免分隔符替换碰撞。
22
+ function lockPath(root, file) {
23
+ const target = path.join(fs.realpathSync.native(path.dirname(file)), path.basename(file));
24
+ const rel = path.relative(fs.realpathSync.native(root), target).split(path.sep).join('/');
25
+ const key = createHash('sha256').update(rel).digest('hex');
26
+ return path.join(root, LOCK_DIR, `${key}.lock`);
27
+ }
28
+
29
+ const alive = (pid) => {
30
+ if (!pid) return false;
31
+ try { process.kill(pid, 0); return true; }
32
+ catch (e) { return e.code === 'EPERM'; } // 存在但不属于当前用户
33
+ };
34
+
35
+ const busy = (lock) => new Error(`需求元信息正在写入,请稍后重试:${lock}`);
36
+ const expired = (file) => Date.now() - fs.statSync(file).mtimeMs > STALE_MS;
37
+
38
+ function removeEmptyLock(lock) {
39
+ try { fs.rmdirSync(lock); return true; }
40
+ catch (e) {
41
+ if (e.code === 'ENOENT') return true;
42
+ if (e.code === 'ENOTEMPTY' || e.code === 'EEXIST') return false;
43
+ throw e;
44
+ }
45
+ }
46
+
47
+ function reclaim(lock) {
48
+ try {
49
+ const owners = fs.readdirSync(lock);
50
+ if (!owners.length && !expired(lock)) return false;
51
+ for (const name of owners) {
52
+ const pid = /^(\d+)-[\da-f-]+\.json$/.exec(name)?.[1];
53
+ const owner = path.join(lock, name);
54
+ if (!pid || alive(Number(pid)) || !expired(owner)) return false;
55
+ // UUID 标记不复用。即使另一个进程已重建目录,也不会删到它的标记。
56
+ try { fs.unlinkSync(owner); } catch (e) { if (e.code !== 'ENOENT') throw e; }
57
+ }
58
+ return removeEmptyLock(lock);
59
+ } catch (e) {
60
+ if (e.code === 'ENOENT') return !fs.existsSync(lock);
61
+ throw e;
62
+ }
63
+ }
64
+
65
+ function acquire(lock) {
66
+ fs.mkdirSync(path.dirname(lock), { recursive: true });
67
+ for (let attempt = 0; attempt < 2; attempt += 1) {
68
+ try { fs.mkdirSync(lock); }
69
+ catch (e) {
70
+ if (e.code !== 'EEXIST') throw e;
71
+ if (reclaim(lock)) continue;
72
+ throw busy(lock);
73
+ }
74
+ const name = `${process.pid}-${randomUUID()}.json`;
75
+ const owner = path.join(lock, name);
76
+ const release = () => {
77
+ try { fs.unlinkSync(owner); } catch (e) { if (e.code !== 'ENOENT') throw e; }
78
+ removeEmptyLock(lock);
79
+ };
80
+ try {
81
+ fs.writeFileSync(owner, `${JSON.stringify({ pid: process.pid, at: new Date().toISOString() })}\n`, { flag: 'wx' });
82
+ // mkdir 后进程若停顿到空目录过期,其他进程可能已经重建目录。
83
+ const owners = fs.readdirSync(lock);
84
+ if (owners.length !== 1 || owners[0] !== name) throw busy(lock);
85
+ return release;
86
+ } catch (e) {
87
+ release();
88
+ if (e.code === 'ENOENT') throw busy(lock);
89
+ throw e;
90
+ }
91
+ }
92
+ throw busy(lock);
93
+ }
94
+
95
+ export function updateMeta(file, update, { root = process.cwd(), allowFinalization = false } = {}) {
96
+ fs.mkdirSync(path.dirname(file), { recursive: true });
97
+ const lock = lockPath(root, file);
98
+ const release = acquire(lock);
99
+ const tmp = path.join(path.dirname(lock), `${path.basename(file)}.${randomUUID()}.tmp`);
100
+ try {
101
+ const current = readMeta(file);
102
+ if (current.pending_finalization && !allowFinalization) throw new Error(`产物收尾尚未完成,先运行 artifact.mjs resume --id ${current.pending_finalization.run_id}`);
103
+ const next = update(current);
104
+ const text = `${JSON.stringify(next, null, 2)}\n`;
105
+ if (!fs.existsSync(file) || fs.readFileSync(file, 'utf8') !== text) {
106
+ fs.writeFileSync(tmp, text);
107
+ fs.renameSync(tmp, file);
108
+ }
109
+ return next;
110
+ } finally {
111
+ fs.rmSync(tmp, { force: true });
112
+ release();
113
+ }
114
+ }
@@ -0,0 +1,21 @@
1
+ // ---------------------------------------------------------------- glob
2
+ // ** 跨目录、* 不跨 /、? 单个字符、{a,b} 展开(括号里同样支持这些写法);不含 / 的模式匹配文件名(同 .gitignore)。不区分大小写。
3
+ // 没有闭合的 { 按普通字符处理(画像里写错也不会卡住)
4
+ function globSource(glob) {
5
+ let re = '';
6
+ for (let i = 0; i < glob.length; i++) {
7
+ const c = glob[i];
8
+ const end = c === '{' ? glob.indexOf('}', i) : -1;
9
+ if (c === '*' && glob[i + 1] === '*') {
10
+ const slash = glob[i + 2] === '/';
11
+ re += slash ? '(?:.*/)?' : '.*';
12
+ i += slash ? 2 : 1;
13
+ } else if (c === '*') re += '[^/]*';
14
+ else if (c === '?') re += '[^/]';
15
+ else if (end > i) { re += `(?:${glob.slice(i + 1, end).split(',').map(globSource).join('|')})`; i = end; }
16
+ else re += c.replace(/[.+^$(){}|[\]\\]/g, '\\$&');
17
+ }
18
+ return re;
19
+ }
20
+ export const globToRegExp = (glob) => new RegExp(`^${globSource(glob)}$`, 'i');
21
+ export const matchGlob = (p, glob) => globToRegExp(glob).test(glob.includes('/') ? p : p.split('/').pop());
@@ -0,0 +1,218 @@
1
+ // 项目布局与配置;不依赖需求写入或任何命令入口。
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const SKILLS_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
8
+ const INSTALL_BASES = ['.agents/skills', '.claude/skills', '.qwen/skills', '.codebuddy/skills'];
9
+ const git = (cwd, args) => spawnSync('git', args, { cwd, encoding: 'utf8' });
10
+ const readJson = (f) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return null; } };
11
+ const toPosix = (p) => p.split(path.sep).join('/');
12
+ const relOf = (root, abs) => toPosix(path.relative(root, abs));
13
+
14
+ // 本工具在项目里的唯一目录
15
+ export const HOME = 'workflow-run';
16
+ export const REQ_DIR = `${HOME}/docs/requirements`;
17
+ export const TEMPLATES_DIR = `${HOME}/templates`;
18
+ export const TMP_DIR = `${HOME}/tmp`;
19
+ export const IGNORE_LINE = `${HOME}/docs/`;
20
+ export const homeDir = (root) => path.join(root, HOME);
21
+ // workflow-run/ 自己是 git 仓库(团队文档仓库克隆到这里)= 独立文档仓库模式
22
+ export const homeIsRepo = (root) => fs.existsSync(path.join(root, HOME, '.git'));
23
+ // 产物种类 → 需求目录里的文件名(只放最新版 <base>.md;版本号在 meta.json 的 versions,旧版归档为 <base>_v<N>.md)
24
+ // 需求名 / 项目名 → 目录名:保留中文,去掉路径与文件系统不允许的字符,空白换成 -
25
+ export function dirName(name) {
26
+ const s = String(name).normalize('NFC').trim()
27
+ .replace(/[\\/:*?"<>|#%{}^~[\]`'$&@!=+,;]+/g, '-')
28
+ .replace(/\s+/g, '-')
29
+ .replace(/-{2,}/g, '-')
30
+ .replace(/^[-.]+|[-.]+$/g, '');
31
+ return [...s].slice(0, 60).join('') || 'unnamed';
32
+ }
33
+
34
+ // ------------------------------------------------------------------ 配置与布局
35
+ // 画像所在目录:本脚本所在的 skills 目录;从安装包调用时(安装器)到项目里已安装的 skills 目录找
36
+ export function profileDir(root) {
37
+ const own = path.join(SKILLS_DIR, 'workflow');
38
+ if (fs.existsSync(path.join(own, 'profile.json')) || fs.existsSync(path.join(own, 'profile.local.json'))) return own;
39
+ for (const b of INSTALL_BASES) { const d = path.join(root, b, 'workflow'); if (fs.existsSync(path.join(d, 'profile.json'))) return d; }
40
+ return own;
41
+ }
42
+
43
+ // workflow/profile.json 的 artifacts,profile.local.json(个人设置,不提交)覆盖其上
44
+ export function artifactsConfig(root) {
45
+ const dir = profileDir(root);
46
+ const team = readJson(path.join(dir, 'profile.json'))?.artifacts ?? {};
47
+ const mine = readJson(path.join(dir, 'profile.local.json'))?.artifacts ?? {};
48
+ const c = { ...team, ...mine };
49
+ return { project: c.project ? String(c.project) : '', commit_prompt: c.commit_prompt !== false, profile_dir: dir };
50
+ }
51
+
52
+ // 产物位置:两种模式都是 workflow-run/docs/requirements/<需求>/<项目>/。
53
+ // mode 只决定谁来提交(project = 随代码提交,repo = workflow-run/ 是独立的文档仓库)、引用怎么写、项目名能不能自动取
54
+ export function layout(root, cfg = artifactsConfig(root)) {
55
+ const home = homeDir(root);
56
+ const base = path.join(root, REQ_DIR);
57
+ if (!homeIsRepo(root)) {
58
+ const project = cfg.project ? dirName(cfg.project) : suggestProject(root);
59
+ return { mode: 'project', ok: true, base, home, repo: null, project, project_configured: !!cfg.project, commit_prompt: cfg.commit_prompt, reqDir: (slug) => path.join(base, slug, project), ref: (abs) => relOf(root, abs) };
60
+ }
61
+ const repoName = remoteName(home);
62
+ const L = { mode: 'repo', base, home, repo: home, repo_rel: HOME, repo_name: repoName, project: cfg.project ? dirName(cfg.project) : null, project_configured: !!cfg.project, commit_prompt: cfg.commit_prompt };
63
+ L.reqDir = (slug) => path.join(base, slug, L.project ?? '_');
64
+ // 文档里引用产物用「文档仓库名:仓库内路径」,各服务、各人的克隆里都一样
65
+ L.ref = (abs) => `${repoName}:${toPosix(path.relative(home, abs))}`;
66
+ if (!L.project) return { ...L, ok: false, need_project: true, suggested_project: suggestProject(root), hint: '文档仓库模式需要项目名(产物放在 workflow-run/docs/requirements/<需求名>/<项目名>/),只需配置一次:问用户这个项目在文档仓库里叫什么(默认 suggested_project),然后运行 config --project <项目名>' };
67
+ return { ...L, ok: true };
68
+ }
69
+
70
+ // 文档仓库名:它的 git 远端仓库名,没有远端时用 workflow-run
71
+ const remoteNames = new Map();
72
+ function remoteName(home) {
73
+ if (!remoteNames.has(home)) {
74
+ const url = git(home, ['remote', 'get-url', 'origin']).stdout?.trim();
75
+ remoteNames.set(home, url ? url.replace(/[/\\]+$/, '').replace(/\.git$/, '').split(/[/\\:]/).pop() || HOME : HOME);
76
+ }
77
+ return remoteNames.get(home);
78
+ }
79
+
80
+ // 项目名建议:git 远端仓库名,取不到用项目目录名
81
+ export function suggestProject(root) {
82
+ const url = git(root, ['remote', 'get-url', 'origin']).stdout?.trim();
83
+ const name = url ? url.replace(/[/\\]+$/, '').replace(/\.git$/, '').split(/[/\\:]/).pop() : path.basename(path.resolve(root));
84
+ return dirName(name);
85
+ }
86
+
87
+ export function setConfig(root, patch, { local = false } = {}) {
88
+ const dir = profileDir(root);
89
+ const f = path.join(dir, local ? 'profile.local.json' : 'profile.json');
90
+ const cur = readJson(f) ?? {};
91
+ const a = { ...(cur.artifacts ?? {}) };
92
+ if (patch.project !== undefined) a.project = dirName(patch.project);
93
+ if (patch.commit_prompt !== undefined) a.commit_prompt = patch.commit_prompt;
94
+ fs.mkdirSync(dir, { recursive: true });
95
+ fs.writeFileSync(f, `${JSON.stringify({ ...cur, artifacts: a }, null, 2)}\n`);
96
+ const L = layout(root);
97
+ return { file: relOf(root, f), artifacts: a, effective: { mode: L.mode, repo: L.repo_rel ?? null, project: L.project, commit_prompt: L.commit_prompt, ok: L.ok, hint: L.ok ? null : L.hint } };
98
+ }
99
+
100
+ // .ignore 里加上需求目录(ripgrep 与 agent 的搜索跳过它;git 不受影响)。返回是否改动
101
+ export function ensureIgnore(root) {
102
+ const f = path.join(root, '.ignore');
103
+ const text = fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : '';
104
+ const norm = (l) => l.trim().replace(/^\//, '').replace(/\/$/, '');
105
+ if (text.split(/\r?\n/).some((l) => norm(l) === norm(IGNORE_LINE))) return false;
106
+ const add = `# workflow-run:需求产物(方案、交付说明、审查报告、技术 / 上线方案)不参与代码搜索,检索交给 DocNexus\n${IGNORE_LINE}\n`;
107
+ fs.writeFileSync(f, text ? `${text.replace(/\s*$/, '')}\n\n${add}` : add);
108
+ return true;
109
+ }
110
+
111
+
112
+ const PROFILE_FIELDS = ['main_branch', 'build', 'test', 'test_single', 'lint', 'config_center', 'deploy.platform', 'deploy.regions', 'job_annotation'];
113
+ const PROFILE_REQUIRED = ['main_branch', 'build', 'test'];
114
+
115
+ const OS_NAMES = { win32: 'windows', darwin: 'macos', linux: 'linux' };
116
+ export function detectEnv() {
117
+ const os = OS_NAMES[process.platform] ?? process.platform;
118
+ let shell;
119
+ if (process.platform === 'win32') {
120
+ shell = spawnSync('pwsh', ['-NoProfile', '-NonInteractive', '-Command', 'exit 0'], { stdio: 'ignore', timeout: 15000 }).status === 0 ? 'pwsh' : 'powershell';
121
+ } else shell = path.basename(process.env.SHELL || 'sh');
122
+ return { os, shell };
123
+ }
124
+ // 终端的写法提示:PowerShell 5.1 没有 && / ||,pwsh 7 有
125
+ export const SHELL_NOTES = {
126
+ powershell: 'Windows PowerShell 5.1:没有 && 和 ||,多条命令用 ; 分开;不要用 2>/dev/null、grep、head 等 Unix 命令',
127
+ pwsh: 'PowerShell 7:支持 &&;不要用 2>/dev/null、grep、head 等 Unix 命令',
128
+ };
129
+ export function readEnv() {
130
+ const rec = readJson(path.join(SKILLS_DIR, 'workflow', 'profile.local.json'))?.env;
131
+ const env = rec?.os ? { os: rec.os, shell: rec.shell ?? null, source: 'install' } : { os: OS_NAMES[process.platform] ?? process.platform, shell: null, source: 'runtime' };
132
+ const note = SHELL_NOTES[env.shell];
133
+ return { ...env, ...(note ? { note } : {}) };
134
+ }
135
+
136
+ // 开发环境配置(toolchain):画像里的路径可能写 $JAVA_HOME / ${VAR} / %VAR% / ~,用 env_vars 与进程环境展开。
137
+ // env_vars 优先(画像里显式声明的是对的),缺失的键回退到本机进程环境(HOME、USERPROFILE 这类)。
138
+ // 展开后为空 = 变量确实没配(不是「留空」,要报出来);路径里有空格照常,不做 shell 求值。
139
+ const VAR_RE = /\$\{(\w+)\}|\$(\w+)|%(\w+)%/g;
140
+ export function expandPath(v, vars = {}, env = process.env) {
141
+ if (typeof v !== 'string' || !v) return { raw: v ?? '', resolved: '', missing: [] };
142
+ const look = (n) => (vars[n] !== undefined && vars[n] !== '' ? vars[n] : (env[n] ?? ''));
143
+ const home = look('HOME') || look('USERPROFILE') || '';
144
+ let s = v;
145
+ if (s === '~' || s.startsWith('~/') || s.startsWith('~\\')) s = home ? home + s.slice(1) : s;
146
+ const missing = [];
147
+ for (const m of v.matchAll(VAR_RE)) { const n = m[1] ?? m[2] ?? m[3]; if (!look(n)) missing.push(n); }
148
+ const resolved = s.replace(VAR_RE, (m, a, b, c) => look(a ?? b ?? c)).replace(/[\\/]+$/, '');
149
+ return { raw: v, resolved, missing };
150
+ }
151
+
152
+ // 画像里的 toolchain(profile.json)与个人覆盖(profile.local.json),逐个子字段合并,后者优先。
153
+ // 「没声明」和「显式写空」是两回事:本机写 "" 表示**不使用**团队那个值(用工具自己的默认配置),
154
+ // 所以要按 null / "" 区分来源,不能只看值真不真。
155
+ export function readToolchain(root) {
156
+ const dir = path.join(SKILLS_DIR, 'workflow');
157
+ const team = readJson(path.join(dir, 'profile.json')) ?? {};
158
+ const mine = readJson(path.join(dir, 'profile.local.json')) ?? {};
159
+ const declared = (o) => typeof o === 'string';
160
+ // 个人声明过(含 "")就以个人为准;否则用团队值。cleared 表示被个人显式留空
161
+ const merge = (t, m) => {
162
+ if (declared(m)) return m === '' ? { value: '', source: 'local', cleared: true } : { value: m, source: 'local' };
163
+ if (declared(t) && t !== '') return { value: t, source: 'team' };
164
+ return { value: '', source: null };
165
+ };
166
+ const vars = { ...(team.env_vars ?? {}), ...(mine.env_vars ?? {}) };
167
+ const fields = {
168
+ java_home: merge(team.toolchain?.java_home, mine.toolchain?.java_home),
169
+ 'maven.settings': merge(team.toolchain?.maven?.settings, mine.toolchain?.maven?.settings),
170
+ 'maven.repository': merge(team.toolchain?.maven?.repository, mine.toolchain?.maven?.repository),
171
+ gradle_user_home: merge(team.toolchain?.gradle_user_home, mine.toolchain?.gradle_user_home),
172
+ node: merge(team.toolchain?.node, mine.toolchain?.node),
173
+ };
174
+ const out = {};
175
+ const cleared = [];
176
+ for (const [k, { value, source, cleared: c }] of Object.entries(fields)) {
177
+ if (c) { cleared.push(k); continue; } // 个人明确不用这个字段:不展开、不校验、也不报缺失
178
+ if (value) out[k] = { ...expandPath(value, vars), source };
179
+ }
180
+ // toolchain 为空时也给出 env_vars,便于 agent 知道该用什么变量写路径
181
+ return { fields: out, env_vars: vars, cleared, configured: Object.keys(out).length > 0 };
182
+ }
183
+
184
+ // 每个字段的路径在本机是否存在(写入画像前、构建跑不起来时核对用)。
185
+ // 只判断存在性,不判断版本对不对;current 是本机当前进程的值,便于和画像对照
186
+ export function checkToolchain(root, { env = process.env } = {}) {
187
+ const tc = readToolchain(root);
188
+ const check = (f) => {
189
+ // 变量没配时展开结果可能是别处真存在的路径($MISSING/bin 展开成 /bin),必须按「没配」算不通过
190
+ let exists = false;
191
+ try { exists = !f.missing.length && !!f.resolved && fs.existsSync(f.resolved); } catch { exists = false; }
192
+ const kind = exists ? (() => { try { return fs.statSync(f.resolved).isDirectory() ? 'dir' : 'file'; } catch { return 'other'; } })() : null;
193
+ return { ...f, exists, kind, ...(f.missing.length ? { unset_vars: f.missing } : {}), ...(f.raw !== f.resolved ? { expanded: true } : {}) };
194
+ };
195
+ const fields = Object.fromEntries(Object.entries(tc.fields).map(([k, f]) => [k, check(f)]));
196
+ const bad = Object.entries(fields).filter(([, f]) => !f.exists).map(([k]) => k);
197
+ return {
198
+ fields, configured: tc.configured, env_vars: tc.env_vars, ok: bad.length === 0,
199
+ missing: bad,
200
+ // 个人在 profile.local.json 里显式留空、表示不用团队那个值的字段(用工具默认配置)
201
+ ...(tc.cleared.length ? { cleared: tc.cleared } : {}),
202
+ // 本机当前值:和画像对不上时,多半是画像抄的是别人的机器
203
+ current: { JAVA_HOME: env.JAVA_HOME ?? null, MAVEN_HOME: env.MAVEN_HOME ?? null, GRADLE_USER_HOME: env.GRADLE_USER_HOME ?? null, node: path.dirname(process.execPath) },
204
+ how: tc.configured ? (bad.length ? `核对 toolchain 里不存在或变量没配的字段:${bad.join('、')}(本机值见 current);改本机的那份用 profile.local.json,见 workflow/references/profile.md` : null) : '还没有配置开发环境:运行 /workflow profile 由脚本推断后确认,见 workflow/references/profile.md',
205
+ };
206
+ }
207
+
208
+ export function readProfile(root) {
209
+ const f = path.join(SKILLS_DIR, 'workflow', 'profile.json');
210
+ const profile = readJson(f);
211
+ const get = (k) => k.split('.').reduce((o, p) => (o == null ? undefined : o[p]), profile);
212
+ const isEmpty = (v) => v == null || v === '' || (Array.isArray(v) && !v.length);
213
+ const empty = profile ? PROFILE_FIELDS.filter((k) => isEmpty(get(k))) : PROFILE_FIELDS;
214
+ return {
215
+ path: relOf(root, f), exists: !!profile, profile: profile ?? {}, empty, env: readEnv(), toolchain: readToolchain(root),
216
+ complete: !!profile && PROFILE_REQUIRED.every((k) => !empty.includes(k)),
217
+ };
218
+ }
@@ -0,0 +1,68 @@
1
+ // 需求目录读取与查询;不写索引或运行状态。
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { layout } from './project.mjs';
5
+ import { FILES, parseFile } from './artifact-model.mjs';
6
+ import { readMeta } from './meta-store.mjs';
7
+
8
+ const relative = (root, file) => path.relative(root, file).split(path.sep).join('/');
9
+ const directories = (dir) => fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.name.startsWith('.'));
10
+
11
+ export function readRequirementDirectories(root, L = layout(root), { allProjects = false, diagnostics = [] } = {}) {
12
+ if ((!allProjects && !L.ok && L.mode === 'repo') || !fs.existsSync(L.base)) return [];
13
+ const out = [];
14
+ for (const req of directories(L.base)) {
15
+ for (const project of directories(path.join(L.base, req.name))) {
16
+ if (!allProjects && project.name !== L.project) continue;
17
+ const abs = path.join(L.base, req.name, project.name);
18
+ const file = path.join(abs, 'meta.json');
19
+ let meta = {}; let valid = true;
20
+ try {
21
+ meta = readMeta(file);
22
+ if ((meta.branches !== undefined && (!Array.isArray(meta.branches) || meta.branches.some((b) => typeof b !== 'string')))
23
+ || (meta.runs !== undefined && (!meta.runs || typeof meta.runs !== 'object' || Array.isArray(meta.runs)))) throw new Error(`无效的需求绑定或运行记录:${file}`);
24
+ } catch (e) {
25
+ diagnostics.push({ code: 'invalid_meta', path: relative(root, file), message: e.message });
26
+ meta = {}; valid = false;
27
+ }
28
+ out.push({ abs, dir: relative(root, abs), slug: req.name, project: project.name, name: meta.name ?? req.name,
29
+ branches: meta.branches ?? [], updated: meta.updated ?? null, meta, valid });
30
+ }
31
+ }
32
+ return out;
33
+ }
34
+
35
+ export function requirements(root, L = layout(root)) {
36
+ return readRequirementDirectories(root, L).map(({ dir, abs, slug, name, branches, updated, meta }) => ({ dir, abs, slug, name, branches, updated, meta }));
37
+ }
38
+
39
+ export function groupRequirements(dirs) {
40
+ const groups = new Map();
41
+ for (const d of dirs) {
42
+ if (!groups.has(d.slug)) groups.set(d.slug, []);
43
+ groups.get(d.slug).push(d);
44
+ }
45
+ return [...groups].map(([slug, rows]) => ({ slug, name: rows.map((d) => d.meta.name).find(Boolean) ?? slug,
46
+ updated: rows.map((d) => d.updated ?? '').sort().at(-1) || null,
47
+ projects: rows.map(({ project, abs, dir, meta }) => ({ project, abs, dir, meta })) }));
48
+ }
49
+
50
+ export function repoRequirements(root, L = layout(root)) {
51
+ return groupRequirements(readRequirementDirectories(root, L, { allProjects: true }));
52
+ }
53
+
54
+ export function artifactFiles(root, { allProjects = false } = {}) {
55
+ const L = layout(root);
56
+ return readRequirementDirectories(root, L, { allProjects }).flatMap((d) => fs.readdirSync(d.abs).flatMap((name) => {
57
+ const p = parseFile(name);
58
+ if (!p) return [];
59
+ const abs = path.join(d.abs, name);
60
+ return [{ abs, rel: relative(root, abs), cite: L.ref(abs), slug: d.slug, project: d.project, ...p,
61
+ ...(name === `${FILES[p.kind]}.md` ? { version: d.meta.versions?.[p.kind] ?? 1 } : {}) }];
62
+ }));
63
+ }
64
+
65
+ export function find(root, branch, L = layout(root)) {
66
+ return requirements(root, L).filter((r) => r.branches.includes(branch))
67
+ .sort((a, b) => String(b.updated).localeCompare(String(a.updated)))[0] ?? null;
68
+ }