peaks-loop 4.1.6 → 4.1.8

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 (90) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +78 -0
  3. package/config/eslint/tsconfig.lint.json +1 -0
  4. package/dist/cli/commands/core/skill-registry-commands.js +9 -4
  5. package/dist/cli/commands/dispatch-from-dag.js +17 -0
  6. package/dist/cli/commands/job-commands.js +15 -5
  7. package/dist/cli/commands/lint-baseline-command.d.ts +15 -0
  8. package/dist/cli/commands/lint-baseline-command.js +64 -0
  9. package/dist/cli/commands/lint-commands.js +27 -51
  10. package/dist/cli/commands/request-command-options.d.ts +6 -0
  11. package/dist/cli/commands/request-commands.js +2 -0
  12. package/dist/cli/commands/request-mark-qa-initiated-command.d.ts +3 -0
  13. package/dist/cli/commands/request-mark-qa-initiated-command.js +80 -0
  14. package/dist/cli/commands/request-transition-failures.js +1 -0
  15. package/dist/cli/commands/reviewer-commands.d.ts +6 -6
  16. package/dist/cli/commands/reviewer-commands.js +154 -56
  17. package/dist/cli/commands/reviewer-config-commands.d.ts +9 -0
  18. package/dist/cli/commands/reviewer-config-commands.js +133 -0
  19. package/dist/services/artifacts/artifact-lint-service.js +102 -27
  20. package/dist/services/artifacts/artifact-prerequisites.d.ts +2 -0
  21. package/dist/services/artifacts/artifact-prerequisites.js +22 -110
  22. package/dist/services/artifacts/artifact-template-bodies.d.ts +7 -1
  23. package/dist/services/artifacts/artifact-template-bodies.js +14 -3
  24. package/dist/services/artifacts/artifact-templates.d.ts +6 -1
  25. package/dist/services/artifacts/artifact-templates.js +8 -5
  26. package/dist/services/artifacts/backcompat-acceptance.d.ts +66 -0
  27. package/dist/services/artifacts/backcompat-acceptance.js +222 -0
  28. package/dist/services/artifacts/prerequisite-checks.d.ts +42 -9
  29. package/dist/services/artifacts/prerequisite-checks.js +35 -11
  30. package/dist/services/artifacts/prerequisite-path-resolver.d.ts +39 -0
  31. package/dist/services/artifacts/prerequisite-path-resolver.js +110 -0
  32. package/dist/services/artifacts/qa-initiated-marker.d.ts +24 -0
  33. package/dist/services/artifacts/qa-initiated-marker.js +36 -0
  34. package/dist/services/artifacts/request-artifact-metadata.d.ts +9 -0
  35. package/dist/services/artifacts/request-artifact-metadata.js +9 -0
  36. package/dist/services/artifacts/request-artifact-service.js +6 -10
  37. package/dist/services/artifacts/request-artifact-state-helpers.d.ts +2 -1
  38. package/dist/services/artifacts/request-artifact-state-helpers.js +6 -3
  39. package/dist/services/dispatch/isolation-lease.d.ts +3 -2
  40. package/dist/services/dispatch/isolation-lease.js +15 -6
  41. package/dist/services/doctor/doctor-service/checks/backcompat-acceptance.d.ts +15 -0
  42. package/dist/services/doctor/doctor-service/checks/backcompat-acceptance.js +53 -0
  43. package/dist/services/doctor/doctor-service/checks/skill-reference-parity.d.ts +38 -0
  44. package/dist/services/doctor/doctor-service/checks/skill-reference-parity.js +243 -0
  45. package/dist/services/doctor/doctor-service/plugin-registry.js +4 -0
  46. package/dist/services/doctor/doctor-service/types.d.ts +12 -0
  47. package/dist/services/job/subagent-job-wrapper.d.ts +20 -7
  48. package/dist/services/job/subagent-job-wrapper.js +53 -5
  49. package/dist/services/lint/eslint-report.d.ts +19 -0
  50. package/dist/services/lint/eslint-report.js +60 -0
  51. package/dist/services/lint/eslint-runner-support.d.ts +18 -1
  52. package/dist/services/lint/eslint-runner-support.js +35 -2
  53. package/dist/services/lint/eslint-runner-types.d.ts +21 -1
  54. package/dist/services/lint/eslint-runner.js +43 -33
  55. package/dist/services/prd/gate-evidence-derivation.d.ts +2 -4
  56. package/dist/services/prd/gate-evidence-derivation.js +3 -1
  57. package/dist/services/qa/bdd-test-style-contract.d.ts +17 -0
  58. package/dist/services/qa/bdd-test-style-contract.js +41 -0
  59. package/dist/services/qa/bdd-test-style-verifier.d.ts +9 -6
  60. package/dist/services/qa/bdd-test-style-verifier.js +24 -37
  61. package/dist/services/rd/reviewer-dispatch-policy.d.ts +18 -14
  62. package/dist/services/rd/reviewer-dispatch-policy.js +14 -11
  63. package/dist/services/release/release-state.js +20 -5
  64. package/dist/services/reviewer/model-family.js +1 -1
  65. package/dist/services/reviewer/reviewer-artifacts.d.ts +12 -0
  66. package/dist/services/reviewer/reviewer-artifacts.js +67 -0
  67. package/dist/services/reviewer/reviewer-config-write.d.ts +18 -0
  68. package/dist/services/reviewer/reviewer-config-write.js +71 -0
  69. package/dist/services/reviewer/reviewer-config.d.ts +33 -5
  70. package/dist/services/reviewer/reviewer-config.js +102 -46
  71. package/dist/services/reviewer/reviewer-envelopes.d.ts +8 -0
  72. package/dist/services/reviewer/reviewer-envelopes.js +53 -0
  73. package/dist/services/reviewer/reviewer-service.d.ts +7 -4
  74. package/dist/services/reviewer/reviewer-service.js +46 -52
  75. package/dist/services/reviewer/reviewer-types.d.ts +9 -1
  76. package/dist/services/session/getSessionDir.js +16 -7
  77. package/dist/services/web/daemon-registry.d.ts +6 -4
  78. package/dist/services/web/daemon-registry.js +92 -17
  79. package/dist/services/workflow/pipeline-verify-gate-support.d.ts +4 -1
  80. package/dist/services/workflow/pipeline-verify-gate-support.js +8 -79
  81. package/dist/services/workflow/pipeline-verify-rd-phase.d.ts +67 -0
  82. package/dist/services/workflow/pipeline-verify-rd-phase.js +122 -0
  83. package/dist/services/workflow/pipeline-verify-service.js +16 -17
  84. package/dist/services/workspace/workspace-service.js +4 -16
  85. package/package.json +5 -5
  86. package/schemas/doctor-report.schema.json +2 -2
  87. package/schemas/reviewer-envelope.schema.json +1 -1
  88. package/skills/bee/peaks-reviewer/SKILL.md +20 -4
  89. package/skills/bee/peaks-reviewer/references/reviewer-schema.md +12 -7
  90. package/skills/bee/peaks-security-audit/SKILL.md +20 -0
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Check: canonical-store vs IDE skill-tree parity
3
+ * (`skills:reference-parity:<ide>:<skill>`).
4
+ *
5
+ * The reported host shape: `~/.peaks/skills/peaks-code/references/fast-lane-norm.md`
6
+ * exists while `~/.claude/skills/peaks-code/references/fast-lane-norm.md` does
7
+ * not. `peaks skill sync` closes that gap, but nothing named it first, so the
8
+ * missing reference surfaced only when a skill's prose cited it.
9
+ *
10
+ * Read-only: the check lists both trees and reports the difference. It never
11
+ * repairs, rewrites, or deletes. A mismatch is a warning — a skill missing one
12
+ * reference still runs — and the message names the LLM-run repair.
13
+ *
14
+ * The canonical store is the anchor: only skills present under
15
+ * `<PEAKS_HOME or ~/.peaks>/skills` are compared, so a user-authored skill that
16
+ * exists only in an IDE root is not reported as drift.
17
+ *
18
+ * Symlinks are followed (`statSync`, not `lstatSync`), so the common junction
19
+ * install compares equal; a real copy whose file set drifted is the case this
20
+ * check exists for. Each directory is visited once by resolved path, so a
21
+ * junction cycle cannot invent phantom paths.
22
+ */
23
+ import type { DoctorCheck, DoctorCheckPlugin } from '../types.js';
24
+ /**
25
+ * Pure comparator. `canonicalRoot` is the canonical skills store
26
+ * (`<PEAKS_HOME or ~/.peaks>/skills`); `ideRoots` are the IDE-side skills
27
+ * directories to compare against it. Roots that do not exist are skipped, so
28
+ * the wrapper may pass every adapter that declares `skillInstall`.
29
+ *
30
+ * Identical trees emit no check at all: the absence of a parity finding is the
31
+ * pass, which keeps the doctor report exactly as long as its findings. A store
32
+ * that exists but cannot be read is a warning, never silence.
33
+ */
34
+ export declare function compareSkillReferenceParity(canonicalRoot: string, ideRoots: ReadonlyArray<{
35
+ ide: string;
36
+ skillsDir: string;
37
+ }>): DoctorCheck[];
38
+ export declare const check: DoctorCheckPlugin;
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Check: canonical-store vs IDE skill-tree parity
3
+ * (`skills:reference-parity:<ide>:<skill>`).
4
+ *
5
+ * The reported host shape: `~/.peaks/skills/peaks-code/references/fast-lane-norm.md`
6
+ * exists while `~/.claude/skills/peaks-code/references/fast-lane-norm.md` does
7
+ * not. `peaks skill sync` closes that gap, but nothing named it first, so the
8
+ * missing reference surfaced only when a skill's prose cited it.
9
+ *
10
+ * Read-only: the check lists both trees and reports the difference. It never
11
+ * repairs, rewrites, or deletes. A mismatch is a warning — a skill missing one
12
+ * reference still runs — and the message names the LLM-run repair.
13
+ *
14
+ * The canonical store is the anchor: only skills present under
15
+ * `<PEAKS_HOME or ~/.peaks>/skills` are compared, so a user-authored skill that
16
+ * exists only in an IDE root is not reported as drift.
17
+ *
18
+ * Symlinks are followed (`statSync`, not `lstatSync`), so the common junction
19
+ * install compares equal; a real copy whose file set drifted is the case this
20
+ * check exists for. Each directory is visited once by resolved path, so a
21
+ * junction cycle cannot invent phantom paths.
22
+ */
23
+ import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs';
24
+ import { homedir } from 'node:os';
25
+ import { join } from 'node:path';
26
+ import { getAdapter, listAdapterIds } from '../../../ide/ide-registry.js';
27
+ const MANAGED_MARKER_SUFFIX = '.peaks-managed';
28
+ /** Atomic-write scratch names the canonical store leaves behind; never assets. */
29
+ const TEMP_ENTRY_PREFIX = '.peaks-tmp-';
30
+ /** Secondary bound: a legitimate skill tree is shallow. */
31
+ const MAX_DEPTH = 24;
32
+ /** How many paths the message names per side, so a large drift stays readable. */
33
+ const REPORT_LIMIT = 3;
34
+ const REPAIR_HINT = 'Ask the LLM to run `peaks skill sync`';
35
+ function listRelativeFiles(root) {
36
+ const walk = { root, into: new Set(), visited: new Set() };
37
+ collectFiles(walk, '', 0);
38
+ return walk.into;
39
+ }
40
+ function collectFiles(walk, prefix, depth) {
41
+ if (depth > MAX_DEPTH)
42
+ return;
43
+ const directory = prefix === '' ? walk.root : join(walk.root, prefix);
44
+ let identity;
45
+ try {
46
+ identity = realpathSync(directory);
47
+ }
48
+ catch {
49
+ // An unreadable directory contributes no comparable files.
50
+ return;
51
+ }
52
+ if (walk.visited.has(identity))
53
+ return;
54
+ walk.visited.add(identity);
55
+ for (const name of readEntryNames(directory).sort()) {
56
+ if (isIgnoredEntryName(name))
57
+ continue;
58
+ const relativePath = prefix === '' ? name : `${prefix}/${name}`;
59
+ const kind = entryKind(join(walk.root, relativePath));
60
+ if (kind === 'directory') {
61
+ collectFiles(walk, relativePath, depth + 1);
62
+ }
63
+ else if (kind === 'file') {
64
+ walk.into.add(relativePath);
65
+ }
66
+ }
67
+ }
68
+ /** Names directly under `directory`; an unreadable directory has none. */
69
+ function readEntryNames(directory) {
70
+ try {
71
+ return readdirSync(directory);
72
+ }
73
+ catch {
74
+ return [];
75
+ }
76
+ }
77
+ /** `.`/`..`, managed sidecars and scratch siblings are not skill assets. */
78
+ function isIgnoredEntryName(name) {
79
+ return (name === '.' ||
80
+ name === '..' ||
81
+ name.endsWith(MANAGED_MARKER_SUFFIX) ||
82
+ name.startsWith(TEMP_ENTRY_PREFIX));
83
+ }
84
+ /** What `absolutePath` is, following symlinks; an unreadable entry is `other`. */
85
+ function entryKind(absolutePath) {
86
+ try {
87
+ const stats = statSync(absolutePath);
88
+ if (stats.isDirectory())
89
+ return 'directory';
90
+ return stats.isFile() ? 'file' : 'other';
91
+ }
92
+ catch {
93
+ // A dangling link or an unreadable entry is not a comparable file.
94
+ return 'other';
95
+ }
96
+ }
97
+ /** Skill names under `root` (directories only, symlinks followed). */
98
+ function listSkillNames(root) {
99
+ const skills = [];
100
+ for (const name of readEntryNames(root).sort()) {
101
+ if (isIgnoredEntryName(name))
102
+ continue;
103
+ if (entryKind(join(root, name)) === 'directory')
104
+ skills.push(name);
105
+ }
106
+ return skills;
107
+ }
108
+ /**
109
+ * Why the canonical store cannot be compared, or null when it is a readable
110
+ * directory. An absent path is handled separately (a fresh host is not a
111
+ * finding); an existing but unusable path is, because it would otherwise look
112
+ * exactly like "no drift".
113
+ */
114
+ function storeProblem(canonicalRoot) {
115
+ let kind;
116
+ try {
117
+ const stats = statSync(canonicalRoot);
118
+ kind = stats.isDirectory() ? 'directory' : stats.isFile() ? 'file' : 'other';
119
+ }
120
+ catch {
121
+ return 'cannot be read';
122
+ }
123
+ if (kind !== 'directory')
124
+ return 'is not a directory';
125
+ try {
126
+ readdirSync(canonicalRoot);
127
+ }
128
+ catch {
129
+ return 'is not readable';
130
+ }
131
+ return null;
132
+ }
133
+ function diffSkillTrees(ide, skill, canonicalFiles, ideFiles) {
134
+ const missing = [...canonicalFiles].filter((path) => !ideFiles.has(path)).sort();
135
+ const extra = [...ideFiles].filter((path) => !canonicalFiles.has(path)).sort();
136
+ if (missing.length === 0 && extra.length === 0)
137
+ return null;
138
+ return { ide, skill, missing, extra };
139
+ }
140
+ function summarize(paths) {
141
+ const shown = paths.slice(0, REPORT_LIMIT).join(', ');
142
+ const rest = paths.length - REPORT_LIMIT;
143
+ return rest > 0 ? `${shown} and ${rest} more` : shown;
144
+ }
145
+ /**
146
+ * Keep a filesystem-derived name inside the check-id schema's id alphabet.
147
+ * The message keeps the real name; only the id is normalised, because the
148
+ * doctor's own `doctor-self:check-id-pattern` check fails the report on an id
149
+ * the schema cannot match.
150
+ */
151
+ function toIdSegment(value) {
152
+ const cleaned = value.replace(/[^A-Za-z0-9._-]/g, '-');
153
+ return /^[A-Za-z0-9]/.test(cleaned) ? cleaned : `s-${cleaned}`;
154
+ }
155
+ function toCheck(issue, canonicalRoot) {
156
+ const parts = [
157
+ `Skill ${issue.skill} under IDE ${issue.ide} diverges from the canonical store at ${canonicalRoot}`
158
+ ];
159
+ if (issue.missing.length > 0)
160
+ parts.push(`missing: ${summarize(issue.missing)}`);
161
+ if (issue.extra.length > 0)
162
+ parts.push(`extra: ${summarize(issue.extra)}`);
163
+ return {
164
+ id: `skills:reference-parity:${toIdSegment(issue.ide)}:${toIdSegment(issue.skill)}`,
165
+ ok: false,
166
+ severity: 'warning',
167
+ message: `${parts.join('; ')}. ${REPAIR_HINT}.`
168
+ };
169
+ }
170
+ /**
171
+ * Pure comparator. `canonicalRoot` is the canonical skills store
172
+ * (`<PEAKS_HOME or ~/.peaks>/skills`); `ideRoots` are the IDE-side skills
173
+ * directories to compare against it. Roots that do not exist are skipped, so
174
+ * the wrapper may pass every adapter that declares `skillInstall`.
175
+ *
176
+ * Identical trees emit no check at all: the absence of a parity finding is the
177
+ * pass, which keeps the doctor report exactly as long as its findings. A store
178
+ * that exists but cannot be read is a warning, never silence.
179
+ */
180
+ export function compareSkillReferenceParity(canonicalRoot, ideRoots) {
181
+ if (!existsSync(canonicalRoot)) {
182
+ return [
183
+ {
184
+ id: 'skills:reference-parity:store',
185
+ ok: true,
186
+ message: `Canonical skill store not found at ${canonicalRoot}; nothing to compare`
187
+ }
188
+ ];
189
+ }
190
+ const problem = storeProblem(canonicalRoot);
191
+ if (problem !== null) {
192
+ return [
193
+ {
194
+ id: 'skills:reference-parity:store',
195
+ ok: false,
196
+ severity: 'warning',
197
+ message: `Canonical skill store at ${canonicalRoot} ${problem}; IDE skill roots were not compared`
198
+ }
199
+ ];
200
+ }
201
+ const canonicalSkills = new Map();
202
+ for (const skill of listSkillNames(canonicalRoot)) {
203
+ canonicalSkills.set(skill, listRelativeFiles(join(canonicalRoot, skill)));
204
+ }
205
+ const checks = [];
206
+ for (const { ide, skillsDir } of ideRoots) {
207
+ if (!existsSync(skillsDir))
208
+ continue;
209
+ for (const skill of [...canonicalSkills.keys()].sort()) {
210
+ const issue = diffSkillTrees(ide, skill, canonicalSkills.get(skill) ?? new Set(), listRelativeFiles(join(skillsDir, skill)));
211
+ if (issue !== null)
212
+ checks.push(toCheck(issue, canonicalRoot));
213
+ }
214
+ }
215
+ return checks;
216
+ }
217
+ function canonicalSkillsStore() {
218
+ const home = process.env.PEAKS_HOME?.trim();
219
+ const root = home !== undefined && home.length > 0 ? home : join(homedir(), '.peaks');
220
+ return join(root, 'skills');
221
+ }
222
+ /** IDE skills dirs from the adapter registry, existing roots only. */
223
+ function existingIdeSkillRoots() {
224
+ const roots = [];
225
+ for (const ide of listAdapterIds()) {
226
+ const skillsDir = getAdapter(ide).skillInstall?.skillsDir;
227
+ if (skillsDir === undefined || !existsSync(skillsDir))
228
+ continue;
229
+ roots.push({ ide, skillsDir });
230
+ }
231
+ return roots;
232
+ }
233
+ function run(context) {
234
+ const injected = context.options.skillParity;
235
+ if (injected !== undefined) {
236
+ return compareSkillReferenceParity(injected.canonicalRoot, injected.ideRoots);
237
+ }
238
+ return compareSkillReferenceParity(canonicalSkillsStore(), existingIdeSkillRoots());
239
+ }
240
+ export const check = {
241
+ name: 'skill-reference-parity',
242
+ run
243
+ };
@@ -34,6 +34,7 @@ import { check as skillNameMatch } from './checks/skill-name-match.js';
34
34
  import { check as skillParse } from './checks/skill-parse.js';
