@aipper/aiws 0.0.24 → 0.0.25

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.
@@ -0,0 +1,338 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs/promises";
3
+ import { pathExists } from "../fs.js";
4
+
5
+ /**
6
+ * @param {string} input
7
+ */
8
+ function normalizeSlashes(input) {
9
+ return String(input || "").replaceAll("\\", "/");
10
+ }
11
+
12
+ /**
13
+ * @param {string} gitRoot
14
+ * @param {string} absPath
15
+ */
16
+ export function relFromRoot(gitRoot, absPath) {
17
+ return normalizeSlashes(path.relative(gitRoot, absPath));
18
+ }
19
+
20
+ /**
21
+ * @param {string} absDir
22
+ * @param {{ maxDepth?: number, maxFiles?: number }} [options]
23
+ * @returns {Promise<string[]>}
24
+ */
25
+ async function listFilesRecursive(absDir, options) {
26
+ const maxDepth = Number(options?.maxDepth ?? 4);
27
+ const maxFiles = Number(options?.maxFiles ?? 200);
28
+ /** @type {string[]} */
29
+ const out = [];
30
+
31
+ /** @param {string} curAbs @param {number} depth */
32
+ async function walk(curAbs, depth) {
33
+ if (depth > maxDepth) return;
34
+ let entries = [];
35
+ try {
36
+ entries = await fs.readdir(curAbs, { withFileTypes: true });
37
+ } catch {
38
+ return;
39
+ }
40
+ entries.sort((a, b) => a.name.localeCompare(b.name));
41
+ for (const entry of entries) {
42
+ if (out.length >= maxFiles) return;
43
+ const nextAbs = path.join(curAbs, entry.name);
44
+ if (entry.isDirectory()) {
45
+ await walk(nextAbs, depth + 1);
46
+ continue;
47
+ }
48
+ if (entry.isFile()) out.push(nextAbs);
49
+ }
50
+ }
51
+
52
+ if (!(await pathExists(absDir))) return out;
53
+ await walk(absDir, 0);
54
+ return out;
55
+ }
56
+
57
+ /**
58
+ * @param {string} gitRoot
59
+ * @param {string} changeDir
60
+ */
61
+ export async function collectCollaborationArtifacts(gitRoot, changeDir) {
62
+ const groups = [
63
+ ["analysis", "analysis"],
64
+ ["patches", "patches"],
65
+ ["review", "review"],
66
+ ["evidence", "evidence"],
67
+ ];
68
+
69
+ /** @type {Record<string, { label: string, dir: string, exists: boolean, count: number, files: string[], truncated: boolean }>} */
70
+ const dirs = {};
71
+ const counts = {
72
+ analysis: 0,
73
+ patches: 0,
74
+ review: 0,
75
+ evidence: 0,
76
+ total: 0,
77
+ };
78
+
79
+ for (const [key, label] of groups) {
80
+ const abs = path.join(changeDir, key);
81
+ const exists = await pathExists(abs);
82
+ const filesAbs = exists ? await listFilesRecursive(abs, { maxDepth: 4, maxFiles: 200 }) : [];
83
+ const files = filesAbs.map((item) => relFromRoot(gitRoot, item));
84
+ dirs[key] = {
85
+ label,
86
+ dir: relFromRoot(gitRoot, abs),
87
+ exists,
88
+ count: files.length,
89
+ files: files.slice(0, 8),
90
+ truncated: files.length > 8,
91
+ };
92
+ counts[key] = files.length;
93
+ counts.total += files.length;
94
+ }
95
+
96
+ return { dirs, counts };
97
+ }
98
+
99
+ /**
100
+ * Evidence_Path is user-declared; we treat it as best-effort hints, not hard gates.
101
+ *
102
+ * @param {string} gitRoot
103
+ * @param {string} changeId
104
+ * @param {string[]} evidencePaths
105
+ * @returns {Promise<{
106
+ * entries: Array<{rel: string, abs: string, exists: boolean, kind: string, isAbsolute: boolean}>,
107
+ * counts: { total: number, exists: number, missing: number, tmp: number, persistent: number, other: number, absolute: number },
108
+ * missing: string[]
109
+ * }>}
110
+ */
111
+ export async function analyzeEvidencePaths(gitRoot, changeId, evidencePaths) {
112
+ const changePrefix = `changes/${changeId}/`;
113
+ const evidencePrefix = `changes/${changeId}/evidence/`;
114
+ const reviewPrefix = `changes/${changeId}/review/`;
115
+
116
+ const entries = await Promise.all(
117
+ (evidencePaths || []).map(async (raw) => {
118
+ const rel = String(raw || "").trim();
119
+ const isAbsolute = path.isAbsolute(rel);
120
+ const abs = isAbsolute ? rel : path.join(gitRoot, rel);
121
+ const exists = rel ? await pathExists(abs) : false;
122
+
123
+ const relNorm = normalizeSlashes(rel);
124
+ let kind = "other";
125
+ if (relNorm.startsWith(".agentdocs/tmp/") || relNorm.startsWith(".agentdocs/")) kind = "tmp";
126
+ else if (relNorm.startsWith(evidencePrefix) || relNorm.startsWith(reviewPrefix) || relNorm.startsWith(changePrefix)) kind = "persistent";
127
+
128
+ return { rel, abs: path.resolve(abs), exists, kind, isAbsolute };
129
+ }),
130
+ );
131
+
132
+ const missing = entries.filter((entry) => entry.rel && !entry.exists).map((entry) => entry.rel);
133
+ const counts = {
134
+ total: entries.filter((entry) => entry.rel).length,
135
+ exists: entries.filter((entry) => entry.rel && entry.exists).length,
136
+ missing: missing.length,
137
+ tmp: entries.filter((entry) => entry.rel && entry.kind === "tmp").length,
138
+ persistent: entries.filter((entry) => entry.rel && entry.kind === "persistent").length,
139
+ other: entries.filter((entry) => entry.rel && entry.kind === "other").length,
140
+ absolute: entries.filter((entry) => entry.rel && entry.isAbsolute).length,
141
+ };
142
+
143
+ return { entries: entries.filter((entry) => entry.rel), counts, missing };
144
+ }
145
+
146
+ /**
147
+ * @param {string[]} a
148
+ * @param {string[]} b
149
+ */
150
+ export function mergeDeclaredValues(a, b) {
151
+ const seen = new Set();
152
+ /** @type {string[]} */
153
+ const out = [];
154
+ for (const raw of [...(a || []), ...(b || [])]) {
155
+ const value = String(raw || "").trim().replace(/^`+/, "").replace(/`+$/, "").trim();
156
+ if (!value) continue;
157
+ if (seen.has(value)) continue;
158
+ seen.add(value);
159
+ out.push(value);
160
+ }
161
+ return out;
162
+ }
163
+
164
+ /**
165
+ * @param {string[]} values
166
+ */
167
+ export function formatDeclaredValues(values) {
168
+ return (values || []).join(", ");
169
+ }
170
+
171
+ /**
172
+ * @param {string} input
173
+ */
174
+ function escapeRegExp(input) {
175
+ return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
176
+ }
177
+
178
+ /**
179
+ * Replace or insert a simple "ID: value" style line in Markdown.
180
+ *
181
+ * @param {string} text
182
+ * @param {string[]} labelCandidates
183
+ * @param {string} value
184
+ * @param {{ insertAfterLabels?: string[] }} options
185
+ */
186
+ export function upsertIdLine(text, labelCandidates, value, options) {
187
+ const src = String(text || "");
188
+ const labels = Array.isArray(labelCandidates) ? labelCandidates : [];
189
+ for (const label of labels) {
190
+ const re = new RegExp(`^(.*${escapeRegExp(label)}.*?[:=][ \\t]*)(.*)$`, "m");
191
+ const match = re.exec(src);
192
+ if (!match) continue;
193
+ const prefix = match[1] || "";
194
+ const replaced = src.replace(re, `${prefix}${value}`);
195
+ return { ok: true, changed: replaced !== src, text: replaced, mode: "replaced", label };
196
+ }
197
+
198
+ const insertAfter = Array.isArray(options?.insertAfterLabels) ? options.insertAfterLabels : [];
199
+ const lines = src.split(/\r?\n/);
200
+ let idx = 0;
201
+ for (let i = 0; i < Math.min(lines.length, 80); i++) {
202
+ const line = lines[i] || "";
203
+ if (insertAfter.some((label) => line.includes(label))) idx = i + 1;
204
+ }
205
+ const insertedLabel = labels[0] || "Evidence_Path";
206
+ lines.splice(idx, 0, `- ${insertedLabel}: ${value}`);
207
+ const inserted = lines.join("\n");
208
+ return { ok: true, changed: inserted !== src, text: inserted, mode: "inserted", label: labels[0] || "" };
209
+ }
210
+
211
+ /**
212
+ * Special-case insertion for proposal.md template style.
213
+ *
214
+ * @param {string} proposalText
215
+ * @param {string} value
216
+ */
217
+ export function upsertProposalEvidencePath(proposalText, value) {
218
+ const src = String(proposalText || "");
219
+ const re = new RegExp(`^(.*${escapeRegExp("Evidence_Path")}.*?[:=][ \\t]*)(.*)$`, "m");
220
+ if (re.test(src)) {
221
+ const match = re.exec(src);
222
+ const prefix = match?.[1] || "";
223
+ const out = src.replace(re, `${prefix}${value}`);
224
+ return { changed: out !== src, text: out, mode: "replaced" };
225
+ }
226
+ const lines = src.split(/\r?\n/);
227
+ let idx = 0;
228
+ for (let i = 0; i < Math.min(lines.length, 120); i++) {
229
+ if ((lines[i] || "").includes("Plan_File")) {
230
+ idx = i + 1;
231
+ break;
232
+ }
233
+ }
234
+ lines.splice(idx, 0, `- \`Evidence_Path\` = ${value}`);
235
+ const inserted = lines.join("\n");
236
+ return { changed: inserted !== src, text: inserted, mode: "inserted" };
237
+ }
238
+
239
+ /**
240
+ * @param {string} changeId
241
+ */
242
+ export function planVerifyHint(changeId) {
243
+ return `执行前质量门(优先):\`aiws change validate ${changeId} --strict\`(AI 工具中等价于 \`$ws-plan-verify\`)`;
244
+ }
245
+
246
+ /**
247
+ * @param {string} absDir
248
+ * @param {(fileName: string) => boolean} predicate
249
+ */
250
+ export async function findLatestFileByMtime(absDir, predicate) {
251
+ /** @type {Array<{ abs: string, mtimeMs: number }>} */
252
+ const matches = [];
253
+ if (!(await pathExists(absDir))) return "";
254
+ try {
255
+ const entries = await fs.readdir(absDir, { withFileTypes: true });
256
+ for (const entry of entries) {
257
+ if (!entry.isFile()) continue;
258
+ if (!predicate(entry.name)) continue;
259
+ const abs = path.join(absDir, entry.name);
260
+ const st = await fs.stat(abs);
261
+ matches.push({ abs, mtimeMs: st.mtimeMs });
262
+ }
263
+ } catch {
264
+ return "";
265
+ }
266
+ matches.sort((a, b) => b.mtimeMs - a.mtimeMs);
267
+ return matches[0]?.abs || "";
268
+ }
269
+
270
+ /**
271
+ * @param {{
272
+ * gitRoot: string,
273
+ * changeId: string,
274
+ * branch: string,
275
+ * status: any,
276
+ * collaboration: any,
277
+ * created: string[],
278
+ * validateRes: any,
279
+ * validateFailed: boolean
280
+ * }} options
281
+ */
282
+ export function buildDeliverySummary(options) {
283
+ const { gitRoot, changeId, branch, status, collaboration, created, validateRes, validateFailed } = options;
284
+ /** @type {string[]} */
285
+ const lines = [];
286
+ lines.push(`# Delivery Summary: ${changeId}`);
287
+ lines.push("");
288
+ lines.push(`Generated: ${new Date().toISOString().replace(/\.\d{3}Z$/, "Z")}`);
289
+ lines.push("");
290
+ lines.push("## Context");
291
+ lines.push(`- Worktree: \`${gitRoot}\``);
292
+ lines.push(`- Branch: \`${branch || "(detached)"}\``);
293
+ lines.push("");
294
+ lines.push("## Status");
295
+ lines.push(`- Phase: \`${status.phase}\``);
296
+ lines.push(`- Tasks: ${status.tasks.done}/${status.tasks.total} (unchecked=${status.tasks.unchecked})`);
297
+ lines.push(`- Truth drift: ${status.driftFiles.length > 0 ? status.driftFiles.join(", ") : "(none)"}`);
298
+ lines.push("");
299
+ lines.push("## Collaboration");
300
+ lines.push(`- analysis: ${collaboration.counts.analysis}`);
301
+ lines.push(`- patches: ${collaboration.counts.patches}`);
302
+ lines.push(`- review: ${collaboration.counts.review}`);
303
+ lines.push(`- evidence dir files: ${collaboration.counts.evidence}`);
304
+ for (const key of ["analysis", "patches", "review"]) {
305
+ const group = collaboration.dirs[key];
306
+ if (!group || group.count === 0) continue;
307
+ lines.push(`- ${group.label} files:`);
308
+ for (const rel of group.files) lines.push(` - \`${rel}\``);
309
+ if (group.truncated) lines.push(" - ...(truncated)");
310
+ }
311
+ lines.push("");
312
+ lines.push("## Bindings");
313
+ if (status.reqId) lines.push(`- Req_ID: \`${status.reqId}\``);
314
+ if (status.probId) lines.push(`- Problem_ID: \`${status.probId}\``);
315
+ if (status.bindings?.contractRow) lines.push(`- Contract_Row: \`${status.bindings.contractRow}\``);
316
+ if (status.bindings?.planFile) lines.push(`- Plan_File: \`${status.bindings.planFile}\``);
317
+ lines.push("");
318
+ lines.push("## Evidence (Created/Collected)");
319
+ if (created.length === 0) lines.push("- (none)");
320
+ else for (const item of created) lines.push(`- \`${item}\``);
321
+ lines.push("");
322
+ lines.push("## Quality Gate");
323
+ if (!validateRes) {
324
+ lines.push("- Strict validation: (skipped via --no-validate)");
325
+ } else {
326
+ lines.push(`- Strict validation ok: \`${validateRes.ok === true}\``);
327
+ lines.push(`- Errors: \`${Array.isArray(validateRes.errors) ? validateRes.errors.length : 0}\``);
328
+ lines.push(`- Warnings: \`${Array.isArray(validateRes.warnings) ? validateRes.warnings.length : 0}\``);
329
+ }
330
+ lines.push("");
331
+ lines.push("## Next");
332
+ lines.push(`- ${planVerifyHint(changeId)}`);
333
+ if (validateFailed) lines.push("- Fix strict validation errors, then re-run `aiws change evidence`");
334
+ else lines.push(`- Verify evidence gate: \`aiws change validate ${changeId} --strict --check-evidence\``);
335
+ if (collaboration.counts.patches > 0) lines.push("- Review delegated patch drafts before apply/merge; do not treat `changes/<id>/patches/` as auto-applied changes");
336
+ if (collaboration.counts.analysis > 0 && collaboration.counts.review === 0) lines.push("- Summarize delegated analysis into `changes/<id>/review/` before delivery");
337
+ return lines.join("\n") + "\n";
338
+ }