swarmdo 1.37.0 → 1.50.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 (57) hide show
  1. package/README.md +9 -5
  2. package/package.json +1 -1
  3. package/v3/@swarmdo/cli/dist/src/apply/apply.js +6 -1
  4. package/v3/@swarmdo/cli/dist/src/changelog/changelog.d.ts +21 -0
  5. package/v3/@swarmdo/cli/dist/src/changelog/changelog.js +43 -0
  6. package/v3/@swarmdo/cli/dist/src/commands/changelog.js +15 -4
  7. package/v3/@swarmdo/cli/dist/src/commands/config.js +37 -1
  8. package/v3/@swarmdo/cli/dist/src/commands/coupling.d.ts +17 -0
  9. package/v3/@swarmdo/cli/dist/src/commands/coupling.js +85 -0
  10. package/v3/@swarmdo/cli/dist/src/commands/hidden-coupling.d.ts +19 -0
  11. package/v3/@swarmdo/cli/dist/src/commands/hidden-coupling.js +92 -0
  12. package/v3/@swarmdo/cli/dist/src/commands/hooks.js +55 -0
  13. package/v3/@swarmdo/cli/dist/src/commands/hotspots.js +2 -1
  14. package/v3/@swarmdo/cli/dist/src/commands/index.js +12 -3
  15. package/v3/@swarmdo/cli/dist/src/commands/ownership.d.ts +18 -0
  16. package/v3/@swarmdo/cli/dist/src/commands/ownership.js +88 -0
  17. package/v3/@swarmdo/cli/dist/src/commands/pack.js +4 -4
  18. package/v3/@swarmdo/cli/dist/src/commands/redact.js +11 -0
  19. package/v3/@swarmdo/cli/dist/src/commands/release.js +27 -5
  20. package/v3/@swarmdo/cli/dist/src/commands/task.js +57 -2
  21. package/v3/@swarmdo/cli/dist/src/config-lint/agents-lint.d.ts +30 -0
  22. package/v3/@swarmdo/cli/dist/src/config-lint/agents-lint.js +87 -0
  23. package/v3/@swarmdo/cli/dist/src/config-lint/commands-lint.d.ts +31 -0
  24. package/v3/@swarmdo/cli/dist/src/config-lint/commands-lint.js +127 -0
  25. package/v3/@swarmdo/cli/dist/src/config-lint/lint.d.ts +8 -0
  26. package/v3/@swarmdo/cli/dist/src/config-lint/lint.js +7 -0
  27. package/v3/@swarmdo/cli/dist/src/coupling/coupling.d.ts +56 -0
  28. package/v3/@swarmdo/cli/dist/src/coupling/coupling.js +86 -0
  29. package/v3/@swarmdo/cli/dist/src/coupling/hidden.d.ts +45 -0
  30. package/v3/@swarmdo/cli/dist/src/coupling/hidden.js +66 -0
  31. package/v3/@swarmdo/cli/dist/src/hooks-recipe/command-guard.d.ts +46 -0
  32. package/v3/@swarmdo/cli/dist/src/hooks-recipe/command-guard.js +120 -0
  33. package/v3/@swarmdo/cli/dist/src/hooks-recipe/recipe.js +8 -0
  34. package/v3/@swarmdo/cli/dist/src/mcp-client.js +4 -0
  35. package/v3/@swarmdo/cli/dist/src/mcp-tools/coupling-tools.d.ts +14 -0
  36. package/v3/@swarmdo/cli/dist/src/mcp-tools/coupling-tools.js +56 -0
  37. package/v3/@swarmdo/cli/dist/src/mcp-tools/index.d.ts +2 -0
  38. package/v3/@swarmdo/cli/dist/src/mcp-tools/index.js +2 -0
  39. package/v3/@swarmdo/cli/dist/src/mcp-tools/ownership-tools.d.ts +14 -0
  40. package/v3/@swarmdo/cli/dist/src/mcp-tools/ownership-tools.js +51 -0
  41. package/v3/@swarmdo/cli/dist/src/mcp-tools/profiles.js +2 -0
  42. package/v3/@swarmdo/cli/dist/src/mcp-tools/task-deps.d.ts +35 -0
  43. package/v3/@swarmdo/cli/dist/src/mcp-tools/task-deps.js +87 -0
  44. package/v3/@swarmdo/cli/dist/src/ownership/ownership.d.ts +61 -0
  45. package/v3/@swarmdo/cli/dist/src/ownership/ownership.js +151 -0
  46. package/v3/@swarmdo/cli/dist/src/pack/pack.d.ts +1 -1
  47. package/v3/@swarmdo/cli/dist/src/pack/pack.js +12 -4
  48. package/v3/@swarmdo/cli/dist/src/redact/redact.js +47 -16
  49. package/v3/@swarmdo/cli/dist/src/redact/sarif.d.ts +28 -0
  50. package/v3/@swarmdo/cli/dist/src/redact/sarif.js +53 -0
  51. package/v3/@swarmdo/cli/dist/src/release/release.d.ts +19 -0
  52. package/v3/@swarmdo/cli/dist/src/release/release.js +28 -0
  53. package/v3/@swarmdo/cli/dist/src/usage/reflect.d.ts +9 -1
  54. package/v3/@swarmdo/cli/dist/src/usage/reflect.js +14 -4
  55. package/v3/@swarmdo/cli/dist/src/util/since.d.ts +13 -0
  56. package/v3/@swarmdo/cli/dist/src/util/since.js +21 -0
  57. package/v3/@swarmdo/cli/package.json +1 -1
