@pbuilder/sdk 0.1.0 → 0.2.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.
@@ -140,11 +140,18 @@ export type ScaffoldOptions = ScaffoldArgs;
140
140
  * source path — distinct from the `rename()` verb, which renames one already-targeted
141
141
  * file's basename at emit time, not a folder-walk's per-entry destination.
142
142
  *
143
- * The walk never descends into a symlinked directory, even when its target resolves
144
- * INSIDE the package boundary (skipped silently, no error — uniform with
145
- * `package-root-containment`'s no-descent rule) and is capped at 10,000 enumerated
146
- * entries per call, failing loud and naming the bound past that (REQ-FSC-09) — a
147
- * resource guard no real schematic collection should approach.
143
+ * A NESTED symlinked directory is never descended, regardless of where its target
144
+ * resolves — skipped silently, no error; enumeration determinism and cycle-safety are the
145
+ * rationale (a symlinked directory could point anywhere, including into a cycle — never
146
+ * descending is the simplest invariant that is safe under all targets, REQ-FSC-09). The
147
+ * walk ROOT (`from` itself) is held to a stricter standard: a symlinked root REJECTS
148
+ * (`invalid-input`) rather than being followed or silently skipped (owner ruling 16) — but
149
+ * this check inspects only `from`'s FINAL path component; a symlink at a MID-path segment
150
+ * (e.g. `from: "link/sub"`) is not detected and the walk proceeds through it, the same
151
+ * documented residual SECURITY.md covers for `create`/`copyIn` reads. The walk is capped
152
+ * at 10,000 enumerated entries per call, failing loud and naming the bound past that
153
+ * (REQ-FSC-09) — a loop-safety/DoS resource guard no real schematic collection should
154
+ * approach.
148
155
  *
149
156
  * **Packaging caveat**: the empty-folder no-op (above) depends on `from` existing ON
150
157
  * DISK at run time — npm tarball packaging commonly DROPS empty directories, so an
@@ -127,11 +127,18 @@ export function create(path, opts) {
127
127
  * source path — distinct from the `rename()` verb, which renames one already-targeted
128
128
  * file's basename at emit time, not a folder-walk's per-entry destination.
129
129
  *
130
- * The walk never descends into a symlinked directory, even when its target resolves
131
- * INSIDE the package boundary (skipped silently, no error — uniform with
132
- * `package-root-containment`'s no-descent rule) and is capped at 10,000 enumerated
133
- * entries per call, failing loud and naming the bound past that (REQ-FSC-09) — a
134
- * resource guard no real schematic collection should approach.
130
+ * A NESTED symlinked directory is never descended, regardless of where its target
131
+ * resolves — skipped silently, no error; enumeration determinism and cycle-safety are the
132
+ * rationale (a symlinked directory could point anywhere, including into a cycle — never
133
+ * descending is the simplest invariant that is safe under all targets, REQ-FSC-09). The
134
+ * walk ROOT (`from` itself) is held to a stricter standard: a symlinked root REJECTS
135
+ * (`invalid-input`) rather than being followed or silently skipped (owner ruling 16) — but
136
+ * this check inspects only `from`'s FINAL path component; a symlink at a MID-path segment
137
+ * (e.g. `from: "link/sub"`) is not detected and the walk proceeds through it, the same
138
+ * documented residual SECURITY.md covers for `create`/`copyIn` reads. The walk is capped
139
+ * at 10,000 enumerated entries per call, failing loud and naming the bound past that
140
+ * (REQ-FSC-09) — a loop-safety/DoS resource guard no real schematic collection should
141
+ * approach.
135
142
  *
136
143
  * **Packaging caveat**: the empty-folder no-op (above) depends on `from` existing ON
137
144
  * DISK at run time — npm tarball packaging commonly DROPS empty directories, so an
@@ -24,7 +24,7 @@ import type { Batch } from "./wire.ts";
24
24
  export type AuthoringVerb = "create" | "modify" | "remove" | "rename" | "move" | "copy" | "copyIn";
25
25
  /**
26
26
  * The closed, author-vocabulary cause of an `AuthoringError` (★D2, ADR-0020). Exactly
27
- * twelve values — adding a thirteenth is a MAJOR change: authors are expected to write
27
+ * eleven values — adding a twelfth is a MAJOR change: authors are expected to write
28
28
  * exhaustive `switch(reason)` blocks, and TypeScript's exhaustiveness check breaks such
29
29
  * a switch on a new member even though nothing breaks at runtime. (V2 → V3 amendment,
30
30
  * 2026-07-10, coordinated with `stage-4-typed-options`: extended from six to eight —
@@ -32,7 +32,10 @@ export type AuthoringVerb = "create" | "modify" | "remove" | "rename" | "move" |
32
32
  * S-002, REQ-AEC-10: extended from eight to twelve — `source-not-found`,
33
33
  * `source-outside-package`, `source-not-regular-file`, `source-unreadable` added, all
34
34
  * four covering the SDK's own pre-emit read/stat of a package-local source for
35
- * `scaffold`/`copyIn`/`create({templateFile})`.)
35
+ * `scaffold`/`copyIn`/`create({templateFile})`. `inline-collection-marker` S-002,
36
+ * REQ-AEC-10 (ADR-0077): narrowed from twelve to eleven — `source-outside-package`
37
+ * retired along with `package-root-containment`; the SDK no longer enforces a
38
+ * containment ceiling, so there is no longer an "outside" for a source to resolve to.)
36
39
  *
37
40
  * @example
38
41
  * switch (err.reason) {
@@ -47,14 +50,13 @@ export type AuthoringVerb = "create" | "modify" | "remove" | "rename" | "move" |
47
50
  * case "invalid-input":
48
51
  * case "reserved-name":
49
52
  * case "source-not-found":
50
- * case "source-outside-package":
51
53
  * case "source-not-regular-file":
52
54
  * case "source-unreadable":
53
55
  * console.error(err.message);
54
56
  * break;
55
57
  * }
56
58
  */
57
- export type AuthoringReason = "path-collision" | "path-not-found" | "unrepresentable-content" | "changes-too-large" | "outside-run" | "unknown" | "invalid-input" | "reserved-name" | "source-not-found" | "source-outside-package" | "source-not-regular-file" | "source-unreadable";
59
+ export type AuthoringReason = "path-collision" | "path-not-found" | "unrepresentable-content" | "changes-too-large" | "outside-run" | "unknown" | "invalid-input" | "reserved-name" | "source-not-found" | "source-not-regular-file" | "source-unreadable";
58
60
  /**
59
61
  * Distinguishes an engine-refused write from an SDK-side misuse (2.4, ADR-0021) —
60
62
  * DERIVED from `reason`, never producer-set.
@@ -10,15 +10,16 @@
10
10
  // only `.message`.
11
11
  import { EmitRejection } from "./emit-rejection.js";
12
12
  // ADR-0021: origin is DERIVED from reason via an exhaustive switch with a `never`
13
- // default arm — adding a 13th reason breaks the BUILD here, forcing a deliberate origin
13
+ // default arm — adding a 12th reason breaks the BUILD here, forcing a deliberate origin
14
14
  // assignment instead of an accidental default (mirrored by the compile-time pin in
15
15
  // test/types/authoring-reason.test.ts). `unknown` maps to "write-rejected" deliberately:
16
16
  // an unclassifiable rejection necessarily arrived through the emit/write seam (the only
17
17
  // place toAuthoringError runs), so the write side is the honest attribution (spec
18
18
  // cross-cutting note 7). `invalid-input`/`reserved-name` (V2 → V3 amendment, REQ-AEC-07/08)
19
19
  // are ALWAYS "authoring-rejected" — same rationale as outside-run: an SDK-side misuse
20
- // detection, not an engine round-trip refusal. The four `source-*` reasons
21
- // (`schematic-local-files` S-002, REQ-AEC-10) are likewise ALWAYS "authoring-rejected" —
20
+ // detection, not an engine round-trip refusal. The three surviving `source-*` reasons
21
+ // (`schematic-local-files` S-002, REQ-AEC-10; `source-outside-package` retired by
22
+ // `inline-collection-marker` S-002, ADR-0077) are likewise ALWAYS "authoring-rejected" —
22
23
  // every one is detected by the SDK's OWN pre-emit read/stat of a package-local source,
23
24
  // never an engine round-trip refusal.
24
25
  function originFor(reason) {
@@ -33,7 +34,6 @@ function originFor(reason) {
33
34
  case "invalid-input":
34
35
  case "reserved-name":
35
36
  case "source-not-found":
36
- case "source-outside-package":
37
37
  case "source-not-regular-file":
38
38
  case "source-unreadable":
39
39
  return "authoring-rejected";
@@ -93,9 +93,13 @@ function primaryPath(directive) {
93
93
  //
94
94
  // REQ-AEC-11 (`schematic-local-files` S-002, V3 neutral wording — no `"copy failed:"`
95
95
  // prefix, dropped because these reasons also fire for `scaffold`/`create({templateFile})`,
96
- // not only the copy-family verbs) adds four MORE families, one per new `source-*` reason.
97
- // Unlike invalid-input/reserved-name, these ARE derivable from `path` alone (always
98
- // package-relative, REQ-PRC-05) — no caller-supplied `message` needed.
96
+ // not only the copy-family verbs) adds three MORE families, one per surviving `source-*`
97
+ // reason (`source-outside-package` retired by `inline-collection-marker` S-002, ADR-0077 —
98
+ // `path-guards.ts#sourceRejection` now owns that reason's former template, and every
99
+ // producer site passes an explicit `message`, so `messageFor` never needs it back). Unlike
100
+ // invalid-input/reserved-name, these ARE derivable from `path` alone (always
101
+ // package-relative, `package-source-io-hygiene` REQ-PSH-01 — successor to the retired
102
+ // `package-root-containment` REQ-PRC-05) — no caller-supplied `message` needed.
99
103
  function messageFor(reason, verb, path) {
100
104
  switch (reason) {
101
105
  case "path-collision":
@@ -111,8 +115,6 @@ function messageFor(reason, verb, path) {
111
115
  return `changes could not be applied: ${reason} — the SDK could not classify this failure`;
112
116
  case "source-not-found":
113
117
  return `source file not found: ${path} does not exist in the package`;
114
- case "source-outside-package":
115
- return `source file outside package: ${path} resolves outside the package boundary`;
116
118
  case "source-not-regular-file":
117
119
  return `source file invalid: ${path} is not a regular file`;
118
120
  case "source-unreadable":
@@ -17,7 +17,6 @@ export interface RunContext {
17
17
  };
18
18
  packageAnchors?: {
19
19
  packageDir: string;
20
- packageRoot: string;
21
20
  };
22
21
  }
23
22
  export declare const RUN_ALS_REGISTRY_KEY = "@pbuilder/sdk:core/context#run-als";
@@ -26,7 +25,6 @@ export declare function isDefineFactoryWrapped(value: unknown): boolean;
26
25
  export declare function currentContext(): RunContext;
27
26
  export declare function requirePackageAnchors(missingAnchorMessage: string): {
28
27
  packageDir: string;
29
- packageRoot: string;
30
28
  };
31
29
  /**
32
30
  * Builds a run-context and runs the factory inside it, flushing buffered
@@ -2,9 +2,9 @@
2
2
  // defineFactory returns a runner that builds the context and runs fn inside the ALS.
3
3
  // The EngineClient is injected by the caller (test passes the fake) — no module global.
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
5
- import { readFileSync, existsSync } from "node:fs";
5
+ import { readFileSync } from "node:fs";
6
6
  import { fileURLToPath } from "node:url";
7
- import { relative, dirname, join } from "node:path";
7
+ import { relative } from "node:path";
8
8
  import { DirectiveFactory } from "./directive-factory.js";
9
9
  import { Session } from "./session.js";
10
10
  import { AuthoringError, invalidInput } from "./authoring-error.js";
@@ -107,7 +107,7 @@ export function currentContext() {
107
107
  return ctx;
108
108
  }
109
109
  // The one gate every package-local read verb (`scaffold`/`copyIn`/`create({templateFile})`)
110
- // passes through: returns the run's two-anchor pair or throws the verb's own
110
+ // passes through: returns the run's sole anchor or throws the verb's own
111
111
  // no-resolution-anchor `invalid-input` when the run opted out of `packageDir`.
112
112
  export function requirePackageAnchors(missingAnchorMessage) {
113
113
  const { packageAnchors } = currentContext();
@@ -127,37 +127,6 @@ function resolvePackageDir(packageDir) {
127
127
  function relativeDir(packageDir) {
128
128
  return relative(process.cwd(), packageDir);
129
129
  }
130
- function missingPackageRootMessage(packageDir) {
131
- return (`invalid input: no collection.json found at or above ${relativeDir(packageDir)} — ` +
132
- "cannot resolve the containment root for this factory's package");
133
- }
134
- // REQ-PRC-02/REQ-PRC-03 (ADR-0046): the CONTAINMENT ceiling — the nearest `collection.json`
135
- // ANCESTOR of `packageDir` (itself included), walked upward from `packageDir` to the
136
- // filesystem root. `collection.json` is a PRESENCE-ONLY marker (never parsed, never read as
137
- // JSON — charter L2 keeps the manifest out of scope). No ancestor found → fail loud
138
- // `invalid-input` (REQ-PRC-03.1) BEFORE any source file is read; the ONLY caller is the
139
- // pre-`als.run` chokepoint below, so this resolves exactly once per run (REQ-PRC-02.1) —
140
- // scaffold/copyIn never re-walk it themselves, they read the already-resolved
141
- // `RunContext.packageRoot`.
142
- function resolvePackageRoot(packageDir) {
143
- let dir = packageDir;
144
- for (;;) {
145
- if (existsSync(join(dir, "collection.json"))) {
146
- return dir;
147
- }
148
- const parent = dirname(dir);
149
- if (parent === dir) {
150
- throw new AuthoringError({
151
- verb: undefined,
152
- path: undefined,
153
- reason: "invalid-input",
154
- appliedCount: 0,
155
- message: missingPackageRootMessage(packageDir),
156
- });
157
- }
158
- dir = parent;
159
- }
160
- }
161
130
  // Author-vocabulary description of a non-ENOENT read failure — never the raw errno
162
131
  // message (no-echo). ENOENT is handled by its own opt-out branch and never reaches this.
163
132
  function describeReadFailure(err) {
@@ -298,12 +267,11 @@ export function defineFactory(fn, options) {
298
267
  let packageAnchors;
299
268
  if (options?.packageDir !== undefined) {
300
269
  const resolvedDir = resolvePackageDir(options.packageDir);
270
+ // REQ-RBV-06: exactly TWO reads, in this order — reserved-name check, then schema
271
+ // validation. No third (containment-ceiling) read exists (ADR-0077 §C).
301
272
  checkReservedNames(resolvedDir);
302
273
  validateAtRunBoundary(resolvedDir, o);
303
- // ADR-0046 / REQ-RBV-06: the containment-ceiling walk shares the SAME pre-`als.run`
304
- // chokepoint as schema/reserved-name validation, not a separate, uncoordinated read
305
- // site — a missing ancestor fails closed here, before `fn` ever runs (REQ-RBV-06.1).
306
- packageAnchors = { packageDir: resolvedDir, packageRoot: resolvePackageRoot(resolvedDir) };
274
+ packageAnchors = { packageDir: resolvedDir };
307
275
  }
308
276
  const ctx = {
309
277
  session: new Session(client),
@@ -2,7 +2,7 @@
2
2
  "manifestVersion": 1,
3
3
  "algorithm": "sha256",
4
4
  "entry": "dist/bin/pbuilder-runner.js",
5
- "packageVersion": "0.1.0",
5
+ "packageVersion": "0.2.2",
6
6
  "files": [
7
7
  {
8
8
  "path": "dist/bin/pbuilder-runner.js",
@@ -10,11 +10,11 @@
10
10
  },
11
11
  {
12
12
  "path": "dist/core/authoring-error.js",
13
- "sha256": "547a9905f3b81a0613fd8bf6cbeb34ce2e0d54f3345b437f418e34ceb8076893"
13
+ "sha256": "cae518ed676614d754a58edb8fbb5c857c9dcdc7994e960d688c662a9774df53"
14
14
  },
15
15
  {
16
16
  "path": "dist/core/context.js",
17
- "sha256": "0a141b1939055518fa8ea6809dfecb43d60bdea816cc85c29c1f177c0c100ce0"
17
+ "sha256": "4f9e5b221964e5e9538c4c34158737d667c2a3bbd97358c750c786e918f0a6e5"
18
18
  },
19
19
  {
20
20
  "path": "dist/core/directive-factory.js",
@@ -98,7 +98,7 @@
98
98
  },
99
99
  {
100
100
  "path": "package.json",
101
- "sha256": "da7b6e33f330e6a15f3d26599ccbf100d4565a510e877876add6c8036a2c941b"
101
+ "sha256": "e67ee94357f6293c57df74c4f8501b9fb013737b7f0c950827d86976bc332a85"
102
102
  }
103
103
  ]
104
104
  }
@@ -10,7 +10,6 @@ export declare function decodeSniffableText(buf: Buffer): string | null;
10
10
  export declare function isSniffableText(buf: Buffer): boolean;
11
11
  interface ClassifyParams {
12
12
  packageDir: string;
13
- packageRoot: string;
14
13
  relPath: string;
15
14
  isTemplateMarked: boolean;
16
15
  /**
@@ -33,8 +32,6 @@ interface ClassifyParams {
33
32
  binary: string;
34
33
  oversized: string;
35
34
  };
36
- /** Precomputed `resolveRealCeiling(packageRoot)` — threaded by loop callers (`runScaffold`). */
37
- realCeiling?: string;
38
35
  }
39
36
  /**
40
37
  * Classifies ONE package-local source: stat-size gate before any content read
@@ -3,24 +3,21 @@
3
3
  // REQ-CCL-01/02/03/06), plus the `.template`/`templateFile` render-request fail-loud
4
4
  // carve-out (REQ-CCL-05). PURE per-file decision (Executor Context §18) — it never throws
5
5
  // for an ORDINARY by-reference verdict; the caller (`expander.ts`) decides what a
6
- // by-reference verdict means for THIS slice (S-001: fail-loud placeholder; S-003: real
7
- // `copyIn` emission).
6
+ // by-reference verdict means for THIS slice (S-003: real `copyIn` emission).
8
7
  //
9
- // Containment (S-002): delegates to `containment.ts`'s `validateSourceContainment` —
10
- // realpath-based, segment-aware, case-fold ceiling check + regular-file allow-list
11
- // (REQ-PRC-01..08) — REPLACING S-001's MINIMAL lexical-only placeholder guard. Containment
12
- // runs BEFORE any of this module's own stat/sniff/budget checks (REQ-PRC-08); the `Stats`
13
- // containment already obtained via `lstat` is reused here for the CCL-06 size gate rather
14
- // than stat'ing the path a second time. A `readFileSync` failure AFTER containment has
15
- // already proven an in-ceiling regular file (e.g. a permission/I/O error between lstat and
16
- // read) classifies `source-unreadable` (REQ-AEC-10) — distinct from a CONTENT-level
17
- // classify failure (binary/oversized), which stays `invalid-input` for `.template`-marked
18
- // entries only (REQ-CCL-05/AEC-12) and by-reference for everything else.
8
+ // ADR-0077: delegates to `path-guards.ts`'s `statSourceForRead` — IO hygiene (regular-file
9
+ // allow-list), no containment ceiling. Runs BEFORE any of this module's own stat/sniff/
10
+ // budget checks; the `Stats` it already obtained is reused here for the CCL-06 size gate
11
+ // rather than stat'ing the path a second time. A `readFileSync` failure AFTER hygiene has
12
+ // already proven a regular file (e.g. a permission/I/O error between stat and read)
13
+ // classifies `source-unreadable` (REQ-AEC-10) — distinct from a CONTENT-level classify
14
+ // failure (binary/oversized), which stays `invalid-input` for `.template`-marked entries
15
+ // only (REQ-CCL-05/AEC-12) and by-reference for everything else.
19
16
  import { readFileSync } from "node:fs";
20
- import { AuthoringError, invalidInput } from "../core/authoring-error.js";
17
+ import { invalidInput } from "../core/authoring-error.js";
21
18
  import { EMIT_BATCH_BUDGET_BYTES, serializedBatchSize } from "../core/wire.js";
22
19
  import { encodeOptions, forceEntry } from "../core/directive-factory.js";
23
- import { validateSourceContainment } from "./containment.js";
20
+ import { sourceRejection, statSourceForRead } from "./path-guards.js";
24
21
  // REQ-CCL-01's whole-file sniff, scoped to what a render REQUEST needs (S-000): valid UTF-8
25
22
  // across the ENTIRE buffer (never a prefix sample — REQ-CCL-03) and no null byte anywhere.
26
23
  // Lives here (the classify leaf) so the module graph stays acyclic — `index.ts` re-exports
@@ -50,7 +47,7 @@ function templateSniffFailMessage(relPath, problem) {
50
47
  "render requests never silently fall back to a copy");
51
48
  }
52
49
  export function classifyTransport(params) {
53
- const { packageDir, packageRoot, relPath, isTemplateMarked, destPath, options, force, failMessages, realCeiling } = params;
50
+ const { packageDir, relPath, isTemplateMarked, destPath, options, force, failMessages } = params;
54
51
  // The fail-loud message pair for a render REQUEST (either kind); undefined ⇒ a failed
55
52
  // gate is an ordinary by-reference verdict.
56
53
  const renderFail = failMessages ??
@@ -60,14 +57,13 @@ export function classifyTransport(params) {
60
57
  oversized: templateSniffFailMessage(relPath, "is too large to render inline (over the 4 MiB limit)"),
61
58
  }
62
59
  : undefined);
63
- // REQ-PRC-08: containment + regular-file eligibility complete BEFORE any content read.
64
- // Throws one of the four `source-*` reasons on failure — regardless of `isTemplateMarked`
65
- // (a missing/outside-package/non-regular SOURCE is a source-read failure, not a
66
- // classify-level CCL-05 content failure; only steps AFTER containment get the
67
- // `.template` invalid-input carve-out below).
68
- const { absPath, stat } = validateSourceContainment({ packageDir, packageRoot, relPath, realCeiling });
60
+ // IO hygiene completes BEFORE any content read. Throws one of the three surviving
61
+ // `source-*` reasons on failure — regardless of `isTemplateMarked` (a missing/
62
+ // non-regular SOURCE is a source-read failure, not a classify-level CCL-05 content
63
+ // failure; only steps AFTER hygiene get the `.template` invalid-input carve-out below).
64
+ const { absPath, stat } = statSourceForRead({ packageDir, relPath });
69
65
  // Stat-size gate BEFORE any content read (REQ-CCL-06): zero content-read calls for an
70
- // over-budget-by-stat file. Reuses containment's own `lstat` — no second stat call.
66
+ // over-budget-by-stat file. Reuses the hygiene guard's own `stat` — no second stat call.
71
67
  if (stat.size > EMIT_BATCH_BUDGET_BYTES) {
72
68
  if (renderFail) {
73
69
  throw invalidInput(renderFail.oversized);
@@ -79,9 +75,13 @@ export function classifyTransport(params) {
79
75
  buf = readFileSync(absPath);
80
76
  }
81
77
  catch {
82
- // Containment already proved an in-ceiling regular file; a read failure THIS LATE is a
83
- // genuine read-path failure (permission/I/O), never a missing/outside-package source.
84
- throw new AuthoringError({ verb: undefined, path: relPath, reason: "source-unreadable", appliedCount: 0 });
78
+ // Hygiene already proved a readable regular file; a read failure THIS LATE is a
79
+ // genuine read-path failure (permission/I/O), never a missing source. Routed through
80
+ // `path-guards.ts`'s own `sourceRejection` (judgment-day G4(i)) — a bare
81
+ // `new AuthoringError(...)` with no `message` falls to `messageFor`'s generic
82
+ // "could not be read" template, silently dropping the failure CATEGORY REQ-AEC-11.1
83
+ // mandates; `sourceRejection` is the one place that template is built.
84
+ throw sourceRejection("source-unreadable", relPath, "permission or I/O error");
85
85
  }
86
86
  const content = decodeSniffableText(buf);
87
87
  if (content === null) {
@@ -22,7 +22,8 @@ export interface ScaffoldArgs {
22
22
  * (`content-classification`); by-value sources emit a `create` directive through the
23
23
  * existing IR. A truly-empty `from` folder no-ops (REQ-FSC-04.1); filters eliminating
24
24
  * every entry fail loud, naming them (REQ-FSC-04.2). `force` passes through unchanged to
25
- * every emitted directive (REQ-FSC-06). The destination lexical guard (REQ-PRC-09) applies
25
+ * every emitted directive (REQ-FSC-06). The destination lexical guard (`ir-path-well-formedness`
26
+ * REQ-IPF-02, re-homed from the retired `package-root-containment` REQ-PRC-09) applies
26
27
  * to the FINAL computed destination, immediately pre-emit. Aggregate size never blocks the
27
28
  * scaffold outright (REQ-04) — the expander chunks via mid-run `session.flush()` calls
28
29
  * (see the module header for the sync/async bridge); run-level atomicity (REQ-05) is free.
@@ -33,7 +33,7 @@ import { EMIT_BATCH_BUDGET_BYTES, serializedBatchSize } from "../core/wire.js";
33
33
  import { walkFolder } from "./walk.js";
34
34
  import { runFilenamePipeline, isIncluded, detectDestinationCollisions, translateTokens } from "./filename-pipeline.js";
35
35
  import { classifyTransport } from "./classify-transport.js";
36
- import { validateDestinationLexical, validateSourceRootContainment, resolveRealCeiling } from "./containment.js";
36
+ import { validateDestinationLexical, validateSourceLexical } from "./path-guards.js";
37
37
  function noResolutionAnchorMessage() {
38
38
  return ("invalid input: scaffold has no package directory to resolve package-local files against — " +
39
39
  "pass `packageDir` to the call that runs this factory");
@@ -45,6 +45,44 @@ function filtersEliminatedEverythingMessage(include, exclude) {
45
45
  return (`invalid input: scaffold filters eliminated every entry — ` +
46
46
  `include: ${JSON.stringify(include ?? [])}, exclude: ${JSON.stringify(exclude ?? [])}`);
47
47
  }
48
+ // judgment-day round 3 fix (F1): a non-array (or an array with a non-string element)
49
+ // used to reach `isIncluded`'s `.some((p) => globToRegex(p).test(relPath))` and either
50
+ // throw a raw TypeError (non-array) or silently compile a non-string element into an
51
+ // always-empty-matching `/^$/` regex (an element that never rejects, never matches) —
52
+ // screened here, at entry, before either filter ever reaches `isIncluded`. No-echo: names
53
+ // the OPTION, never echoes the (possibly huge or malformed) value itself.
54
+ function filterOptionShapeMessage(option) {
55
+ return `invalid input: scaffold "${option}" must be an array of strings`;
56
+ }
57
+ function validateFilterOptionShape(option, value) {
58
+ if (value === undefined) {
59
+ return;
60
+ }
61
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
62
+ throw invalidInput(filterOptionShapeMessage(option));
63
+ }
64
+ }
65
+ // Owner ruling 17 (2026-07-29, judgment-day round 3): `from` resolving to the package root
66
+ // itself — `""`, `"."`, or `"./"` — used to enumerate the ENTIRE `packageDir`, never
67
+ // rejected: none of these three literals contain a `..` segment or an absolute form, so
68
+ // `validateSourceLexical` let them straight through to `walkFolder`. `scaffold` mirrors A
69
+ // FOLDER into `to`; the package root is not a folder an author names on purpose to mirror
70
+ // wholesale, and doing so silently is a strictly worse surprise than the analogous
71
+ // symlinked-root rejection (ruling 16) — same posture, same reason. Also closes a related
72
+ // theoretical: `resolve("")`/`resolve(".")`/`resolve("./")` all equal `packageDir` itself,
73
+ // so the (unresolved) question of whether `packageDir` being a symlink should exempt the
74
+ // walk-root symlink check never arises for these three forms — they never reach the walk
75
+ // at all.
76
+ const DEGENERATE_FROM_VALUES = new Set(["", ".", "./"]);
77
+ function degenerateFromMessage(from) {
78
+ return (`invalid input: scaffold "from" (${JSON.stringify(from)}) refers to the package directory ` +
79
+ `itself — scaffold never implicitly mirrors the whole package; point "from" at a real subfolder`);
80
+ }
81
+ function validateNonDegenerateFrom(from) {
82
+ if (DEGENERATE_FROM_VALUES.has(from)) {
83
+ throw invalidInput(degenerateFromMessage(from));
84
+ }
85
+ }
48
86
  // REQ-04's serialized-size heuristic (S-004): tracks what the PENDING batch would
49
87
  // serialize to via `serializedBatchSize`'s envelope shape — the EXACT same measurement the
50
88
  // fake applies at emit time — a lowering heuristic, not a second size authority (ADR-0018
@@ -59,7 +97,8 @@ const EMPTY_BATCH_SIZE = serializedBatchSize([]);
59
97
  * (`content-classification`); by-value sources emit a `create` directive through the
60
98
  * existing IR. A truly-empty `from` folder no-ops (REQ-FSC-04.1); filters eliminating
61
99
  * every entry fail loud, naming them (REQ-FSC-04.2). `force` passes through unchanged to
62
- * every emitted directive (REQ-FSC-06). The destination lexical guard (REQ-PRC-09) applies
100
+ * every emitted directive (REQ-FSC-06). The destination lexical guard (`ir-path-well-formedness`
101
+ * REQ-IPF-02, re-homed from the retired `package-root-containment` REQ-PRC-09) applies
63
102
  * to the FINAL computed destination, immediately pre-emit. Aggregate size never blocks the
64
103
  * scaffold outright (REQ-04) — the expander chunks via mid-run `session.flush()` calls
65
104
  * (see the module header for the sync/async bridge); run-level atomicity (REQ-05) is free.
@@ -73,19 +112,32 @@ export function runScaffold(args) {
73
112
  }
74
113
  const ctx = currentContext();
75
114
  const { session, factory } = ctx;
76
- const { packageDir, packageRoot } = requirePackageAnchors(noResolutionAnchorMessage());
77
- // The ceiling's realpath is a RUN invariant (not one of the pinned per-candidate
78
- // validation steps) — resolve it once for both the root check below and the whole
79
- // entry loop.
80
- const realCeiling = resolveRealCeiling(packageRoot);
81
- // SEC (owner-ratified final-verify remediation): the walk ROOT itself must be
82
- // containment-checked BEFORE `walkFolder` ever enumerates it — otherwise an escaping
83
- // `from` (e.g. `../secrets`) would readdirSync/lstatSync the whole out-of-ceiling
84
- // subtree (bounded by `walk.ts`'s 10k-entry cap) before any per-entry containment
85
- // check had a chance to fire. Reuses the SAME lexical + realpath ceiling machinery the
86
- // per-entry loop below already uses via `classifyTransport` → `validateSourceContainment`
87
- // — no parallel check forked for this directory case.
88
- validateSourceRootContainment({ packageDir, packageRoot, relPath: args.from, realCeiling });
115
+ const { packageDir } = requirePackageAnchors(noResolutionAnchorMessage());
116
+ // judgment-day round 3 fix (F4): destination validated AFTER context resolution (`ctx`/
117
+ // `packageDir` above), not before it — round 2 placed this call at the very top of the
118
+ // function, ABOVE `currentContext()`, so an escaping `to` called OUTSIDE any run reported
119
+ // `invalid-input` where `copyIn` (whose own version of this same guard already runs
120
+ // AFTER its `currentContext()`/`requirePackageAnchors` calls, see `index.ts`'s
121
+ // `runCopyIn`) reports `outside-run` — the two package-local verbs disagreed on which
122
+ // failure wins when BOTH apply. `runScaffold` now mirrors `runCopyIn`'s exact ordering:
123
+ // ctx → packageDir → destination guard → (new F7/F1 screens below) → source guard. The
124
+ // existing post-rename/post-token-translation validation of the FINAL `destPath` inside
125
+ // the loop below is unchanged — rename/token substitution can still alter the string
126
+ // after this raw-input screen passes.
127
+ validateDestinationLexical(args.to);
128
+ // Owner ruling 17 (F7): a degenerate `from` (`""`, `"."`, `"./"`) rejects before it ever
129
+ // reaches the walk — see `validateNonDegenerateFrom`'s own comment above.
130
+ validateNonDegenerateFrom(args.from);
131
+ // judgment-day round 3 fix (F1): include/exclude shape-screened before either ever
132
+ // reaches `isIncluded` (see `validateFilterOptionShape`'s own comment above).
133
+ validateFilterOptionShape("include", args.include);
134
+ validateFilterOptionShape("exclude", args.exclude);
135
+ // Screen call site 2 (REQ-IPF-01): the walk ROOT itself must be lexically screened
136
+ // BEFORE `walkFolder` ever enumerates it — otherwise an escaping `from` (e.g.
137
+ // `../secrets`) would readdirSync/lstatSync the whole tree (bounded by `walk.ts`'s
138
+ // 10k-entry cap) before any check had a chance to fire. Check-before-walk ordering
139
+ // preserved verbatim (design §4).
140
+ validateSourceLexical(args.from);
89
141
  const fromAbs = join(packageDir, args.from);
90
142
  const walked = walkFolder(fromAbs, undefined, args.from);
91
143
  if (walked.length === 0) {
@@ -108,6 +160,18 @@ export function runScaffold(args) {
108
160
  let pendingSize = serializedBatchSize(seedPending);
109
161
  for (const result of pipelineResults) {
110
162
  const sourceRelPath = posix.join(args.from, result.sourceRelPath);
163
+ // judgment-day round 3 fix (F2): `posix.join(toPrefix, result.destRelPath)` NORMALIZES
164
+ // away any `..` segment in `result.destRelPath` BEFORE the post-join
165
+ // `validateDestinationLexical(destPath)` below ever runs — a `rename` value like
166
+ // `"../evil.ts"` joined against a one-segment `to` (e.g. `"out"`) collapses to
167
+ // `"evil.ts"`, which contains no literal `..` and sails through the post-join guard
168
+ // even though it never lands under `to` at all (REQ-FSC-02's mirror-under-`to`
169
+ // invariant, violated silently). Validating the PRE-join `result.destRelPath` catches
170
+ // every literal `..` segment a rename rule can introduce, regardless of whether `to`'s
171
+ // own depth happens to "cancel" it out after joining — the post-join guard below stays
172
+ // as a second, independent check (e.g. for a `to` prefix itself carrying a stray
173
+ // segment after token translation).
174
+ validateDestinationLexical(result.destRelPath);
111
175
  // destPath computed BEFORE classify (reordered from the source-only call this
112
176
  // replaces): REQ-CCL-02's budget is evaluated against the PROSPECTIVE `create`
113
177
  // directive this source would emit, so classifyTransport needs the same
@@ -115,10 +179,8 @@ export function runScaffold(args) {
115
179
  const destPath = posix.join(toPrefix, result.destRelPath);
116
180
  const verdict = classifyTransport({
117
181
  packageDir,
118
- packageRoot,
119
182
  relPath: sourceRelPath,
120
183
  isTemplateMarked: result.isTemplateMarked,
121
- realCeiling,
122
184
  destPath,
123
185
  options: args.options ?? {},
124
186
  force: args.force,
@@ -126,9 +188,10 @@ export function runScaffold(args) {
126
188
  validateDestinationLexical(destPath);
127
189
  // S-003: a by-reference verdict emits a real `copyIn` directive — `from` is the
128
190
  // package-relative source path (REQ-BRC-07), never the resolved absolute path;
129
- // containment already validated this source inside `classifyTransport`
130
- // (`validateSourceContainment` runs BEFORE the stat/sniff/budget gates, REQ-PRC-08),
131
- // so no second containment check is needed here.
191
+ // hygiene already validated this source inside `classifyTransport`
192
+ // (`statSourceForRead` runs BEFORE the stat/sniff/budget gates), so no second
193
+ // hygiene check is needed here. Per-entry sources are SDK-computed from an
194
+ // already-screened root and are NOT re-lexically-screened (design §4 carve-out).
132
195
  const directive = verdict.verdict === "by-value"
133
196
  ? factory.create({
134
197
  pathTemplate: destPath,
@@ -1,8 +1,11 @@
1
1
  /**
2
2
  * Translates on-disk filename tokens to the wire `pathTemplate` syntax the ENGINE
3
3
  * substitutes (obs #915 ruling 4) — the SDK never renders these itself, only rewrites the
4
- * marker syntax. `__name@dasherize__` → `{= name | dasherize =}`; a bare `__name__`
5
- * (no `@pipe`) → `{= name =}`.
4
+ * marker syntax. `__name@dasherize__` → `{= .name | dasherize =}`; a bare `__name__`
5
+ * (no `@pipe`) → `{= .name =}`. The dotted field reference is REQUIRED by the engine's
6
+ * templating (bare `{= name =}` was migrated away — docs/templating/migration-note.md in
7
+ * the engine repo); emitting the bare form makes every tokenized filename fail
8
+ * path-render at ingest (`path-render-failed`, exit 2).
6
9
  */
7
10
  export declare function translateTokens(path: string): string;
8
11
  /** REQ-FSC-05 step (3): strips a `.template` suffix from the (post-translation) path. */
@@ -35,5 +38,12 @@ export declare function isIncluded(relPath: string, include: readonly string[] |
35
38
  * destination (after the filename pipeline collapses their names), reject fail-loud,
36
39
  * deterministically, naming ALL offending source paths — never last-writer-wins, never
37
40
  * dependent on walk order.
41
+ *
42
+ * judgment-day round 3 fix (F5): keyed on `posix.normalize(destRelPath)`, not the raw
43
+ * string — a `rename` value like `"./b.ts"` and a sibling literal `"b.ts"` are the SAME
44
+ * destination post-normalization (the expander's own `posix.join` would collapse them
45
+ * identically) but previously formed two distinct map keys, so the collision went
46
+ * undetected here and surfaced later as whatever error family the SECOND write happened
47
+ * to hit, instead of this REQ's deterministic, both-offenders-named rejection.
38
48
  */
39
49
  export declare function detectDestinationCollisions(results: readonly PipelineResult[]): void;