@crewhaus/harness-registry 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,84 @@
1
+ # @crewhaus/harness-registry
2
+
3
+ The machine-wide harness registry — one JSON document
4
+ (`<registryRoot>/harnesses.json`, format `v: 2`) listing every harness
5
+ registered on this machine, plus user-configured scan roots and group
6
+ definitions. This is the registry-file layer behind the harness manager and
7
+ its CLI twins.
8
+
9
+ Pure registry-file layer by design: it never parses specs (callers supply
10
+ `specName`/`target`) and never scans the filesystem for harnesses
11
+ (discovery is the inventory layer's job).
12
+
13
+ ## Roots and switches
14
+
15
+ - Registry root: the directory containing `harnesses.json` —
16
+ `CREWHAUS_REGISTRY_ROOT`, default `~/.crewhaus`. An explicit `root`
17
+ option wins over the env var.
18
+ - `CREWHAUS_NO_REGISTRY=1` — global opt-out: every write becomes a no-op
19
+ while reads keep working.
20
+
21
+ ## Document shape (v2)
22
+
23
+ `harnesses[]` entries carry a stable crypto-random id (`hrn_` + 16
24
+ lowercase hex, minted on first registration), the absolute `dir` (THE
25
+ upsert identity key), `specName`/`target`, provenance
26
+ (`origin: scan | manual | run-hook | import` + `originDetail`), ISO
27
+ `registeredAt`/`lastSeen`, user-managed `groups`/`tags`/`pinned`/`notes`,
28
+ `kind: local | remote`, a `watchme: { share }` compat block, opaque
29
+ `remotes[]` deployment pointers, and `missingSince`. Top-level `scanRoots[]`
30
+ (`dir`, `depth`, `auto`, `rescanIntervalMin`, `lastScanAt`) and `groups[]`
31
+ (`name`, `order`, `color`) ride along.
32
+
33
+ The format is **additive**: unknown fields anywhere in the document are
34
+ tolerated on read and preserved on rewrite, so older and newer CLIs can
35
+ share one file. Documents with `v < 2` (or none — the legacy watchme
36
+ registry format) are lifted best-effort on read and healed on the next
37
+ write.
38
+
39
+ ## Write discipline
40
+
41
+ Atomic tmp+rename with per-writer-unique tmp names, file mode `0600`,
42
+ directory mode `0700`, and read-merge-write with a small
43
+ fingerprint-checked retry loop so two same-machine writers do not lose each
44
+ other's rows. Vanished directories are **never silently pruned**: `list()`
45
+ stamps `missingSince` (and clears it when the dir is back); only an
46
+ explicit `remove()` deletes a row. `list()`'s stamp/lift persists are
47
+ best-effort — on an unwritable registry root it warns and returns the
48
+ computed view un-persisted rather than failing the read.
49
+
50
+ ## API
51
+
52
+ `openHangarRegistry({ root?, watchmeRoot?, now?, env?, onWarn? })` returns
53
+ `{ path, disabled, list, get, upsert, remove, relocate, setGroups, setTags,
54
+ setPinned, setNotes, listGroups, addGroup, updateGroup, removeGroup,
55
+ reorderGroups, listScanRoots, addScanRoot, updateScanRoot, removeScanRoot,
56
+ registerHook, seedFromWatchme }`.
57
+
58
+ - `upsert` is keyed by absolute dir: new entries mint an id; refreshes keep
59
+ `id`/`registeredAt`/`origin` and the user-managed fields
60
+ (groups/tags/pinned/notes are **never clobbered** by a refresh), update
61
+ `lastSeen` plus any descriptive fields provided, and clear `missingSince`.
62
+ - `relocate(id, newDir)` points an entry at a new directory under the same
63
+ id (it throws if `newDir` already belongs to another entry).
64
+ - `registerHook({ dir, specName?, target?, originDetail })` — and the
65
+ module-level `registerHarnessHook(fields, opts?)` — is the best-effort
66
+ self-registration entry point for CLI hooks: it never throws (any failure
67
+ collapses into `{ ok: false }`, because a registry write must never fail
68
+ the command that triggered it) and respects `CREWHAUS_NO_REGISTRY`.
69
+
70
+ ## watchme interop
71
+
72
+ Watchme membership means **explicitly watched** — only the watchme verbs
73
+ (`watchme start`, `watchme stop --forget`) enroll or un-enroll a harness.
74
+ Interop goes through `@crewhaus/watchme-store`'s own API (never by touching
75
+ its file format):
76
+
77
+ - `seedFromWatchme()` merges the watchme registry in once (idempotent —
78
+ safe to call every boot; already-registered dirs are left untouched).
79
+ Imported entries get `origin: "import"` / `originDetail: "watchme"`.
80
+ - `upsert`/`relocate` mirror **freshness only** onto a watchme row that
81
+ already exists (dir/specName/target); they never create a watchme row,
82
+ never delete one, and never touch `share` or `agentId`. `remove()` does
83
+ not touch the watchme registry at all. A mirror failure never fails the
84
+ primary write (it is reported via `onWarn`, silent by default).
package/dist/doc.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ import type { HangarRegistryDoc } from "./types.js";
2
+ export declare const REGISTRY_FILENAME = "harnesses.json";
3
+ /** Shape of a minted harness id: `hrn_` + 16 lowercase hex. */
4
+ export declare const HARNESS_ID_RE: RegExp;
5
+ /** Mint a crypto-random id not present in `taken`. */
6
+ export declare function mintHarnessId(taken: ReadonlySet<string>): string;
7
+ export declare const asRecord: (value: unknown) => Record<string, unknown> | undefined;
8
+ export type NormalizeCtx = {
9
+ readonly nowIso: string;
10
+ /** Mint an id for `dir`, avoiding everything in `taken`. */
11
+ readonly mint: (dir: string, taken: Set<string>) => string;
12
+ };
13
+ export declare const EMPTY_DOC: HangarRegistryDoc;
14
+ /**
15
+ * Normalize a parsed document. `lifted` reports whether persisting the
16
+ * normalized form would change the file in a schema-meaningful way (pre-v2
17
+ * document, or entries that needed an id minted) — the signal `list()` uses
18
+ * to heal the file on read.
19
+ */
20
+ export declare function normalizeDoc(rawUnknown: unknown, ctx: NormalizeCtx): {
21
+ doc: HangarRegistryDoc;
22
+ lifted: boolean;
23
+ };
24
+ /** Stable on-disk ordering: harnesses/scanRoots by dir, groups by order. */
25
+ export declare function sortDoc(doc: HangarRegistryDoc): HangarRegistryDoc;
26
+ /**
27
+ * Cheap change fingerprint of the registry file (inode + mtime + size,
28
+ * bigint stats). Compared before a rename lands to detect a concurrent
29
+ * writer; `"absent"` when the file does not exist.
30
+ */
31
+ export declare function fingerprintPath(path: string): string;
32
+ /** Synchronous sleep for retry backoff (runtime-neutral, no busy loop). */
33
+ export declare function sleepSync(ms: number): void;
package/dist/doc.js ADDED
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Tolerant document model for `harnesses.json`: parse-anything reads, a
3
+ * best-effort lift of pre-v2 (watchme-format) documents, unknown-field
4
+ * preservation, stable on-disk sorting, and the small pure helpers behind
5
+ * the read-merge-write loop (id minting, stat fingerprints, sync sleep).
6
+ *
7
+ * Everything here is pure or fs-read-only; all writing lives in
8
+ * `registry.ts` so there is exactly one write path.
9
+ */
10
+ import { randomBytes } from "node:crypto";
11
+ import { statSync } from "node:fs";
12
+ import { basename, resolve } from "node:path";
13
+ export const REGISTRY_FILENAME = "harnesses.json";
14
+ /** Shape of a minted harness id: `hrn_` + 16 lowercase hex. */
15
+ export const HARNESS_ID_RE = /^hrn_[0-9a-f]{16}$/;
16
+ const ORIGINS = ["scan", "manual", "run-hook", "import"];
17
+ /** Mint a crypto-random id not present in `taken`. */
18
+ export function mintHarnessId(taken) {
19
+ for (;;) {
20
+ const id = `hrn_${randomBytes(8).toString("hex")}`;
21
+ if (!taken.has(id))
22
+ return id;
23
+ }
24
+ }
25
+ const asString = (value) => typeof value === "string" ? value : undefined;
26
+ const asStringArray = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
27
+ export const asRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value)
28
+ ? value
29
+ : undefined;
30
+ /** ISO 8601 from an ISO string (kept), an epoch-ms number (lifted — the
31
+ * watchme v1 timestamp format), or anything else (the fallback). */
32
+ const toIso = (value, fallback) => {
33
+ if (typeof value === "string" && value.length > 0)
34
+ return value;
35
+ if (typeof value === "number" && Number.isFinite(value))
36
+ return new Date(value).toISOString();
37
+ return fallback;
38
+ };
39
+ /** Normalize one raw harness record; `undefined` for rows with no usable
40
+ * `dir` (skipped, watchme posture — dropped only when the doc is rewritten). */
41
+ function normalizeEntry(raw, ctx, taken, liftingV1) {
42
+ const dirRaw = asString(raw["dir"]);
43
+ if (dirRaw === undefined || dirRaw.length === 0)
44
+ return undefined;
45
+ const dir = resolve(dirRaw);
46
+ const idRaw = asString(raw["id"]);
47
+ const minted = idRaw === undefined || !HARNESS_ID_RE.test(idRaw);
48
+ const id = minted ? ctx.mint(dir, taken) : idRaw;
49
+ const originRaw = raw["origin"];
50
+ const origin = ORIGINS.includes(originRaw)
51
+ ? originRaw
52
+ : liftingV1
53
+ ? "import"
54
+ : "manual";
55
+ const originDetail = asString(raw["originDetail"]) ?? (liftingV1 ? "watchme" : "");
56
+ // v1 carried a top-level `share` flag; v2 nests it under `watchme.share`,
57
+ // so a lift moves the flag instead of spreading the stale copy along.
58
+ const watchmeRaw = asRecord(raw["watchme"]);
59
+ const share = typeof watchmeRaw?.["share"] === "boolean" ? watchmeRaw["share"] : raw["share"] === true;
60
+ const carried = liftingV1
61
+ ? Object.fromEntries(Object.entries(raw).filter(([key]) => key !== "share"))
62
+ : raw;
63
+ const entry = {
64
+ ...carried,
65
+ id,
66
+ dir,
67
+ specName: asString(raw["specName"]) ?? basename(dir),
68
+ target: asString(raw["target"]) ?? "unknown",
69
+ origin,
70
+ originDetail,
71
+ registeredAt: toIso(raw["registeredAt"], ctx.nowIso),
72
+ lastSeen: toIso(raw["lastSeen"], ctx.nowIso),
73
+ groups: asStringArray(raw["groups"]),
74
+ tags: asStringArray(raw["tags"]),
75
+ pinned: raw["pinned"] === true,
76
+ notes: asString(raw["notes"]) ?? "",
77
+ kind: raw["kind"] === "remote" ? "remote" : "local",
78
+ watchme: { ...watchmeRaw, share },
79
+ remotes: Array.isArray(raw["remotes"])
80
+ ? raw["remotes"].filter((item) => asRecord(item) !== undefined)
81
+ : [],
82
+ missingSince: asString(raw["missingSince"]) ?? null,
83
+ };
84
+ return { entry, minted };
85
+ }
86
+ function normalizeScanRoot(raw) {
87
+ const dirRaw = asString(raw["dir"]);
88
+ if (dirRaw === undefined || dirRaw.length === 0)
89
+ return undefined;
90
+ return {
91
+ ...raw,
92
+ dir: resolve(dirRaw),
93
+ depth: typeof raw["depth"] === "number" ? raw["depth"] : 6,
94
+ auto: raw["auto"] !== false,
95
+ rescanIntervalMin: typeof raw["rescanIntervalMin"] === "number" ? raw["rescanIntervalMin"] : 15,
96
+ lastScanAt: asString(raw["lastScanAt"]) ?? null,
97
+ };
98
+ }
99
+ function normalizeGroupDef(raw, index) {
100
+ const name = asString(raw["name"]);
101
+ if (name === undefined || name.length === 0)
102
+ return undefined;
103
+ return {
104
+ ...raw,
105
+ name,
106
+ order: typeof raw["order"] === "number" ? raw["order"] : index + 1,
107
+ color: asString(raw["color"]) ?? "",
108
+ };
109
+ }
110
+ export const EMPTY_DOC = { v: 2, harnesses: [], scanRoots: [], groups: [] };
111
+ /**
112
+ * Normalize a parsed document. `lifted` reports whether persisting the
113
+ * normalized form would change the file in a schema-meaningful way (pre-v2
114
+ * document, or entries that needed an id minted) — the signal `list()` uses
115
+ * to heal the file on read.
116
+ */
117
+ export function normalizeDoc(rawUnknown, ctx) {
118
+ const raw = asRecord(rawUnknown) ?? {};
119
+ const liftingV1 = raw["v"] !== 2;
120
+ const rawHarnesses = Array.isArray(raw["harnesses"]) ? raw["harnesses"] : [];
121
+ // Pre-collect valid ids so minting never collides with a later row.
122
+ const taken = new Set();
123
+ for (const rec of rawHarnesses) {
124
+ const id = asRecord(rec)?.["id"];
125
+ if (typeof id === "string" && HARNESS_ID_RE.test(id))
126
+ taken.add(id);
127
+ }
128
+ let minted = false;
129
+ const byDir = new Map();
130
+ for (const rec of rawHarnesses) {
131
+ const record = asRecord(rec);
132
+ if (record === undefined)
133
+ continue;
134
+ const normalized = normalizeEntry(record, ctx, taken, liftingV1);
135
+ if (normalized === undefined)
136
+ continue;
137
+ minted = minted || normalized.minted;
138
+ byDir.set(normalized.entry.dir, normalized.entry); // last-wins per dir
139
+ }
140
+ const scanRoots = [];
141
+ if (Array.isArray(raw["scanRoots"])) {
142
+ for (const rec of raw["scanRoots"]) {
143
+ const record = asRecord(rec);
144
+ const normalized = record === undefined ? undefined : normalizeScanRoot(record);
145
+ if (normalized !== undefined)
146
+ scanRoots.push(normalized);
147
+ }
148
+ }
149
+ const groups = [];
150
+ if (Array.isArray(raw["groups"])) {
151
+ let index = 0;
152
+ for (const rec of raw["groups"]) {
153
+ const record = asRecord(rec);
154
+ const normalized = record === undefined ? undefined : normalizeGroupDef(record, index);
155
+ if (normalized !== undefined) {
156
+ groups.push(normalized);
157
+ index += 1;
158
+ }
159
+ }
160
+ }
161
+ const doc = {
162
+ ...raw,
163
+ v: 2,
164
+ harnesses: [...byDir.values()],
165
+ scanRoots,
166
+ groups,
167
+ };
168
+ return { doc, lifted: liftingV1 || minted };
169
+ }
170
+ /** Stable on-disk ordering: harnesses/scanRoots by dir, groups by order. */
171
+ export function sortDoc(doc) {
172
+ return {
173
+ ...doc,
174
+ harnesses: [...doc.harnesses].sort((a, b) => a.dir.localeCompare(b.dir)),
175
+ scanRoots: [...doc.scanRoots].sort((a, b) => a.dir.localeCompare(b.dir)),
176
+ groups: [...doc.groups].sort((a, b) => a.order - b.order || a.name.localeCompare(b.name)),
177
+ };
178
+ }
179
+ /**
180
+ * Cheap change fingerprint of the registry file (inode + mtime + size,
181
+ * bigint stats). Compared before a rename lands to detect a concurrent
182
+ * writer; `"absent"` when the file does not exist.
183
+ */
184
+ export function fingerprintPath(path) {
185
+ try {
186
+ const st = statSync(path, { bigint: true });
187
+ return `${st.ino}:${st.mtimeNs}:${st.size}`;
188
+ }
189
+ catch {
190
+ return "absent";
191
+ }
192
+ }
193
+ /** Synchronous sleep for retry backoff (runtime-neutral, no busy loop). */
194
+ export function sleepSync(ms) {
195
+ const shared = new Int32Array(new SharedArrayBuffer(4));
196
+ Atomics.wait(shared, 0, 0, ms);
197
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * `@crewhaus/harness-registry` — the machine-wide harness registry file
3
+ * layer behind the harness manager: one `harnesses.json` (format v2) under
4
+ * the registry root (`CREWHAUS_REGISTRY_ROOT`, default `~/.crewhaus`)
5
+ * listing every registered harness with a stable `hrn_` id, plus scan
6
+ * roots and group definitions.
7
+ *
8
+ * Pure registry-file layer by design: no spec parsing (callers supply
9
+ * `specName`/`target`) and no filesystem scanning (discovery is the
10
+ * inventory layer's job). Writes are atomic tmp+rename, mode 0600, with a
11
+ * read-merge-write retry loop for same-machine multi-writer races;
12
+ * `CREWHAUS_NO_REGISTRY=1` turns every write into a no-op while reads keep
13
+ * working. Interop with the legacy watchme registry (seed merge +
14
+ * best-effort write-through) goes through `@crewhaus/watchme-store`'s own
15
+ * API.
16
+ */
17
+ export { HARNESS_ID_RE, REGISTRY_FILENAME } from "./doc.js";
18
+ export { openHangarRegistry, registerHarnessHook, resolveRegistryRoot, type HangarRegistry, type ListOptions, type OpenHangarRegistryOptions, type RegisterHookFields, type RegisterHookResult, type UpsertFields, } from "./registry.js";
19
+ export type { GroupDef, HangarHarnessEntry, HangarRegistryDoc, HarnessKind, HarnessOrigin, ScanRoot, } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * `@crewhaus/harness-registry` — the machine-wide harness registry file
3
+ * layer behind the harness manager: one `harnesses.json` (format v2) under
4
+ * the registry root (`CREWHAUS_REGISTRY_ROOT`, default `~/.crewhaus`)
5
+ * listing every registered harness with a stable `hrn_` id, plus scan
6
+ * roots and group definitions.
7
+ *
8
+ * Pure registry-file layer by design: no spec parsing (callers supply
9
+ * `specName`/`target`) and no filesystem scanning (discovery is the
10
+ * inventory layer's job). Writes are atomic tmp+rename, mode 0600, with a
11
+ * read-merge-write retry loop for same-machine multi-writer races;
12
+ * `CREWHAUS_NO_REGISTRY=1` turns every write into a no-op while reads keep
13
+ * working. Interop with the legacy watchme registry (seed merge +
14
+ * best-effort write-through) goes through `@crewhaus/watchme-store`'s own
15
+ * API.
16
+ */
17
+ export { HARNESS_ID_RE, REGISTRY_FILENAME } from "./doc.js";
18
+ export { openHangarRegistry, registerHarnessHook, resolveRegistryRoot, } from "./registry.js";
@@ -0,0 +1,140 @@
1
+ import type { GroupDef, HangarHarnessEntry, HarnessKind, HarnessOrigin, ScanRoot } from "./types.js";
2
+ export type OpenHangarRegistryOptions = {
3
+ /** Directory containing `harnesses.json`. Wins over the env var. */
4
+ readonly root?: string;
5
+ /** Root of the legacy watchme registry (for seed + write-through).
6
+ * Default: `CREWHAUS_WATCHME_ROOT` or `~/.crewhaus/watchme`. */
7
+ readonly watchmeRoot?: string;
8
+ /** Clock (epoch ms); injected so tests are deterministic. */
9
+ readonly now?: () => number;
10
+ /** Environment to consult; defaults to `process.env`. When supplied it is
11
+ * used EXCLUSIVELY, so tests are isolated from the real environment. */
12
+ readonly env?: Readonly<Record<string, string | undefined>>;
13
+ /** Receives one line per best-effort failure (watchme write-through).
14
+ * Default: silent — hooks run on every CLI command and must stay quiet. */
15
+ readonly onWarn?: (message: string) => void;
16
+ /** Internal test seam: invoked after every document read inside the
17
+ * read-merge-write loop (used to exercise the concurrent-writer retry). */
18
+ readonly hooks?: {
19
+ readonly afterRead?: () => void;
20
+ };
21
+ };
22
+ /** Fields accepted by {@link HangarRegistry.upsert}. Only `dir` is
23
+ * required; callers supply `specName`/`target` (no spec parsing here). */
24
+ export type UpsertFields = {
25
+ readonly dir: string;
26
+ readonly specName?: string;
27
+ readonly target?: string;
28
+ /** Recorded on first registration only; refreshes never rewrite it. */
29
+ readonly origin?: HarnessOrigin;
30
+ readonly originDetail?: string;
31
+ readonly kind?: HarnessKind;
32
+ readonly watchme?: {
33
+ readonly share: boolean;
34
+ };
35
+ readonly remotes?: ReadonlyArray<Readonly<Record<string, unknown>>>;
36
+ /** Initial value for new entries; ignored on refresh (use `setGroups`). */
37
+ readonly groups?: readonly string[];
38
+ /** Initial value for new entries; ignored on refresh (use `setTags`). */
39
+ readonly tags?: readonly string[];
40
+ /** Initial value for new entries; ignored on refresh (use `setPinned`). */
41
+ readonly pinned?: boolean;
42
+ /** Initial value for new entries; ignored on refresh (use `setNotes`). */
43
+ readonly notes?: string;
44
+ };
45
+ export type ListOptions = {
46
+ /** Include entries whose dir is currently missing (default true — a
47
+ * vanished harness is surfaced with `missingSince`, never hidden). */
48
+ readonly includeMissing?: boolean;
49
+ };
50
+ export type RegisterHookFields = {
51
+ readonly dir: string;
52
+ readonly specName?: string;
53
+ readonly target?: string;
54
+ /** Which command touched the harness, e.g. `run|compile|eval|dev`. */
55
+ readonly originDetail: string;
56
+ };
57
+ export type RegisterHookResult = {
58
+ readonly ok: boolean;
59
+ readonly id?: string;
60
+ readonly error?: string;
61
+ };
62
+ export type HangarRegistry = {
63
+ /** Absolute path of the registry file. */
64
+ readonly path: string;
65
+ /** True when `CREWHAUS_NO_REGISTRY` disabled all writes. */
66
+ readonly disabled: boolean;
67
+ /** All entries, missing-dir state freshly stamped (and persisted, along
68
+ * with any pending v1 lift, unless writes are disabled). An unwritable
69
+ * registry root degrades to the computed, un-persisted view (reported
70
+ * via `onWarn`) — a read surface never fails on a persist error. */
71
+ list(opts?: ListOptions): HangarHarnessEntry[];
72
+ /** Look up by absolute dir or `hrn_` id; liveness is recomputed for the
73
+ * returned entry but nothing is persisted. */
74
+ get(dirOrId: string): HangarHarnessEntry | undefined;
75
+ /** Upsert keyed by absolute dir. New entries mint a stable id; refreshes
76
+ * keep `id`/`registeredAt`/`origin` and the user-managed fields
77
+ * (groups/tags/pinned/notes), refresh `lastSeen` and any descriptive
78
+ * fields provided, and clear `missingSince`. */
79
+ upsert(fields: UpsertFields): HangarHarnessEntry;
80
+ /** Remove the registry row only — the directory is never touched. */
81
+ remove(dirOrId: string): boolean;
82
+ /** Point an entry at a new dir (same id), clearing `missingSince`.
83
+ * Throws if `newDir` is already registered to a different entry. */
84
+ relocate(id: string, newDir: string): HangarHarnessEntry | undefined;
85
+ setGroups(dirOrId: string, groups: readonly string[]): HangarHarnessEntry | undefined;
86
+ setTags(dirOrId: string, tags: readonly string[]): HangarHarnessEntry | undefined;
87
+ setPinned(dirOrId: string, pinned: boolean): HangarHarnessEntry | undefined;
88
+ setNotes(dirOrId: string, notes: string): HangarHarnessEntry | undefined;
89
+ listGroups(): GroupDef[];
90
+ /** Idempotent by name; new groups append at the end of the order. */
91
+ addGroup(def: {
92
+ readonly name: string;
93
+ readonly color?: string;
94
+ }): GroupDef;
95
+ /** Rename and/or recolor; a rename rewrites entry membership too.
96
+ * Throws when renaming onto an existing group. */
97
+ updateGroup(name: string, patch: {
98
+ readonly name?: string;
99
+ readonly color?: string;
100
+ }): GroupDef | undefined;
101
+ /** Drops the definition AND strips the name from every entry. */
102
+ removeGroup(name: string): boolean;
103
+ /** Groups listed first in the given order, unlisted ones keep their
104
+ * relative order after; all orders renumbered 1..n. */
105
+ reorderGroups(names: readonly string[]): GroupDef[];
106
+ listScanRoots(): ScanRoot[];
107
+ /** Upsert keyed by absolute dir. Defaults: depth 6, auto true,
108
+ * rescanIntervalMin 15, lastScanAt null. */
109
+ addScanRoot(fields: {
110
+ readonly dir: string;
111
+ readonly depth?: number;
112
+ readonly auto?: boolean;
113
+ readonly rescanIntervalMin?: number;
114
+ }): ScanRoot;
115
+ updateScanRoot(dir: string, patch: Partial<Pick<ScanRoot, "depth" | "auto" | "rescanIntervalMin" | "lastScanAt">>): ScanRoot | undefined;
116
+ removeScanRoot(dir: string): boolean;
117
+ /** The best-effort self-registration entry point for CLI hooks: never
118
+ * throws, respects `CREWHAUS_NO_REGISTRY`, registers with origin
119
+ * `run-hook`. */
120
+ registerHook(fields: RegisterHookFields): RegisterHookResult;
121
+ /** One-time merge of the legacy watchme registry (idempotent — safe to
122
+ * call every boot; already-registered dirs are left untouched). Imported
123
+ * entries get origin `import` / originDetail `watchme`. */
124
+ seedFromWatchme(): {
125
+ imported: number;
126
+ };
127
+ };
128
+ /** Resolve the registry ROOT directory (the one containing
129
+ * `harnesses.json`): `CREWHAUS_REGISTRY_ROOT` or `~/.crewhaus`. */
130
+ export declare function resolveRegistryRoot(env?: Readonly<Record<string, string | undefined>>): string;
131
+ /** Open the registry (file created lazily on first write). */
132
+ export declare function openHangarRegistry(opts?: OpenHangarRegistryOptions): HangarRegistry;
133
+ /**
134
+ * The ~10-line CLI-hook entry point: open the default registry and record
135
+ * that a command touched `dir`. Never throws — any failure (including a
136
+ * broken registry root) is swallowed into `{ ok: false }`, because a
137
+ * registry write must never fail the command that triggered it. Respects
138
+ * `CREWHAUS_NO_REGISTRY`.
139
+ */
140
+ export declare function registerHarnessHook(fields: RegisterHookFields, opts?: OpenHangarRegistryOptions): RegisterHookResult;
@@ -0,0 +1,596 @@
1
+ /**
2
+ * The machine-wide harness registry — one JSON document
3
+ * (`<registryRoot>/harnesses.json`, format v2) listing every harness the
4
+ * user has registered on this machine, plus scan roots and group
5
+ * definitions.
6
+ *
7
+ * Roots and switches:
8
+ * - registry root: `CREWHAUS_REGISTRY_ROOT` (the DIRECTORY containing
9
+ * `harnesses.json`), default `~/.crewhaus`; an explicit `root` option
10
+ * wins over the env var.
11
+ * - `CREWHAUS_NO_REGISTRY=1` — global opt-out: every write becomes a
12
+ * no-op while reads keep working.
13
+ *
14
+ * Write discipline (the watchme-store registry posture, promoted):
15
+ * - atomic tmp+rename with a per-writer-unique tmp name, file mode 0600,
16
+ * directory mode 0700;
17
+ * - read-merge-write with a small fingerprint-checked retry loop so two
18
+ * same-machine writers do not lose each other's rows;
19
+ * - vanished directories are NEVER silently pruned — `list()` stamps
20
+ * `missingSince` (and clears it when the dir is back), and only an
21
+ * explicit `remove()` deletes a row.
22
+ *
23
+ * watchme interop: `seedFromWatchme()` merges the legacy watchme registry
24
+ * in once (idempotent, safe every boot), and `upsert`/`relocate` MIRROR
25
+ * freshness (dir/specName/target) onto a watchme row that ALREADY exists,
26
+ * best-effort. Hangar-side writes never create a watchme row, never delete
27
+ * one, and never touch `share`/`agentId` — watchme membership means
28
+ * "explicitly watched" and belongs to the watchme verbs (`watchme start`,
29
+ * `watchme stop --forget`) alone. The mirror uses `@crewhaus/watchme-store`'s
30
+ * own API — this package never touches the watchme file format directly.
31
+ */
32
+ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from "node:fs";
33
+ import { homedir } from "node:os";
34
+ import { basename, join, resolve } from "node:path";
35
+ import { openHarnessRegistry as openWatchmeRegistry } from "@crewhaus/watchme-store";
36
+ import { EMPTY_DOC, HARNESS_ID_RE, REGISTRY_FILENAME, fingerprintPath, mintHarnessId, normalizeDoc, sleepSync, sortDoc, } from "./doc.js";
37
+ /** Resolve the registry ROOT directory (the one containing
38
+ * `harnesses.json`): `CREWHAUS_REGISTRY_ROOT` or `~/.crewhaus`. */
39
+ export function resolveRegistryRoot(env = process.env) {
40
+ const fromEnv = env["CREWHAUS_REGISTRY_ROOT"];
41
+ if (fromEnv !== undefined && fromEnv.length > 0)
42
+ return resolve(fromEnv);
43
+ return join(homedir(), ".crewhaus");
44
+ }
45
+ const MAX_WRITE_ATTEMPTS = 5;
46
+ /** Open the registry (file created lazily on first write). */
47
+ export function openHangarRegistry(opts = {}) {
48
+ const env = opts.env ?? process.env;
49
+ const root = opts.root !== undefined ? resolve(opts.root) : resolveRegistryRoot(env);
50
+ const watchmeEnv = env["CREWHAUS_WATCHME_ROOT"];
51
+ const watchmeRoot = opts.watchmeRoot ??
52
+ (watchmeEnv !== undefined && watchmeEnv.length > 0
53
+ ? resolve(watchmeEnv)
54
+ : join(homedir(), ".crewhaus", "watchme"));
55
+ const noRegistry = env["CREWHAUS_NO_REGISTRY"];
56
+ const disabled = noRegistry === "1" || noRegistry === "true";
57
+ const path = join(root, REGISTRY_FILENAME);
58
+ const now = opts.now ?? Date.now;
59
+ const onWarn = opts.onWarn ?? (() => { });
60
+ const afterRead = opts.hooks?.afterRead;
61
+ const nowIso = () => new Date(now()).toISOString();
62
+ // Ids minted for a dir stay stable within this handle even before they
63
+ // are persisted (e.g. repeated reads of a v1 doc under NO_REGISTRY).
64
+ const mintCache = new Map();
65
+ const mint = (dir, taken) => {
66
+ const cached = mintCache.get(dir);
67
+ if (cached !== undefined && !taken.has(cached)) {
68
+ taken.add(cached);
69
+ return cached;
70
+ }
71
+ const id = mintHarnessId(taken);
72
+ taken.add(id);
73
+ mintCache.set(dir, id);
74
+ return id;
75
+ };
76
+ const read = () => {
77
+ const fp = fingerprintPath(path);
78
+ let existed = false;
79
+ let healable = false;
80
+ let parsed;
81
+ try {
82
+ const text = readFileSync(path, "utf8");
83
+ existed = true;
84
+ parsed = JSON.parse(text);
85
+ healable = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed);
86
+ }
87
+ catch {
88
+ // Missing file → empty registry; unreadable/garbage file → empty view,
89
+ // healed wholesale by the next write (watchme posture — never healed
90
+ // by a read, in case the content is hand-recoverable).
91
+ parsed = undefined;
92
+ }
93
+ const { doc, lifted } = healable
94
+ ? normalizeDoc(parsed, { nowIso: nowIso(), mint })
95
+ : { doc: EMPTY_DOC, lifted: false };
96
+ afterRead?.();
97
+ return { doc, existed, healable, lifted, fp };
98
+ };
99
+ const writeDoc = (doc) => {
100
+ if (!existsSync(root))
101
+ mkdirSync(root, { recursive: true, mode: 0o700 });
102
+ // Per-writer-unique tmp name: two concurrent writers must never share a
103
+ // staging file, or one could rename the other's half-written content.
104
+ const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`;
105
+ writeFileSync(tmp, `${JSON.stringify(sortDoc(doc), null, 2)}\n`, { mode: 0o600 });
106
+ try {
107
+ renameSync(tmp, path);
108
+ }
109
+ catch (err) {
110
+ try {
111
+ unlinkSync(tmp);
112
+ }
113
+ catch {
114
+ // Best-effort tmp cleanup; the original error is what matters.
115
+ }
116
+ throw err;
117
+ }
118
+ };
119
+ /** Read-merge-write with a fingerprint-checked retry loop: if another
120
+ * writer landed between our read and our rename, re-read and re-apply
121
+ * rather than clobbering their rows. Disabled mode computes the result
122
+ * against the current file but never writes. `degradeOnWriteError` is for
123
+ * read-triggered persists (list()'s stamp/lift heals): a failing write
124
+ * (EROFS, EACCES, ENOSPC) warns and returns the computed view un-persisted
125
+ * — mirroring the disabled path — instead of failing a semantic read. */
126
+ const mutate = (fn, mutateOpts = {}) => {
127
+ if (disabled) {
128
+ const out = fn(read());
129
+ return { result: out.result, wrote: false };
130
+ }
131
+ const tryWrite = (doc) => {
132
+ try {
133
+ writeDoc(doc);
134
+ return true;
135
+ }
136
+ catch (err) {
137
+ if (mutateOpts.degradeOnWriteError !== true)
138
+ throw err;
139
+ onWarn(`harness-registry: could not persist to ${path} (continuing with the un-persisted view): ${err instanceof Error ? err.message : String(err)}`);
140
+ return false;
141
+ }
142
+ };
143
+ for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt++) {
144
+ const state = read();
145
+ const out = fn(state);
146
+ if (!out.write)
147
+ return { result: out.result, wrote: false };
148
+ if (fingerprintPath(path) !== state.fp) {
149
+ sleepSync(1 + attempt * 2);
150
+ continue;
151
+ }
152
+ return { result: out.result, wrote: tryWrite(out.doc) };
153
+ }
154
+ // Contention exhausted the retries: land last-writer-wins on a final
155
+ // fresh read (still merge-based, so only same-instant races can lose).
156
+ const state = read();
157
+ const out = fn(state);
158
+ if (!out.write)
159
+ return { result: out.result, wrote: false };
160
+ return { result: out.result, wrote: tryWrite(out.doc) };
161
+ };
162
+ const findEntry = (doc, dirOrId) => HARNESS_ID_RE.test(dirOrId)
163
+ ? doc.harnesses.find((e) => e.id === dirOrId)
164
+ : doc.harnesses.find((e) => e.dir === resolve(dirOrId));
165
+ const replaceEntry = (doc, entry) => ({
166
+ ...doc,
167
+ harnesses: [...doc.harnesses.filter((e) => e.id !== entry.id), entry],
168
+ });
169
+ // ---- watchme mirror (best-effort, never fails the primary write) --------
170
+ const watchme = () => openWatchmeRegistry(watchmeRoot, { now, onWarn: () => { } });
171
+ const warnInterop = (op, err) => onWarn(`harness-registry: watchme ${op} write-through failed: ${err instanceof Error ? err.message : String(err)}`);
172
+ /**
173
+ * Freshness-only mirror: refresh the dir/specName/target of a watchme row
174
+ * that ALREADY exists, and nothing else. A hangar-side write never CREATES
175
+ * a watchme row (membership means "explicitly watched" — only the watchme
176
+ * verbs enroll, so `watchme stop --forget` stays durable) and never
177
+ * touches `share`/`agentId` (those belong to the watchme verbs too — a
178
+ * fresh hangar row defaulting share:false must not clobber an enrolled
179
+ * share:true). `previousDir` handles relocate: the pre-existing row is
180
+ * looked up at the OLD dir and moved.
181
+ */
182
+ const watchmeRefresh = (entry, previousDir) => {
183
+ try {
184
+ const reg = watchme();
185
+ const fromDir = previousDir ?? entry.dir;
186
+ const prev = reg.list().find((e) => e.dir === fromDir);
187
+ if (prev === undefined)
188
+ return; // never explicitly watched — never create
189
+ if (previousDir !== undefined && previousDir !== entry.dir)
190
+ reg.deregister(previousDir);
191
+ reg.register({
192
+ dir: entry.dir,
193
+ specName: entry.specName,
194
+ target: entry.target,
195
+ ...(prev.share !== undefined ? { share: prev.share } : {}),
196
+ ...(prev.agentId !== undefined ? { agentId: prev.agentId } : {}),
197
+ });
198
+ }
199
+ catch (err) {
200
+ warnInterop("register", err);
201
+ }
202
+ };
203
+ // ---- API ----------------------------------------------------------------
204
+ const list = (listOpts = {}) => {
205
+ const includeMissing = listOpts.includeMissing !== false;
206
+ const stampIso = nowIso();
207
+ const { result } = mutate((state) => {
208
+ let stampsChanged = false;
209
+ const entries = state.doc.harnesses.map((entry) => {
210
+ const alive = existsSync(entry.dir);
211
+ if (!alive && entry.missingSince === null) {
212
+ stampsChanged = true;
213
+ return { ...entry, missingSince: stampIso };
214
+ }
215
+ if (alive && entry.missingSince !== null) {
216
+ stampsChanged = true;
217
+ return { ...entry, missingSince: null };
218
+ }
219
+ return entry;
220
+ });
221
+ // Persist when stamps moved, or to heal a pre-v2 / id-less document.
222
+ // A registry that has never been written is NOT created by a read.
223
+ const write = stampsChanged || (state.existed && state.healable && state.lifted);
224
+ return { doc: { ...state.doc, harnesses: entries }, result: entries, write };
225
+ // degrade: list() is semantically a READ — an unwritable registry root
226
+ // (root-owned ~/.crewhaus, read-only home fs, disk full) must not take
227
+ // down every read surface just because a stamp/lift wanted persisting.
228
+ }, { degradeOnWriteError: true });
229
+ const sorted = [...result].sort((a, b) => a.dir.localeCompare(b.dir));
230
+ return includeMissing ? sorted : sorted.filter((e) => e.missingSince === null);
231
+ };
232
+ const get = (dirOrId) => {
233
+ const entry = findEntry(read().doc, dirOrId);
234
+ if (entry === undefined)
235
+ return undefined;
236
+ const alive = existsSync(entry.dir);
237
+ if (!alive && entry.missingSince === null)
238
+ return { ...entry, missingSince: nowIso() };
239
+ if (alive && entry.missingSince !== null)
240
+ return { ...entry, missingSince: null };
241
+ return entry;
242
+ };
243
+ const upsert = (fields) => {
244
+ const dir = resolve(fields.dir);
245
+ const stampIso = nowIso();
246
+ const { result, wrote } = mutate((state) => {
247
+ const existing = state.doc.harnesses.find((e) => e.dir === dir);
248
+ let entry;
249
+ if (existing !== undefined) {
250
+ entry = {
251
+ ...existing,
252
+ specName: fields.specName ?? existing.specName,
253
+ target: fields.target ?? existing.target,
254
+ kind: fields.kind ?? existing.kind,
255
+ watchme: fields.watchme !== undefined
256
+ ? { ...existing.watchme, share: fields.watchme.share }
257
+ : existing.watchme,
258
+ remotes: fields.remotes !== undefined ? [...fields.remotes] : existing.remotes,
259
+ lastSeen: stampIso,
260
+ missingSince: null,
261
+ };
262
+ }
263
+ else {
264
+ const taken = new Set(state.doc.harnesses.map((e) => e.id));
265
+ entry = {
266
+ id: mint(dir, taken),
267
+ dir,
268
+ specName: fields.specName ?? basename(dir),
269
+ target: fields.target ?? "unknown",
270
+ origin: fields.origin ?? "manual",
271
+ originDetail: fields.originDetail ?? "",
272
+ registeredAt: stampIso,
273
+ lastSeen: stampIso,
274
+ groups: [...(fields.groups ?? [])],
275
+ tags: [...(fields.tags ?? [])],
276
+ pinned: fields.pinned ?? false,
277
+ notes: fields.notes ?? "",
278
+ kind: fields.kind ?? "local",
279
+ watchme: { share: fields.watchme?.share ?? false },
280
+ remotes: fields.remotes !== undefined ? [...fields.remotes] : [],
281
+ missingSince: null,
282
+ };
283
+ }
284
+ return {
285
+ doc: {
286
+ ...state.doc,
287
+ harnesses: [...state.doc.harnesses.filter((e) => e.dir !== dir), entry],
288
+ },
289
+ result: entry,
290
+ write: true,
291
+ };
292
+ });
293
+ if (wrote)
294
+ watchmeRefresh(result);
295
+ return result;
296
+ };
297
+ const remove = (dirOrId) => {
298
+ const { result, wrote } = mutate((state) => {
299
+ const entry = findEntry(state.doc, dirOrId);
300
+ if (entry === undefined)
301
+ return { doc: state.doc, result: undefined, write: false };
302
+ return {
303
+ doc: { ...state.doc, harnesses: state.doc.harnesses.filter((e) => e.id !== entry.id) },
304
+ result: entry,
305
+ write: true,
306
+ };
307
+ });
308
+ // Deliberately NO watchme mirror: removing a hangar row never
309
+ // un-watches a harness the user explicitly enrolled.
310
+ return wrote && result !== undefined;
311
+ };
312
+ const relocate = (id, newDir) => {
313
+ const dir = resolve(newDir);
314
+ const stampIso = nowIso();
315
+ let oldDir;
316
+ const { result, wrote } = mutate((state) => {
317
+ const entry = state.doc.harnesses.find((e) => e.id === id);
318
+ if (entry === undefined)
319
+ return { doc: state.doc, result: undefined, write: false };
320
+ const conflict = state.doc.harnesses.find((e) => e.dir === dir && e.id !== id);
321
+ if (conflict !== undefined) {
322
+ throw new Error(`harness-registry: cannot relocate ${id} to ${dir} — already registered as ${conflict.id}`);
323
+ }
324
+ oldDir = entry.dir;
325
+ const next = { ...entry, dir, missingSince: null, lastSeen: stampIso };
326
+ return { doc: replaceEntry(state.doc, next), result: next, write: true };
327
+ });
328
+ if (wrote && result !== undefined && oldDir !== undefined && oldDir !== result.dir) {
329
+ // Move a PRE-EXISTING watchme row along with the relocate (a dir
330
+ // refresh of an explicitly-watched harness); never creates one.
331
+ watchmeRefresh(result, oldDir);
332
+ }
333
+ return result;
334
+ };
335
+ const patchEntry = (dirOrId, patch) => {
336
+ const { result } = mutate((state) => {
337
+ const entry = findEntry(state.doc, dirOrId);
338
+ if (entry === undefined)
339
+ return { doc: state.doc, result: undefined, write: false };
340
+ const next = patch(entry);
341
+ return { doc: replaceEntry(state.doc, next), result: next, write: true };
342
+ });
343
+ return result;
344
+ };
345
+ const mutateGroups = (fn) => {
346
+ const { result } = mutate((state) => {
347
+ const out = fn(state.doc.groups, state);
348
+ return {
349
+ doc: {
350
+ ...state.doc,
351
+ groups: [...out.groups],
352
+ harnesses: out.harnesses !== undefined ? [...out.harnesses] : state.doc.harnesses,
353
+ },
354
+ result: out.result,
355
+ write: out.write,
356
+ };
357
+ });
358
+ return result;
359
+ };
360
+ const addGroup = (def) => mutateGroups((groups) => {
361
+ const existing = groups.find((g) => g.name === def.name);
362
+ if (existing !== undefined) {
363
+ if (def.color !== undefined && def.color !== existing.color) {
364
+ const next = { ...existing, color: def.color };
365
+ return {
366
+ groups: groups.map((g) => (g.name === def.name ? next : g)),
367
+ result: next,
368
+ write: true,
369
+ };
370
+ }
371
+ return { groups, result: existing, write: false };
372
+ }
373
+ const order = groups.reduce((max, g) => Math.max(max, g.order), 0) + 1;
374
+ const next = { name: def.name, order, color: def.color ?? "" };
375
+ return { groups: [...groups, next], result: next, write: true };
376
+ });
377
+ const updateGroup = (name, patch) => mutateGroups((groups, state) => {
378
+ const existing = groups.find((g) => g.name === name);
379
+ if (existing === undefined)
380
+ return { groups, result: undefined, write: false };
381
+ const nextName = patch.name ?? existing.name;
382
+ if (nextName !== name && groups.some((g) => g.name === nextName)) {
383
+ throw new Error(`harness-registry: group "${nextName}" already exists`);
384
+ }
385
+ const next = { ...existing, name: nextName, color: patch.color ?? existing.color };
386
+ const harnesses = nextName === name
387
+ ? undefined
388
+ : state.doc.harnesses.map((e) => e.groups.includes(name)
389
+ ? { ...e, groups: e.groups.map((g) => (g === name ? nextName : g)) }
390
+ : e);
391
+ return {
392
+ groups: groups.map((g) => (g.name === name ? next : g)),
393
+ ...(harnesses !== undefined ? { harnesses } : {}),
394
+ result: next,
395
+ write: true,
396
+ };
397
+ });
398
+ const removeGroup = (name) => mutateGroups((groups, state) => {
399
+ if (!groups.some((g) => g.name === name))
400
+ return { groups, result: false, write: false };
401
+ const harnesses = state.doc.harnesses.map((e) => e.groups.includes(name) ? { ...e, groups: e.groups.filter((g) => g !== name) } : e);
402
+ return {
403
+ groups: groups.filter((g) => g.name !== name),
404
+ harnesses,
405
+ result: true,
406
+ write: true,
407
+ };
408
+ });
409
+ const reorderGroups = (names) => mutateGroups((groups) => {
410
+ const byOrder = [...groups].sort((a, b) => a.order - b.order || a.name.localeCompare(b.name));
411
+ const listed = names
412
+ .map((name) => byOrder.find((g) => g.name === name))
413
+ .filter((g) => g !== undefined);
414
+ const rest = byOrder.filter((g) => !names.includes(g.name));
415
+ const next = [...listed, ...rest].map((g, index) => ({ ...g, order: index + 1 }));
416
+ return { groups: next, result: next, write: next.length > 0 };
417
+ });
418
+ const listGroups = () => [...read().doc.groups].sort((a, b) => a.order - b.order || a.name.localeCompare(b.name));
419
+ const addScanRoot = (fields) => {
420
+ const dir = resolve(fields.dir);
421
+ const { result } = mutate((state) => {
422
+ const existing = state.doc.scanRoots.find((r) => r.dir === dir);
423
+ const next = existing !== undefined
424
+ ? {
425
+ ...existing,
426
+ depth: fields.depth ?? existing.depth,
427
+ auto: fields.auto ?? existing.auto,
428
+ rescanIntervalMin: fields.rescanIntervalMin ?? existing.rescanIntervalMin,
429
+ }
430
+ : {
431
+ dir,
432
+ depth: fields.depth ?? 6,
433
+ auto: fields.auto ?? true,
434
+ rescanIntervalMin: fields.rescanIntervalMin ?? 15,
435
+ lastScanAt: null,
436
+ };
437
+ return {
438
+ doc: {
439
+ ...state.doc,
440
+ scanRoots: [...state.doc.scanRoots.filter((r) => r.dir !== dir), next],
441
+ },
442
+ result: next,
443
+ write: true,
444
+ };
445
+ });
446
+ return result;
447
+ };
448
+ const updateScanRoot = (dirRaw, patch) => {
449
+ const dir = resolve(dirRaw);
450
+ const { result } = mutate((state) => {
451
+ const existing = state.doc.scanRoots.find((r) => r.dir === dir);
452
+ if (existing === undefined)
453
+ return { doc: state.doc, result: undefined, write: false };
454
+ const next = {
455
+ ...existing,
456
+ depth: patch.depth ?? existing.depth,
457
+ auto: patch.auto ?? existing.auto,
458
+ rescanIntervalMin: patch.rescanIntervalMin ?? existing.rescanIntervalMin,
459
+ lastScanAt: patch.lastScanAt !== undefined ? patch.lastScanAt : existing.lastScanAt,
460
+ };
461
+ return {
462
+ doc: {
463
+ ...state.doc,
464
+ scanRoots: state.doc.scanRoots.map((r) => (r.dir === dir ? next : r)),
465
+ },
466
+ result: next,
467
+ write: true,
468
+ };
469
+ });
470
+ return result;
471
+ };
472
+ const removeScanRoot = (dirRaw) => {
473
+ const dir = resolve(dirRaw);
474
+ const { result } = mutate((state) => {
475
+ if (!state.doc.scanRoots.some((r) => r.dir === dir)) {
476
+ return { doc: state.doc, result: false, write: false };
477
+ }
478
+ return {
479
+ doc: { ...state.doc, scanRoots: state.doc.scanRoots.filter((r) => r.dir !== dir) },
480
+ result: true,
481
+ write: true,
482
+ };
483
+ });
484
+ return result;
485
+ };
486
+ const listScanRoots = () => [...read().doc.scanRoots].sort((a, b) => a.dir.localeCompare(b.dir));
487
+ const registerHook = (fields) => {
488
+ try {
489
+ if (disabled)
490
+ return { ok: false, error: "registry disabled (CREWHAUS_NO_REGISTRY)" };
491
+ const entry = upsert({
492
+ dir: fields.dir,
493
+ specName: fields.specName,
494
+ target: fields.target,
495
+ origin: "run-hook",
496
+ originDetail: fields.originDetail,
497
+ });
498
+ return { ok: true, id: entry.id };
499
+ }
500
+ catch (err) {
501
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
502
+ }
503
+ };
504
+ const seedFromWatchme = () => {
505
+ if (disabled)
506
+ return { imported: 0 };
507
+ let source;
508
+ try {
509
+ source = watchme().list();
510
+ }
511
+ catch (err) {
512
+ warnInterop("seed", err);
513
+ return { imported: 0 };
514
+ }
515
+ if (source.length === 0)
516
+ return { imported: 0 };
517
+ const { result } = mutate((state) => {
518
+ const have = new Set(state.doc.harnesses.map((e) => e.dir));
519
+ const taken = new Set(state.doc.harnesses.map((e) => e.id));
520
+ const added = [];
521
+ for (const src of source) {
522
+ const dir = resolve(src.dir);
523
+ if (have.has(dir))
524
+ continue;
525
+ have.add(dir);
526
+ added.push({
527
+ id: mint(dir, taken),
528
+ dir,
529
+ specName: src.specName,
530
+ target: src.target,
531
+ origin: "import",
532
+ originDetail: "watchme",
533
+ registeredAt: new Date(src.registeredAt).toISOString(),
534
+ lastSeen: new Date(src.lastSeen).toISOString(),
535
+ groups: [],
536
+ tags: [],
537
+ pinned: false,
538
+ notes: "",
539
+ kind: "local",
540
+ watchme: { share: src.share === true },
541
+ remotes: [],
542
+ missingSince: null,
543
+ // Kept as a pass-through field so a later delegation round-trips it.
544
+ ...(src.agentId !== undefined ? { agentId: src.agentId } : {}),
545
+ });
546
+ }
547
+ if (added.length === 0)
548
+ return { doc: state.doc, result: 0, write: false };
549
+ return {
550
+ doc: { ...state.doc, harnesses: [...state.doc.harnesses, ...added] },
551
+ result: added.length,
552
+ write: true,
553
+ };
554
+ });
555
+ return { imported: result };
556
+ };
557
+ return {
558
+ path,
559
+ disabled,
560
+ list,
561
+ get,
562
+ upsert,
563
+ remove,
564
+ relocate,
565
+ setGroups: (dirOrId, groups) => patchEntry(dirOrId, (e) => ({ ...e, groups: [...groups] })),
566
+ setTags: (dirOrId, tags) => patchEntry(dirOrId, (e) => ({ ...e, tags: [...tags] })),
567
+ setPinned: (dirOrId, pinned) => patchEntry(dirOrId, (e) => ({ ...e, pinned })),
568
+ setNotes: (dirOrId, notes) => patchEntry(dirOrId, (e) => ({ ...e, notes })),
569
+ listGroups,
570
+ addGroup,
571
+ updateGroup,
572
+ removeGroup,
573
+ reorderGroups,
574
+ listScanRoots,
575
+ addScanRoot,
576
+ updateScanRoot,
577
+ removeScanRoot,
578
+ registerHook,
579
+ seedFromWatchme,
580
+ };
581
+ }
582
+ /**
583
+ * The ~10-line CLI-hook entry point: open the default registry and record
584
+ * that a command touched `dir`. Never throws — any failure (including a
585
+ * broken registry root) is swallowed into `{ ok: false }`, because a
586
+ * registry write must never fail the command that triggered it. Respects
587
+ * `CREWHAUS_NO_REGISTRY`.
588
+ */
589
+ export function registerHarnessHook(fields, opts = {}) {
590
+ try {
591
+ return openHangarRegistry(opts).registerHook(fields);
592
+ }
593
+ catch (err) {
594
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
595
+ }
596
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Record schemas for the machine-wide harness registry file
3
+ * (`<registryRoot>/harnesses.json`, format `v: 2`).
4
+ *
5
+ * Format discipline is ADDITIVE: every shape carries an index signature so
6
+ * fields written by a newer CLI are tolerated on read and preserved verbatim
7
+ * on rewrite — an older CLI must never strip what a newer one recorded.
8
+ * Documents with `v < 2` (or no `v` at all — the legacy watchme-format
9
+ * registry) are lifted best-effort on read; the lift persists on the next
10
+ * write.
11
+ *
12
+ * This package is a pure registry-file layer: it never parses specs and
13
+ * never scans the filesystem for harnesses. Callers supply `specName` and
14
+ * `target`; discovery lives elsewhere.
15
+ */
16
+ /** How an entry first got into the registry. Stable across refreshes. */
17
+ export type HarnessOrigin = "scan" | "manual" | "run-hook" | "import";
18
+ /** Local checkout vs a remote deployment-pointer row. */
19
+ export type HarnessKind = "local" | "remote";
20
+ /** One registered harness. Identity is the absolute `dir` (the upsert key); */
21
+ /** `id` is minted once on first registration and stays stable thereafter. */
22
+ export type HangarHarnessEntry = {
23
+ /** `hrn_` + 16 lowercase hex, crypto-random; stable across renames. */
24
+ readonly id: string;
25
+ /** Absolute harness directory — THE upsert identity key. */
26
+ readonly dir: string;
27
+ /** Spec `name:` as supplied by the caller; refreshed on touch. */
28
+ readonly specName: string;
29
+ /** Target shape as supplied by the caller; refreshed on touch. */
30
+ readonly target: string;
31
+ readonly origin: HarnessOrigin;
32
+ /** e.g. `run|compile|eval|dev` for `run-hook`, `watchme` for `import`. */
33
+ readonly originDetail: string;
34
+ /** ISO 8601; set once at first registration. */
35
+ readonly registeredAt: string;
36
+ /** ISO 8601; refreshed on every upsert. */
37
+ readonly lastSeen: string;
38
+ /** User-managed; never clobbered by an upsert refresh. */
39
+ readonly groups: readonly string[];
40
+ /** User-managed; never clobbered by an upsert refresh. */
41
+ readonly tags: readonly string[];
42
+ /** User-managed; pinned entries survive prune prompts. */
43
+ readonly pinned: boolean;
44
+ /** User-managed free text; never clobbered by an upsert refresh. */
45
+ readonly notes: string;
46
+ readonly kind: HarnessKind;
47
+ /** Carried through for watchme registry compatibility. */
48
+ readonly watchme: {
49
+ readonly share: boolean;
50
+ readonly [extra: string]: unknown;
51
+ };
52
+ /** Opaque deployment-pointer objects; passed through untouched. */
53
+ readonly remotes: ReadonlyArray<Readonly<Record<string, unknown>>>;
54
+ /** ISO 8601 stamped when the dir vanishes; cleared when it is back.
55
+ * Vanished entries are NEVER silently pruned from the file. */
56
+ readonly missingSince: string | null;
57
+ /** Unknown fields from newer writers, preserved on rewrite. */
58
+ readonly [extra: string]: unknown;
59
+ };
60
+ /** One user-configured scan root (walked by the inventory layer, not here). */
61
+ export type ScanRoot = {
62
+ /** Absolute directory to walk. */
63
+ readonly dir: string;
64
+ readonly depth: number;
65
+ readonly auto: boolean;
66
+ readonly rescanIntervalMin: number;
67
+ /** ISO 8601 of the last completed walk, or null if never walked. */
68
+ readonly lastScanAt: string | null;
69
+ readonly [extra: string]: unknown;
70
+ };
71
+ /** One flat, ordered, colored group definition. */
72
+ export type GroupDef = {
73
+ readonly name: string;
74
+ /** 1-based display order. */
75
+ readonly order: number;
76
+ /** CSS color string; empty when unset. */
77
+ readonly color: string;
78
+ readonly [extra: string]: unknown;
79
+ };
80
+ /** The whole `harnesses.json` document. */
81
+ export type HangarRegistryDoc = {
82
+ readonly v: 2;
83
+ readonly harnesses: readonly HangarHarnessEntry[];
84
+ readonly scanRoots: readonly ScanRoot[];
85
+ readonly groups: readonly GroupDef[];
86
+ readonly [extra: string]: unknown;
87
+ };
package/dist/types.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Record schemas for the machine-wide harness registry file
3
+ * (`<registryRoot>/harnesses.json`, format `v: 2`).
4
+ *
5
+ * Format discipline is ADDITIVE: every shape carries an index signature so
6
+ * fields written by a newer CLI are tolerated on read and preserved verbatim
7
+ * on rewrite — an older CLI must never strip what a newer one recorded.
8
+ * Documents with `v < 2` (or no `v` at all — the legacy watchme-format
9
+ * registry) are lifted best-effort on read; the lift persists on the next
10
+ * write.
11
+ *
12
+ * This package is a pure registry-file layer: it never parses specs and
13
+ * never scans the filesystem for harnesses. Callers supply `specName` and
14
+ * `target`; discovery lives elsewhere.
15
+ */
16
+ export {};
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@crewhaus/harness-registry",
3
+ "version": "0.5.0",
4
+ "type": "module",
5
+ "description": "Machine-wide harness registry (harnesses.json v2) — stable hrn_ ids, groups/tags/pins, scan roots, missing-dir stamping, and watchme registry interop behind the harness manager",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "test": "bun test src"
16
+ },
17
+ "dependencies": {
18
+ "@crewhaus/watchme-store": "0.5.0"
19
+ },
20
+ "license": "Apache-2.0",
21
+ "author": {
22
+ "name": "Max Meier",
23
+ "email": "max@crewhaus.ai",
24
+ "url": "https://crewhaus.ai"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/crewhaus/factory.git",
29
+ "directory": "packages/harness-registry"
30
+ },
31
+ "homepage": "https://github.com/crewhaus/factory/tree/main/packages/harness-registry#readme",
32
+ "bugs": {
33
+ "url": "https://github.com/crewhaus/factory/issues"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "files": ["dist", "README.md", "LICENSE", "NOTICE"]
39
+ }