35
35
  import { check as skillRunbook } from './checks/skill-runbook.js';
36
36
  import { check as skillApplyNote } from './checks/skill-apply-note.js';
37
+ import { check as skillReferenceParity } from './checks/skill-reference-parity.js';
37
38
  import { check as schemaValidity } from './checks/schema-validity.js';
38
39
  import { check as userConfig } from './checks/user-config.js';
39
40
  import { check as skillPresence } from './checks/skill-presence.js';
@@ -49,6 +50,7 @@ import { check as workspaceLayout } from './checks/workspace-layout.js';
49
50
  import { check as gateguardConflict } from './checks/gateguard-conflict.js';
50
51
  import { check as eccHooksSchemaDrift } from './checks/ecc-hooks-schema-drift.js';
51
52
  import { check as checkIdSchema } from './checks/check-id-schema.js';
53
+ import { check as backcompatAcceptance } from './checks/backcompat-acceptance.js';
52
54
  import { check as l3OrphanSessions } from './checks/l3-orphan-sessions.js';
53
55
  import { check as l3MemoryHealth } from './checks/l3-memory-health.js';
54
56
  /**
@@ -63,6 +65,7 @@ export const PLUGINS = [
63
65
  skillParse, // id prefix "skill-parse:"
64
66
  skillRunbook, // id prefix "skill-runbook:"
65
67
  skillApplyNote, // id prefix "skill-apply-note:"
68
+ skillReferenceParity, // ids "skills:reference-parity:<ide>:<skill>" + "skills:reference-parity:store"
66
69
  schemaValidity, // id prefix "schema:"
67
70
  userConfig, // id "config:user"
68
71
  skillPresence, // ids "skill-presence:current" + "skill-presence:freshness"
@@ -77,6 +80,7 @@ export const PLUGINS = [
77
80
  workspaceLayout, // id "build:workspace-layout-canonical"
78
81
  gateguardConflict, // id "integration:gateguard-peaks-conflict"
79
82
  eccHooksSchemaDrift, // id "integration:ecc-hooks-schema-drift"
83
+ backcompatAcceptance, // id "config:backcompat-acceptance"
80
84
  checkIdSchema, // id "doctor-self:check-id-pattern"
81
85
  l3OrphanSessions, // id "L3:l3-orphan-sessions"
82
86
  l3MemoryHealth // id "L3:l3-memory-health"
@@ -108,6 +108,18 @@ export type DoctorOptions = {
108
108
  gateguardProbe?: GateguardProbe;
109
109
  /** Injected for the integration:ecc-hooks-schema-drift check (defaults to defaultEccHooksDriftProbe on disk). */
