@nodii/dev 0.6.80 → 0.6.82
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 +13 -0
- package/dist/core.js +1 -1
- package/dist/figma-scope.js +28 -41
- package/dist/review.js +4 -4
- package/dist/safety.js +232 -11
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -271,6 +271,19 @@ Sibling sections don't conflict. Dev
|
|
|
271
271
|
refuses an overlap with `SCOPE_CONFLICT`; the CLI prints Dev's message, then
|
|
272
272
|
the set holding the overlapping scope. `figma lock` without `--scope` locks the
|
|
273
273
|
whole file, as older CLIs do, and that conflicts with every other set.
|
|
274
|
+
|
|
275
|
+
**A DS component set in the Freeze (NODII-DEV-CLI-70).** A lane may lock only
|
|
276
|
+
the component sets its Freeze names. A Surface's nodes come from the DS
|
|
277
|
+
catalog (`registry.json`). A DS component set (Empty State, Pagination) is not
|
|
278
|
+
a Surface, so its node comes from the design catalogue
|
|
279
|
+
(`design-catalog.json`): the entry whose `figma.componentSetKey` (or
|
|
280
|
+
`figma.componentKey`) is the key names its `figma.fileKey` and
|
|
281
|
+
`figma.nodeId`. `lane check`'s Figma boundary resolves it the same way. The
|
|
282
|
+
CLI never reads Figma REST for this. A key in neither catalogue is refused with
|
|
283
|
+
`FIGMA_KEY_UNKNOWN`; the fix is to publish the key on its design catalogue
|
|
284
|
+
entry in the design-system repository (the Figma MCP's
|
|
285
|
+
`search_design_system` returns it as `componentSetKey`).
|
|
286
|
+
|
|
274
287
|
`figma scope add` widens a set you hold, with the same check; nothing is ever
|
|
275
288
|
widened silently. `figma scope set` narrows a set you hold to exactly the
|
|
276
289
|
scopes you give, and releases the rest for other sets: for example, a set
|
package/dist/core.js
CHANGED
|
@@ -4,7 +4,7 @@ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
|
4
4
|
import { homedir, platform } from "node:os";
|
|
5
5
|
import { dirname, join } from "node:path";
|
|
6
6
|
|
|
7
|
-
export const VERSION = "0.6.
|
|
7
|
+
export const VERSION = "0.6.82";
|
|
8
8
|
export const configPath = () =>
|
|
9
9
|
process.env.NODII_DEV_CONFIG_PATH ??
|
|
10
10
|
join(homedir(), ".config/nodii-dev/config.json");
|
package/dist/figma-scope.js
CHANGED
|
@@ -290,50 +290,37 @@ export const SWAP_BOUNDARIES = (key = "<key>") => `\`nodii-dev lane freeze swap
|
|
|
290
290
|
|
|
291
291
|
const outside = (message, details) => new CliError("FIGMA_OUTSIDE_LANE_SCOPE", `${message} Change the scope only with ${SWAP_BOUNDARIES()}, or ask the coordinator to amend the lane.`, 2, details);
|
|
292
292
|
|
|
293
|
-
const setLookups = new Map();
|
|
294
|
-
export const clearComponentSetLookups = () => setLookups.clear();
|
|
295
|
-
|
|
296
293
|
/**
|
|
297
|
-
*
|
|
298
|
-
*
|
|
299
|
-
*
|
|
300
|
-
*
|
|
301
|
-
*
|
|
294
|
+
* How a key the DS catalog does not list as a Surface (a DS component set,
|
|
295
|
+
* NODII-DEV-CLI-70) resolves: the design catalogue entry that publishes it
|
|
296
|
+
* (figma.componentSetKey or figma.componentKey) names its file and node. Both
|
|
297
|
+
* come from the DS repository's build, not from a lane-given flag, and the CLI
|
|
298
|
+
* never reads Figma REST for them (operator ruling of 3 Nov: Figma through the
|
|
299
|
+
* MCP). NODII_DEV_DS_DESIGN_CATALOG_URL can point the read elsewhere, as
|
|
300
|
+
* NODII_DEV_DS_REGISTRY_URL can for the registry. A catalogue with no entries
|
|
301
|
+
* list is refused, never read as empty. One read of the catalogue per lookup.
|
|
302
302
|
*/
|
|
303
|
-
export function
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
if (!
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
try {
|
|
315
|
-
const meta = (await get(`/component_sets/${encodeURIComponent(key)}`))?.meta;
|
|
316
|
-
return meta?.node_id && meta?.file_key ? { key, fileKey: meta.file_key, nodeId: meta.node_id, name: meta.name ?? null } : null;
|
|
317
|
-
} catch (error) {
|
|
318
|
-
if (error?.code === "FIGMA_NOT_FOUND") return null;
|
|
319
|
-
throw error;
|
|
320
|
-
}
|
|
321
|
-
})();
|
|
322
|
-
// A failed read is not remembered; the next caller asks again.
|
|
323
|
-
lookup.catch(() => setLookups.delete(key));
|
|
324
|
-
setLookups.set(key, lookup);
|
|
325
|
-
}
|
|
326
|
-
return setLookups.get(key);
|
|
303
|
+
export function designCatalogSets({ fetchImpl = fetch, url = process.env.NODII_DEV_DS_DESIGN_CATALOG_URL || DS_DESIGN_CATALOG_URL } = {}) {
|
|
304
|
+
let entries;
|
|
305
|
+
return async (key) => {
|
|
306
|
+
entries ??= fetchDsJson(url, { fetchImpl }).then((catalog) => {
|
|
307
|
+
if (!Array.isArray(catalog?.entries)) throw new CliError("DS_CATALOG_INVALID", "The design catalogue has no entries list.", 1);
|
|
308
|
+
return catalog.entries;
|
|
309
|
+
});
|
|
310
|
+
const entry = (await entries).find((item) => [item?.figma?.componentSetKey, item?.figma?.componentKey].includes(key));
|
|
311
|
+
if (!entry?.figma?.fileKey || !entry.figma.nodeId) return null;
|
|
312
|
+
return { key, fileKey: entry.figma.fileKey, nodeId: entry.figma.nodeId, name: entry.title ?? entry.key ?? null };
|
|
313
|
+
};
|
|
327
314
|
}
|
|
328
315
|
|
|
329
316
|
/**
|
|
330
317
|
* What each published set key in a file names (MW8-20): a Surface's nodes and
|
|
331
|
-
* state frames from the DS catalog; else, through `lookupSet`, the
|
|
332
|
-
*
|
|
333
|
-
* node as the one frame. `onlyIfNeeded(resolvedSoFar)` returning false skips
|
|
334
|
-
*
|
|
318
|
+
* state frames from the DS catalog; else, through `lookupSet`, the design
|
|
319
|
+
* catalogue entry that publishes the key (a DS component set,
|
|
320
|
+
* NODII-DEV-CLI-70), its own node as the one frame. `onlyIfNeeded(resolvedSoFar)` returning false skips
|
|
321
|
+
* those lookups. A key that names nothing in this file is refused.
|
|
335
322
|
*/
|
|
336
|
-
export async function componentSetsIn(fileKey, keys, { surfaces = [], lookupSet =
|
|
323
|
+
export async function componentSetsIn(fileKey, keys, { surfaces = [], lookupSet = designCatalogSets(), onlyIfNeeded } = {}) {
|
|
337
324
|
const sets = new Map();
|
|
338
325
|
for (const key of keys) {
|
|
339
326
|
const surface = surfaces.find((item) => item.componentSetKey === key && item.fileKey === fileKey);
|
|
@@ -344,10 +331,10 @@ export async function componentSetsIn(fileKey, keys, { surfaces = [], lookupSet
|
|
|
344
331
|
for (const key of rest) {
|
|
345
332
|
const set = await lookupSet(key);
|
|
346
333
|
if (!set)
|
|
347
|
-
throw new CliError("FIGMA_KEY_UNKNOWN", `${key} is neither a Surface in the DS catalog nor a component set Figma
|
|
334
|
+
throw new CliError("FIGMA_KEY_UNKNOWN", `${key} is neither a Surface in the DS catalog nor the published key of a design catalogue entry. A DS component set is resolved only through the design catalogue (figma.componentSetKey beside figma.nodeId), so publish its key there, in the design-system repository: the Figma MCP's search_design_system returns it as componentSetKey.`, 1, { fileKey, key });
|
|
348
335
|
if (set.fileKey !== fileKey)
|
|
349
336
|
throw new CliError("FIGMA_KEY_UNKNOWN", `${key}${set.name ? ` (${set.name})` : ""} is in file ${set.fileKey}, not ${fileKey}.`, 1, { fileKey, key, setFileKey: set.fileKey });
|
|
350
|
-
sets.set(key, { key, fileKey, name: set.name, nodeIds: [set.nodeId], frames: [{ nodeId: set.nodeId, state: "default" }] });
|
|
337
|
+
sets.set(key, { key, fileKey, name: set.name ?? null, nodeIds: [set.nodeId], frames: [{ nodeId: set.nodeId, state: "default" }] });
|
|
351
338
|
}
|
|
352
339
|
return sets;
|
|
353
340
|
}
|
|
@@ -357,7 +344,7 @@ export async function componentSetsIn(fileKey, keys, { surfaces = [], lookupSet
|
|
|
357
344
|
* write (lockScopes = null) outside the lane's scope. `scope` null = the lane
|
|
358
345
|
* declared none, so nothing is bounded here.
|
|
359
346
|
*/
|
|
360
|
-
export async function assertWithinLaneScope(scope, fileKey, lockScopes, { catalog = loadDsCatalog, lookupSet =
|
|
347
|
+
export async function assertWithinLaneScope(scope, fileKey, lockScopes, { catalog = loadDsCatalog, lookupSet = designCatalogSets() } = {}) {
|
|
361
348
|
if (scope === null) return { checked: false };
|
|
362
349
|
const file = scope.find((item) => item.fileKey === fileKey);
|
|
363
350
|
if (!file)
|
|
@@ -366,7 +353,7 @@ export async function assertWithinLaneScope(scope, fileKey, lockScopes, { catalo
|
|
|
366
353
|
const wide = lockScopes.length ? lockScopes.filter((item) => item.kind !== "component") : [{ kind: "file" }];
|
|
367
354
|
if (wide.length)
|
|
368
355
|
throw outside(`This lane may lock only its component sets in ${fileKey}, not ${wide.map((item) => item.kind).join(", ")}.`, { fileKey, scope: file });
|
|
369
|
-
// Surfaces first;
|
|
356
|
+
// Surfaces first; a DS set's key is looked up only when a node is still unaccounted for.
|
|
370
357
|
const allowedBy = (sets) => new Set([...sets.values()].flatMap((set) => set.nodeIds));
|
|
371
358
|
const sets = await componentSetsIn(fileKey, file.componentSets, {
|
|
372
359
|
surfaces: await catalog(),
|
package/dist/review.js
CHANGED
|
@@ -10,7 +10,7 @@ import { dirname, join } from "node:path";
|
|
|
10
10
|
import { promisify } from "node:util";
|
|
11
11
|
import { CliError, encode } from "./core.js";
|
|
12
12
|
import { pickerPrompt } from "./gather.js";
|
|
13
|
-
import { componentSetsIn,
|
|
13
|
+
import { componentSetsIn, designCatalogSets } from "./figma-scope.js";
|
|
14
14
|
import { gitPrivatePath } from "./safety.js";
|
|
15
15
|
|
|
16
16
|
const execFileAsync = promisify(execFile);
|
|
@@ -414,10 +414,10 @@ export const frameUrl = (fileKey, nodeId) => `https://www.figma.com/design/${fil
|
|
|
414
414
|
/**
|
|
415
415
|
* The frames in the Freeze's Figma boundary: each component set's state
|
|
416
416
|
* nodes from the DS catalog (its main node as "default" when it has none),
|
|
417
|
-
* or, for a DS component set, its own node as
|
|
418
|
-
* key (NODII-DEV-CLI-70); a whole-file boundary is the whole file.
|
|
417
|
+
* or, for a DS component set, its own node as the design catalogue
|
|
418
|
+
* publishes it under the key (NODII-DEV-CLI-70); a whole-file boundary is the whole file.
|
|
419
419
|
*/
|
|
420
|
-
export async function boundaryFrames(figma, { catalog, lookupSet =
|
|
420
|
+
export async function boundaryFrames(figma, { catalog, lookupSet = designCatalogSets() } = {}) {
|
|
421
421
|
const surfaces = figma.some((file) => file.componentSetKeys?.length) ? await catalog() : [];
|
|
422
422
|
const frames = [];
|
|
423
423
|
for (const file of figma) {
|
package/dist/safety.js
CHANGED
|
@@ -63,6 +63,80 @@ function words(command) {
|
|
|
63
63
|
return out;
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
+
// A heredoc body read as text by a known text reader is not commands the shell
|
|
67
|
+
// runs, so it is dropped before the command is judged: a note that says
|
|
68
|
+
// "git push" is not a push (hub-266). The readers are `cat` and `tee`, and a
|
|
69
|
+
// message read from stdin (`git commit -F -`, `--body-file -`), with nothing
|
|
70
|
+
// piped after it. Every other heredoc (`bash <<EOF`, `ssh host <<EOF`,
|
|
71
|
+
// `cat <<EOF | sh`, a program this list does not know) is judged as commands:
|
|
72
|
+
// the hook fails closed (P-8). A body is dropped only when its delimiter is a
|
|
73
|
+
// whole word the hook reads exactly as the shell does, the rest of the command
|
|
74
|
+
// has no group, loop or substitution, and the command is one of two shapes
|
|
75
|
+
// that cannot run the text: only commands that never run a file (FILE_ONLY;
|
|
76
|
+
// no git, which runs hooks and aliases), or one lone `git`, `gh` or
|
|
77
|
+
// `nodii-dev` reading its message from stdin. Anything else (`bash x.sh`,
|
|
78
|
+
// `python3 x.py`, `./x.sh`, `git commit` after writing a hook) might run it.
|
|
79
|
+
const HEREDOC = /(?<!<)<<(?!<)(-?)\s*(["']?)([A-Za-z_][A-Za-z0-9_]*)\2(?=$|[\s;&|<>()])/g;
|
|
80
|
+
const HEREDOC_START = /(?<!<)<<(?!<)-?\s*\S/;
|
|
81
|
+
const GROUPED = /[(){}`]|\$\(|<\(|>\(/;
|
|
82
|
+
const FILE_ONLY = new Set(["cat", "tee", "echo", "printf", "true", "cd", "mkdir", "ls", "pwd", "wc", "head", "tail"]);
|
|
83
|
+
const MESSAGE_READERS = new Set(["git", "gh", "nodii-dev"]);
|
|
84
|
+
const GH_MESSAGE_VERBS = new Set(["pr", "issue", "release"]);
|
|
85
|
+
// Options that name a program to run: git's -c (an alias `!sh x.sh`), --exec-path, --config-env; nodii-dev's gates.
|
|
86
|
+
const RUNS_PROGRAM = /^(?:-c|--exec-path(?:=.*)?|--config-env(?:=.*)?|--gate(?:=.*)?|--run(?:=.*)?)$/;
|
|
87
|
+
function runsNothing(command) {
|
|
88
|
+
if (GROUPED.test(command.replace(/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g, "x"))) return false;
|
|
89
|
+
const parts = segments(command).map((segment) => {
|
|
90
|
+
const texts = segment.map((x) => x.text);
|
|
91
|
+
const at = texts.findIndex((x) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(x));
|
|
92
|
+
return at === -1 ? null : { texts, at, name: texts[at].startsWith("./") ? null : texts[at].replace(/^\S*\//, "") };
|
|
93
|
+
}).filter(Boolean);
|
|
94
|
+
if (parts.every((x) => FILE_ONLY.has(x.name))) return true;
|
|
95
|
+
if (parts.length !== 1 || !MESSAGE_READERS.has(parts[0].name)) return false;
|
|
96
|
+
const { texts, at, name } = parts[0];
|
|
97
|
+
if (texts.slice(at + 1).some((x) => RUNS_PROGRAM.test(x))) return false;
|
|
98
|
+
return name !== "gh" || GH_MESSAGE_VERBS.has(texts[at + 1]);
|
|
99
|
+
}
|
|
100
|
+
const TEXT_READER = /^(?:\S*\/)?(?:cat|tee)$/;
|
|
101
|
+
const STDIN_MESSAGE = /(?:^|\s)(?:-F\s*-|--file(?:=|\s+)-|--body-file(?:=|\s+)-|--comment-file(?:=|\s+)-)(?:\s|$)/;
|
|
102
|
+
function textHeredoc(line, at, length) {
|
|
103
|
+
// Inside a substitution ($(...), `...`, <(...)) the text becomes another command's input or arguments.
|
|
104
|
+
if (/\$\(|<\(|>\(|`/.test(line.slice(0, at))) return false;
|
|
105
|
+
const owner = line.slice(0, at).split(/&&|\|\||[;|(]/).at(-1).trim();
|
|
106
|
+
const after = line.slice(at + length).split(/&&|\|\||;/)[0];
|
|
107
|
+
if (/[|`]|\$\(|<\(|>\(/.test(after)) return false;
|
|
108
|
+
const name = owner.split(/\s+/).find((x) => x && !/^[A-Z_][A-Z0-9_]*=/.test(x)) ?? "";
|
|
109
|
+
if (TEXT_READER.test(name)) return true;
|
|
110
|
+
return /^(?:\S*\/)?(?:git|gh|nodii-dev)$/.test(name) && STDIN_MESSAGE.test(`${owner} ${after}`);
|
|
111
|
+
}
|
|
112
|
+
export function withoutHeredocBodies(command) {
|
|
113
|
+
const lines = String(command).split("\n");
|
|
114
|
+
const out = [];
|
|
115
|
+
// The command lines alone, without delimiter lines, for the check that nothing runs the text.
|
|
116
|
+
const commands = [];
|
|
117
|
+
const pending = [];
|
|
118
|
+
for (const line of lines) {
|
|
119
|
+
if (pending.length) {
|
|
120
|
+
const next = pending[0];
|
|
121
|
+
const text = next.tabs ? line.replace(/^\t+/, "") : line;
|
|
122
|
+
if (text === next.word) { pending.shift(); out.push(line); continue; }
|
|
123
|
+
if (next.keep) { out.push(line); commands.push(line); }
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
out.push(line);
|
|
127
|
+
commands.push(line);
|
|
128
|
+
const found = [...line.matchAll(HEREDOC)];
|
|
129
|
+
// A heredoc whose delimiter the hook cannot read exactly (`<<E"OF"`, `<<\EOF`) keeps everything after it.
|
|
130
|
+
if (line.split(HEREDOC_START).length - 1 !== found.length) { pending.push({ word: null, keep: true }); continue; }
|
|
131
|
+
for (const match of found)
|
|
132
|
+
pending.push({ word: match[3], tabs: match[1] === "-", keep: !textHeredoc(line, match.index, match[0].length) });
|
|
133
|
+
}
|
|
134
|
+
const stripped = out.join("\n");
|
|
135
|
+
// The text is dropped only when nothing else in the command can run it.
|
|
136
|
+
if (stripped !== String(command) && !runsNothing(commands.join("\n"))) return String(command);
|
|
137
|
+
return stripped;
|
|
138
|
+
}
|
|
139
|
+
|
|
66
140
|
function commandHas(tokens, ...sequence) {
|
|
67
141
|
return tokens.some((_, at) => sequence.every((part, offset) => tokens[at + offset] === part));
|
|
68
142
|
}
|
|
@@ -118,7 +192,10 @@ function createsBranch(after) {
|
|
|
118
192
|
// A hook bypass by another name is still --no-verify: lefthook's and husky's
|
|
119
193
|
// off switches, and pointing Git's hooks somewhere else.
|
|
120
194
|
const HOOK_BYPASS = /(?:^|[\s;&|(])(?:export\s+|env\s+)?(?:LEFTHOOK\s*=\s*["']?(?:0|false|off)\b|HUSKY\s*=\s*["']?0\b)|\bcore\.hooks[Pp]ath\b/;
|
|
121
|
-
const usesNoVerify = (
|
|
195
|
+
const usesNoVerify = (raw) => {
|
|
196
|
+
const command = withoutHeredocBodies(raw);
|
|
197
|
+
return gitInvocations(words(command)).some((x) => x.args.includes("--no-verify")) || HOOK_BYPASS.test(command);
|
|
198
|
+
};
|
|
122
199
|
|
|
123
200
|
// Operator, 29 Oct: a pattern kill on macOS once killed every agent on the
|
|
124
201
|
// machine. Only a PID the caller started (and saved) may be killed.
|
|
@@ -197,7 +274,7 @@ function outsideWorktree(target, context, relativeKnown) {
|
|
|
197
274
|
path = resolve(context.cwd, path);
|
|
198
275
|
}
|
|
199
276
|
const inside = (root) => { const rel = relative(root, path); return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); };
|
|
200
|
-
return !inside(context.root) && !WRITABLE_ELSEWHERE().some(inside);
|
|
277
|
+
return !inside(context.root) && !(context.laneRoots ?? []).some(inside) && !WRITABLE_ELSEWHERE().some(inside);
|
|
201
278
|
}
|
|
202
279
|
|
|
203
280
|
function gitOutsideWorktree(tokens, context) {
|
|
@@ -217,6 +294,129 @@ function gitOutsideWorktree(tokens, context) {
|
|
|
217
294
|
return null;
|
|
218
295
|
}
|
|
219
296
|
|
|
297
|
+
const insideRoot = (root, path) => { const rel = relative(root, path); return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); };
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* The directory each `git push` in a command runs in: its `-C`/`--work-tree`,
|
|
301
|
+
* resolved against the last `cd`/`pushd`/`popd` before it. null when a variable,
|
|
302
|
+
* a substitution, `--git-dir`, a GIT_DIR/GIT_WORK_TREE/GIT_COMMON_DIR setting or
|
|
303
|
+
* `env --chdir` makes it unknowable; the hook refuses such a push.
|
|
304
|
+
*/
|
|
305
|
+
const GIT_PLACE_ENV = /^GIT_(?:DIR|WORK_TREE|COMMON_DIR)=/;
|
|
306
|
+
export function pushTargets(raw, cwd) {
|
|
307
|
+
const out = [];
|
|
308
|
+
let dir = cwd;
|
|
309
|
+
// A path from `from`, as the shell and git place it; null when unknowable.
|
|
310
|
+
const place = (path, from) => {
|
|
311
|
+
if (path === undefined) return homedir();
|
|
312
|
+
if (path.includes("$") || path.includes("`")) return null;
|
|
313
|
+
if (path === "~" || path.startsWith("~/")) return join(homedir(), path.slice(1));
|
|
314
|
+
if (isAbsolute(path)) return resolve(path);
|
|
315
|
+
return from === null ? null : resolve(from, path);
|
|
316
|
+
};
|
|
317
|
+
// A `cd` inside `( ... )` ends with the subshell.
|
|
318
|
+
const outer = [];
|
|
319
|
+
// pushd's directory stack, for popd. A popd or bare pushd it cannot follow makes the directory unknown.
|
|
320
|
+
const pushed = [];
|
|
321
|
+
// An exported or assigned GIT_DIR (or kin) moves every later git command somewhere the hook cannot follow.
|
|
322
|
+
let gitEnvMoved = false;
|
|
323
|
+
for (const segment of segments(withoutHeredocBodies(raw))) {
|
|
324
|
+
const all = segment.map((x) => x.text);
|
|
325
|
+
const lead = all.findIndex((x) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(x));
|
|
326
|
+
const texts = lead === -1 ? [] : all.slice(lead);
|
|
327
|
+
const movesGit = all.some((x) => GIT_PLACE_ENV.test(x));
|
|
328
|
+
const envAt = texts.findIndex((x) => /^(?:\S*\/)?env$/.test(x));
|
|
329
|
+
const envChdir = envAt !== -1 && texts.slice(envAt + 1).some((x, i, rest) => rest.slice(0, i).every((y) => y.startsWith("-") || y.includes("=")) && /^(?:-[a-zA-Z]*C.*|--chdir(?:=.*)?)$/.test(x));
|
|
330
|
+
if (movesGit && !texts.some((x) => x === "git" || x.endsWith("/git"))) gitEnvMoved = true;
|
|
331
|
+
while (texts[0]?.startsWith("(")) { texts[0] = texts[0].slice(1); outer.push(dir); if (!texts[0]) texts.shift(); }
|
|
332
|
+
const closing = texts.length && !texts.at(-1).includes("(") ? /\)+$/.exec(texts.at(-1))?.[0].length ?? 0 : 0;
|
|
333
|
+
if (closing) texts[texts.length - 1] = texts.at(-1).slice(0, -closing);
|
|
334
|
+
// A builtin's arguments, without redirects (`> /dev/null`, `2>&1`).
|
|
335
|
+
const args = texts.slice(1).filter((x, i, all) => !/^\d*[<>]/.test(x) && !/^\d*[<>]{1,2}&?$/.test(all[i - 1] ?? ""));
|
|
336
|
+
const where = args.find((x) => !/^-[a-zA-Z]*$/.test(x));
|
|
337
|
+
if (texts[0] === "cd") dir = args.includes("-") ? null : place(where, dir);
|
|
338
|
+
else if (texts[0] === "pushd") { if (where === undefined || /^[+-]\d+$/.test(where)) dir = null; else { pushed.push(dir); dir = place(where, dir); } }
|
|
339
|
+
else if (texts[0] === "popd") dir = where === undefined && pushed.length ? pushed.pop() : null;
|
|
340
|
+
else for (let at = 0; at < texts.length; at += 1) {
|
|
341
|
+
if (texts[at] !== "git" && !texts[at].endsWith("/git")) continue;
|
|
342
|
+
let cursor = at + 1;
|
|
343
|
+
let target = envChdir ? null : dir;
|
|
344
|
+
let gitDir = false;
|
|
345
|
+
while (cursor < texts.length && texts[cursor].startsWith("-")) {
|
|
346
|
+
const option = texts[cursor];
|
|
347
|
+
// Each -C is relative to the one before it, as git reads them.
|
|
348
|
+
if (["-C", "--work-tree"].includes(option) && texts[cursor + 1] !== undefined) target = place(texts[cursor + 1], target);
|
|
349
|
+
else if (option.startsWith("--work-tree=")) target = place(option.slice("--work-tree=".length), target);
|
|
350
|
+
else if (option === "--git-dir" || option.startsWith("--git-dir=")) gitDir = true;
|
|
351
|
+
cursor += ["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"].includes(option) ? 2 : 1;
|
|
352
|
+
}
|
|
353
|
+
// A repository named apart from the directory (--git-dir, GIT_DIR) cannot be placed, whatever -C says.
|
|
354
|
+
if (texts[cursor] === "push") out.push(gitDir || gitEnvMoved || movesGit ? null : target);
|
|
355
|
+
}
|
|
356
|
+
for (let n = 0; n < closing && outer.length; n += 1) dir = outer.pop();
|
|
357
|
+
}
|
|
358
|
+
return out;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** Every worktree the lane declares: its repositories, its own worktree and its Freeze boundaries.repos. */
|
|
362
|
+
export async function laneWorktrees(lane, { request = devRequest, root = null } = {}) {
|
|
363
|
+
const paths = [
|
|
364
|
+
root,
|
|
365
|
+
lane?.worktree,
|
|
366
|
+
...(lane?.repositories ?? []).map((x) => x?.worktree),
|
|
367
|
+
...(lane?.freeze?.boundaries?.repos ?? []).map((x) => x?.worktree),
|
|
368
|
+
];
|
|
369
|
+
if (lane?.key && !lane?.freeze?.boundaries?.repos) {
|
|
370
|
+
try {
|
|
371
|
+
const freeze = (await request("GET", `/api/v1/lanes/${encode(lane.key)}/freeze`)).data?.freeze;
|
|
372
|
+
paths.push(...(freeze?.boundaries?.repos ?? []).map((x) => x?.worktree));
|
|
373
|
+
} catch {}
|
|
374
|
+
}
|
|
375
|
+
const real = await Promise.all(paths.filter((x) => typeof x === "string" && x).map((x) => realpath(x).catch(() => resolve(x))));
|
|
376
|
+
return [...new Set(real)];
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** The head, origin/main and local review receipt of one worktree. */
|
|
380
|
+
export async function repoReviewState(dir) {
|
|
381
|
+
const root = await realpath(await git(dir, "rev-parse", "--show-toplevel"));
|
|
382
|
+
const receiptText = await optional(await gitPrivatePath(root, REVIEW_RECEIPT));
|
|
383
|
+
return {
|
|
384
|
+
root,
|
|
385
|
+
head: await git(root, "rev-parse", "HEAD"),
|
|
386
|
+
base: await git(root, "rev-parse", "origin/main").catch(() => null),
|
|
387
|
+
receipt: receiptText ? JSON.parse(receiptText) : null,
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const SCOPE_CODES = new Set(["SAFETY_OTHER_WORKTREE", "SAFETY_WRITE_OUTSIDE_WORKTREE"]);
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* A multi-repo lane owns every worktree it declares (hub-266). When a
|
|
395
|
+
* command reaches past the hook's own worktree, load the lane's worktrees, and
|
|
396
|
+
* judge each push by the repository it pushes. Only a proven lane context with
|
|
397
|
+
* resolvers (from safetyContext) is expanded; a plain context is left as given.
|
|
398
|
+
*/
|
|
399
|
+
export async function expandLaneScope(command, context, { reviewState = repoReviewState } = {}) {
|
|
400
|
+
if (!provenLane(context) || typeof context.loadLaneRoots !== "function") return context;
|
|
401
|
+
const targets = pushTargets(command, context.cwd);
|
|
402
|
+
const reaches = targets.some((x) => x && !insideRoot(context.root, x)) || commandViolations(command, context).some((x) => SCOPE_CODES.has(x.code));
|
|
403
|
+
if (!reaches) return context;
|
|
404
|
+
context.laneRoots = await context.loadLaneRoots();
|
|
405
|
+
if (!targets.length) return context;
|
|
406
|
+
const repos = [];
|
|
407
|
+
for (const target of targets) {
|
|
408
|
+
if (!target || insideRoot(context.root, target)) {
|
|
409
|
+
repos.push({ root: context.root, head: context.head, base: context.base, receipt: context.reviewReceipt });
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
const state = await reviewState(target).catch(() => null);
|
|
413
|
+
if (!state || !context.laneRoots.includes(state.root)) repos.push({ root: state?.root ?? target, foreign: true });
|
|
414
|
+
else repos.push(state);
|
|
415
|
+
}
|
|
416
|
+
context.pushRepos = repos;
|
|
417
|
+
return context;
|
|
418
|
+
}
|
|
419
|
+
|
|
220
420
|
function deployCommand(tokens, command) {
|
|
221
421
|
if (commandHas(tokens, "tofu", "apply")) return true;
|
|
222
422
|
if (commandHas(tokens, "terraform", "apply")) return true;
|
|
@@ -277,7 +477,8 @@ const provenLane = (context) => context.provenLane === true || (context.provenLa
|
|
|
277
477
|
const nudgeViolation = (violation) => `nodii-dev safety: unproven lane context; ${violation.message.replace(/\bblocked\b/gi, "would be blocked")}`;
|
|
278
478
|
|
|
279
479
|
/** Data-dependent checks nudge, rather than silently passing, when their source is not available yet. */
|
|
280
|
-
export function commandNudges(
|
|
480
|
+
export function commandNudges(raw, context) {
|
|
481
|
+
const command = withoutHeredocBodies(raw);
|
|
281
482
|
const tokens = words(command);
|
|
282
483
|
const nudges = [];
|
|
283
484
|
if (deployCommand(tokens, command) && !context.deployGrantKnown)
|
|
@@ -294,7 +495,8 @@ export function commandNudges(command, context) {
|
|
|
294
495
|
}
|
|
295
496
|
|
|
296
497
|
/** Every costly or irreversible shell mistake AGENT-HARNESS-15 blocks. */
|
|
297
|
-
export function commandViolations(
|
|
498
|
+
export function commandViolations(raw, context) {
|
|
499
|
+
const command = withoutHeredocBodies(raw);
|
|
298
500
|
const tokens = words(command);
|
|
299
501
|
const gitCommands = gitInvocations(tokens);
|
|
300
502
|
const violations = [];
|
|
@@ -329,7 +531,7 @@ export function commandViolations(command, context) {
|
|
|
329
531
|
block("SAFETY_FORCE_PUSH", "A force push rewrites history others may hold; a lane pushes fast-forward only. Ask the coordinator.");
|
|
330
532
|
if (context.root) {
|
|
331
533
|
const other = gitOutsideWorktree(tokens, context);
|
|
332
|
-
if (other) block("SAFETY_OTHER_WORKTREE", `git ${other.verb} in ${other.target} touches a checkout outside this lane's worktree ${context.root}.`);
|
|
534
|
+
if (other) block("SAFETY_OTHER_WORKTREE", `git ${other.verb} in ${other.target} touches a checkout outside this lane's worktree${context.laneRoots?.length > 1 ? `s (${context.laneRoots.join(", ")})` : ` ${context.root}`}.`);
|
|
333
535
|
const relativeKnown = !/(?:^|[;&|(\s])(?:cd|pushd)\s/.test(command);
|
|
334
536
|
const outside = writeTargets(command).filter((target) => outsideWorktree(target, context, relativeKnown));
|
|
335
537
|
if (outside.length)
|
|
@@ -341,13 +543,27 @@ export function commandViolations(command, context) {
|
|
|
341
543
|
else if (!context.noVerifyReason) block("SAFETY_NO_VERIFY_REASON", "A coordinator may use --no-verify only with a recorded reason.");
|
|
342
544
|
}
|
|
343
545
|
|
|
546
|
+
// A push whose repository cannot be named (a variable, a substitution, --git-dir)
|
|
547
|
+
// cannot have its review checked, so it is refused, not judged as the hook's own (P-8).
|
|
548
|
+
if (lane && gitCommands.some((x) => x.verb === "push") && pushTargets(command, context.cwd ?? context.root).includes(null))
|
|
549
|
+
block("SAFETY_PUSH_TARGET_UNKNOWN", "Push blocked: the hook cannot tell which repository this push runs in. Push with a literal path: git -C <worktree> push, or cd <worktree> && git push.");
|
|
344
550
|
if (lane && context.reviewFlowKnown && gitCommands.some((x) => x.verb === "push")) {
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
551
|
+
// Each push is judged against the repository it pushes (hub-266):
|
|
552
|
+
// its own head, origin/main and review receipt, in its own worktree.
|
|
553
|
+
const repos = context.pushRepos?.length ? context.pushRepos : [{ root: context.root, head: context.head, base: context.base, receipt: context.reviewReceipt }];
|
|
554
|
+
for (const repo of repos) {
|
|
555
|
+
if (repo.foreign) {
|
|
556
|
+
block("SAFETY_OTHER_WORKTREE", `git push in ${repo.root} touches a checkout outside this lane's worktrees (${[context.root, ...(context.laneRoots ?? []).filter((x) => x !== context.root)].join(", ")}).`);
|
|
557
|
+
continue;
|
|
558
|
+
}
|
|
559
|
+
const where = repo.root && repo.root !== context.root ? ` in ${repo.root}` : "";
|
|
560
|
+
const receipt = repo.receipt;
|
|
561
|
+
if (!receipt) block("SAFETY_REVIEW_REQUIRED", `Push blocked: no review receipt for ${repo.head}${where}. Run nodii-dev lane check from that worktree after the gates are green.`);
|
|
562
|
+
else if (receipt.commit !== repo.head)
|
|
563
|
+
block("SAFETY_REVIEW_COMMIT", `Push blocked: review covers ${receipt.commit}, not ${repo.head}${where}.`);
|
|
564
|
+
else if (receipt.base !== repo.base)
|
|
565
|
+
block("SAFETY_REVIEW_BASE", `Push blocked: review used base ${receipt.base}, but origin/main is ${repo.base}${where}. Re-review the current diff.`);
|
|
566
|
+
}
|
|
351
567
|
}
|
|
352
568
|
|
|
353
569
|
if (/(?:^|[\s/])(?:nodii-dev|@nodii\/dev(?:@[^\s]+)?)\s+(?:login|logout|agent\s+register)(?:\s|$)/.test(command))
|
|
@@ -509,6 +725,8 @@ export async function safetyContext(cwd = process.cwd(), { request = devRequest,
|
|
|
509
725
|
const goText = env.NODII_DEV_GO_FILE ? await optional(env.NODII_DEV_GO_FILE) : null;
|
|
510
726
|
const ownership = laneOwnership(lane, root);
|
|
511
727
|
const laneProject = laneStack(lane?.key);
|
|
728
|
+
let laneRoots = null;
|
|
729
|
+
const loadLaneRoots = lane ? async () => (laneRoots ??= await laneWorktrees(lane, { request, root })) : null;
|
|
512
730
|
return {
|
|
513
731
|
cwd: await realpath(cwd).catch(() => payloadCwd(cwd)), root, branch, head, base, role, lane, provenLane: Boolean(lane), reviewFlowKnown,
|
|
514
732
|
ownedPaths: ownership.paths,
|
|
@@ -520,6 +738,8 @@ export async function safetyContext(cwd = process.cwd(), { request = devRequest,
|
|
|
520
738
|
deployGrants: deployGrantsFrom(goText),
|
|
521
739
|
deployGrantKnown: goText !== null,
|
|
522
740
|
noVerifyReason: env.NODII_DEV_NO_VERIFY_REASON?.trim() || null,
|
|
741
|
+
laneRoots: [root],
|
|
742
|
+
loadLaneRoots,
|
|
523
743
|
};
|
|
524
744
|
}
|
|
525
745
|
|
|
@@ -542,6 +762,7 @@ export async function safetyPreHook(payload, contextOrResolver = safetyContext)
|
|
|
542
762
|
context.cwd = await realpath(cwd).catch(() => resolve(cwd));
|
|
543
763
|
if (SHELL_TOOLS.has(tool)) {
|
|
544
764
|
const command = String(payload.tool_input?.command ?? "");
|
|
765
|
+
await expandLaneScope(command, context);
|
|
545
766
|
const violation = commandViolations(command, context)[0];
|
|
546
767
|
if (violation && provenLane(context)) blocked(violation);
|
|
547
768
|
if (usesNoVerify(command) && context.role === "coordinator" && context.noVerifyReason)
|