@@ -42,6 +42,41 @@ export declare function readyTasks(store: TaskStore): TaskRecord[];
42
42
  export declare function blockedTasks(store: TaskStore): BlockedInfo[];
43
43
  /** Tasks that became ready exactly because `completedTaskId` completed. */
44
44
  export declare function unblockedBy(store: TaskStore, completedTaskId: string): TaskRecord[];
45
+ export interface DeadBlock {
46
+ task: TaskRecord;
47
+ /**
48
+ * The terminal-dead dependency ids in this task's dependency closure — the
49
+ * failed, cancelled, or missing tasks that make it permanently unreachable
50
+ * until a human retries/cancels/creates them. Deterministic (sorted).
51
+ */
52
+ rootCause: string[];
53
+ }
54
+ export interface TaskDagHealth {
55
+ /** pending tasks whose unmet deps can STILL complete — a transient wait */
56
+ liveBlocked: TaskRecord[];
57
+ /** pending tasks that can NEVER become ready without human intervention */
58
+ deadBlocked: DeadBlock[];
59
+ /**
60
+ * true when pending work exists but nothing is ready AND nothing is
61
+ * in_progress — the DAG cannot advance on its own. A coordinator looping on
62
+ * `task dispatch` would otherwise spin forever doing nothing.
63
+ */
64
+ deadlocked: boolean;
65
+ }
66
+ /**
67
+ * Classify every blocked task as live- vs dead-blocked and report a global
68
+ * deadlock verdict. Pure.
69
+ *
70
+ * This is Apache Airflow's `upstream_failed` state + DAG-deadlock detection,
71
+ * ported onto the beads-style task DAG (see the module header): a dependency
72
+ * that failed / was cancelled / is missing NEVER satisfies (only 'completed'
73
+ * does), so every task transitively downstream is permanently stuck until a
74
+ * human intervenes. `blockedTasks()` reports the wait but can't tell a
75
+ * transient wait from a permanent one — the dispatcher then skips a
76
+ * failed-dep block every pass, indistinguishable from a normal wait, and the
77
+ * DAG quietly wedges. This turns that silent stall into a named diagnostic.
78
+ */
79
+ export declare function taskDagHealth(store: TaskStore): TaskDagHealth;
45
80
  /**
46
81
  * Flat dependency view: one line per task, dependencies inline with their
47
82
  * states. A DAG has no single tree; a flat annotated list stays honest for
@@ -94,6 +94,93 @@ export function blockedTasks(store) {
94
94
  export function unblockedBy(store, completedTaskId) {
95
95
  return Object.values(store.tasks).filter((t) => t.status === 'pending' && (t.dependsOn ?? []).includes(completedTaskId) && isReady(store, t));
96
96
  }
97
+ /**
98
+ * Classify every blocked task as live- vs dead-blocked and report a global
99
+ * deadlock verdict. Pure.
100
+ *
101
+ * This is Apache Airflow's `upstream_failed` state + DAG-deadlock detection,
102
+ * ported onto the beads-style task DAG (see the module header): a dependency
103
+ * that failed / was cancelled / is missing NEVER satisfies (only 'completed'
104
+ * does), so every task transitively downstream is permanently stuck until a
105
+ * human intervenes. `blockedTasks()` reports the wait but can't tell a
106
+ * transient wait from a permanent one — the dispatcher then skips a
107
+ * failed-dep block every pass, indistinguishable from a normal wait, and the
108
+ * DAG quietly wedges. This turns that silent stall into a named diagnostic.
109
+ */
110
+ export function taskDagHealth(store) {
111
+ // canComplete(id): can this task ever reach status 'completed'?
112
+ // completed → yes; failed/cancelled/missing → no; pending/in_progress →
113
+ // only if EVERY dependency can complete. Memoized; a cycle (the store is
114
+ // acyclic by invariant, but guard anyway) resolves to false.
115
+ const memo = new Map();
116
+ const visiting = new Set();
117
+ const canComplete = (id) => {
118
+ const cached = memo.get(id);
119
+ if (cached !== undefined)
120
+ return cached;
121
+ const task = store.tasks[id];
122
+ if (!task)
123
+ return false; // missing id — blocks forever
124
+ if (task.status === 'completed')
125
+ return true;
126
+ if (task.status === 'failed' || task.status === 'cancelled')
127
+ return false;
128
+ if (visiting.has(id))
129
+ return false; // cycle guard
130
+ visiting.add(id);
131
+ const ok = (task.dependsOn ?? []).every((d) => canComplete(d));
132
+ visiting.delete(id);
133
+ memo.set(id, ok);
134
+ return ok;
135
+ };
136
+ // The terminal-dead ids (failed/cancelled/missing) reachable from a task,
137
+ // descending THROUGH still-pending intermediates to name the real culprit.
138
+ const deadRoots = (task) => {
139
+ const found = new Set();
140
+ const seen = new Set();
141
+ const stack = [...(task.dependsOn ?? [])];
142
+ while (stack.length) {
143
+ const id = stack.pop();
144
+ if (seen.has(id))
145
+ continue;
146
+ seen.add(id);
147
+ const dep = store.tasks[id];
148
+ if (!dep) {
149
+ found.add(id);
150
+ continue;
151
+ } // missing
152
+ if (dep.status === 'failed' || dep.status === 'cancelled') {
153
+ found.add(id);
154
+ continue;
155
+ }
156
+ if (dep.status === 'completed')
157
+ continue; // satisfied — not a culprit
158
+ for (const d of dep.dependsOn ?? [])
159
+ stack.push(d); // pending/in_progress → descend
160
+ }
161
+ return [...found].sort();
162
+ };
163
+ const liveBlocked = [];
164
+ const deadBlocked = [];
165
+ for (const task of Object.values(store.tasks)) {
166
+ if (task.status !== 'pending')
167
+ continue;
168
+ const deps = task.dependsOn ?? [];
169
+ if (deps.length === 0)
170
+ continue; // ready (dep-free), not blocked
171
+ if (deps.every((id) => satisfies(store.tasks[id])))
172
+ continue; // ready, not blocked
173
+ if (deps.every((id) => canComplete(id)))
174
+ liveBlocked.push(task);
175
+ else
176
+ deadBlocked.push({ task, rootCause: deadRoots(task) });
177
+ }
178
+ const all = Object.values(store.tasks);
179
+ const anyPending = all.some((t) => t.status === 'pending');
180
+ const anyInProgress = all.some((t) => t.status === 'in_progress');
181
+ const deadlocked = anyPending && readyTasks(store).length === 0 && !anyInProgress;
182
+ return { liveBlocked, deadBlocked, deadlocked };
183
+ }
97
184
  const STATUS_MARK = {
98
185
  completed: '✔',
99
186
  in_progress: '▶',
@@ -0,0 +1,61 @@
1
+ /**
2
+ * ownership.ts — per-file authorship concentration + BUS FACTOR from git history.
3
+ *
4
+ * "Who owns this file, and what breaks if they leave?" answered from data. For
5
+ * every file we compute the dominant author (main-dev), how concentrated the
6
+ * churn is in that one person (ownership share), how many hands have touched it,
7
+ * and its bus factor — the smallest set of top authors whose combined churn
8
+ * clears half the file. A bus factor of 1 is a key-person risk: one departure
9
+ * orphans the file. A repo-level "truck factor" answers the same question for
10
+ * the whole codebase.
11
+ *
12
+ * This is the code-maat `main-dev` / `entity-ownership` analysis (Tornhill,
13
+ * *Your Code as a Crime Scene*), surfaced as CodeScene's "Knowledge Map" and
14
+ * "Bus Factor". The scoring core is a pure fold over the SAME `git log --numstat`
15
+ * dump `hotspots`/`coupling` already parse — it reuses that Commit type +
16
+ * parseGitLog and is unit-tested without a repo. `%aN` (mailmap-folded author)
17
+ * means name/email variants of one person count as one owner.
18
+ */
19
+ import type { Commit } from '../hotspots/hotspots.js';
20
+ export interface FileOwnership {
21
+ path: string;
22
+ /** dominant author: most churn, tie → most commits, tie → name ascending */
23
+ owner: string;
24
+ /** owner churn / total file churn ∈ (0,1]; 1.0 = a single hand */
25
+ ownership: number;
26
+ /** distinct authors who touched the file */
27
+ authors: number;
28
+ /** total added+deleted across all commits */
29
+ churn: number;
30
+ /** commits touching the file */
31
+ commits: number;
32
+ /** smallest # of top-churn authors whose cumulative churn EXCEEDS 50% */
33
+ busFactor: number;
34
+ /** busFactor === 1 — a single point of knowledge (one departure orphans it) */
35
+ keyPersonRisk: boolean;
36
+ }
37
+ export interface RepoBusFactor {
38
+ /** the covering set: fewest top authors whose cumulative churn exceeds 50% */
39
+ authors: string[];
40
+ /** authors.length — the repo "truck factor" */
41
+ factor: number;
42
+ }
43
+ export interface OwnershipOptions {
44
+ /** drop files with total churn below this (default 1 → skips pure-binary edits) */
45
+ minChurn?: number;
46
+ /** keep only the top N files after ranking (default: all) */
47
+ top?: number;
48
+ }
49
+ /** Aggregate commits into per-file ownership, scored and ranked. Pure. */
50
+ export declare function computeOwnership(commits: Commit[], opts?: OwnershipOptions): FileOwnership[];
51
+ /**
52
+ * Repo-level truck factor: the fewest top authors whose combined churn across
53
+ * the WHOLE history exceeds half the total. If that set is one person, a single
54
+ * departure takes the majority of the codebase's institutional knowledge. Pure.
55
+ */
56
+ export declare function repoBusFactor(commits: Commit[]): RepoBusFactor;
57
+ /** Export the knowledge map as CSV for spreadsheets / staffing review. Pure. */
58
+ export declare function ownershipToCsv(files: FileOwnership[]): string;
59
+ /** Human-readable knowledge map. Pure. */
60
+ export declare function formatOwnership(files: FileOwnership[]): string;
61
+ //# sourceMappingURL=ownership.d.ts.map
@@ -0,0 +1,151 @@
1
+ /**
2
+ * ownership.ts — per-file authorship concentration + BUS FACTOR from git history.
3
+ *
4
+ * "Who owns this file, and what breaks if they leave?" answered from data. For
5
+ * every file we compute the dominant author (main-dev), how concentrated the
6
+ * churn is in that one person (ownership share), how many hands have touched it,
7
+ * and its bus factor — the smallest set of top authors whose combined churn
8
+ * clears half the file. A bus factor of 1 is a key-person risk: one departure
9
+ * orphans the file. A repo-level "truck factor" answers the same question for
10
+ * the whole codebase.
11
+ *
12
+ * This is the code-maat `main-dev` / `entity-ownership` analysis (Tornhill,
13
+ * *Your Code as a Crime Scene*), surfaced as CodeScene's "Knowledge Map" and
14
+ * "Bus Factor". The scoring core is a pure fold over the SAME `git log --numstat`
15
+ * dump `hotspots`/`coupling` already parse — it reuses that Commit type +
16
+ * parseGitLog and is unit-tested without a repo. `%aN` (mailmap-folded author)
17
+ * means name/email variants of one person count as one owner.
18
+ */
19
+ import { toCsv } from '../util/csv.js';
20
+ /**
21
+ * Bus factor of a churn distribution: the smallest number of top-churn authors
22
+ * whose cumulative churn STRICTLY exceeds half the total. An author sitting at
23
+ * exactly 50% is not enough on their own (you'd need one more), which is what
24
+ * makes an even two-way split a bus factor of 2. Pure.
25
+ */
26
+ function busFactorOf(authors, total) {
27
+ const byChurn = authors.slice().sort((x, y) => y.churn - x.churn || (x.name < y.name ? -1 : x.name > y.name ? 1 : 0));
28
+ const threshold = total / 2;
29
+ let cum = 0;
30
+ let k = 0;
31
+ for (const a of byChurn) {
32
+ cum += a.churn;
33
+ k++;
34
+ if (cum > threshold)
35
+ break;
36
+ }
37
+ return Math.max(1, k);
38
+ }
39
+ /** Aggregate commits into per-file ownership, scored and ranked. Pure. */
40
+ export function computeOwnership(commits, opts = {}) {
41
+ const minChurn = opts.minChurn ?? 1;
42
+ const acc = new Map();
43
+ for (const c of commits) {
44
+ // Fold this commit's numstat lines into per-path churn first, so a path that
45
+ // appears twice in one commit (rename collisions) counts as ONE commit.
46
+ const perPath = new Map();
47
+ for (const f of c.files) {
48
+ if (!f.path)
49
+ continue;
50
+ perPath.set(f.path, (perPath.get(f.path) ?? 0) + f.added + f.deleted);
51
+ }
52
+ for (const [path, churn] of perPath) {
53
+ let fa = acc.get(path);
54
+ if (!fa) {
55
+ fa = { churn: 0, commits: 0, byAuthor: new Map() };
56
+ acc.set(path, fa);
57
+ }
58
+ fa.churn += churn;
59
+ fa.commits += 1;
60
+ let a = fa.byAuthor.get(c.author);
61
+ if (!a) {
62
+ a = { name: c.author, churn: 0, commits: 0 };
63
+ fa.byAuthor.set(c.author, a);
64
+ }
65
+ a.churn += churn;
66
+ a.commits += 1;
67
+ }
68
+ }
69
+ const out = [];
70
+ for (const [path, fa] of acc) {
71
+ if (fa.churn < minChurn)
72
+ continue;
73
+ const authors = [...fa.byAuthor.values()];
74
+ // owner: most churn, tie → most commits (sustained involvement), tie → name asc
75
+ const owner = authors
76
+ .slice()
77
+ .sort((x, y) => y.churn - x.churn || y.commits - x.commits || (x.name < y.name ? -1 : x.name > y.name ? 1 : 0))[0];
78
+ const ownership = fa.churn > 0 ? Math.round((owner.churn / fa.churn) * 100) / 100 : 0;
79
+ const busFactor = busFactorOf(authors, fa.churn);
80
+ out.push({
81
+ path,
82
+ owner: owner.name,
83
+ ownership,
84
+ authors: authors.length,
85
+ churn: fa.churn,
86
+ commits: fa.commits,
87
+ busFactor,
88
+ keyPersonRisk: busFactor === 1,
89
+ });
90
+ }
91
+ // Deterministic ranking: most fragile first — lowest bus factor, then most
92
+ // concentrated (ownership desc), then most churn, then path asc for stable ties.
93
+ out.sort((x, y) => x.busFactor - y.busFactor ||
94
+ y.ownership - x.ownership ||
95
+ y.churn - x.churn ||
96
+ (x.path < y.path ? -1 : x.path > y.path ? 1 : 0));
97
+ return opts.top && opts.top > 0 ? out.slice(0, opts.top) : out;
98
+ }
99
+ /**
100
+ * Repo-level truck factor: the fewest top authors whose combined churn across
101
+ * the WHOLE history exceeds half the total. If that set is one person, a single
102
+ * departure takes the majority of the codebase's institutional knowledge. Pure.
103
+ */
104
+ export function repoBusFactor(commits) {
105
+ const byAuthor = new Map();
106
+ let total = 0;
107
+ for (const c of commits) {
108
+ for (const f of c.files) {
109
+ const ch = f.added + f.deleted;
110
+ byAuthor.set(c.author, (byAuthor.get(c.author) ?? 0) + ch);
111
+ total += ch;
112
+ }
113
+ }
114
+ const sorted = [...byAuthor.entries()].sort((x, y) => y[1] - x[1] || (x[0] < y[0] ? -1 : x[0] > y[0] ? 1 : 0));
115
+ const threshold = total / 2;
116
+ const authors = [];
117
+ let cum = 0;
118
+ for (const [name, ch] of sorted) {
119
+ authors.push(name);
120
+ cum += ch;
121
+ if (cum > threshold)
122
+ break;
123
+ }
124
+ return { authors, factor: authors.length };
125
+ }
126
+ /** Export the knowledge map as CSV for spreadsheets / staffing review. Pure. */
127
+ export function ownershipToCsv(files) {
128
+ const headers = ['path', 'owner', 'ownership', 'busFactor', 'authors', 'churn', 'commits', 'keyPersonRisk'];
129
+ const rows = files.map((f) => [f.path, f.owner, f.ownership, f.busFactor, f.authors, f.churn, f.commits, f.keyPersonRisk]);
130
+ return toCsv(headers, rows);
131
+ }
132
+ /** Human-readable knowledge map. Pure. */
133
+ export function formatOwnership(files) {
134
+ if (files.length === 0)
135
+ return 'no ownership data found (no matching history)';
136
+ const lines = [];
137
+ lines.push('rank bus own% authors churn commits owner file');
138
+ files.forEach((f, i) => {
139
+ const rank = String(i + 1).padStart(4);
140
+ const bus = String(f.busFactor).padStart(3);
141
+ const own = `${Math.round(f.ownership * 100)}%`.padStart(5);
142
+ const authors = String(f.authors).padStart(7);
143
+ const churn = String(f.churn).padStart(6);
144
+ const commits = String(f.commits).padStart(7);
145
+ const owner = (f.owner.length > 20 ? f.owner.slice(0, 19) + '…' : f.owner).padEnd(20);
146
+ const risk = f.keyPersonRisk ? ' ⚠ key-person' : '';
147
+ lines.push(`${rank} ${bus} ${own} ${authors} ${churn} ${commits} ${owner} ${f.path}${risk}`);
148
+ });
149
+ return lines.join('\n');
150
+ }
151
+ //# sourceMappingURL=ownership.js.map
@@ -54,5 +54,5 @@ export declare function packFiles(input: PackFile[], opts?: PackOptions): PackRe
54
54
  * `dir/`, `*.ext` globs, `**` depth globs (gitignore(5) semantics), leading `/`
55
55
  * anchors, and `!` negation. Not the full spec (no nested ignore files).
56
56
  */
57
- export declare function makeIgnoreMatcher(patterns: string[]): (relPath: string) => boolean;
57
+ export declare function makeIgnoreMatcher(patterns: string[]): (relPath: string, isDir?: boolean) => boolean;
58
58
  //# sourceMappingURL=pack.d.ts.map
@@ -201,19 +201,24 @@ export function makeIgnoreMatcher(patterns) {
201
201
  // Only a slash-free pattern (`dir`, `*.ext`) matches at any depth.
202
202
  const anchored = leadingSlash || body.includes('/');
203
203
  const re = new RegExp('^' + globToRegExp(body) + (dirOnly ? '(/|$)' : '($|/)'));
204
- return { negate, anchored, re };
204
+ return { negate, anchored, dirOnly, re };
205
205
  });
