@dzhechkov/harness-core 0.3.149 → 0.4.1

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 (107) hide show
  1. package/.dz-manifest.json +399 -55
  2. package/README.md +80 -3
  3. package/dist/agentdb-index.d.ts.map +1 -1
  4. package/dist/agentdb-index.js +10 -2
  5. package/dist/agentdb-index.js.map +1 -1
  6. package/dist/backlog-embed.d.ts +94 -0
  7. package/dist/backlog-embed.d.ts.map +1 -0
  8. package/dist/backlog-embed.js +138 -0
  9. package/dist/backlog-embed.js.map +1 -0
  10. package/dist/backlog.d.ts +180 -7
  11. package/dist/backlog.d.ts.map +1 -1
  12. package/dist/backlog.js +429 -26
  13. package/dist/backlog.js.map +1 -1
  14. package/dist/challenge-panel.d.ts +3 -0
  15. package/dist/challenge-panel.d.ts.map +1 -1
  16. package/dist/challenge-panel.js +3 -0
  17. package/dist/challenge-panel.js.map +1 -1
  18. package/dist/export-holdout.d.ts +149 -0
  19. package/dist/export-holdout.d.ts.map +1 -0
  20. package/dist/export-holdout.js +198 -0
  21. package/dist/export-holdout.js.map +1 -0
  22. package/dist/feature-adr-checkpoints.d.ts +82 -0
  23. package/dist/feature-adr-checkpoints.d.ts.map +1 -1
  24. package/dist/feature-adr-checkpoints.js +138 -1
  25. package/dist/feature-adr-checkpoints.js.map +1 -1
  26. package/dist/feature-adr-routing.d.ts +3 -0
  27. package/dist/feature-adr-routing.d.ts.map +1 -1
  28. package/dist/feature-adr-routing.js +3 -0
  29. package/dist/feature-adr-routing.js.map +1 -1
  30. package/dist/guard.d.ts +42 -0
  31. package/dist/guard.d.ts.map +1 -1
  32. package/dist/guard.js +73 -1
  33. package/dist/guard.js.map +1 -1
  34. package/dist/index.d.ts +17 -2
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +28 -1
  37. package/dist/index.js.map +1 -1
  38. package/dist/loop-blobs.generated.d.ts +33 -0
  39. package/dist/loop-blobs.generated.d.ts.map +1 -0
  40. package/dist/loop-blobs.generated.js +101 -0
  41. package/dist/loop-blobs.generated.js.map +1 -0
  42. package/dist/loop-lint.d.ts +63 -0
  43. package/dist/loop-lint.d.ts.map +1 -0
  44. package/dist/loop-lint.js +606 -0
  45. package/dist/loop-lint.js.map +1 -0
  46. package/dist/loop-plan.d.ts +416 -0
  47. package/dist/loop-plan.d.ts.map +1 -0
  48. package/dist/loop-plan.js +1151 -0
  49. package/dist/loop-plan.js.map +1 -0
  50. package/dist/loop-render.d.ts +104 -0
  51. package/dist/loop-render.d.ts.map +1 -0
  52. package/dist/loop-render.js +989 -0
  53. package/dist/loop-render.js.map +1 -0
  54. package/dist/loop-trace.d.ts +204 -0
  55. package/dist/loop-trace.d.ts.map +1 -0
  56. package/dist/loop-trace.js +550 -0
  57. package/dist/loop-trace.js.map +1 -0
  58. package/dist/mutation-gate.d.ts +247 -0
  59. package/dist/mutation-gate.d.ts.map +1 -0
  60. package/dist/mutation-gate.js +535 -0
  61. package/dist/mutation-gate.js.map +1 -0
  62. package/dist/no-stubs.d.ts +53 -0
  63. package/dist/no-stubs.d.ts.map +1 -0
  64. package/dist/no-stubs.js +190 -0
  65. package/dist/no-stubs.js.map +1 -0
  66. package/dist/package-skill-layouts.d.ts +67 -0
  67. package/dist/package-skill-layouts.d.ts.map +1 -0
  68. package/dist/package-skill-layouts.js +81 -0
  69. package/dist/package-skill-layouts.js.map +1 -0
  70. package/dist/patterns.d.ts.map +1 -1
  71. package/dist/patterns.js +156 -75
  72. package/dist/patterns.js.map +1 -1
  73. package/dist/recall-domain-boost.d.ts +96 -0
  74. package/dist/recall-domain-boost.d.ts.map +1 -0
  75. package/dist/recall-domain-boost.js +158 -0
  76. package/dist/recall-domain-boost.js.map +1 -0
  77. package/dist/store-lock.d.ts +108 -0
  78. package/dist/store-lock.d.ts.map +1 -0
  79. package/dist/store-lock.js +231 -0
  80. package/dist/store-lock.js.map +1 -0
  81. package/dist/workflows.d.ts +16 -22
  82. package/dist/workflows.d.ts.map +1 -1
  83. package/dist/workflows.js +17 -98
  84. package/dist/workflows.js.map +1 -1
  85. package/package.json +7 -5
  86. package/sbom.json +1062 -202
  87. package/src/agentdb-index.ts +10 -1
  88. package/src/backlog-embed.ts +156 -0
  89. package/src/backlog.ts +536 -28
  90. package/src/challenge-panel.ts +4 -0
  91. package/src/export-holdout.ts +235 -0
  92. package/src/feature-adr-checkpoints.ts +192 -1
  93. package/src/feature-adr-routing.ts +4 -0
  94. package/src/guard.ts +106 -1
  95. package/src/index.ts +72 -1
  96. package/src/loop-blobs.generated.ts +114 -0
  97. package/src/loop-lint.ts +643 -0
  98. package/src/loop-plan.ts +1419 -0
  99. package/src/loop-render.ts +1050 -0
  100. package/src/loop-trace.ts +650 -0
  101. package/src/mutation-gate.ts +701 -0
  102. package/src/no-stubs.ts +204 -0
  103. package/src/package-skill-layouts.ts +107 -0
  104. package/src/patterns.ts +135 -60
  105. package/src/recall-domain-boost.ts +178 -0
  106. package/src/store-lock.ts +258 -0
  107. package/src/workflows.ts +18 -117
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Domain-aware recall re-ranking — the pure half of `dz recall --domain <name>`.
3
+ *
4
+ * WHY THIS EXISTS. `dz teach --domain <name>` has always recorded a domain, and
5
+ * `dz recall --all --stats` prints the per-domain histogram — but the RANKING path
6
+ * (`recallHybrid`: lexical FTS5 + optional vector leg merged by RRF) never looked at
7
+ * the field. So a store shared by different KINDS of work returns them interleaved:
8
+ * medical-research lessons dilute a coding recall and vice versa, and the dilution
9
+ * gets worse as either side grows.
10
+ *
11
+ * WHY A BOOST AND NOT A FILTER. Cross-pollination here is real, not theoretical:
12
+ * "a reviewer's evidence needs the same execute-don't-describe discipline as your
13
+ * own claims" was learned reviewing code and applies verbatim to medical sources;
14
+ * the medical report's core insight ("was the source ever opened?") is the same
15
+ * principle as our claim-check. A hard filter would cut exactly the transfers that
16
+ * make one store worth more than two. So: matching-domain hits move UP, foreign
17
+ * ones stay in the list.
18
+ *
19
+ * THE PROMISE, NARROWLY: this reorders. It NEVER drops a hit, never invents one,
20
+ * and never changes how many are returned. If the boost is wrong, the cost is
21
+ * ordering; it can't hide a lesson from you.
22
+ */
23
+
24
+ import type { RecallHit } from './patterns.js';
25
+
26
+ /** How many places a same-domain lesson may climb. STATED AS POSITIONS, not as a
27
+ * score multiplier: "moves up at most two places" is a sentence a reader can check
28
+ * against the output, while "index × 0.55" is an opaque constant whose behaviour
29
+ * changes with position (it could not lift index 2 past index 1 at all, but did
30
+ * lift index 3 past index 2 — an accident, not a design). A bounded lift keeps
31
+ * lexical relevance dominant: a domain tag is a hint about relevance, not evidence
32
+ * of it, so it breaks near-ties instead of overruling the ranking. */
33
+ export const DOMAIN_LIFT_EXACT = 2;
34
+
35
+ /** A prefix/suffix relative (`health-research` against `health`) climbs less. */
36
+ export const DOMAIN_LIFT_RELATED = 1;
37
+
38
+ export type DomainMatch = 'exact' | 'related' | 'none';
39
+
40
+ /** Normalize a domain tag for comparison: case- and separator-insensitive, so
41
+ * `Health-Research`, `health_research` and `health research` are one domain. */
42
+ export function normalizeDomain(domain: string | null | undefined): string {
43
+ return String(domain ?? '')
44
+ .toLowerCase()
45
+ .replace(/[\s_]+/g, '-')
46
+ // COLLAPSE hyphen runs. `Health - Research` became `health---research`, which the
47
+ // doc comment above calls one domain with `health-research` and the code then
48
+ // treated as unrelated. Only ordering is at stake here — the export hold-out has its
49
+ // own stricter key — but a comment that describes behaviour the code lacks is the
50
+ // same defect wherever it sits.
51
+ .replace(/-{2,}/g, '-')
52
+ .replace(/^-+|-+$/g, '');
53
+ }
54
+
55
+ /** How a hit's domain relates to the requested one. `related` covers the common
56
+ * hierarchy shapes (`health` ↔ `health-research`) without a taxonomy: a taxonomy
57
+ * nobody maintains drifts, and a wrong taxonomy is worse than none. */
58
+ export function domainMatch(hitDomain: string | null | undefined, wanted: string | null | undefined): DomainMatch {
59
+ const a = normalizeDomain(hitDomain);
60
+ const b = normalizeDomain(wanted);
61
+ if (a === '' || b === '') return 'none';
62
+ if (a === b) return 'exact';
63
+ if (a.startsWith(`${b}-`) || b.startsWith(`${a}-`)) return 'related';
64
+ return 'none';
65
+ }
66
+
67
+ export interface DomainBoostResult {
68
+ readonly hits: readonly RecallHit[];
69
+ /** How many hits MATCHED the domain (exactly / relatedly). */
70
+ readonly exact: number;
71
+ readonly related: number;
72
+ /** How many hits actually CHANGED position. Counted separately because the note
73
+ * used to print the match counts as "lifted" — an exact match already at rank 0,
74
+ * or a list that is entirely one domain, matches without moving, and calling that
75
+ * "lifted" tells the reader the ranking changed when it did not. */
76
+ readonly moved: number;
77
+ /** True when NOTHING in the result matched: the caller says so out loud rather
78
+ * than implying the ranking is domain-aware when it had nothing to work with. */
79
+ readonly noMatches: boolean;
80
+ }
81
+
82
+ /**
83
+ * Re-rank hits so same-domain lessons surface first, keeping every hit.
84
+ *
85
+ * Effective position = `index - lift`. The original relevance order dominates; the
86
+ * domain only breaks near-ties, and the lift is BOUNDED so a tail match can never
87
+ * teleport to the top. Ties keep the incoming order (stable sort), so the function
88
+ * is deterministic — the same input always yields the same output, which is what
89
+ * makes it testable at all.
90
+ */
91
+ export function applyDomainBoost(hits: readonly RecallHit[], wanted: string | null | undefined): DomainBoostResult {
92
+ const target = normalizeDomain(wanted);
93
+ if (target === '' || hits.length === 0) {
94
+ return { hits, exact: 0, related: 0, moved: 0, noMatches: true };
95
+ }
96
+ let exact = 0;
97
+ let related = 0;
98
+ const scored = hits.map((hit, index) => {
99
+ const match = domainMatch(hit.pattern.domain, target);
100
+ if (match === 'exact') exact += 1;
101
+ else if (match === 'related') related += 1;
102
+ const lift = match === 'exact' ? DOMAIN_LIFT_EXACT : match === 'related' ? DOMAIN_LIFT_RELATED : 0;
103
+ return { hit, index, lift, effective: index - lift };
104
+ });
105
+ // Tie-break: at equal effective position the LIFTED hit goes first, then the
106
+ // original order. Without this the foreign hit it landed level with won the tie
107
+ // by having the lower original index, so a lift of N moved the hit only N-1
108
+ // places — the code quietly delivered less than the constant promised. A test
109
+ // asserting the documented bound caught it; the fix is here, not in the test.
110
+ scored.sort((a, b) => (a.effective - b.effective) || (b.lift - a.lift) || (a.index - b.index));
111
+ const reordered = scored.map((s) => s.hit);
112
+ let moved = 0;
113
+ scored.forEach((s, newIndex) => { if (s.index !== newIndex) moved += 1; });
114
+ return { hits: reordered, exact, related, moved, noMatches: exact === 0 && related === 0 };
115
+ }
116
+
117
+ /**
118
+ * How many hits the CUT hid that an unboosted recall would have shown.
119
+ *
120
+ * WHY THIS EXISTS. `applyDomainBoost` never drops a hit — but the CLI still cuts the
121
+ * list at `--limit`, and a promotion INTO the top N necessarily pushes something out
122
+ * of it. Cross-model review found the resulting sentence to be a lie by omission: the
123
+ * note said "foreign-domain lessons kept" while `foreign-B`, visible without
124
+ * `--domain`, had vanished from the printed output. Both statements were true of
125
+ * different lists, which is exactly how an honest tool ends up misleading its reader.
126
+ *
127
+ * The fix is not to stop promoting — that would be the filter we refused to build. It
128
+ * is to COUNT what fell past the cut and say so, because the reader can act on that
129
+ * (raise `--limit`) only if they know it happened.
130
+ *
131
+ * Compares by identity: both lists hold the same hit objects.
132
+ */
133
+ export function countDisplacedByCut(
134
+ original: readonly RecallHit[],
135
+ boosted: readonly RecallHit[],
136
+ limit: number,
137
+ ): number {
138
+ if (!Number.isFinite(limit) || limit <= 0) return 0;
139
+ const shownAfter = new Set(boosted.slice(0, limit));
140
+ let displaced = 0;
141
+ for (const hit of original.slice(0, limit)) {
142
+ if (!shownAfter.has(hit)) displaced += 1;
143
+ }
144
+ return displaced;
145
+ }
146
+
147
+ /** The line that reports the cut. Empty when nothing was displaced, so the common
148
+ * case stays quiet. */
149
+ export function renderDomainCutNote(displaced: number, limit: number): string {
150
+ if (displaced <= 0) return '';
151
+ const plural = displaced === 1 ? 'lesson' : 'lessons';
152
+ return ` ${displaced} lower-ranked ${plural} fell past the --limit ${limit} cut to make room — raise --limit to see them (the boost promotes; the cut is what hides)`;
153
+ }
154
+
155
+ /** One honest line about what the boost did — including the case where it did
156
+ * nothing, which a silent reorder would hide.
157
+ *
158
+ * The two tail phrases below are a WIRE CONTRACT: `learning_bridge.py` in the
159
+ * `goap-research-ed25519` skill detects whether the installed `dz` supports
160
+ * `--domain` by looking for them, because an older CLI ignores the flag and exits 0
161
+ * (so an exit code cannot tell the versions apart). A test pins both strings — if you
162
+ * reword them, update the bridge in the same change or you switch that loop into
163
+ * permanent degraded mode without a single test turning red. */
164
+ export function renderDomainBoostNote(result: DomainBoostResult, wanted: string): string {
165
+ if (result.noMatches) {
166
+ return ` domain "${wanted}": no lesson in this result carries it — order unchanged, nothing was hidden`;
167
+ }
168
+ const parts = [`${result.exact} exact`];
169
+ if (result.related > 0) parts.push(`${result.related} related`);
170
+ const effect = result.moved === 0
171
+ ? 'the order was already correct — nothing moved'
172
+ : `${result.moved} changed position`;
173
+ // The counts describe the CANDIDATES the boost ranked, which is a longer list than
174
+ // the one printed (the caller over-fetches, then cuts at --limit). Saying "3 changed
175
+ // position" above two printed lines reads as an arithmetic error unless the note
176
+ // names the list it is talking about — so it does.
177
+ return ` domain "${wanted}": among ${result.hits.length} candidate(s) — ${parts.join(', ')} match(es), ${effect}; foreign-domain lessons kept (a boost, not a filter)`;
178
+ }
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Cross-process exclusive lock for the JSON pattern store — built on `proper-lockfile`.
3
+ *
4
+ * WHY THIS EXISTS. The JSON backend writes ATOMICALLY (temp file + rename), so no reader
5
+ * ever sees a torn file. That is a different property from the one needed here. A teach is
6
+ * a read-modify-write: load every record, add one, write them all back. Two teaches that
7
+ * overlap both load the same N records, and each writes back N+1 — the second rename wins
8
+ * and the first lesson is gone. BOTH processes report success, so a lost lesson is silent.
9
+ * Atomicity prevents corruption; only mutual exclusion prevents a lost update.
10
+ *
11
+ * The SQLite backend has its own transaction locking and does not go through here.
12
+ *
13
+ * WHY `proper-lockfile` AND NOT THE PREVIOUS HAND-ROLLED LOCK. An independent review
14
+ * (Codex gpt-5.6-sol) graded the hand-rolled `wx`-file lock F. Its findings, and how this
15
+ * implementation answers them:
16
+ *
17
+ * 1. *Stale-break deleted a successor's live lock* — the old code `rmSync`'d a lock file
18
+ * by PATHNAME after deciding it was stale, so two waiters breaking the same stale lock
19
+ * could delete each other's freshly created locks in a cascade. `proper-lockfile`
20
+ * acquires with an atomic `mkdir`, and a waiter that breaks a stale lock retries with
21
+ * staleness DISABLED, so per acquisition attempt it can remove at most the one lock it
22
+ * observed as stale — never a successor's fresh lock in a loop. The residual
23
+ * microsecond window (stat-stale → holder replaced → rmdir) is closed by DETECTION:
24
+ * every holder heartbeats its lock's mtime and treats a foreign mtime as ECOMPROMISED,
25
+ * which {@link withStoreLock} converts into a loud error instead of a silent lost
26
+ * update. (This is also the model the RVF spec uses for `.rvf` writer locks:
27
+ * single-writer advisory lock file + ownership verification before unlink —
28
+ * `ruvector/docs/research/rvf/spec/09-concurrency-versioning.md`.)
29
+ *
30
+ * 2. *"Unparseable means dead" deleted live locks* — there is no lock BODY to parse any
31
+ * more. The lock is a directory; its existence is the lock, so the empty-file /
32
+ * half-written-file misclassification class is structurally gone.
33
+ *
34
+ * 3. *Age was mistaken for liveness* — staleness is now filesystem mtime plus a HEARTBEAT:
35
+ * the holder refreshes the lock's mtime on a timer (every `staleMs / 2`, ≥ 1s), so a
36
+ * holder slower than `staleMs` is never broken while alive, and a crashed holder's lock
37
+ * stops being refreshed and is reclaimed after `staleMs`. Nothing trusts a
38
+ * self-reported timestamp, so a forged far-future `ts` can no longer block forever.
39
+ * NOTE: the heartbeat runs on the event loop, so a SYNCHRONOUS critical section longer
40
+ * than `staleMs` could still be observed as stale — keep {@link withStoreLockSync}
41
+ * bodies short (they are: single-file JSON rewrites) or raise `staleMs`.
42
+ *
43
+ * 4. *The timeout was not an acquisition deadline* — the retry loops below compute a real
44
+ * deadline (`now + timeoutMs`), re-check it after EVERY sleep, clamp the last sleep to
45
+ * the remaining budget, and never acquire after the deadline has passed.
46
+ *
47
+ * 5. *The lock was not store-wide* — every JSON-tier writer in `patterns.ts` now runs
48
+ * under this lock (see the writer inventory in that module).
49
+ *
50
+ * On timeout this THROWS ({@link StoreLockTimeoutError}) rather than proceeding unlocked.
51
+ * Proceeding would restore exactly the silent lost-update this exists to stop, and a teach
52
+ * that failed loudly can be retried — one that vanished cannot.
53
+ *
54
+ * MIGRATION: the pre-`proper-lockfile` implementation left a regular FILE at
55
+ * `.dz/store.lock`; the library's lock is a DIRECTORY at the same path. A leftover file
56
+ * from a crashed old process is removed only once it is older than `staleMs` — a fresh
57
+ * one is honoured as held, same as any other lock.
58
+ */
59
+
60
+ import { mkdirSync, rmSync, statSync } from 'node:fs';
61
+ import { join, resolve } from 'node:path';
62
+ import { lockSync } from 'proper-lockfile';
63
+
64
+ /** A lock whose HEARTBEAT stopped this long ago is presumed abandoned (crashed holder). */
65
+ export const STALE_LOCK_MS = 30_000;
66
+ /** Give up waiting after this long and say so, rather than blocking a CLI forever. */
67
+ export const LOCK_TIMEOUT_MS = 10_000;
68
+
69
+ /** `proper-lockfile` silently clamps `stale` up to this minimum. */
70
+ const MIN_STALE_MS = 2_000;
71
+
72
+ /** Path of the lock guarding a project's pattern store (a DIRECTORY when held). */
73
+ export function storeLockPath(projectRoot: string): string {
74
+ return join(projectRoot, '.dz', 'store.lock');
75
+ }
76
+
77
+ /** Options accepted by {@link withStoreLock} / {@link withStoreLockSync}. */
78
+ export interface StoreLockOptions {
79
+ /** Heartbeat-stopped threshold before a lock is presumed abandoned (min 2000, lib-enforced). */
80
+ readonly staleMs?: number;
81
+ /** Acquisition deadline. Also overridable via `DZ_STORE_LOCK_TIMEOUT_MS` (tests/ops). */
82
+ readonly timeoutMs?: number;
83
+ /** Delay between acquisition attempts while the lock is held by someone else. */
84
+ readonly pollMs?: number;
85
+ }
86
+
87
+ /** Acquisition gave up at the deadline. Nothing was written; the operation can be retried. */
88
+ export class StoreLockTimeoutError extends Error {
89
+ readonly code = 'ELOCKTIMEOUT';
90
+ constructor(lockPath: string, waitedMs: number) {
91
+ super(
92
+ `the pattern store at ${lockPath} stayed locked for ${waitedMs}ms — ` +
93
+ 'another dz process is still writing. Nothing was written; retry.',
94
+ );
95
+ this.name = 'StoreLockTimeoutError';
96
+ }
97
+ }
98
+
99
+ /**
100
+ * The holder detected that its lock was broken out from under it (ECOMPROMISED) — e.g. a
101
+ * waiter reclaimed the lock after this process was suspended past `staleMs`. The critical
102
+ * section DID run, but it may have raced another writer, so the operation must be treated
103
+ * as failed and retried (store writes are idempotent by deterministic record id).
104
+ */
105
+ export class StoreLockCompromisedError extends Error {
106
+ readonly code = 'ECOMPROMISED';
107
+ constructor(lockPath: string, cause: Error) {
108
+ super(`the pattern store lock at ${lockPath} was compromised while held (${cause.message}) — retry the operation.`);
109
+ this.name = 'StoreLockCompromisedError';
110
+ }
111
+ }
112
+
113
+ const defaultTimeoutMs = (): number => {
114
+ const env = Number(process.env['DZ_STORE_LOCK_TIMEOUT_MS']);
115
+ return Number.isFinite(env) && env > 0 ? env : LOCK_TIMEOUT_MS;
116
+ };
117
+
118
+ const sleep = (ms: number): Promise<void> => new Promise((r) => { setTimeout(r, ms); });
119
+
120
+ /** Synchronous sleep without spinning (Atomics.wait on a throwaway buffer). */
121
+ const sleepSync = (ms: number): void => {
122
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
123
+ };
124
+
125
+ /**
126
+ * Remove a REGULAR-FILE lock left by the pre-`proper-lockfile` implementation, but only
127
+ * once it is stale — a fresh legacy lock belongs to a live old-version process and is
128
+ * honoured. (Never deletes a directory: that is a live library lock.)
129
+ */
130
+ function clearStaleLegacyLockFile(lockPath: string, staleMs: number): void {
131
+ try {
132
+ const st = statSync(lockPath);
133
+ if (st.isFile() && Date.now() - st.mtimeMs >= staleMs) rmSync(lockPath, { force: true });
134
+ } catch { /* gone already — fine */ }
135
+ }
136
+
137
+ interface Acquired {
138
+ readonly release: () => void;
139
+ readonly compromise: () => Error | undefined;
140
+ }
141
+
142
+ /**
143
+ * One acquisition attempt. Returns `'held'` when someone else holds the lock (retry later);
144
+ * throws on real I/O errors. `mkdir`-based, so creation is atomic; staleness is heartbeat
145
+ * mtime, and the library's own stale-break retries with staleness disabled (see header §1).
146
+ */
147
+ function tryAcquire(projectRoot: string, staleMs: number, onCompromised: (e: Error) => void): Acquired | 'held' {
148
+ const lockPath = storeLockPath(projectRoot);
149
+ try {
150
+ const release = lockSync(resolve(projectRoot, '.dz', 'store'), {
151
+ lockfilePath: lockPath,
152
+ stale: staleMs,
153
+ realpath: false, // the guarded resource is a concept, not an existing file
154
+ onCompromised,
155
+ });
156
+ return {
157
+ release: () => {
158
+ try {
159
+ release();
160
+ } catch { /* ERELEASED after a compromise — the lock is no longer ours to remove */ }
161
+ },
162
+ compromise: () => undefined,
163
+ };
164
+ } catch (err) {
165
+ const code = (err as NodeJS.ErrnoException).code;
166
+ if (code === 'ELOCKED') return 'held';
167
+ if (code === 'ENOTDIR') {
168
+ // A stale legacy FILE lock: the library can only rmdir directories. Clear it (only
169
+ // if actually stale) and report 'held' so the caller's loop retries.
170
+ clearStaleLegacyLockFile(lockPath, staleMs);
171
+ return 'held';
172
+ }
173
+ throw err;
174
+ }
175
+ }
176
+
177
+ function resolveOpts(opts: StoreLockOptions): { staleMs: number; timeoutMs: number; pollMs: number } {
178
+ return {
179
+ staleMs: Math.max(opts.staleMs ?? STALE_LOCK_MS, MIN_STALE_MS),
180
+ timeoutMs: opts.timeoutMs ?? defaultTimeoutMs(),
181
+ pollMs: opts.pollMs ?? 25,
182
+ };
183
+ }
184
+
185
+ /**
186
+ * Run `fn` while holding the store lock, releasing it however `fn` ends.
187
+ *
188
+ * Throws {@link StoreLockTimeoutError} when the lock cannot be acquired by the deadline
189
+ * (nothing has run), and {@link StoreLockCompromisedError} when the lock was broken while
190
+ * `fn` ran (it DID run, but may have raced — retry; store writes are idempotent).
191
+ */
192
+ export async function withStoreLock<T>(
193
+ projectRoot: string,
194
+ fn: () => Promise<T>,
195
+ opts: StoreLockOptions = {},
196
+ ): Promise<T> {
197
+ const { staleMs, timeoutMs, pollMs } = resolveOpts(opts);
198
+ mkdirSync(join(projectRoot, '.dz'), { recursive: true });
199
+ const started = Date.now();
200
+ const deadline = started + timeoutMs;
201
+ let compromised: Error | undefined;
202
+ const onCompromised = (e: Error): void => { compromised = e; };
203
+ for (;;) {
204
+ const got = tryAcquire(projectRoot, staleMs, onCompromised);
205
+ if (got !== 'held') {
206
+ let result: T;
207
+ try {
208
+ result = await fn();
209
+ } finally {
210
+ got.release();
211
+ }
212
+ if (compromised !== undefined) throw new StoreLockCompromisedError(storeLockPath(projectRoot), compromised);
213
+ return result;
214
+ }
215
+ const now = Date.now();
216
+ if (now >= deadline) throw new StoreLockTimeoutError(storeLockPath(projectRoot), now - started);
217
+ await sleep(Math.min(pollMs, deadline - now));
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Synchronous {@link withStoreLock}, for the store's synchronous writers (prune / remove).
223
+ * Same deadline and failure semantics. The heartbeat cannot fire while `fn` blocks the
224
+ * event loop, so keep bodies well under `staleMs` (they are: single-file JSON rewrites).
225
+ *
226
+ * CAVEAT: do not contend with an ASYNC `withStoreLock` holder in the SAME process — the
227
+ * sync wait blocks the event loop that would release that holder, so the wait can only
228
+ * end in the loud {@link StoreLockTimeoutError} (never a lost update). Cross-process
229
+ * contention, the case this lock exists for, is unaffected.
230
+ */
231
+ export function withStoreLockSync<T>(
232
+ projectRoot: string,
233
+ fn: () => T,
234
+ opts: StoreLockOptions = {},
235
+ ): T {
236
+ const { staleMs, timeoutMs, pollMs } = resolveOpts(opts);
237
+ mkdirSync(join(projectRoot, '.dz'), { recursive: true });
238
+ const started = Date.now();
239
+ const deadline = started + timeoutMs;
240
+ let compromised: Error | undefined;
241
+ const onCompromised = (e: Error): void => { compromised = e; };
242
+ for (;;) {
243
+ const got = tryAcquire(projectRoot, staleMs, onCompromised);
244
+ if (got !== 'held') {
245
+ let result: T;
246
+ try {
247
+ result = fn();
248
+ } finally {
249
+ got.release();
250
+ }
251
+ if (compromised !== undefined) throw new StoreLockCompromisedError(storeLockPath(projectRoot), compromised);
252
+ return result;
253
+ }
254
+ const now = Date.now();
255
+ if (now >= deadline) throw new StoreLockTimeoutError(storeLockPath(projectRoot), now - started);
256
+ sleepSync(Math.min(pollMs, deadline - now));
257
+ }
258
+ }
package/src/workflows.ts CHANGED
@@ -1,123 +1,24 @@
1
1
  /**
2
- * Dynamic workflow templates for Opus 4.8+ orchestration.
2
+ * RETIRED — the ADR-005 workflow templates are gone (feature loop-designer, AM-6 / architecture
3
+ * §8.2). They emitted a pre-`meta`/`phases` format (`export default {tasks, maxConcurrency}`) the
4
+ * current Workflow runtime cannot execute — a broken command, not a feature.
3
5
  *
4
- * Per ADR-005: workflows live in the orchestration layer only.
5
- * They generate JS scripts that Claude Code's dynamic workflow engine executes.
6
- * Core schema, adapters, and skill content remain model-agnostic.
6
+ * Replacement: `dz workflow init` (scaffold a `loop-plan/1` plan), `dz workflow validate`,
7
+ * `dz workflow render` (plan executable region-delimited loop script), plus the sibling gates
8
+ * `dz workflow-lint` and `dz workflow-trace`. See `loop-plan.ts` / `loop-render.ts`.
7
9
  *
8
- * @packageDocumentation
10
+ * BREAKING (deliberate, channeled): removing `WorkflowTemplate`/`WORKFLOWS`/`getWorkflow` is a
11
+ * public API change for harness-core. harness-core is 0.x, where MINOR is this repo's breaking
12
+ * channel; the removal is named in the CHANGELOG and README — never silent. The only internal
13
+ * importer was `harness-cli`'s `cmdWorkflow` (MEASURED at plan time), rewritten in the same change.
14
+ *
15
+ * This module stays as a deprecation shim so stale imports fail LOUDLY with a pointer, not with a
16
+ * confusing "module not found".
9
17
  */
10
18
 
11
- /** A workflow template generates a JS orchestration script from parameters. */
12
- export interface WorkflowTemplate {
13
- readonly name: string;
14
- readonly description: string;
15
- readonly generate: (options: WorkflowOptions) => string;
16
- }
17
-
18
- /** Options passed to workflow generation. */
19
- export interface WorkflowOptions {
20
- readonly projectRoot: string;
21
- readonly dryRun?: boolean;
22
- readonly packages?: readonly string[];
23
- }
24
-
25
- const coverageLift: WorkflowTemplate = {
26
- name: 'coverage-lift',
27
- description: 'Lift Tier-A package coverage to ≥95% using parallel agents per package.',
28
- generate: (opts) => `
29
- // Dynamic Workflow: Coverage Lift
30
- // Generated for: ${opts.projectRoot}
31
- // Per ADR-005: orchestration only — no adapter/core changes
32
-
33
- const tierA = ${JSON.stringify(opts.packages ?? [
34
- 'core', 'memory', 'harness-core', 'harness-cli',
35
- 'harness-presets', 'mcp-server-tools',
36
- 'adapter-claude', 'adapter-codex', 'adapter-opencode', 'adapter-hermes',
37
- 'skills-qe',
38
- ])};
39
-
40
- const tasks = tierA.map(pkg => ({
41
- name: \`coverage-\${pkg}\`,
42
- description: \`Lift @dzhechkov/\${pkg} to ≥95% line coverage. Run: pnpm --filter @dzhechkov/\${pkg} test -- --coverage. Add tests for uncovered lines.\`,
43
- }));
44
-
45
- // Claude Code dynamic workflow engine will:
46
- // 1. Spawn one agent per task (up to 16 concurrent)
47
- // 2. Each agent reads coverage, writes tests, re-runs coverage
48
- // 3. Results aggregated when all agents complete
49
- export default { tasks, maxConcurrency: 4${opts.dryRun ? ', dryRun: true' : ''} };
50
- `.trim(),
51
- };
52
-
53
- const mutationKill: WorkflowTemplate = {
54
- name: 'mutation-kill',
55
- description: 'Kill surviving mutants across core packages using parallel Stryker runs.',
56
- generate: (opts) => `
57
- // Dynamic Workflow: Mutation Kill
58
- // Generated for: ${opts.projectRoot}
59
-
60
- const packages = ${JSON.stringify(opts.packages ?? ['core', 'memory', 'harness-core'])};
61
-
62
- const tasks = packages.map(pkg => ({
63
- name: \`mutate-\${pkg}\`,
64
- description: \`Run Stryker on @dzhechkov/\${pkg}, analyze survivors, write tests to kill them. Target: ≥80% mutation score.\`,
65
- }));
66
-
67
- export default { tasks, maxConcurrency: 3${opts.dryRun ? ', dryRun: true' : ''} };
68
- `.trim(),
69
- };
70
-
71
- const canonicalize: WorkflowTemplate = {
72
- name: 'canonicalize',
73
- description: 'Canonicalize packages from vendored directories into @dzhechkov/* namespace.',
74
- generate: (opts) => `
75
- // Dynamic Workflow: Canonicalize
76
- // Generated for: ${opts.projectRoot}
77
-
78
- const tasks = [
79
- { name: 'discover', description: 'Scan vendored directories for un-canonicalized packages.' },
80
- { name: 'copy', description: 'Copy discovered packages to packages/@dzhechkov/. Exclude node_modules, .git, runtime state.' },
81
- { name: 'metadata', description: 'Add publishConfig, repository, homepage to each package.json.' },
82
- { name: 'verify', description: 'Run byte-level diff between source and canonical. 0 missing, 0 changed.' },
83
- { name: 'test', description: 'Run canonical-packages structural tests. All must pass.' },
84
- ];
85
-
86
- export default { tasks, maxConcurrency: 2${opts.dryRun ? ', dryRun: true' : ''} };
87
- `.trim(),
88
- };
89
-
90
- const securityAudit: WorkflowTemplate = {
91
- name: 'security-audit',
92
- description: 'Run adversarial security audit with parallel boundary scanning.',
93
- generate: (opts) => `
94
- // Dynamic Workflow: Security Audit
95
- // Generated for: ${opts.projectRoot}
96
-
97
- const tasks = [
98
- { name: 'npm-audit', description: 'Run pnpm audit, capture baseline.' },
99
- { name: 'gitleaks', description: 'Run gitleaks detect, document findings.' },
100
- { name: 'boundaries', description: 'Verify all 8 input boundaries have runtime guards.' },
101
- { name: 'payloads', description: 'Test aidefence payloads against boundaries.' },
102
- { name: 'report', description: 'Generate security-audit.md with 6 H2 sections.' },
103
- ];
104
-
105
- export default { tasks, maxConcurrency: 3${opts.dryRun ? ', dryRun: true' : ''} };
106
- `.trim(),
107
- };
108
-
109
- /** All registered workflow templates. */
110
- export const WORKFLOWS: Record<string, WorkflowTemplate> = {
111
- 'coverage-lift': coverageLift,
112
- 'mutation-kill': mutationKill,
113
- 'canonicalize': canonicalize,
114
- 'security-audit': securityAudit,
115
- };
116
-
117
- /** Valid workflow names. */
118
- export const WORKFLOW_NAMES = Object.keys(WORKFLOWS);
19
+ /** The pinned retirement message the CLI prints (tested by workflow-legacy-shim.test.ts). */
20
+ export const WORKFLOW_TEMPLATES_RETIRED_MESSAGE =
21
+ 'dz workflow: the ADR-005 templates are retired (they emitted a pre-meta format the runtime cannot run) — use dz workflow init/render';
119
22
 
120
- /** Look up a workflow by name. */
121
- export function getWorkflow(name: string): WorkflowTemplate | undefined {
122
- return WORKFLOWS[name];
123
- }
23
+ /** Empty by design: no legacy template names remain. */
24
+ export const WORKFLOW_NAMES: string[] = [];