yadflow 4.10.0 → 4.11.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/CHANGELOG.md +97 -0
- package/README.md +12 -3
- package/bin/commands.mjs +5 -1
- package/bin/yad.mjs +109 -15
- package/cli/agent-guard-worker.mjs +13 -0
- package/cli/agent-guard.mjs +1053 -57
- package/cli/agent-rules.mjs +34 -3
- package/cli/argv-flags.mjs +2 -2
- package/cli/brain/vendor/LICENSE-graphology-library.txt +21 -0
- package/cli/brain/vendor/LICENSE-graphology.txt +21 -0
- package/cli/brain/vendor/LICENSE-sigma.txt +12 -0
- package/cli/brain/vendor/graphology-library.min.js +2 -0
- package/cli/brain/vendor/graphology.umd.min.js +2 -0
- package/cli/brain/vendor/sigma.min.js +1369 -0
- package/cli/brain/view/app.js +382 -0
- package/cli/brain/view/index.html +63 -0
- package/cli/brain/view/live.css +228 -0
- package/cli/brain/view/live.html +110 -0
- package/cli/brain/view/live.js +884 -0
- package/cli/brain/view/style.css +141 -0
- package/cli/brain-about.mjs +206 -0
- package/cli/brain-activity.mjs +285 -0
- package/cli/brain-skills.mjs +118 -0
- package/cli/brain-vendor.mjs +71 -0
- package/cli/brain-view.mjs +344 -0
- package/cli/brain.mjs +810 -0
- package/cli/ci-check.mjs +3 -3
- package/cli/doctor.mjs +80 -13
- package/cli/epic-state.mjs +93 -1
- package/cli/epic.mjs +15 -3
- package/cli/errors.mjs +2 -1
- package/cli/find-product.mjs +69 -15
- package/cli/foundation-publish.mjs +256 -0
- package/cli/gate.mjs +29 -3
- package/cli/git-read.mjs +38 -0
- package/cli/guard-stream.mjs +409 -0
- package/cli/hook.mjs +59 -9
- package/cli/issues-act.mjs +57 -13
- package/cli/issues-write.mjs +19 -6
- package/cli/issues.mjs +62 -23
- package/cli/lib.mjs +37 -2
- package/cli/local-page.mjs +138 -0
- package/cli/machine.mjs +1 -1
- package/cli/manifest.mjs +50 -0
- package/cli/map/view/app.js +712 -0
- package/cli/map/view/index.html +50 -0
- package/cli/map/view/style.css +142 -0
- package/cli/map-view.mjs +186 -0
- package/cli/map.mjs +637 -0
- package/cli/members.mjs +9 -15
- package/cli/next.mjs +1 -1
- package/cli/openpr.mjs +2 -2
- package/cli/plan.mjs +125 -0
- package/cli/platform.mjs +5 -5
- package/cli/product-index.mjs +1 -1
- package/cli/protection.mjs +32 -0
- package/cli/reconcile.mjs +8 -2
- package/cli/report.mjs +9 -3
- package/cli/reports-dir.mjs +391 -0
- package/cli/reports.mjs +65 -0
- package/cli/run-checks.mjs +5 -2
- package/cli/scan.mjs +1 -1
- package/cli/setup.mjs +30 -5
- package/cli/standup.mjs +87 -71
- package/cli/status.mjs +6 -5
- package/cli/test-agents-file.mjs +614 -8
- package/cli/test-brain-activity.mjs +753 -0
- package/cli/test-brain-view.mjs +381 -0
- package/cli/test-brain.mjs +795 -0
- package/cli/test-guide.mjs +211 -0
- package/cli/test-machine.mjs +59 -0
- package/cli/test-map.mjs +615 -0
- package/cli/test-reports.mjs +382 -0
- package/cli/test-run-checks.mjs +4 -0
- package/cli/test-worktree.mjs +24 -3
- package/cli/toolbox-connect.mjs +21 -6
- package/cli/toolbox.mjs +59 -4
- package/cli/update-commit.mjs +101 -9
- package/cli/usage.mjs +8 -4
- package/package.json +8 -4
- package/skills/yad-architecture/SKILL.md +22 -4
- package/skills/yad-change/SKILL.md +3 -1
- package/skills/yad-change/references/triage.md +2 -0
- package/skills/yad-checks/SKILL.md +2 -0
- package/skills/yad-checks/references/check-gates.md +8 -5
- package/skills/yad-checks/templates/checks/build-test-lint.sh +7 -0
- package/skills/yad-checks/templates/checks/install-deps.sh +6 -0
- package/skills/yad-checks/templates/checks/package-manager.sh +42 -0
- package/skills/yad-checks/templates/github/yad-checks.yml +3 -2
- package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +3 -2
- package/skills/yad-checks/templates/hooks/yad-activity.mjs +238 -0
- package/skills/yad-connect-repos/SKILL.md +14 -0
- package/skills/yad-discovery/SKILL.md +11 -0
- package/skills/yad-discovery/references/foundation-schema.md +11 -0
- package/skills/yad-docs/templates/app/package-lock.json +18 -10
- package/skills/yad-docs/templates/app/package.json +6 -1
- package/skills/yad-epic/SKILL.md +3 -0
- package/skills/yad-epic/references/state-schema.md +35 -1
- package/skills/yad-guide/SKILL.md +4 -4
- package/skills/yad-implement/SKILL.md +76 -15
- package/skills/yad-issues/SKILL.md +2 -1
- package/skills/yad-pr-template/templates/checks/pr-template.sh +8 -4
- package/skills/yad-pr-template/templates/checks/pr-title.sh +8 -4
- package/skills/yad-spec/SKILL.md +19 -0
- package/skills/yad-stories/SKILL.md +22 -4
- package/skills/yad-stories/references/story-schema.md +1 -1
package/cli/issues-write.mjs
CHANGED
|
@@ -7,14 +7,14 @@
|
|
|
7
7
|
import fs from 'node:fs';
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import { run, readJSON, forTerminal, c, log, fail, hand, info, ok as said, warn, emitJSON } from './lib.mjs';
|
|
10
|
-
import { epicFiles, productConfigPath } from './manifest.mjs';
|
|
10
|
+
import { epicFiles, isVerifiedLedger, productConfigPath } from './manifest.mjs';
|
|
11
11
|
import { epicIds, epicRoot, isGenesisType, isValidEpicId, PRODUCT_EPICS, WORK_ITEM_TYPES } from './epic-state.mjs';
|
|
12
12
|
import { addItemLabels, closeItem, commentOnItem, removeItemLabels } from './platform.mjs';
|
|
13
13
|
import { productIdentity } from './members.mjs';
|
|
14
14
|
import { prTarget } from './pr-list.mjs';
|
|
15
15
|
import { repoSources } from './standup.mjs';
|
|
16
16
|
import { api, shown, whyFailed, httpStatus, TIMEOUT } from './protection.mjs';
|
|
17
|
-
import { labelRules, pick, pickType, itemStatus } from './issues.mjs';
|
|
17
|
+
import { labelRules, pick, pickType, itemStatus, otherLabels } from './issues.mjs';
|
|
18
18
|
import { runEpicNew, epicIdFrom } from './epic.mjs';
|
|
19
19
|
import { allLinks, combinedStage, epicStage, itemKey, readLinks, writeLinks } from './issue-links.mjs';
|
|
20
20
|
|
|
@@ -117,6 +117,9 @@ export async function runIssuesShow(root, { ref, json = false, env = process.env
|
|
|
117
117
|
if (json) return emitJSON({ ok: true, ...out });
|
|
118
118
|
log(`${c.bold(out.ref)} ${out.title ?? '(confidential: open it on GitLab to read it)'}`);
|
|
119
119
|
info(`${out.state} · priority ${out.priority ?? 'none'} · type ${out.type ?? 'none'} · assigned ${out.assignees.join(', ') || 'nobody'}`);
|
|
120
|
+
// #514: the labels that are none of yad's own. Each was made safe to print when it was read.
|
|
121
|
+
const others = otherLabels(out.labels, rules);
|
|
122
|
+
if (others.length) info(`labels ${others.join(', ')}`);
|
|
120
123
|
if (out.url) info(out.url);
|
|
121
124
|
if (out.body) log(`\n${out.body}`);
|
|
122
125
|
return undefined;
|
|
@@ -163,7 +166,7 @@ function makeEntry(t, item, now) {
|
|
|
163
166
|
}
|
|
164
167
|
|
|
165
168
|
// Add the link (or find the one there) and write back. `{ entry, created, back }`.
|
|
166
|
-
function linkAndWriteBack(root, epic, t, item, { rules, epicType, now, runner }) {
|
|
169
|
+
export function linkAndWriteBack(root, epic, t, item, { rules, epicType, now, runner }) {
|
|
167
170
|
const items = readLinks(root, epic);
|
|
168
171
|
const key = itemKey({ host: t.host, repo: t.repo, number: item.number });
|
|
169
172
|
let entry = items.find((l) => itemKey(l) === key);
|
|
@@ -221,6 +224,16 @@ function registeredTargets(root, { env, runner }) {
|
|
|
221
224
|
}
|
|
222
225
|
|
|
223
226
|
// Bring each linked item up to date. `only` limits it to one epic's items. Returns the plan of what happened.
|
|
227
|
+
// How a changed record reaches the team (#512): `commit <file>` and, on a verified Product, the PR route. The
|
|
228
|
+
// Product's pr-title and pr-template checks let a PR of these records alone (issue-links files, the roadmap-items
|
|
229
|
+
// file, step owner files) through from any branch, and a review/EP-* branch would advance a step. The gates run
|
|
230
|
+
// the default branch's copy of the checks (#426), so that holds once a `yad update` carrying them has merged.
|
|
231
|
+
// Like `yad assign` (owners.mjs): with no verified Product there are no Product checks to name.
|
|
232
|
+
export function recordRoute(root, file) {
|
|
233
|
+
if (!isVerifiedLedger(readJSON(productConfigPath(root), null))) return `commit ${file}`;
|
|
234
|
+
return `commit ${file} on a branch of its own, not review/…, in a PR titled like \`chore: record tracker links\` — the Product checks let a PR of these records alone through, once a \`yad update\` that carries them has merged on the default branch`;
|
|
235
|
+
}
|
|
236
|
+
|
|
224
237
|
export function syncItems(root, { only = null, dryRun = false, close = true, env = process.env, runner = run, now = Date.now() } = {}) {
|
|
225
238
|
const links = allLinks(root);
|
|
226
239
|
const epicsOf = (key) => links.byItem.get(key) || [];
|
|
@@ -296,7 +309,7 @@ export async function runIssuesSync(root, { dryRun = false, json = false, env =
|
|
|
296
309
|
for (const s of r.skipped) warn(s);
|
|
297
310
|
for (const e of r.unreadable) warn(`${e}: its .sdlc/issue-links.json could not be read, so status labels and closes were held back`);
|
|
298
311
|
if (!r.items.length && !r.skipped.length && !r.unreadable.length) info('no items are linked to an epic');
|
|
299
|
-
else if (!dryRun) info('
|
|
312
|
+
else if (!dryRun) info(`${recordRoute(root, 'any .sdlc/issue-links.json this changed')}, so the team keeps the record`);
|
|
300
313
|
return undefined;
|
|
301
314
|
}
|
|
302
315
|
|
|
@@ -310,7 +323,7 @@ export function syncAfterGate(root, epic, { env = process.env, runner = run, now
|
|
|
310
323
|
const r = syncItems(root, { only: epic, close: false, env, runner, now });
|
|
311
324
|
const changed = r.items.filter((i) => i.commented || i.labelled.length || i.removed.length);
|
|
312
325
|
for (const i of changed) info(`updated ${i.ref}: ${[i.commented && 'comment', ...i.labelled.map((l) => `+${forTerminal(l)}`), ...i.removed.map((l) => `-${forTerminal(l)}`)].filter(Boolean).join(', ')}`);
|
|
313
|
-
if (changed.some((i) => i.commented)) info('
|
|
326
|
+
if (changed.some((i) => i.commented)) info(`${recordRoute(root, '.sdlc/issue-links.json')}, so the team keeps the record`);
|
|
314
327
|
for (const i of r.items) for (const f of i.failed) warn(`${i.ref}: ${forTerminal(f)}. The gate still passed; \`yad issues sync\` catches up`);
|
|
315
328
|
for (const s of r.skipped) warn(s);
|
|
316
329
|
} catch (e) {
|
|
@@ -332,7 +345,7 @@ export async function runIssuesLink(root, { ref, epic: raw, json = false, now =
|
|
|
332
345
|
if (json) return emitJSON({ ok: true, epic, url: entry.url, number: entry.number, created, commented: back.commented, labelled: back.labelled, failed: back.failed, notes: back.notes });
|
|
333
346
|
said(`${created ? 'linked' : 'already linked:'} ${got.label === 'Product' ? '' : forTerminal(got.label)}#${entry.number} → ${epic}`);
|
|
334
347
|
sayBack(back);
|
|
335
|
-
if (created) info('
|
|
348
|
+
if (created) info(`${recordRoute(root, '.sdlc/issue-links.json')}, so the team sees the link`);
|
|
336
349
|
return undefined;
|
|
337
350
|
}
|
|
338
351
|
|
package/cli/issues.mjs
CHANGED
|
@@ -9,14 +9,15 @@
|
|
|
9
9
|
// - a GitLab confidential item keeps its number and facts, and its title is never read into the model.
|
|
10
10
|
// Status is worked out from facts (open or closed, and later the linked epic). A `status:` label is never read.
|
|
11
11
|
import fs from 'node:fs';
|
|
12
|
-
import { run, readJSON, forTerminal, c, log, fail, hand, info, note } from './lib.mjs';
|
|
12
|
+
import { run, readJSON, forTerminal, c, log, fail, hand, info, note, warn } from './lib.mjs';
|
|
13
13
|
import { productConfigPath } from './manifest.mjs';
|
|
14
14
|
import { platformLogin } from './platform.mjs';
|
|
15
15
|
import { readMembers, productIdentity } from './members.mjs';
|
|
16
16
|
import { prTarget } from './pr-list.mjs';
|
|
17
17
|
import { repoSources, whoseAccount } from './standup.mjs';
|
|
18
18
|
import { api, httpStatus, shown, whyFailed, PAGE, TIMEOUT } from './protection.mjs';
|
|
19
|
-
import { esc
|
|
19
|
+
import { esc } from './usage.mjs';
|
|
20
|
+
import { writeOrSave } from './reports-dir.mjs';
|
|
20
21
|
import { allLinks, combinedStage, epicStage, itemKey } from './issue-links.mjs';
|
|
21
22
|
|
|
22
23
|
export const MAX_ITEMS = 1000;
|
|
@@ -71,6 +72,22 @@ export function pickType(labels, table) {
|
|
|
71
72
|
return ordinary.value ? ordinary : pick(labels, part((f) => f));
|
|
72
73
|
}
|
|
73
74
|
|
|
75
|
+
// #514 — what a label is to yad: one of its own (a priority, type or status spelling, or an item's `epic:` link) or
|
|
76
|
+
// any other. `owner` names which, so a write can say which flag sets it.
|
|
77
|
+
export function labelOwner(name, rules) {
|
|
78
|
+
const l = labelKey(name);
|
|
79
|
+
if (/^epic:/.test(l)) return 'epic';
|
|
80
|
+
for (const kind of ['priority', 'type', 'status']) if (Object.values(rules[kind]).some((names) => names.some((n) => labelKey(n) === l))) return kind;
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
// THE one way #514 compares two label names: as an item's labels are read (`clean`: control and invisible
|
|
84
|
+
// characters out, each run of spaces one space, trimmed), in any case. Every comparison of a name a person
|
|
85
|
+
// typed, an item carries, a repo has or a rule lists goes through it — two spellings of one rule let a
|
|
86
|
+
// double-spaced `priority: P1` past the refusal of yad's own labels (review 2).
|
|
87
|
+
export const labelKey = (name) => clean(name).toLowerCase();
|
|
88
|
+
// An item's labels that are none of yad's own, in the order the platform gave them.
|
|
89
|
+
export const otherLabels = (labels, rules) => labels.filter((l) => labelOwner(l, rules) === null);
|
|
90
|
+
|
|
74
91
|
// ---- reading ---------------------------------------------------------------------------------------
|
|
75
92
|
|
|
76
93
|
const str = (v) => (typeof v === 'string' && v ? v : null);
|
|
@@ -247,9 +264,13 @@ const list = (v) => String(v).split(',').map((x) => x.trim()).filter(Boolean);
|
|
|
247
264
|
const lower = (v) => String(v).toLowerCase();
|
|
248
265
|
|
|
249
266
|
// Narrow and sort. `mine` (from `--me`) is a map `platform\0host` → this person's login.
|
|
250
|
-
|
|
267
|
+
// `label` (#514): each value is a comma list, and an item must carry one name of EVERY value — so
|
|
268
|
+
// `--label a --label b` asks for both and `--label a,b` for either. Whole names, any case.
|
|
269
|
+
export function applyFilters(items, { priority, type, status, assignee, repo, label = [], since, until, date = 'created', sort = 'priority', mine = null } = {}) {
|
|
251
270
|
const inList = (want, v, none) => !want || list(want).map(lower).includes(lower(v ?? none));
|
|
252
|
-
const
|
|
271
|
+
const labelSets = (Array.isArray(label) ? label : [label]).filter((v) => v != null).map((v) => list(v).map(labelKey));
|
|
272
|
+
const hasLabels = (i) => { const have = new Set(i.labels.map(labelKey)); return labelSets.every((any) => any.some((n) => have.has(n))); };
|
|
273
|
+
const out = items.filter((i) => inList(priority, i.priority, 'none') && inList(type, i.type, 'none') && inList(status, i.status, '') && inList(repo, i.repo, '') && hasLabels(i)
|
|
253
274
|
&& (!assignee || (lower(assignee) === 'none' ? i.assignees.length === 0 : i.assignees.some((a) => [a.login, a.member].filter(Boolean).map(lower).includes(lower(assignee)))))
|
|
254
275
|
&& (!mine || i.assignees.some((a) => mine.get(`${i.platform}\0${i.host}`)?.toLowerCase() === a.login.toLowerCase()))
|
|
255
276
|
&& (!since || (i[date] && i[date] >= since)) && (!until || (i[date] && i[date] <= until)));
|
|
@@ -269,10 +290,14 @@ const who = (i) => (i.assignees.length ? i.assignees.map((a) => a.member || a.lo
|
|
|
269
290
|
const counts = (s) => `${s.total} item${s.total === 1 ? '' : 's'}: ${STATUSES.map((v) => `${s.status[v]} ${v}`).join(', ')}; ${s.priority.none} with no priority, ${s.type.none} with no type, ${s.unassigned} unassigned`;
|
|
270
291
|
const gaps = (m) => [...m.notRead, ...m.notes];
|
|
271
292
|
|
|
272
|
-
|
|
293
|
+
// An item's other labels as text, or '' (#514). Label names are the platform's text: `clean` made them safe to print.
|
|
294
|
+
const othersOf = (i, rules) => otherLabels(i.labels, rules);
|
|
295
|
+
|
|
296
|
+
function renderText(m, rules = labelRules(null)) {
|
|
273
297
|
info(c.bold(counts(m.summary)));
|
|
274
298
|
for (const i of m.items) {
|
|
275
|
-
|
|
299
|
+
const others = othersOf(i, rules);
|
|
300
|
+
log(` ${i.ref.padEnd(14)} ${(i.priority ?? '--').padEnd(3)} ${(i.type ?? '-').padEnd(12)} ${i.status.padEnd(12)} ${who(i).padEnd(16)} ${i.title}${others.length ? c.dim(` {${others.join(', ')}}`) : ''}${i.flags.length ? c.yellow(` [${i.flags.join('; ')}]`) : ''}`);
|
|
276
301
|
}
|
|
277
302
|
if (!m.items.length) log(m.notRead.length ? ' nothing found in the repos that answered' : ' no items');
|
|
278
303
|
for (const g of gaps(m)) note(c.yellow(g));
|
|
@@ -282,10 +307,10 @@ function renderText(m) {
|
|
|
282
307
|
// are the triggers of GitHub's automatic links (`https:`, `www.`, an address's `@`).
|
|
283
308
|
export const mdEscape = (s) => String(s ?? '').replace(/\r?\n/g, ' ').replace(/([\\`*_{}[\]()<>#|!~&:@])/g, '\\$1').replace(/(?<![a-z0-9])www\./gi, (w) => `${w.slice(0, 3)}\\.`);
|
|
284
309
|
|
|
285
|
-
export function renderMarkdown(m) {
|
|
286
|
-
const L = ['# Issues and work items', '', `- ${counts(m.summary)}`, `- Closed items since ${m.closedSince}`, '', '| Item | Priority | Type | Status | Assignee | Due | Title | Notes |', '
|
|
310
|
+
export function renderMarkdown(m, rules = labelRules(null)) {
|
|
311
|
+
const L = ['# Issues and work items', '', `- ${counts(m.summary)}`, `- Closed items since ${m.closedSince}`, '', '| Item | Priority | Type | Status | Assignee | Due | Title | Labels | Notes |', '|---|---|---|---|---|---|---|---|---|'];
|
|
287
312
|
for (const i of m.items) {
|
|
288
|
-
L.push(`| ${i.url ? `[${mdEscape(i.ref)}](${i.url.replace(/[()|]/g, (ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`)})` : mdEscape(i.ref)} | ${i.priority ?? 'none'} | ${i.type ?? 'none'} | ${i.status} | ${mdEscape(who(i))} | ${i.due ?? ''} | ${mdEscape(i.title)} | ${mdEscape(i.flags.join('; '))} |`);
|
|
313
|
+
L.push(`| ${i.url ? `[${mdEscape(i.ref)}](${i.url.replace(/[()|]/g, (ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`)})` : mdEscape(i.ref)} | ${i.priority ?? 'none'} | ${i.type ?? 'none'} | ${i.status} | ${mdEscape(who(i))} | ${i.due ?? ''} | ${mdEscape(i.title)} | ${mdEscape(othersOf(i, rules).join(', '))} | ${mdEscape(i.flags.join('; '))} |`);
|
|
289
314
|
}
|
|
290
315
|
if (gaps(m).length) L.push('', '## Not read, or incomplete', '', ...gaps(m).map((g) => `- ${mdEscape(g)}`));
|
|
291
316
|
L.push('', `_${FOOTER}_`, '');
|
|
@@ -296,17 +321,21 @@ const options = (values) => values.map((v) => `<option value="${esc(lower(v))}">
|
|
|
296
321
|
|
|
297
322
|
// One self-contained file. The table is written here, escaped, and reads with scripting off. The script only
|
|
298
323
|
// hides and re-orders those rows using their data attributes; it never builds markup from an item's text.
|
|
299
|
-
export function renderHtml(m) {
|
|
324
|
+
export function renderHtml(m, rules = labelRules(null)) {
|
|
300
325
|
const people = [...new Set(m.items.flatMap((i) => i.assignees.map((a) => a.member || a.login)))].sort();
|
|
326
|
+
// #514: every other label seen, once each (the first spelling met), for the Label filter.
|
|
327
|
+
const labelNames = [...new Map(m.items.flatMap((i) => othersOf(i, rules)).map((l) => [lower(l), l]).reverse()).values()].sort((a, b) => lower(a).localeCompare(lower(b)));
|
|
301
328
|
const repos = [...new Set(m.items.map((i) => i.repo))].sort();
|
|
302
329
|
const cell = (label, inner, cls = '') => `<td data-label="${label}"${cls ? ` class="${cls}"` : ''}>${inner}</td>`;
|
|
303
330
|
const row = (i) => {
|
|
304
331
|
const members = i.assignees.map((a) => lower(a.member || a.login)).join('\n');
|
|
332
|
+
const others = othersOf(i, rules);
|
|
305
333
|
const num = i.url ? `<a href="${esc(i.url)}" rel="noopener noreferrer">${esc(i.ref)}</a>` : esc(i.ref);
|
|
306
|
-
return `<tr data-priority="${rank(PRIORITIES, i.priority)}" data-p="${esc(lower(i.priority ?? 'none'))}" data-type="${rank(ITEM_TYPES, i.type)}" data-t="${esc(lower(i.type ?? 'none'))}" data-status="${rank(STATUSES, i.status)}" data-s="${esc(i.status)}" data-repo="${esc(lower(i.repo))}" data-members="${esc(members)}" data-created="${esc(i.created ?? '')}" data-updated="${esc(i.updated ?? '')}" data-due="${esc(i.due ?? '')}" data-ref="${esc(i.ref)}">`
|
|
334
|
+
return `<tr data-priority="${rank(PRIORITIES, i.priority)}" data-p="${esc(lower(i.priority ?? 'none'))}" data-type="${rank(ITEM_TYPES, i.type)}" data-t="${esc(lower(i.type ?? 'none'))}" data-status="${rank(STATUSES, i.status)}" data-s="${esc(i.status)}" data-repo="${esc(lower(i.repo))}" data-members="${esc(members)}" data-l="${esc(others.map(lower).join('\n'))}" data-created="${esc(i.created ?? '')}" data-updated="${esc(i.updated ?? '')}" data-due="${esc(i.due ?? '')}" data-ref="${esc(i.ref)}">`
|
|
307
335
|
+ cell('Item', num, 'ref') + cell('Priority', i.priority ? `<span class="pri pri-${esc(lower(i.priority))}">${esc(i.priority)}</span>` : '<span class="dim">none</span>')
|
|
308
336
|
+ cell('Type', i.type ? esc(i.type) : '<span class="dim">none</span>') + cell('Status', `<span class="st st-${rank(STATUSES, i.status)}">${esc(i.status)}</span>`)
|
|
309
337
|
+ cell('Title', `${esc(i.title)}${i.flags.map((f) => `<span class="flag">${esc(f)}</span>`).join('')}`, 'title') + cell('Assignee', i.assignees.length ? esc(who(i)) : '<span class="dim">unassigned</span>')
|
|
338
|
+
+ cell('Labels', others.length ? others.map((l) => `<span class="lbl">${esc(l)}</span>`).join(' ') : '<span class="dim">none</span>')
|
|
310
339
|
+ cell('Epic', i.epic ? esc(i.epic.id) : '<span class="dim">none</span>') + cell('Created', esc(i.created ?? ''), 'date') + cell('Updated', esc(i.updated ?? ''), 'date') + cell('Due', esc(i.due ?? ''), 'date') + '</tr>';
|
|
311
340
|
};
|
|
312
341
|
const th = (key, label) => `<th scope="col"${key ? ` aria-sort="none"` : ''}>${key ? `<button type="button" data-sort="${key}">${label}</button>` : label}</th>`;
|
|
@@ -324,15 +353,15 @@ export function renderHtml(m) {
|
|
|
324
353
|
.filters label{display:flex;flex-direction:column;font-size:12px;color:var(--dim);gap:2px}select,input,#reset{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:5px;padding:4px 6px;min-height:32px}#reset{align-self:flex-end;cursor:pointer}
|
|
325
354
|
#count{margin:0 0 8px;color:var(--dim)}table{width:100%;border-collapse:collapse}th,td{text-align:left;padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:top}th{font-size:12px;color:var(--dim);white-space:nowrap}th button{all:unset;cursor:pointer}th button:focus-visible{outline:2px solid var(--link)}
|
|
326
355
|
[aria-sort=ascending] button::after{content:" ▲"}[aria-sort=descending] button::after{content:" ▼"}td.ref,td.date{white-space:nowrap}td.title{min-width:260px;overflow-wrap:anywhere}
|
|
327
|
-
.pri{font-weight:600}.pri-p0{color:var(--p0)}.pri-p1{color:var(--p1)}.st{white-space:nowrap}.st-0{color:var(--dim)}.flag{display:block;color:var(--warn);font-size:12px}
|
|
356
|
+
.pri{font-weight:600}.pri-p0{color:var(--p0)}.pri-p1{color:var(--p1)}.st{white-space:nowrap}.st-0{color:var(--dim)}.flag{display:block;color:var(--warn);font-size:12px}.lbl{display:inline-block;border:1px solid var(--line);border-radius:10px;padding:0 6px;font-size:12px;white-space:nowrap}
|
|
328
357
|
footer{color:var(--dim);font-size:12px;margin-top:20px;border-top:1px solid var(--line);padding-top:10px}
|
|
329
358
|
@media (max-width:720px){thead{position:absolute;left:-9999px}tr{display:block;border:1px solid var(--line);border-radius:8px;margin:0 0 10px;padding:6px 10px}td{display:flex;gap:10px;border:0;padding:3px 0}td::before{content:attr(data-label);color:var(--dim);flex:0 0 72px;font-size:12px}td:empty{display:none}td.title{min-width:0;display:block}td.title::before{display:block}}
|
|
330
359
|
</style></head><body><div class="wrap"><h1>Issues and work items</h1>
|
|
331
360
|
<p class="sub">${esc(counts(m.summary))}. Closed items since ${esc(m.closedSince)}.</p>
|
|
332
361
|
${missing.length ? `<section class="gaps"><h2>Not read, or incomplete</h2><ul>${missing.map((g) => `<li>${esc(g)}</li>`).join('')}</ul></section>` : ''}
|
|
333
|
-
<form class="filters" id="filters">${select('f-member', 'Member', `<option value="\n">Unassigned</option>${options(people)}`)}${select('f-t', 'Type', `${options(ITEM_TYPES)}<option value="none">None</option>`)}${select('f-p', 'Priority', `${options(PRIORITIES)}<option value="none">None</option>`)}${select('f-s', 'Status', options(STATUSES))}${select('f-repo', 'Repo', options(repos))}
|
|
362
|
+
<form class="filters" id="filters">${select('f-member', 'Member', `<option value="\n">Unassigned</option>${options(people)}`)}${select('f-t', 'Type', `${options(ITEM_TYPES)}<option value="none">None</option>`)}${select('f-p', 'Priority', `${options(PRIORITIES)}<option value="none">None</option>`)}${select('f-s', 'Status', options(STATUSES))}${select('f-repo', 'Repo', options(repos))}${select('f-l', 'Label', options(labelNames))}
|
|
334
363
|
<label>Date<select id="f-date">${DATE_FIELDS.map((d) => `<option value="${d}">${d[0].toUpperCase()}${d.slice(1)}</option>`).join('')}</select></label><label>From<input type="date" id="f-from"></label><label>To<input type="date" id="f-to"></label><button type="reset" id="reset">Clear</button></form>
|
|
335
|
-
<p id="count" role="status"></p><table><thead><tr>${th('ref', 'Item')}${th('priority', 'Priority')}${th('type', 'Type')}${th('status', 'Status')}${th('', 'Title')}${th('', 'Assignee')}${th('', 'Epic')}${th('created', 'Created')}${th('updated', 'Updated')}${th('due', 'Due')}</tr></thead>
|
|
364
|
+
<p id="count" role="status"></p><table><thead><tr>${th('ref', 'Item')}${th('priority', 'Priority')}${th('type', 'Type')}${th('status', 'Status')}${th('', 'Title')}${th('', 'Assignee')}${th('', 'Labels')}${th('', 'Epic')}${th('created', 'Created')}${th('updated', 'Updated')}${th('due', 'Due')}</tr></thead>
|
|
336
365
|
<tbody id="rows">${m.items.map(row).join('\n')}</tbody></table>${m.items.length ? '' : `<p class="dim">${m.notRead.length ? 'Nothing found in the repos that answered.' : 'No items.'}</p>`}
|
|
337
366
|
<footer>${esc(FOOTER)}</footer></div>
|
|
338
367
|
<script>${PAGE_SCRIPT}</script></body></html>\n`;
|
|
@@ -340,13 +369,13 @@ ${missing.length ? `<section class="gaps"><h2>Not read, or incomplete</h2><ul>${
|
|
|
340
369
|
|
|
341
370
|
// Fixed text: no value from an item is ever part of this script.
|
|
342
371
|
const PAGE_SCRIPT = `(function(){var body=document.getElementById('rows'),rows=[].slice.call(body.rows),all=rows.length,$=function(i){return document.getElementById(i)},count=$('count');
|
|
343
|
-
function apply(){var m=$('f-member').value,t=$('f-t').value,p=$('f-p').value,s=$('f-s').value,r=$('f-repo').value,d=$('f-date').value,a=$('f-from').value,b=$('f-to').value,n=0;rows.forEach(function(x){var v=x.dataset[d],on=(!t||x.dataset.t===t)&&(!p||x.dataset.p===p)&&(!s||x.dataset.s===s)&&(!r||x.dataset.repo===r)&&(!m||(m==='\\n'?x.dataset.members==='':x.dataset.members.split('\\n').indexOf(m)>=0))&&(!a||(v&&v>=a))&&(!b||(v&&v<=b));x.hidden=!on;if(on)n++});count.textContent='Showing '+n+' of '+all}
|
|
372
|
+
function apply(){var m=$('f-member').value,t=$('f-t').value,p=$('f-p').value,s=$('f-s').value,r=$('f-repo').value,l=$('f-l').value,d=$('f-date').value,a=$('f-from').value,b=$('f-to').value,n=0;rows.forEach(function(x){var v=x.dataset[d],on=(!t||x.dataset.t===t)&&(!p||x.dataset.p===p)&&(!s||x.dataset.s===s)&&(!r||x.dataset.repo===r)&&(!l||x.dataset.l.split('\\n').indexOf(l)>=0)&&(!m||(m==='\\n'?x.dataset.members==='':x.dataset.members.split('\\n').indexOf(m)>=0))&&(!a||(v&&v>=a))&&(!b||(v&&v<=b));x.hidden=!on;if(on)n++});count.textContent='Showing '+n+' of '+all}
|
|
344
373
|
var form=$('filters');form.addEventListener('input',apply);form.addEventListener('change',apply);form.addEventListener('reset',function(){setTimeout(apply,0)});form.addEventListener('submit',function(e){e.preventDefault()});
|
|
345
374
|
var num={priority:1,type:1,status:1};document.querySelectorAll('[data-sort]').forEach(function(btn){btn.addEventListener('click',function(){var k=btn.dataset.sort,th=btn.parentNode,up=th.getAttribute('aria-sort')!=='ascending';document.querySelectorAll('th[aria-sort]').forEach(function(h){h.setAttribute('aria-sort','none')});th.setAttribute('aria-sort',up?'ascending':'descending');rows.sort(function(x,y){var a=x.dataset[k],b=y.dataset[k];if(!a!==!b)return a?-1:1;var c=num[k]?a-b:a.localeCompare(b,undefined,{numeric:true});return up?c:-c});rows.forEach(function(x){body.appendChild(x)})})});apply()})();`;
|
|
346
375
|
|
|
347
376
|
// ---- the commands ----------------------------------------------------------------------------------
|
|
348
377
|
|
|
349
|
-
const LIST_ONLY = new Set(['--priority', '--type', '--status', '--assignee', '--me', '--repo', '--since', '--until', '--date', '--sort', '--closed-since', '--format', '--out', '--json', '--dir']);
|
|
378
|
+
const LIST_ONLY = new Set(['--priority', '--type', '--status', '--label', '--assignee', '--me', '--repo', '--since', '--until', '--date', '--sort', '--closed-since', '--format', '--out', '--json', '--dir']);
|
|
350
379
|
// The Markdown link of an item's URL, with the characters that would end it encoded.
|
|
351
380
|
export const mdUrl = (u) => u.replace(/[()|]/g, (ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
352
381
|
|
|
@@ -372,12 +401,14 @@ function closedSince(value, now) {
|
|
|
372
401
|
}
|
|
373
402
|
|
|
374
403
|
// `yad issues [list]`. Returns the model (E1 makes it the `--json` answer), or undefined after refusing.
|
|
375
|
-
export async function runIssuesList(root, { priority = null, type = null, status = null, assignee = null, me = false, repo = null, since = null, until = null, date = null, sort = null, closedSince: closed = null, format = null, out = null, json = false, now = Date.now(), env = process.env, runner, loginOf = platformLogin } = {}) {
|
|
404
|
+
export async function runIssuesList(root, { priority = null, type = null, status = null, label = [], assignee = null, me = false, repo = null, since = null, until = null, date = null, sort = null, closedSince: closed = null, format = null, out = null, json = false, now = Date.now(), env = process.env, runner, loginOf = platformLogin } = {}) {
|
|
376
405
|
const refuse = (msg, hint) => { fail(msg); if (hint) hand(hint); process.exitCode = 1; };
|
|
377
406
|
if (!fs.existsSync(productConfigPath(root))) return refuse('not a Product (no .sdlc/product.json here)', 'run it from the Product, or pass --dir');
|
|
378
407
|
if (!format && out) format = /\.html?$/i.test(out) ? 'html' : 'md';
|
|
379
408
|
if (format && !['md', 'html'].includes(format)) return refuse(`unknown --format ${forTerminal(String(format))}`, 'use --format md or --format html (or --json for the data)');
|
|
380
409
|
if (assignee && me) return refuse('pass --assignee <login> or --me, not both');
|
|
410
|
+
const labels = (Array.isArray(label) ? label : [label]).filter((v) => v != null);
|
|
411
|
+
if (labels.some((v) => !list(v).length)) return refuse('--label needs a label name', 'pass --label <name>; repeat it to ask for more than one, or give a comma list for any of them');
|
|
381
412
|
for (const bad of [checkValues('--priority', priority, [...PRIORITIES, 'none']), checkValues('--type', type, [...ITEM_TYPES, 'none']), checkValues('--status', status, STATUSES), oneValue('--sort', sort, SORTS), oneValue('--date', date, DATE_FIELDS)]) if (bad) return refuse(bad);
|
|
382
413
|
for (const [flag, v] of [['--since', since], ['--until', until]]) if (v && !realDate(v)) return refuse(`${flag} must be a real date, YYYY-MM-DD (got ${forTerminal(String(v))})`);
|
|
383
414
|
const window = closedSince(closed, now);
|
|
@@ -400,16 +431,21 @@ export async function runIssuesList(root, { priority = null, type = null, status
|
|
|
400
431
|
const bad = list(repo).filter((v) => !known.map(lower).includes(lower(v)));
|
|
401
432
|
if (bad.length) return refuse(`no repo named ${forTerminal(bad.join(', '))}`, `use one of: ${known.join(', ')}`);
|
|
402
433
|
}
|
|
403
|
-
const items = applyFilters(whole.items, { priority, type, status, assignee, repo, since, until, date: date ? lower(date) : 'created', sort: sort ? lower(sort) : 'priority', mine });
|
|
434
|
+
const items = applyFilters(whole.items, { priority, type, status, label: labels, assignee, repo, since, until, date: date ? lower(date) : 'created', sort: sort ? lower(sort) : 'priority', mine });
|
|
404
435
|
const model = { ...whole, items, summary: summarize(items), unfiltered: whole.items.length };
|
|
436
|
+
const rules = labelRules(readJSON(productConfigPath(root), null));
|
|
405
437
|
if (format) {
|
|
406
|
-
|
|
407
|
-
|
|
438
|
+
// E180: with no --out, saved in the local reports folder, named by the repos it covers and its count.
|
|
439
|
+
const scope = repo ? list(repo).join(' ') : 'all repos';
|
|
440
|
+
const saved = writeOrSave(root, { out, kind: 'issues', scope, state: `${items.length} items`, ext: format, content: format === 'md' ? renderMarkdown(model, rules) : renderHtml(model, rules), command: 'issues list', env });
|
|
441
|
+
if (saved.problem) return refuse(saved.problem);
|
|
442
|
+
for (const w of saved.warnings) warn(w);
|
|
443
|
+
const dest = saved.file;
|
|
408
444
|
if (json) note(`wrote ${format.toUpperCase()} report → ${dest}`); else info(`wrote ${format.toUpperCase()} report → ${c.bold(dest)}`);
|
|
409
445
|
for (const g of gaps(model)) if (!json) note(c.yellow(g));
|
|
410
446
|
return { ...model, out: dest };
|
|
411
447
|
}
|
|
412
|
-
if (!json) renderText(model);
|
|
448
|
+
if (!json) renderText(model, rules);
|
|
413
449
|
return { ...model, out: null };
|
|
414
450
|
}
|
|
415
451
|
|
|
@@ -418,11 +454,14 @@ export function readLabels(t, runner) {
|
|
|
418
454
|
const gh = t.platform === 'github';
|
|
419
455
|
const at = gh ? `repos/${t.repo}/labels?per_page=${PAGE}` : `projects/${encodeURIComponent(t.repo)}/labels?per_page=${PAGE}`;
|
|
420
456
|
const names = new Set();
|
|
457
|
+
// #514: `keys` and `real` are by `labelKey`; `names` stays lower-cased only, as its other callers read it.
|
|
458
|
+
const keys = new Set();
|
|
459
|
+
const real = new Map(); // labelKey → the repo's own spelling, so a label is added and removed as the repo spells it
|
|
421
460
|
for (let page = 1; page <= MAX_PAGES; page++) {
|
|
422
461
|
const res = api(runner, t.cli, t.host, `${at}&page=${page}`);
|
|
423
462
|
if (!res.ok || !Array.isArray(res.body)) return { ok: false, why: whyFailed(res.ok ? { unreadable: true } : res, { platform: t.platform, host: t.host, what: `the labels of ${shown(t.repo)}`, plural: true }) };
|
|
424
|
-
for (const l of res.body) if (typeof l?.name === 'string') names.add(l.name.toLowerCase());
|
|
425
|
-
if (res.body.length < PAGE) return { ok: true, names };
|
|
463
|
+
for (const l of res.body) if (typeof l?.name === 'string') { names.add(l.name.toLowerCase()); const k = labelKey(l.name); keys.add(k); if (!real.has(k)) real.set(k, l.name); }
|
|
464
|
+
if (res.body.length < PAGE) return { ok: true, names, keys, real };
|
|
426
465
|
}
|
|
427
466
|
return { ok: false, why: `${shown(t.repo)} has more labels than yad reads` };
|
|
428
467
|
}
|
package/cli/lib.mjs
CHANGED
|
@@ -403,14 +403,49 @@ export function run(cmd, args = [], opts = {}) {
|
|
|
403
403
|
// --json run its stdout is our stderr instead (E1).
|
|
404
404
|
const stdio = jsonRun && opts.stdio === 'inherit' ? ['inherit', 2, 'inherit'] : opts.stdio;
|
|
405
405
|
const r = spawnSync(cmd, args, { encoding: 'utf8', ...opts, ...(stdio === undefined ? {} : { stdio }) });
|
|
406
|
+
const ok = r.status === 0;
|
|
407
|
+
let stderr = (r.stderr || '').trim();
|
|
408
|
+
// git too (#526): with glab as git's login helper (`glab auth login`), git passes glab's warning through on a
|
|
409
|
+
// push, fetch, pull, ls-remote or clone.
|
|
410
|
+
if (/^(?:glab|git)(?:\.exe)?$/i.test(path.basename(String(cmd)))) stderr = withoutGlabConfigWarning(stderr, { ok });
|
|
406
411
|
return {
|
|
407
|
-
ok
|
|
412
|
+
ok,
|
|
408
413
|
code: r.status,
|
|
409
414
|
stdout: (r.stdout || '').trim(),
|
|
410
|
-
stderr
|
|
415
|
+
stderr,
|
|
411
416
|
error: r.error,
|
|
412
417
|
};
|
|
413
418
|
}
|
|
419
|
+
|
|
420
|
+
// #509 — glab with more than one config file prints a warning block on EVERY run, before its own output:
|
|
421
|
+
// Warning: Multiple config files found. Only the first one will be used.
|
|
422
|
+
// Using: <file>
|
|
423
|
+
// Ignoring: <file>
|
|
424
|
+
// Consider consolidating to one location to avoid confusion.
|
|
425
|
+
// It is not an error (the run still exits 0 when it works), but every caller that shows stderr as the
|
|
426
|
+
// reason cuts that reason short, so the warning was all a person saw and the real error was cut off. So the
|
|
427
|
+
// block is dropped from what yad reads. When the run FAILED, one short line goes BEFORE the real error
|
|
428
|
+
// instead, because a login saved in the ignored file is not used — often the very reason the run failed — and
|
|
429
|
+
// a line after glab's long error would be cut off. It shares its line with the error's first line, so a caller
|
|
430
|
+
// that shows only stderr's first line still shows the error. Only that exact block is removed. git's own calls get
|
|
431
|
+
// the same (#526): git passes its login helper's stderr through, and that helper can be glab.
|
|
432
|
+
export function withoutGlabConfigWarning(stderr = '', { ok = true } = {}) {
|
|
433
|
+
const lines = String(stderr).split('\n');
|
|
434
|
+
const isStart = (l) => /^Warning: Multiple config files found\b/i.test(l.trim());
|
|
435
|
+
if (!lines.some(isStart)) return stderr;
|
|
436
|
+
// Every block: one git push runs its login helper more than once (`get`, then `store` or `erase`), and glab
|
|
437
|
+
// prints the block each time (#526 review).
|
|
438
|
+
const kept = [];
|
|
439
|
+
for (let i = 0; i < lines.length; i++) {
|
|
440
|
+
if (!isStart(lines[i])) { kept.push(lines[i]); continue; }
|
|
441
|
+
while (i + 1 < lines.length && /^\s+(?:Using|Ignoring):/.test(lines[i + 1])) i += 1;
|
|
442
|
+
if (i + 1 < lines.length && /^Consider consolidating\b/i.test(lines[i + 1].trim())) i += 1;
|
|
443
|
+
}
|
|
444
|
+
const rest = kept.join('\n').trim();
|
|
445
|
+
if (ok) return rest;
|
|
446
|
+
const hint = 'glab reads only one of its two config files, so a login saved in the other is not used (see `yad doctor`, glab-config)';
|
|
447
|
+
return rest ? `${hint} — ${rest}` : hint;
|
|
448
|
+
}
|
|
414
449
|
export const has = (cmd) => run(process.platform === 'win32' ? 'where' : 'which', [cmd]).ok;
|
|
415
450
|
|
|
416
451
|
// An npm launcher (`npm`, `npx`) is a `.cmd` file on Windows, which Node will not start without a shell
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// A page served to this machine only, or written as one self-contained file (E177, shared since E181).
|
|
2
|
+
//
|
|
3
|
+
// `yad brain view` (E177) and `yad map` (E181) both draw a page in the person's browser. The rules that keep
|
|
4
|
+
// that page safe live here, once:
|
|
5
|
+
// - the server binds 127.0.0.1 on a random port; every request needs the one-time key (`?t=`), compared in
|
|
6
|
+
// constant time; the Host header must be the address printed (no DNS rebinding); GET and HEAD only; a
|
|
7
|
+
// fixed route table, so no request path ever reaches the filesystem; strict headers (CSP, no-store,
|
|
8
|
+
// no-referrer, no framing);
|
|
9
|
+
// - the self-contained file holds every script and style inline, allowed by their hashes and nothing else,
|
|
10
|
+
// with the data in a `<script type="application/json">` that no name can close;
|
|
11
|
+
// - a file the person names is written by a temp file and a rename, never through a link, and a warning
|
|
12
|
+
// says when it sits in a git work tree that does not ignore it.
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import http from 'node:http';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
17
|
+
import { spawnSync } from 'node:child_process';
|
|
18
|
+
import { writePlain } from './brain.mjs';
|
|
19
|
+
|
|
20
|
+
export const CSP = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
|
|
21
|
+
export const BASE_HEADERS = Object.freeze({
|
|
22
|
+
'Content-Security-Policy': CSP,
|
|
23
|
+
'X-Content-Type-Options': 'nosniff',
|
|
24
|
+
'Cache-Control': 'no-store',
|
|
25
|
+
'Referrer-Policy': 'no-referrer',
|
|
26
|
+
'Cross-Origin-Resource-Policy': 'same-origin',
|
|
27
|
+
'Cross-Origin-Opener-Policy': 'same-origin',
|
|
28
|
+
'X-Frame-Options': 'DENY',
|
|
29
|
+
});
|
|
30
|
+
export const TYPES = Object.freeze({ html: 'text/html; charset=utf-8', js: 'text/javascript; charset=utf-8', css: 'text/css; charset=utf-8', json: 'application/json; charset=utf-8' });
|
|
31
|
+
|
|
32
|
+
// Is `given` the token? A length check first: `timingSafeEqual` throws on buffers of different lengths.
|
|
33
|
+
export function tokenMatches(given, token) {
|
|
34
|
+
if (typeof given !== 'string') return false;
|
|
35
|
+
const a = Buffer.from(given);
|
|
36
|
+
const b = Buffer.from(token);
|
|
37
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Start a locked-down page server: { url, token, port, host, server, close() }.
|
|
41
|
+
// routes(token) → Map(pathname → () => { type, body, status? }) — a request path is only ever a KEY.
|
|
42
|
+
// stream optional { path, attach(req, res, headers), close() } — a one-way event stream (SSE).
|
|
43
|
+
export function startPageServer({ routes, stream = null, host = '127.0.0.1', port = 0, failText = 'the page could not read its files' }) {
|
|
44
|
+
const token = randomBytes(24).toString('hex');
|
|
45
|
+
const table = routes(token);
|
|
46
|
+
let expectedHost = null;
|
|
47
|
+
const server = http.createServer((req, res) => {
|
|
48
|
+
const send = (status, type, body, extra = {}) => {
|
|
49
|
+
res.writeHead(status, { ...BASE_HEADERS, 'Content-Type': type, ...extra });
|
|
50
|
+
res.end(req.method === 'HEAD' ? undefined : body);
|
|
51
|
+
};
|
|
52
|
+
const text = (status, msg, extra) => send(status, 'text/plain; charset=utf-8', `${msg}\n`, extra);
|
|
53
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return text(405, 'method not allowed', { Allow: 'GET, HEAD' });
|
|
54
|
+
if (req.headers.host !== expectedHost) return text(403, 'forbidden');
|
|
55
|
+
let url;
|
|
56
|
+
try { url = new URL(req.url, `http://${expectedHost}`); } catch { return text(400, 'bad request'); }
|
|
57
|
+
if (!tokenMatches(url.searchParams.get('t'), token)) return text(403, 'forbidden');
|
|
58
|
+
if (stream && url.pathname === (stream.path || '/events') && req.method === 'GET') return stream.attach(req, res, BASE_HEADERS);
|
|
59
|
+
const route = table.get(url.pathname);
|
|
60
|
+
if (!route) return text(404, 'not found');
|
|
61
|
+
try {
|
|
62
|
+
const r = route();
|
|
63
|
+
return send(r.status || 200, r.type, r.body);
|
|
64
|
+
} catch {
|
|
65
|
+
return text(500, failText);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
return new Promise((resolve, reject) => {
|
|
69
|
+
server.once('error', reject);
|
|
70
|
+
server.listen(port, host, () => {
|
|
71
|
+
const a = server.address();
|
|
72
|
+
expectedHost = `${host}:${a.port}`;
|
|
73
|
+
resolve({
|
|
74
|
+
url: `http://${expectedHost}/?t=${token}`, token, port: a.port, host, server,
|
|
75
|
+
close: () => new Promise((done) => { stream?.close(); server.closeAllConnections?.(); server.close(() => done()); }),
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// JSON that can sit inside a <script> element: nothing in it can end the element or start a comment.
|
|
82
|
+
export const scriptSafeJSON = (value) => JSON.stringify(value)
|
|
83
|
+
.replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026')
|
|
84
|
+
.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
|
|
85
|
+
const sha256b64 = (s) => createHash('sha256').update(s, 'utf8').digest('base64');
|
|
86
|
+
|
|
87
|
+
export const SERVED_START = '<!--SERVED:start-->';
|
|
88
|
+
export const SERVED_END = '<!--SERVED:end-->';
|
|
89
|
+
|
|
90
|
+
// One HTML file with everything inline, and a CSP that allows exactly the inline blocks it holds (by hash)
|
|
91
|
+
// and no network at all. `shell` is the served page: its `<script src>` tags sit between the SERVED markers
|
|
92
|
+
// and are cut out by them (never by matching HTML with a pattern), its stylesheet link becomes a <style>, and
|
|
93
|
+
// `<!--SCRIPTS-->` becomes the data block followed by each script.
|
|
94
|
+
export function inlineSnapshot({ shell, scripts, css, dataId, data }) {
|
|
95
|
+
// A script's own text must not hold `</script`, or the file would end it early: checked here, so a future
|
|
96
|
+
// file that holds one fails loudly instead of breaking the page.
|
|
97
|
+
for (const s of scripts) if (/<\/script/i.test(s)) throw new Error('an inline script holds </script');
|
|
98
|
+
const csp = [
|
|
99
|
+
"default-src 'none'",
|
|
100
|
+
`script-src ${scripts.map((s) => `'sha256-${sha256b64(s)}'`).join(' ')}`,
|
|
101
|
+
`style-src 'sha256-${sha256b64(css)}'`,
|
|
102
|
+
"img-src data:", "base-uri 'none'", "form-action 'none'",
|
|
103
|
+
].join('; ');
|
|
104
|
+
// The key placeholder goes before anything is spliced in: the data's own names may hold the same text.
|
|
105
|
+
const page = shell.replaceAll('__TOKEN__', '');
|
|
106
|
+
const from = page.indexOf(SERVED_START);
|
|
107
|
+
const to = page.indexOf(SERVED_END);
|
|
108
|
+
if (from < 0 || to < from) throw new Error(`the page has no ${SERVED_START} … ${SERVED_END} block`);
|
|
109
|
+
const body = (page.slice(0, from) + page.slice(to + SERVED_END.length))
|
|
110
|
+
.replace(/<link rel="stylesheet"[^>]*>/, () => `<style>${css}</style>`)
|
|
111
|
+
.replace('<!--SCRIPTS-->', () => [
|
|
112
|
+
`<script type="application/json" id="${dataId}">${scriptSafeJSON(data)}</script>`,
|
|
113
|
+
...scripts.map((s) => `<script>${s}</script>`),
|
|
114
|
+
].join('\n'));
|
|
115
|
+
return body
|
|
116
|
+
.replace(/<meta http-equiv="Content-Security-Policy"[^>]*>/, () => `<meta http-equiv="Content-Security-Policy" content="${csp}">`);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Write `data` to the path the person named, by a temp file and a rename, refusing a link at the target (a
|
|
120
|
+
// rename replaces a link, but a person who put one there means the file it points at). → null | problem
|
|
121
|
+
export function writeOwnFile(file, data) {
|
|
122
|
+
let st = null;
|
|
123
|
+
try { st = fs.lstatSync(file); } catch { /* new file */ }
|
|
124
|
+
if (st && !st.isFile()) return `${file} is not a plain file (a link or a folder) — name another path`;
|
|
125
|
+
const dir = path.dirname(file);
|
|
126
|
+
if (!fs.existsSync(dir)) return `the folder ${dir} does not exist`;
|
|
127
|
+
writePlain(dir, path.basename(file), data);
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Is `file` inside a git work tree, and NOT ignored there? Then committing it is one `git add .` away.
|
|
132
|
+
export function trackedRisk(file, runner = spawnSync) {
|
|
133
|
+
const dir = path.dirname(file);
|
|
134
|
+
const inTree = runner('git', ['-C', dir, 'rev-parse', '--is-inside-work-tree'], { encoding: 'utf8' });
|
|
135
|
+
if (inTree.status !== 0 || String(inTree.stdout).trim() !== 'true') return false;
|
|
136
|
+
const ignored = runner('git', ['-C', dir, 'check-ignore', '-q', '--', path.basename(file)], { encoding: 'utf8' });
|
|
137
|
+
return ignored.status === 1;
|
|
138
|
+
}
|
package/cli/machine.mjs
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// need no Docker, so a repo that names none is never asked about.
|
|
9
9
|
// glab more than one glab config file. glab then reads only one and ignores the other (a login saved
|
|
10
10
|
// there is not used), and warns on every run, which breaks JSON for a tool that reads its output
|
|
11
|
-
// and its errors together.
|
|
11
|
+
// and its errors together. yad's own glab calls drop that warning (`run` in cli/lib.mjs, #509).
|
|
12
12
|
import fs from 'node:fs';
|
|
13
13
|
import os from 'node:os';
|
|
14
14
|
import path from 'node:path';
|
package/cli/manifest.mjs
CHANGED
|
@@ -829,6 +829,56 @@ export const agentGuardAdapters = (dest) => Object.freeze({
|
|
|
829
829
|
});
|
|
830
830
|
export const AGENT_GUARD_ADAPTERS = agentGuardAdapters(AGENT_GUARD_WIRING[0].dest);
|
|
831
831
|
|
|
832
|
+
// The live activity record (E178): AFTER each tool an agent uses, `yad-activity.mjs` appends one line to the
|
|
833
|
+
// repo's `<git common dir>/yad-activity.jsonl` — the kind of action (read, search, edit, run), the repo's files
|
|
834
|
+
// it touched, the time — which `yad brain view --live` draws. OFF by default: wired only while the Product
|
|
835
|
+
// config says `"activity": true`, in the Product and in each code repo cloned here. It never starts yad (it
|
|
836
|
+
// fires on every read), writes only allowlisted fields, and always exits 0 with nothing on stdout.
|
|
837
|
+
//
|
|
838
|
+
// A LIST of adapters, not one per target: Cursor needs two events (an edit and a shell command each have their
|
|
839
|
+
// own, and no read event exists that takes no answer — `beforeReadFile` must answer allow/deny), so Cursor
|
|
840
|
+
// sessions show edits and runs only. Each adapter is merged and unmerged on its own event; the two Cursor ones
|
|
841
|
+
// share one command, which `mergeHookSettings` matches per event.
|
|
842
|
+
export const ACTIVITY_WIRING = [
|
|
843
|
+
{ src: 'skills/yad-checks/templates/hooks/yad-activity.mjs', dest: 'hooks/yad-activity.mjs' },
|
|
844
|
+
];
|
|
845
|
+
// In a code repo the script goes in `checks/`, as the agent guard's does (REPO_AGENT_GUARD_DEST).
|
|
846
|
+
export const REPO_ACTIVITY_DEST = 'checks/yad-activity.mjs';
|
|
847
|
+
export const activityAdapters = (dest) => Object.freeze([
|
|
848
|
+
Object.freeze({
|
|
849
|
+
target: '.claude',
|
|
850
|
+
label: 'activity record',
|
|
851
|
+
settings: '.claude/settings.json',
|
|
852
|
+
event: 'PostToolUse',
|
|
853
|
+
nested: true,
|
|
854
|
+
preamble: null,
|
|
855
|
+
// Every tool the live view draws: reads, searches, edits and shell commands.
|
|
856
|
+
matcher: 'Read|Grep|Glob|Edit|Write|MultiEdit|NotebookEdit|Bash',
|
|
857
|
+
projectDirEnv: CLAUDE_PROJECT_DIR_ENV,
|
|
858
|
+
// Quoted and anchored on the project root, and the format said, for the reasons capture's entry gives.
|
|
859
|
+
command: `node "$${CLAUDE_PROJECT_DIR_ENV}/${dest}" --format claude`,
|
|
860
|
+
observe: true,
|
|
861
|
+
wiring: Object.freeze([]),
|
|
862
|
+
legacyCommands: Object.freeze([]),
|
|
863
|
+
}),
|
|
864
|
+
...['afterFileEdit', 'afterShellExecution'].map((event) => Object.freeze({
|
|
865
|
+
target: '.cursor',
|
|
866
|
+
label: 'activity record',
|
|
867
|
+
settings: '.cursor/hooks.json',
|
|
868
|
+
event,
|
|
869
|
+
nested: false,
|
|
870
|
+
preamble: Object.freeze({ version: 1 }),
|
|
871
|
+
matcher: null,
|
|
872
|
+
projectDirEnv: CURSOR_PROJECT_DIR_ENV,
|
|
873
|
+
// Relative and unquoted, for the reason the ledger guard's Cursor entry is (see above).
|
|
874
|
+
command: `node ${dest} --format cursor`,
|
|
875
|
+
observe: true,
|
|
876
|
+
wiring: Object.freeze([]),
|
|
877
|
+
legacyCommands: Object.freeze([]),
|
|
878
|
+
})),
|
|
879
|
+
]);
|
|
880
|
+
export const ACTIVITY_ADAPTERS = activityAdapters(ACTIVITY_WIRING[0].dest);
|
|
881
|
+
|
|
832
882
|
// The Claude adapter's fields under their original names. Kept because they are what the shipped
|
|
833
883
|
// error text and the existing tests name, and renaming a constant buys nothing; new code should read
|
|
834
884
|
// the adapter, since these three describe ONE harness and the engine now supports two.
|