110
110
  eccHooksDriftProbe?: EccHooksDriftProbe;
111
+ /**
112
+ * Injected roots for the `skills:reference-parity` check. When omitted the
113
+ * check binds `$PEAKS_HOME`/`~/.peaks` and the adapter registry. Tests pass
114
+ * temp directories here, so no test reads the real home directory.
115
+ */
116
+ skillParity?: {
117
+ canonicalRoot: string;
118
+ ideRoots: ReadonlyArray<{
119
+ ide: string;
120
+ skillsDir: string;
121
+ }>;
122
+ };
111
123
  /**
112
124
  * root for the L3:l3-memory-health check (defaults to
113
125
  * `findProjectRoot(process.cwd())`). Tests use this to point the
@@ -25,11 +25,24 @@ export declare class SubAgentJobWrapper {
25
25
  constructor(store: JobStateStore, dispatch: DispatchFn);
26
26
  wrap(input: WrapInput): Promise<WrapOutput>;
27
27
  canCheckpointDone(jobId: string, batchId: string): boolean;
28
- cleanup(input: {
29
- jobId: string;
30
- batchId: string;
31
- force: boolean;
32
- }): Promise<{
33
- cleaned: boolean;
34
- }>;
28
+ cleanup(input: CleanupInput): Promise<CleanupResult>;
29
+ }
30
+ export interface CleanupInput {
31
+ jobId: string;
32
+ batchId: string;
33
+ force: boolean;
34
+ /**
35
+ * On-disk ledger context, supplied by the CLI. Omitted by same-process
36
+ * callers, which keep the in-memory map above as their pending set.
37
+ */
38
+ projectRoot?: string;
39
+ sessionId?: string;
40
+ }
41
+ export interface CleanupResult {
42
+ cleaned: boolean;
43
+ cleanedRecords: string[];
44
+ skipped: {
45
+ recordPath: string;
46
+ reason: string;
47
+ }[];
35
48
  }
