@rbbtsn0w/adg 0.7.2-beta.2 → 0.8.0-beta.2

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.
@@ -0,0 +1,250 @@
1
+ import { lstatSync, mkdirSync, readFileSync, readlinkSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync, cpSync } from "node:fs";
2
+ import { dirname, join, relative, resolve } from "node:path";
3
+ import { ensureDir } from "./fsutil.js";
4
+ /** Exported so tests assert against this exact string instead of duplicating it. */
5
+ export const FOREIGN_REASON = "a real, non-ADG-owned directory or file already exists at this path";
6
+ /**
7
+ * Only the variant's `kind` is included in the thrown message, never the
8
+ * full object: a `SlotObservation`/`SlotDesire`/`SlotAction` can carry a
9
+ * `target` (a filesystem path), and this path is meant to be unreachable —
10
+ * if it's ever hit anyway (a bug, or a caller bypassing the type checker),
11
+ * the error shouldn't be the thing that leaks a path into a log or an
12
+ * uncaught-exception report.
13
+ */
14
+ function assertNever(x) {
15
+ const kind = typeof x === "object" && x !== null && "kind" in x ? String(x.kind) : "unknown";
16
+ throw new Error(`unreachable projection state: ${kind}`);
17
+ }
18
+ export function reconcileSlot(desired, observed) {
19
+ if (desired.kind === "in-place")
20
+ return { kind: "noop" };
21
+ if (desired.kind === "absent") {
22
+ switch (observed.kind) {
23
+ case "absent": return { kind: "noop" };
24
+ case "symlink": return { kind: "remove-link" };
25
+ case "owned-dir": return { kind: "remove-link" };
26
+ case "foreign": return { kind: "skip-foreign", reason: FOREIGN_REASON }; // not ours; can't confirm "absent"
27
+ default: return assertNever(observed);
28
+ }
29
+ }
30
+ if (desired.kind === "linked") {
31
+ switch (observed.kind) {
32
+ case "absent": return { kind: "create-link", target: desired.target };
33
+ case "symlink":
34
+ if (observed.broken)
35
+ return { kind: "relink", target: desired.target };
36
+ return observed.target === desired.target
37
+ ? { kind: "noop" }
38
+ : { kind: "relink", target: desired.target };
39
+ case "owned-dir": return { kind: "relink", target: desired.target };
40
+ case "foreign": return { kind: "skip-foreign", reason: FOREIGN_REASON };
41
+ default: return assertNever(observed);
42
+ }
43
+ }
44
+ return assertNever(desired);
45
+ }
46
+ // ── IO layer ─────────────────────────────────────────────────────────────
47
+ /**
48
+ * Marker file written at the root of every copy-fallback directory this
49
+ * module creates (`<dir>/.adg-owned`), so a later `observeSlot` can tell it
50
+ * apart from a same-shaped foreign directory — a real (non-symlink) dir
51
+ * otherwise carries no signal of who created it. Exported so a caller that
52
+ * needs to construct the marker path itself (e.g. to exclude it from a
53
+ * content listing) doesn't have to duplicate the filename.
54
+ */
55
+ export const OWNERSHIP_MARKER = ".adg-owned";
56
+ /**
57
+ * A directory merely named `.adg-owned` proves nothing — a foreign directory
58
+ * could coincidentally contain that name, or someone could create it
59
+ * deliberately, and either way `observeSlot` would misclassify real content
60
+ * as ours to `remove-link`/`relink`. Require exact content, not just
61
+ * presence, so the marker can't be spoofed by an empty or arbitrary file.
62
+ */
63
+ const OWNERSHIP_MARKER_MAGIC = "adg-projection-slot/v1\n";
64
+ function hasOwnershipMarker(path) {
65
+ const markerPath = join(path, OWNERSHIP_MARKER);
66
+ try {
67
+ // lstat first, not just readFileSync (which follows symlinks): a
68
+ // foreign directory could plant `.adg-owned` as a symlink to some other
69
+ // file that happens to contain the magic string, spoofing ownership.
70
+ // Require the marker to be a real, non-symlink regular file.
71
+ if (!lstatSync(markerPath).isFile())
72
+ return false;
73
+ return readFileSync(markerPath, "utf8") === OWNERSHIP_MARKER_MAGIC;
74
+ }
75
+ catch (error) {
76
+ if (!isEnoent(error))
77
+ throw error;
78
+ return false;
79
+ }
80
+ }
81
+ /** Rethrow anything but "the path doesn't exist" — an EACCES/EPERM/ENOTDIR
82
+ * on lstat means something real is there and unreadable, not absent; letting
83
+ * a caller treat that as absent risks a write/removal against a path it
84
+ * couldn't actually stat. */
85
+ function isEnoent(error) {
86
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
87
+ }
88
+ function isBrokenLink(path, stat) {
89
+ try {
90
+ stat(path); // follows the link
91
+ return false;
92
+ }
93
+ catch (error) {
94
+ if (!isEnoent(error))
95
+ throw error;
96
+ return true;
97
+ }
98
+ }
99
+ /**
100
+ * Classify what's actually at `path` on disk: one lstat, plus a follow-up
101
+ * stat of the target to determine `broken` for a symlink, or a read of the
102
+ * ownership marker file to distinguish `owned-dir` from `foreign` for a real
103
+ * directory.
104
+ */
105
+ export function observeSlot(path, opts = {}) {
106
+ const lstat = opts.lstat ?? lstatSync;
107
+ const stat = opts.stat ?? statSync;
108
+ let st;
109
+ try {
110
+ st = lstat(path);
111
+ }
112
+ catch (error) {
113
+ if (!isEnoent(error))
114
+ throw error;
115
+ return { kind: "absent" };
116
+ }
117
+ if (st.isSymbolicLink()) {
118
+ return {
119
+ kind: "symlink",
120
+ target: resolve(dirname(path), readlinkSync(path)),
121
+ // stat (follows the link), not existsSync: existsSync reports any
122
+ // failure as false, so an EACCES/EPERM on the target would be read as
123
+ // "broken" and drive a destructive relink. Only ENOENT means broken;
124
+ // anything else rethrows, same as the lstat above.
125
+ broken: isBrokenLink(path, stat),
126
+ };
127
+ }
128
+ if (st.isDirectory() && hasOwnershipMarker(path)) {
129
+ return { kind: "owned-dir" };
130
+ }
131
+ return { kind: "foreign" };
132
+ }
133
+ /**
134
+ * Remove whatever `reconcileSlot` has already established is ours at `path`
135
+ * (a symlink or an owned-dir — never foreign; `remove-link`/`relink` are
136
+ * only ever returned for those two observations). A symlink is trusted and
137
+ * removed outright; a real directory is re-checked for the ownership marker
138
+ * immediately before the recursive delete, rather than fully trusting the
139
+ * caller's already-computed action — the cheap belt-and-suspenders check
140
+ * that actually bounds the blast radius of a caller bug or a stale action.
141
+ *
142
+ * Symlink removal uses `unlinkSync`, not `rmSync(..., { force: true })`: on
143
+ * Node < 24 the latter follows the link, hits `ENOENT` at the (possibly
144
+ * absent) target, and `force` then swallows that error without unlinking
145
+ * the symlink itself — the same quirk `rmIfSymlink` in agents/antigravity.ts
146
+ * works around today.
147
+ */
148
+ function removeOwned(path) {
149
+ let st;
150
+ try {
151
+ st = lstatSync(path);
152
+ }
153
+ catch (error) {
154
+ if (!isEnoent(error))
155
+ throw error;
156
+ return; // already absent
157
+ }
158
+ if (st.isSymbolicLink()) {
159
+ unlinkSync(path);
160
+ return;
161
+ }
162
+ // Re-check right before the recursive delete rather than fully trusting
163
+ // the caller's action: reconcileSlot only ever returns remove-link/relink
164
+ // for a symlink or owned-dir observation, but a caller bug, a stale action
165
+ // computed against an earlier observation, or a race could still reach
166
+ // here with something else — including a plain file, not just a foreign
167
+ // directory. Check that explicitly before hasOwnershipMarker: joining the
168
+ // marker name onto a file path and lstat'ing it throws ENOTDIR, which
169
+ // would otherwise surface in place of this function's own clear refusal.
170
+ if (!st.isDirectory()) {
171
+ throw new Error(`refusing to remove ${path}: it is a real file, not a directory or symlink — ` +
172
+ "removeOwned must only ever be called for a symlink or an owned-dir observation");
173
+ }
174
+ if (!hasOwnershipMarker(path)) {
175
+ throw new Error(`refusing to remove ${path}: it is a real directory without the ADG ownership marker (${OWNERSHIP_MARKER}) — ` +
176
+ "removeOwned must only ever be called for a symlink or an owned-dir observation");
177
+ }
178
+ rmSync(path, { recursive: true, force: true });
179
+ }
180
+ function createLink(path, target, symlink, cp) {
181
+ ensureDir(dirname(path));
182
+ try {
183
+ symlink(relative(dirname(path), target), path, "dir");
184
+ return;
185
+ }
186
+ catch {
187
+ // fall through to the copy fallback below
188
+ }
189
+ // create-link/relink should only ever reach here right after path was
190
+ // confirmed absent (relink's caller already ran removeOwned; create-link's
191
+ // caller only fires on an absent observation) — but don't fully trust
192
+ // that: a race against another process, or a caller bug, could still land
193
+ // real content here between the observation and this call. Refuse to copy
194
+ // into/over it rather than silently merging or overwriting.
195
+ if (observeSlot(path).kind !== "absent") {
196
+ throw new Error(`refusing copy-fallback at ${path}: expected it to be absent, but something is already there`);
197
+ }
198
+ // Matches `linkOrCopy` in agents/antigravity.ts, which this replaces in
199
+ // Phase 3. Note `dereference: true` would NOT make this more robust
200
+ // against a symlink *inside* `target`: as of Node 25 it has no effect on
201
+ // symlinks nested in a recursive directory copy (verified — they are
202
+ // recreated as symlinks with or without it), so it would only add a
203
+ // claim the flag doesn't deliver. Hardening the fallback against nested
204
+ // symlinks is a behavior change, not a port, and belongs with the real
205
+ // call sites in Phase 3.
206
+ //
207
+ // Marker written both before AND after the (potentially large, potentially
208
+ // failing) recursive copy — each half guards a different failure:
209
+ // - Before: if cp throws partway through, or the process is killed
210
+ // outright (no catch/finally runs for that case either way), the
211
+ // marker has already landed, so the next observeSlot classifies the
212
+ // partial directory as owned-dir (reclaimable via relink) rather than
213
+ // foreign (unrecoverable by ADG). Relies on cp merging into an
214
+ // already-existing destination directory rather than erroring —
215
+ // verified separately.
216
+ // - After: if `target` itself contains a root-level file also named
217
+ // OWNERSHIP_MARKER, cp overwrites our just-written marker with that
218
+ // file's content when it copies target's own tree — verified directly
219
+ // (cpSync does overwrite a same-named destination file with the
220
+ // source's version). Rewriting after a successful copy guarantees the
221
+ // final on-disk marker is ours regardless of what target contained.
222
+ const markerPath = join(path, OWNERSHIP_MARKER);
223
+ mkdirSync(path);
224
+ writeFileSync(markerPath, OWNERSHIP_MARKER_MAGIC);
225
+ cp(target, path, { recursive: true });
226
+ writeFileSync(markerPath, OWNERSHIP_MARKER_MAGIC);
227
+ }
228
+ /** Perform the action `reconcileSlot` decided on at `path`. The only function
229
+ * in this module that writes to disk. */
230
+ export function applySlotAction(path, action, opts = {}) {
231
+ const symlink = opts.symlink ?? symlinkSync;
232
+ const cp = opts.cp ?? cpSync;
233
+ switch (action.kind) {
234
+ case "noop":
235
+ case "skip-foreign":
236
+ return;
237
+ case "remove-link":
238
+ removeOwned(path);
239
+ return;
240
+ case "create-link":
241
+ createLink(path, action.target, symlink, cp);
242
+ return;
243
+ case "relink":
244
+ removeOwned(path);
245
+ createLink(path, action.target, symlink, cp);
246
+ return;
247
+ default:
248
+ assertNever(action);
249
+ }
250
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rbbtsn0w/adg",
3
- "version": "0.7.2-beta.2",
3
+ "version": "0.8.0-beta.2",
4
4
  "description": "Agent Directory Group (ADG) toolkit — two domains: plugins and skills.",
5
5
  "type": "module",
6
6
  "license": "MIT",