206
206
  // Ignored status of a single path (last-match-wins over the ordered rules).
207
- const ruleVerdict = (path) => {
207
+ // `isDirComponent` is whether the entry named by the path's LAST segment is a
208
+ // directory: a trailing-slash (dir-only) pattern matches directories ONLY per
209
+ // gitignore(5), so `build/` must NOT fire on a regular file named `build`.
210
+ const ruleVerdict = (path, isDirComponent) => {
208
211
  let ignored = false;
209
212
  for (const r of rules) {
213
+ if (r.dirOnly && !isDirComponent)
214
+ continue; // dir-only pattern can't match a file
210
215
  const candidates = r.anchored ? [path] : [path, ...path.split('/').map((_, i, a) => a.slice(i).join('/'))];
211
216
  if (candidates.some((c) => r.re.test(c)))
212
217
  ignored = !r.negate;
213
218
  }
214
219
  return ignored;
215
220
  };
216
- return (relPath) => {
221
+ return (relPath, isDir = false) => {
217
222
  // Walk ancestor dirs top-down: once a parent directory is excluded, the file
218
223
  // stays excluded — a negation cannot re-include under an excluded parent
219
224
  // (gitignore(5): "not possible to re-include a file if a parent directory of
@@ -227,7 +232,10 @@ export function makeIgnoreMatcher(patterns) {
227
232
  return true;
228
233
  continue; // excluded ancestor carries down
229
234
  }
230
- const verdict = ruleVerdict(parts.slice(0, i + 1).join('/'));
235
+ // Ancestor prefixes are directories by construction; only the final entry's
236
+ // type comes from the caller (a filesystem walker knows dir vs file).
237
+ const componentIsDir = isLast ? isDir : true;
238
+ const verdict = ruleVerdict(parts.slice(0, i + 1).join('/'), componentIsDir);
231
239
  if (isLast)
232
240
  return verdict;
233
241
  parentIgnored = verdict; // this directory prefix carries forward
@@ -44,25 +44,39 @@ export const RULES = [
44
44
  * Keyword set mirrors gitleaks' reference `generic-api-key` rule (adds bare
45
45
  * `key`, `credential`, `creds` so `PRIVATE_KEY=`/`ENCRYPTION_KEY=`/`DB_CREDENTIAL=`
46
46
  * secrets reach the entropy check). The `[:=]` immediately after the keyword
47
- * anchors it, so `keyboard=`/`monkey_val=` don't match; the entropy + length
48
- * gates keep low-entropy values (paths, short flags) from being flagged. The
49
- * value class also stops at the URL/query delimiters `&`, `?`, `#` (absent from
50
- * base64/base64url/hex token alphabets): otherwise a query-string secret like
51
- * `client_secret=…&api_key=…` over-captures past the `&` into the next secret,
52
- * and that inflated span overlapping a range the high-confidence RULES pass
53
- * already claimed gets dropped entirely, leaving the first secret unredacted.
47
+ * anchors it, so `keyboard=`/`monkey_val=` don't match. A `(?<![A-Za-z])` guard
48
+ * requires the keyword NOT be glued to a preceding letter, so a common word that
49
+ * merely ENDS in a keyword `monkey=`/`donkey=`/`whiskey=`/`turkey=` (end in
50
+ * `key`), `compass=`/`bypass=` (end in `pass`) is no longer flagged as a
51
+ * secret, while a `_`/`-`-separated name (`PRIVATE_KEY`, `x-api-key`) still
52
+ * matches (`_`/`-` aren't letters). The entropy + length gates keep low-entropy
53
+ * values (paths, short flags) out. The value class also stops at the URL/query
54
+ * delimiters `&`, `?`, `#` (absent from base64/base64url/hex token alphabets):
55
+ * otherwise a query-string secret like `client_secret=…&api_key=…` over-captures
56
+ * past the `&` into the next secret. It CANNOT stop at `/ : . = + ~`, though —
57
+ * base64/base64url/connection-string secrets contain those — so a recognized
58
+ * token glued on by one of them still over-captures; the entropy pass in
59
+ * `collectHits` handles that by CLIPPING the span at the claimed range rather
60
+ * than dropping the finding (which would leak the leading secret, #100).
54
61
  */
55
- const ASSIGNMENT_RE = /(?:pass(?:word|phrase|wd)?|pwd|secret|token|api[_-]?key|apikey|access[_-]?key|auth[_-]?token|client[_-]?secret|credential|creds|key)["']?\s*[:=]\s*["']?([^\s"'`,;&?#]{8,})/gi;
62
+ const ASSIGNMENT_RE = /(?<![A-Za-z])(?:pass(?:word|phrase|wd)?|pwd|secret|token|api[_-]?key|apikey|access[_-]?key|auth[_-]?token|client[_-]?secret|credential|creds|key)["']?\s*[:=]\s*["']?([^\s"'`,;&?#]{8,})/gi;
56
63
  /** Shannon entropy in bits/char. Pure; used by the assignment fallback. */
57
64
  export function shannonEntropy(s) {
58
65
  if (!s)
59
66
  return 0;
67
+ // Iterate AND normalize by code points, not UTF-16 code units. `for..of` /
68
+ // spread yield one symbol per code point, but `s.length` counts an astral
69
+ // char (emoji, CJK Ext-B, math alphanumerics) as 2 units — so dividing the
70
+ // per-symbol counts by s.length made the probabilities sum to <1 and
71
+ // under-counted entropy up to ~2×, letting a high-entropy secret with astral
72
+ // chars fall under the threshold and pass through UN-redacted (#95).
73
+ const cps = [...s];
60
74
  const freq = new Map();
61
- for (const ch of s)
75
+ for (const ch of cps)
62
76
  freq.set(ch, (freq.get(ch) ?? 0) + 1);
63
77
  let bits = 0;
64
78
  for (const n of freq.values()) {
65
- const p = n / s.length;
79
+ const p = n / cps.length;
66
80
  bits -= p * Math.log2(p);
67
81
  }
68
82
  return bits;
@@ -109,15 +123,32 @@ function collectHits(text, opts) {
109
123
  while ((m = ASSIGNMENT_RE.exec(text)) !== null) {
110
124
  const value = m[1];
111
125
  const start = m.index + m[0].indexOf(value);
112
- const end = start + value.length;
113
- if (overlaps(start, end))
114
- continue;
115
- if (isAllowlisted(value, opts.allowlist))
126
+ let end = start + value.length;
127
+ let match = value;
128
+ // The value class must include `/ : . = + ~` for base64/base64url/conn-string
129
+ // secrets, so a recognized RULES token (GitHub PAT, AWS key, …) glued on by
130
+ // one of those separators gets over-captured into this span. When that
131
+ // happens, DON'T drop the finding on overlap — the leading high-entropy
132
+ // secret would leak in cleartext (only the trailing token got masked, #100).
133
+ // Instead clip the span to end at the earliest claimed range within it and
134
+ // re-gate the leading fragment; the trailing token keeps its RULES redaction.
135
+ const overlapping = claimed.filter(([s, e]) => start < e && end > s);
136
+ if (overlapping.length > 0) {
137
+ // value's own start already sits inside a claimed secret → fully covered
138
+ if (overlapping.some(([s, e]) => s <= start && start < e))
139
+ continue;
140
+ const clipTo = Math.min(...overlapping.map(([s]) => s));
141
+ match = text.slice(start, clipTo).replace(/[^A-Za-z0-9]+$/, ''); // drop the trailing separator
142
+ end = start + match.length;
143
+ if (match.length < 8)
144
+ continue; // clipped leading fragment too short to be a secret
145
+ }
146
+ if (isAllowlisted(match, opts.allowlist))
116
147
  continue;
117
- if (shannonEntropy(value) < threshold)
148
+ if (shannonEntropy(match) < threshold)
118
149
  continue;
119
150
  claimed.push([start, end]);
120
- hits.push({ ruleId: 'high-entropy-assignment', description: 'High-entropy secret assignment', index: start, match: value });
151
+ hits.push({ ruleId: 'high-entropy-assignment', description: 'High-entropy secret assignment', index: start, match });
121
152
  }
122
153
  }
123
154
  return hits.sort((a, b) => a.index - b.index);
@@ -0,0 +1,28 @@
1
+ /**
2
+ * sarif.ts — render redact secret-scan findings as a SARIF 2.1.0 document.
3
+ *
4
+ * SARIF (Static Analysis Results Interchange Format) is a ratified OASIS
5
+ * standard that GitHub code-scanning ingests via `github/codeql-action/
6
+ * upload-sarif`. Emit it from `redact --scan` in CI and leaked-secret findings
7
+ * surface as alerts in the Security tab + PR annotations instead of dying in
8
+ * the build log — the same thing gitleaks/trufflehog/ggshield do with their
9
+ * `--report-format sarif`.
10
+ *
11
+ * Pure + deterministic: findings in, JSON string out. No fs/network.
12
+ */
13
+ import type { Finding } from './redact.js';
14
+ export interface SarifOptions {
15
+ /** SARIF tool.driver.name (default 'swarmdo-redact') */
16
+ toolName?: string;
17
+ /** SARIF tool.driver.version — omitted from the document when not given */
18
+ toolVersion?: string;
19
+ /**
20
+ * URI for the artifact each finding lives in. `redact --scan` reads a STREAM
21
+ * (stdin / wrapped output), so there is no committed file by default; pass
22
+ * this (e.g. from `--source <path>`) to anchor the alerts onto a repo path.
23
+ */
24
+ artifactUri?: string;
25
+ }
26
+ /** Render `findings` as a SARIF 2.1.0 document string. Pure + deterministic. */
27
+ export declare function toSarif(findings: Finding[], opts?: SarifOptions): string;
28
+ //# sourceMappingURL=sarif.d.ts.map
@@ -0,0 +1,53 @@
1
+ /**
2
+ * sarif.ts — render redact secret-scan findings as a SARIF 2.1.0 document.
3
+ *
4
+ * SARIF (Static Analysis Results Interchange Format) is a ratified OASIS
5
+ * standard that GitHub code-scanning ingests via `github/codeql-action/
6
+ * upload-sarif`. Emit it from `redact --scan` in CI and leaked-secret findings
7
+ * surface as alerts in the Security tab + PR annotations instead of dying in
8
+ * the build log — the same thing gitleaks/trufflehog/ggshield do with their
9
+ * `--report-format sarif`.
10
+ *
11
+ * Pure + deterministic: findings in, JSON string out. No fs/network.
12
+ */
13
+ const SARIF_SCHEMA = 'https://json.schemastore.org/sarif-2.1.0.json';
14
+ const INFO_URI = 'the upstream project (see NOTICE)';
15
+ /** Render `findings` as a SARIF 2.1.0 document string. Pure + deterministic. */
16
+ export function toSarif(findings, opts = {}) {
17
+ const toolName = opts.toolName ?? 'swarmdo-redact';
18
+ // One rule descriptor per distinct ruleId, in first-seen order. Findings
19
+ // carry their own description, so the entropy fallback (not in RULES) is
20
+ // covered too — every result.ruleId is guaranteed to appear in rules[].
21
+ const ruleIndex = new Map();
22
+ const rules = [];
23
+ for (const f of findings) {
24
+ if (ruleIndex.has(f.ruleId))
25
+ continue;
26
+ ruleIndex.set(f.ruleId, rules.length);
27
+ rules.push({ id: f.ruleId, name: f.ruleId, shortDescription: { text: f.description } });
28
+ }
29
+ const results = findings.map((f) => {
30
+ const physicalLocation = {
31
+ region: { startLine: f.line, startColumn: f.column },
32
+ };
33
+ if (opts.artifactUri)
34
+ physicalLocation.artifactLocation = { uri: opts.artifactUri };
35
+ return {
36
+ ruleId: f.ruleId,
37
+ ruleIndex: ruleIndex.get(f.ruleId),
38
+ level: 'error',
39
+ message: { text: `Possible secret: ${f.description}` },
40
+ locations: [{ physicalLocation }],
41
+ };
42
+ });
43
+ const driver = { name: toolName, informationUri: INFO_URI, rules };
44
+ if (opts.toolVersion)
45
+ driver.version = opts.toolVersion;
46
+ const doc = {
47
+ $schema: SARIF_SCHEMA,
48
+ version: '2.1.0',
49
+ runs: [{ tool: { driver }, results }],
50
+ };
51
+ return JSON.stringify(doc, null, 2);
52
+ }
53
+ //# sourceMappingURL=sarif.js.map
@@ -69,4 +69,23 @@ export declare const DOC_FILES: string[];
69
69
  export declare function planRelease(input: ReleaseInput): ReleasePlan;
70
70
  /** One-line human rendering of a step (for the dry-run plan). */
71
71
  export declare function renderStep(s: ReleaseStep): string;
72
+ export interface SiteIdentity {
73
+ name: string;
74
+ email: string;
75
+ }
76
+ /**
77
+ * Resolve the committer identity for the throwaway swarmdo.com clone. That
78
+ * clone inherits no identity, and a machine may have only a *local* (per-repo)
79
+ * git user — so `git commit` there dies with "Author identity unknown" unless
80
+ * we inject one. Prefer the operator's configured identity; fall back to the
81
+ * Swarmdo bot so the site deploy never fails on a missing global git config.
82
+ * `readConfig` is injected (real: `git -C <root> config <key>`) so this stays
83
+ * pure and unit-testable.
84
+ */
85
+ export declare function resolveSiteIdentity(readConfig: (key: string) => string | undefined): SiteIdentity;
86
+ /**
87
+ * `git commit` argv for the site sync — injects the identity via `-c` so the
88
+ * commit succeeds without a global git user, and keeps the bot co-author trailer.
89
+ */
90
+ export declare function siteCommitArgs(version: string, id: SiteIdentity): string[];
72
91
  //# sourceMappingURL=release.d.ts.map
@@ -83,4 +83,32 @@ export function renderStep(s) {
83
83
  case 'deploy-site': return `deploy website → SwarmDo/swarmdo.com (copy working copy, push, curl-verify swarmdo.com serves ${s.version})`;
84
84
  }
85
85
  }
86
+ /**
87
+ * Resolve the committer identity for the throwaway swarmdo.com clone. That
88
+ * clone inherits no identity, and a machine may have only a *local* (per-repo)
89
+ * git user — so `git commit` there dies with "Author identity unknown" unless
90
+ * we inject one. Prefer the operator's configured identity; fall back to the
91
+ * Swarmdo bot so the site deploy never fails on a missing global git config.
92
+ * `readConfig` is injected (real: `git -C <root> config <key>`) so this stays
93
+ * pure and unit-testable.
94
+ */
95
+ export function resolveSiteIdentity(readConfig) {
96
+ const name = (readConfig('user.name') || '').trim();
97
+ const email = (readConfig('user.email') || '').trim();
98
+ return {
99
+ name: name || 'Swarmdo',
100
+ email: email || 'maintainers@swarmdo.com',
101
+ };
102
+ }
103
+ /**
104
+ * `git commit` argv for the site sync — injects the identity via `-c` so the
105
+ * commit succeeds without a global git user, and keeps the bot co-author trailer.
106
+ */
107
+ export function siteCommitArgs(version, id) {
108
+ return [
109
+ '-c', `user.name=${id.name}`,
110
+ '-c', `user.email=${id.email}`,
111
+ 'commit', '-m', `release: sync site for v${version}\n\nCo-Authored-By: Swarmdo <maintainers@swarmdo.com>`,
112
+ ];
113
+ }
86
114
  //# sourceMappingURL=release.js.map
@@ -90,7 +90,15 @@ export declare function nextDay(iso: string): string;
90
90
  * Pure. Used to derive a `--period 1m|3m|…` window start from today.
91
91
  */
92
92
  export declare function monthsBefore(iso: string, n: number): string;
93
- /** Inclusive whole-day span between two ISO dates (from <= to). Pure. */
93
+ /**
94
+ * Inclusive whole-day span between two ISO dates (from <= to). Pure.
95
+ *
96
+ * Counts on the UTC timeline (`Date.UTC`), NOT local midnights: a local
97
+ * `new Date('…T00:00:00')` is DST-sensitive, so a range crossing a spring-forward
98
+ * day (only 23h long) would floor-divide to one day short — e.g. under
99
+ * TZ=America/New_York a full March would read 30. UTC calendar midnights are
100
+ * always an exact 86.4M ms apart, so this is correct in every process timezone.
101
+ */
94
102
  export declare function spanDays(from: string, to: string): number;
95
103
  /** Longest run of consecutive calendar days present in the set. Pure. */
96
104
  export declare function longestStreakOf(days: string[]): number;