@@ -1,3 +1,6 @@
1
+ import { getErrorMessage } from 'peaks-loop-shared/result';
2
+ import { readActiveDispatchIndex } from '../dispatch/active-dispatch-index.js';
3
+ import { markCompleted } from '../dispatch/dispatch-record-writer.js';
1
4
  export class SubAgentJobWrapper {
2
5
  store;
3
6
  dispatch;
@@ -25,10 +28,55 @@ export class SubAgentJobWrapper {
25
28
  return !set?.has(batchId);
26
29
  }
27
30
  async cleanup(input) {
28
- const set = this.dispatchedBatches.get(input.jobId);
29
- if (!set?.has(input.batchId))
30
- return { cleaned: true };
31
- set.delete(input.batchId);
32
- return { cleaned: true };
31
+ this.dispatchedBatches.get(input.jobId)?.delete(input.batchId);
32
+ if (input.projectRoot === undefined || input.sessionId === undefined) {
33
+ return { cleaned: true, cleanedRecords: [], skipped: [] };
34
+ }
35
+ return cleanLedgerBatch({
36
+ projectRoot: input.projectRoot,
37
+ sessionId: input.sessionId,
38
+ batchId: input.batchId,
39
+ force: input.force
40
+ });
41
+ }
42
+ }
43
+ /**
44
+ * Clean a batch by its rows in `.peaks/_sub_agents/<sessionId>/active-dispatches.json`
45
+ * — the ledger the dispatching process wrote, not a set a fresh CLI process
46
+ * cannot have populated.
47
+ *
48
+ * A row is finalized (`status: 'done'` on the record, row removed from the
49
+ * index) when it is `queued`, the same rows `sub-agent finalize --batch` acts
50
+ * on. `--force` extends that to rows in any other status. An absent batch
51
+ * cleans nothing and reports `cleaned: false`: "nothing to clean" must not
52
+ * read as "cleaned it".
53
+ */
54
+ function cleanLedgerBatch(input) {
55
+ const result = { cleaned: false, cleanedRecords: [], skipped: [] };
56
+ const rows = Object.values(readActiveDispatchIndex(input.projectRoot, input.sessionId));
57
+ for (const entry of rows) {
58
+ if (entry.batchId !== input.batchId)
59
+ continue;
60
+ if (entry.status !== 'queued' && !input.force) {
61
+ result.skipped.push({
62
+ recordPath: entry.recordPath,
63
+ reason: `status is ${entry.status}; pass --force to clean it anyway`
64
+ });
65
+ continue;
66
+ }
67
+ try {
68
+ markCompleted({
69
+ recordPath: entry.recordPath,
70
+ projectRoot: input.projectRoot,
71
+ status: 'done',
72
+ outcome: 'success'
73
+ });
74
+ result.cleanedRecords.push(entry.recordPath);
75
+ }
76
+ catch (error) {
77
+ result.skipped.push({ recordPath: entry.recordPath, reason: getErrorMessage(error) });
78
+ }
33
79
  }
80
+ result.cleaned = result.cleanedRecords.length > 0;
81
+ return result;
34
82
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * eslint JSON report → findings + the population they were found in
3
+ * (backlog §2.41). Split out of `eslint-runner-support.ts` for the 300-raw-line
4
+ * cap; `eslint-runner.ts` is the only caller.
5
+ */
6
+ import type { EslintFinding } from './eslint-runner-types.js';
7
+ export type ParsedReport = {
8
+ readonly findings: EslintFinding[];
9
+ /** Files eslint actually examined — the population behind the findings. */
10
+ readonly checkedFiles: number;
11
+ /** Entries eslint skipped instead of examining. */
12
+ readonly ignoredFiles: number;
13
+ };
14
+ /**
15
+ * Counting a skipped entry's "File ignored" warning as a finding is what made
16
+ * an empty run read as a populated one. Throws on unparseable stdout; the
17
+ * caller reports that as `execution-failed`.
18
+ */
19
+ export declare function parseEslintReport(stdout: string): ParsedReport;
@@ -0,0 +1,60 @@
1
+ import { isIgnoredMessage, severityFor } from './eslint-runner-support.js';
2
+ function messagesOf(entry) {
3
+ return Array.isArray(entry.messages)
4
+ ? entry.messages
5
+ : [];
6
+ }
7
+ function parentFileOf(entry) {
8
+ return typeof entry.filePath === 'string'
9
+ ? entry.filePath
10
+ : '';
11
+ }
12
+ /** A skipped entry carries no lint result at all — it is not a finding. */
13
+ function isIgnoredEntry(messages) {
14
+ return messages.some((m) => m !== null &&
15
+ typeof m === 'object' &&
16
+ typeof m.message === 'string' &&
17
+ isIgnoredMessage(m.message));
18
+ }
19
+ function toFinding(m, parentFile) {
20
+ if (m === null || typeof m !== 'object')
21
+ return null;
22
+ return {
23
+ filePath: typeof m.filePath === 'string' && m.filePath.length > 0 ? m.filePath : parentFile,
24
+ line: typeof m.line === 'number' ? m.line : 0,
25
+ column: typeof m.column === 'number' ? m.column : 0,
26
+ ruleId: typeof m.ruleId === 'string' ? m.ruleId : null,
27
+ severity: severityFor(m.severity),
28
+ message: typeof m.message === 'string' ? m.message : ''
29
+ };
30
+ }
31
+ /**
32
+ * Counting a skipped entry's "File ignored" warning as a finding is what made
33
+ * an empty run read as a populated one. Throws on unparseable stdout; the
34
+ * caller reports that as `execution-failed`.
35
+ */
36
+ export function parseEslintReport(stdout) {
37
+ const findings = [];
38
+ let checkedFiles = 0;
39
+ let ignoredFiles = 0;
40
+ if (stdout.trim().length === 0)
41
+ return { findings, checkedFiles, ignoredFiles };
42
+ const parsed = JSON.parse(stdout);
43
+ for (const entry of parsed) {
44
+ if (typeof entry !== 'object' || entry === null)
45
+ continue;
46
+ const messages = messagesOf(entry);
47
+ if (isIgnoredEntry(messages)) {
48
+ ignoredFiles += 1;
49
+ continue;
50
+ }
51
+ checkedFiles += 1;
52
+ const parentFile = parentFileOf(entry);
53
+ for (const m of messages) {
54
+ const finding = toFinding(m, parentFile);
55
+ if (finding !== null)
56
+ findings.push(finding);
57
+ }
58
+ }
59
+ return { findings, checkedFiles, ignoredFiles };
60
+ }
@@ -17,6 +17,23 @@ export declare function matchBaseline(finding: EslintFinding, baseline: readonly
17
17
  export declare function aggregateRedLine(baseline: readonly BaselineViolation[]): readonly RedLineEntry[];
18
18
  export declare const EMPTY_DIFF_RANGE: readonly DiffRange[];
19
19
  export declare const EMPTY_REDLINE: readonly RedLineEntry[];
20
- export declare function emptyResult(state: EslintState, start: number, rawOutput: string, reason?: string): EslintRunResult;
20
+ /**
21
+ * eslint skips dot-paths by default (backlog §2.41): a hand-run over
22
+ * `.husky/*.mjs` answers "File ignored by default" and exits 0, so a run that
23
+ * examined nothing is indistinguishable from a clean one. Any path SEGMENT
24
+ * starting with a dot (but not the `.`/`..` navigational segments) makes the
25
+ * requested scope one eslint will not look at unaided.
26
+ */
27
+ export declare function isDotPathScope(scope: string | undefined): boolean;
28
+ /** A message eslint emits for an entry it skipped instead of examining. */
29
+ export declare function isIgnoredMessage(message: string): boolean;
30
+ /** The §2.41 refusal text for an examined population of 0. */
31
+ export declare function emptyPopulationReason(scope: string | undefined, ignoredFiles: number): string;
32
+ export type EmptyDetail = {
33
+ readonly reason?: string;
34
+ readonly checkedFiles?: number;
35
+ readonly ignoredFiles?: number;
36
+ };
37
+ export declare function emptyResult(state: EslintState, start: number, rawOutput: string, detail?: EmptyDetail): EslintRunResult;
21
38
  export declare function buildEslintArgs(options: EslintRunOptions): string[];
22
39
  export type { DiffRange };
@@ -150,14 +150,42 @@ export function aggregateRedLine(baseline) {
150
150
  }
151
151
  export const EMPTY_DIFF_RANGE = [];
152
152
  export const EMPTY_REDLINE = [];
153
- export function emptyResult(state, start, rawOutput, reason) {
153
+ /**
154
+ * eslint skips dot-paths by default (backlog §2.41): a hand-run over
155
+ * `.husky/*.mjs` answers "File ignored by default" and exits 0, so a run that
156
+ * examined nothing is indistinguishable from a clean one. Any path SEGMENT
157
+ * starting with a dot (but not the `.`/`..` navigational segments) makes the
158
+ * requested scope one eslint will not look at unaided.
159
+ */
160
+ export function isDotPathScope(scope) {
161
+ if (scope === undefined || scope.length === 0)
162
+ return false;
163
+ return scope
164
+ .split(/[\\/]/)
165
+ .some((segment) => segment.length > 1 && segment.startsWith('.') && segment !== '..');
166
+ }
167
+ /** A message eslint emits for an entry it skipped instead of examining. */
168
+ export function isIgnoredMessage(message) {
169
+ return /^File ignored/.test(message);
170
+ }
171
+ /** The §2.41 refusal text for an examined population of 0. */
172
+ export function emptyPopulationReason(scope, ignoredFiles) {
173
+ const populationNote = ignoredFiles > 0
174
+ ? ` ${ignoredFiles} path(s) were skipped as ignored (eslint ignores dot-directories by default).`
175
+ : '';
176
+ return (`the requested scope "${scope ?? '.'}" examined 0 files; a finding count over an empty population ` +
177
+ `cannot be told apart from a clean run.${populationNote} Pass --allow-empty to accept an empty population.`);
178
+ }
179
+ export function emptyResult(state, start, rawOutput, detail = {}) {
154
180
  return {
155
181
  state,
156
182
  findings: [],
157
183
  summary: { error: 0, warn: 0, info: 0 },
158
184
  durationMs: Date.now() - start,
159
185
  rawOutput,
160
- ...(reason === undefined ? {} : { reason }),
186
+ checkedFiles: detail.checkedFiles ?? 0,
187
+ ignoredFiles: detail.ignoredFiles ?? 0,
188
+ ...(detail.reason === undefined ? {} : { reason: detail.reason }),
161
189
  baselineWaived: [],
162
190
  redLine: EMPTY_REDLINE
163
191
  };
@@ -181,6 +209,11 @@ export function buildEslintArgs(options) {
181
209
  // `options.configPath`.
182
210
  const effectiveConfigPath = options.configPath ?? join('config', 'eslint', '.peaks-rules.cjs');
183
211
  args.push('--config', effectiveConfigPath);
212
+ // A dot-path scope is invisible to eslint's default ignore rules (§2.41).
213
+ // `--no-ignore` is only sound here because the caller named the scope
214
+ // explicitly; the default scope (`.`) never takes this branch.
215
+ if (isDotPathScope(options.scope))
216
+ args.push('--no-ignore');
184
217
  args.push(...(options.scope !== undefined && options.scope.length > 0 ? [options.scope] : ['.']));
185
218
  return args;
186
219
  }
@@ -10,7 +10,13 @@ export declare const ESLINT_PACKAGE_PINS: {
10
10
  readonly typescriptEslintPlugin: "8.66.0";
11
11
  };
12
12
  export type RedLineMode = 'none' | 'baseline-aware';
13
- export type EslintState = 'ok' | 'eslint-missing' | 'npx-failed' | 'execution-failed' | 'baseline-missing';
13
+ export type EslintState = 'ok' | 'eslint-missing' | 'npx-failed' | 'execution-failed' | 'baseline-missing'
14
+ /**
15
+ * eslint ran and examined ZERO files. A count of findings over an empty
16
+ * population cannot be told apart from a clean run, so it is refused unless
17
+ * the caller opts in with `allowEmpty` (backlog §2.41).
18
+ */
19
+ | 'empty-scope';
14
20
  export type EslintFinding = {
15
21
  readonly filePath: string;
16
22
  readonly line: number;
@@ -45,6 +51,15 @@ export type EslintRunResult = {
45
51
  readonly summary: EslintSummary;
46
52
  readonly durationMs: number;
47
53
  readonly rawOutput: string;
54
+ /**
55
+ * Files eslint actually examined (backlog §2.41). A finding count is only
56
+ * meaningful next to the population that produced it: "0 findings" over 0
57
+ * files is indistinguishable from "0 findings" over 2000. Entries eslint
58
+ * skipped ("File ignored …") do not count; they are reported separately.
59
+ */
60
+ readonly checkedFiles: number;
61
+ /** Entries eslint skipped, e.g. a dot-path without `--no-ignore`. */
62
+ readonly ignoredFiles: number;
48
63
  /**
49
64
  * Why a non-`ok` state was reached. Four different conditions — an
50
65
  * unbuildable argument list, a spawn failure, a signal kill (which is how a
@@ -66,6 +81,11 @@ export type EslintRunOptions = {
66
81
  readonly diffOnly?: boolean;
67
82
  readonly baselineFile?: string;
68
83
  readonly redLineMode?: RedLineMode;
84
+ /**
85
+ * Accept an examined population of 0 instead of refusing it. The explicit
86
+ * opt-in §2.41 requires; without it `runEslint` returns `empty-scope`.
87
+ */
88
+ readonly allowEmpty?: boolean;
69
89
  };
70
90
  export type EslintMessage = {
71
91
  filePath?: unknown;