@pbuilder/sdk 0.1.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.
Files changed (121) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +202 -0
  3. package/dist/bin/pbuilder-codegen.js +506 -0
  4. package/dist/bin/pbuilder-runner.d.ts +1 -0
  5. package/dist/bin/pbuilder-runner.js +47 -0
  6. package/dist/commons/classify-content.d.ts +40 -0
  7. package/dist/commons/classify-content.js +32 -0
  8. package/dist/commons/index.d.ts +271 -0
  9. package/dist/commons/index.js +276 -0
  10. package/dist/conformance/index.d.ts +115 -0
  11. package/dist/conformance/index.js +218 -0
  12. package/dist/conformance/run-vehicle.d.ts +19 -0
  13. package/dist/conformance/run-vehicle.js +104 -0
  14. package/dist/core/authoring-error.d.ts +116 -0
  15. package/dist/core/authoring-error.js +205 -0
  16. package/dist/core/base-handle.d.ts +17 -0
  17. package/dist/core/base-handle.js +4 -0
  18. package/dist/core/context.d.ts +85 -0
  19. package/dist/core/context.js +356 -0
  20. package/dist/core/deep-equal.d.ts +1 -0
  21. package/dist/core/deep-equal.js +29 -0
  22. package/dist/core/define-dialect.d.ts +94 -0
  23. package/dist/core/define-dialect.js +121 -0
  24. package/dist/core/dialect-error.d.ts +8 -0
  25. package/dist/core/dialect-error.js +26 -0
  26. package/dist/core/dialect-handle.d.ts +21 -0
  27. package/dist/core/dialect-handle.js +382 -0
  28. package/dist/core/directive-factory.d.ts +47 -0
  29. package/dist/core/directive-factory.js +154 -0
  30. package/dist/core/emit-rejection.d.ts +19 -0
  31. package/dist/core/emit-rejection.js +31 -0
  32. package/dist/core/engine-client.d.ts +7 -0
  33. package/dist/core/engine-client.js +5 -0
  34. package/dist/core/fs-errors.d.ts +1 -0
  35. package/dist/core/fs-errors.js +5 -0
  36. package/dist/core/handle-state.d.ts +24 -0
  37. package/dist/core/handle-state.js +4 -0
  38. package/dist/core/index.d.ts +10 -0
  39. package/dist/core/index.js +6 -0
  40. package/dist/core/jsx-name-validator.d.ts +19 -0
  41. package/dist/core/jsx-name-validator.js +104 -0
  42. package/dist/core/reject-tail.d.ts +23 -0
  43. package/dist/core/reject-tail.js +63 -0
  44. package/dist/core/schema/input-rejection.d.ts +4 -0
  45. package/dist/core/schema/input-rejection.js +32 -0
  46. package/dist/core/schema/schema-digest.d.ts +1 -0
  47. package/dist/core/schema/schema-digest.js +7 -0
  48. package/dist/core/schema/schema-discovery.d.ts +13 -0
  49. package/dist/core/schema/schema-discovery.js +51 -0
  50. package/dist/core/schema/schema-locate.d.ts +10 -0
  51. package/dist/core/schema/schema-locate.js +192 -0
  52. package/dist/core/schema/schema-model.d.ts +18 -0
  53. package/dist/core/schema/schema-model.js +15 -0
  54. package/dist/core/schema/schema-parse.d.ts +20 -0
  55. package/dist/core/schema/schema-parse.js +80 -0
  56. package/dist/core/schema/schema-sufficiency.d.ts +17 -0
  57. package/dist/core/schema/schema-sufficiency.js +54 -0
  58. package/dist/core/schema/schema-validate.d.ts +14 -0
  59. package/dist/core/schema/schema-validate.js +64 -0
  60. package/dist/core/session.d.ts +13 -0
  61. package/dist/core/session.js +72 -0
  62. package/dist/core/wire.d.ts +87 -0
  63. package/dist/core/wire.js +49 -0
  64. package/dist/dialects/react/ast.d.ts +25 -0
  65. package/dist/dialects/react/ast.js +80 -0
  66. package/dist/dialects/react/index.d.ts +39 -0
  67. package/dist/dialects/react/index.js +71 -0
  68. package/dist/dialects/react/ops.d.ts +56 -0
  69. package/dist/dialects/react/ops.js +186 -0
  70. package/dist/dialects/typescript/ast.d.ts +42 -0
  71. package/dist/dialects/typescript/ast.js +93 -0
  72. package/dist/dialects/typescript/index.d.ts +32 -0
  73. package/dist/dialects/typescript/index.js +40 -0
  74. package/dist/dialects/typescript/ops.d.ts +123 -0
  75. package/dist/dialects/typescript/ops.js +365 -0
  76. package/dist/dry-run/index.d.ts +2 -0
  77. package/dist/dry-run/index.js +1 -0
  78. package/dist/dry-run/plan.d.ts +69 -0
  79. package/dist/dry-run/plan.js +44 -0
  80. package/dist/index.d.ts +1 -0
  81. package/dist/index.js +3 -0
  82. package/dist/runner-manifest.json +104 -0
  83. package/dist/scaffold/classify-transport.d.ts +57 -0
  84. package/dist/scaffold/classify-transport.js +123 -0
  85. package/dist/scaffold/containment.d.ts +54 -0
  86. package/dist/scaffold/containment.js +242 -0
  87. package/dist/scaffold/expander.d.ts +30 -0
  88. package/dist/scaffold/expander.js +161 -0
  89. package/dist/scaffold/filename-pipeline.d.ts +39 -0
  90. package/dist/scaffold/filename-pipeline.js +125 -0
  91. package/dist/scaffold/index.d.ts +45 -0
  92. package/dist/scaffold/index.js +99 -0
  93. package/dist/scaffold/walk.d.ts +25 -0
  94. package/dist/scaffold/walk.js +124 -0
  95. package/dist/testing/contract-fake.d.ts +17 -0
  96. package/dist/testing/contract-fake.js +221 -0
  97. package/dist/testing/index.d.ts +84 -0
  98. package/dist/testing/index.js +82 -0
  99. package/dist/testing/rejection-messages.d.ts +7 -0
  100. package/dist/testing/rejection-messages.js +12 -0
  101. package/dist/transport/bootstrap-bridge.d.ts +33 -0
  102. package/dist/transport/bootstrap-bridge.js +65 -0
  103. package/dist/transport/error-text.d.ts +8 -0
  104. package/dist/transport/error-text.js +44 -0
  105. package/dist/transport/exit-codes.d.ts +2 -0
  106. package/dist/transport/exit-codes.js +35 -0
  107. package/dist/transport/factory-pointer.d.ts +32 -0
  108. package/dist/transport/factory-pointer.js +63 -0
  109. package/dist/transport/frame-reader.d.ts +10 -0
  110. package/dist/transport/frame-reader.js +81 -0
  111. package/dist/transport/framing.d.ts +20 -0
  112. package/dist/transport/framing.js +98 -0
  113. package/dist/transport/runner.d.ts +25 -0
  114. package/dist/transport/runner.js +308 -0
  115. package/dist/transport/single-instance-probe.d.ts +23 -0
  116. package/dist/transport/single-instance-probe.js +119 -0
  117. package/dist/transport/stdio-engine-client.d.ts +27 -0
  118. package/dist/transport/stdio-engine-client.js +243 -0
  119. package/dist/transport/wire-protocol.d.ts +33 -0
  120. package/dist/transport/wire-protocol.js +22 -0
  121. package/package.json +93 -0
@@ -0,0 +1,44 @@
1
+ // Frozen seven-row wire→author verb map — delete→remove, identity elsewhere (including
2
+ // copyIn→copyIn). EXPORTED for the D3 consistency test (test-only reach, §4.6b): NOT
3
+ // re-exported by src/dry-run/index.ts or ./commons. The Record<Directive["op"], DryRunVerb>
4
+ // annotation itself compile-enforces totality over wire ops and value-membership in
5
+ // DryRunVerb; Object.freeze makes the "frozen" claim literal at runtime.
6
+ export const WIRE_TO_AUTHOR_VERB = Object.freeze({
7
+ create: "create",
8
+ modify: "modify",
9
+ delete: "remove",
10
+ rename: "rename",
11
+ move: "move",
12
+ copy: "copy",
13
+ copyIn: "copyIn",
14
+ });
15
+ /**
16
+ * Renders a directive snapshot as an author-vocabulary plan.
17
+ *
18
+ * Each entry carries the author verb (per the frozen `WIRE_TO_AUTHOR_VERB` table above)
19
+ * and the primary source path of the operation:
20
+ * create → create.pathTemplate
21
+ * modify → modify.path
22
+ * delete → delete.path (rendered as author verb "remove")
23
+ * rename → rename.path
24
+ * move → move.path
25
+ * copy → copy.from (primary source path)
26
+ * copyIn → copyIn.from (primary source path, REQ-BRC-07 package-relative)
27
+ */
28
+ export function dryRunPlan(snapshot) {
29
+ return snapshot.map((d) => {
30
+ const verb = WIRE_TO_AUTHOR_VERB[d.op];
31
+ switch (d.op) {
32
+ // "rendered" — every `create` IS a render request, inline `template` or
33
+ // `templateFile` alike (REQ-DRE-05.3's indistinguishability).
34
+ case "create": return { verb, path: d.create.pathTemplate, kind: "rendered" };
35
+ case "modify": return { verb, path: d.modify.path };
36
+ case "delete": return { verb, path: d.delete.path };
37
+ case "rename": return { verb, path: d.rename.path };
38
+ case "move": return { verb, path: d.move.path };
39
+ case "copy": return { verb, path: d.copy.from };
40
+ // "copied" — a copyIn NEVER renders (REQ-FEH-03); DRE-05.2's always-copied pin.
41
+ case "copyIn": return { verb, path: d.copyIn.from, kind: "copied" };
42
+ }
43
+ });
44
+ }
@@ -0,0 +1 @@
1
+ export * from "./commons/index.ts";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ // Umbrella entry (PKG-01): re-exports the commons surface only.
2
+ // The core kit is NOT re-exported from the umbrella — it is an internal boundary (ADR-0009).
3
+ export * from "./commons/index.js";
@@ -0,0 +1,104 @@
1
+ {
2
+ "manifestVersion": 1,
3
+ "algorithm": "sha256",
4
+ "entry": "dist/bin/pbuilder-runner.js",
5
+ "packageVersion": "0.1.0",
6
+ "files": [
7
+ {
8
+ "path": "dist/bin/pbuilder-runner.js",
9
+ "sha256": "589bb4be31a6ec3e2043f29f1c664b59a10106461fa26f39a0e0647450f226eb"
10
+ },
11
+ {
12
+ "path": "dist/core/authoring-error.js",
13
+ "sha256": "547a9905f3b81a0613fd8bf6cbeb34ce2e0d54f3345b437f418e34ceb8076893"
14
+ },
15
+ {
16
+ "path": "dist/core/context.js",
17
+ "sha256": "0a141b1939055518fa8ea6809dfecb43d60bdea816cc85c29c1f177c0c100ce0"
18
+ },
19
+ {
20
+ "path": "dist/core/directive-factory.js",
21
+ "sha256": "06f13f234f77bfd749139d937b7d2381a0d72b364d9f68912a0bccbc7ee43cf3"
22
+ },
23
+ {
24
+ "path": "dist/core/emit-rejection.js",
25
+ "sha256": "c81b169f05ecc251a374c593d3d3a86eaef79d5fbddbb379c3db0b8cc62ad962"
26
+ },
27
+ {
28
+ "path": "dist/core/fs-errors.js",
29
+ "sha256": "2b94dc59e783947a812980ed8f95d4ff45a983feafef0cdcbd47a3f6eaf67326"
30
+ },
31
+ {
32
+ "path": "dist/core/schema/input-rejection.js",
33
+ "sha256": "35af35b5176418b432edee714781ff2109402857743576ca661aa978149e950d"
34
+ },
35
+ {
36
+ "path": "dist/core/schema/schema-discovery.js",
37
+ "sha256": "a6b499fe8db7a3424a7ccb7a4167c19c7e91b9cb095e347d01cf2f70418538c0"
38
+ },
39
+ {
40
+ "path": "dist/core/schema/schema-locate.js",
41
+ "sha256": "e009cb5aad5da8777c1d02fb95bd46817e2d90e1f46b51c1b3ab5e408f44ab88"
42
+ },
43
+ {
44
+ "path": "dist/core/schema/schema-model.js",
45
+ "sha256": "7e9e3077326d3aa54ac431d1b6243d2f1302178f095be073ddc2caf365d2600d"
46
+ },
47
+ {
48
+ "path": "dist/core/schema/schema-parse.js",
49
+ "sha256": "4a04bbde1280346a9507510ec40afd4cb11ebc47d0a1030b52ae7a541af0b92e"
50
+ },
51
+ {
52
+ "path": "dist/core/schema/schema-validate.js",
53
+ "sha256": "5fd413555c634a0ab2eafb7623d8cc1f0f5e1f7ccd76d07902f269fd8fd966c9"
54
+ },
55
+ {
56
+ "path": "dist/core/session.js",
57
+ "sha256": "4661d074fa557ec01981df7d19b5a722d89135693eaea727a849d03bd08fdd51"
58
+ },
59
+ {
60
+ "path": "dist/core/wire.js",
61
+ "sha256": "b3ff9a33176024da8cc49f9556ace93ec22c20c260174b3bf2de2788bffd4d39"
62
+ },
63
+ {
64
+ "path": "dist/transport/error-text.js",
65
+ "sha256": "1a86edbd4060839b309cf5c2144f5c05e1889a62d6eb0d6090b733257157253c"
66
+ },
67
+ {
68
+ "path": "dist/transport/exit-codes.js",
69
+ "sha256": "bade80e088984872ab8e1ba24a54adcf455c157ef1247194a9da6270db45aefe"
70
+ },
71
+ {
72
+ "path": "dist/transport/factory-pointer.js",
73
+ "sha256": "348901046255c39618b02c8d21342aa30f10126c9438e11c4d168d56b8629619"
74
+ },
75
+ {
76
+ "path": "dist/transport/frame-reader.js",
77
+ "sha256": "6c16f935d745bad19e1c0f729dc929a63cf65da392dce2a0cd551b71c35df3f8"
78
+ },
79
+ {
80
+ "path": "dist/transport/framing.js",
81
+ "sha256": "8e0e0240d36e7d8f3a8066d11f1c1a884e6fcad6c955443f2fb05db34ef729f7"
82
+ },
83
+ {
84
+ "path": "dist/transport/runner.js",
85
+ "sha256": "6c587dcbd5ac45a6f49bf06e0566669d19ce504cf041ab1fad22794291c4411f"
86
+ },
87
+ {
88
+ "path": "dist/transport/single-instance-probe.js",
89
+ "sha256": "0986893b484321d5ec9d22fd3eb0d3626d337a91b9a1c3a9e5ffc19d6a4ec5db"
90
+ },
91
+ {
92
+ "path": "dist/transport/stdio-engine-client.js",
93
+ "sha256": "57f6f76bd05bf623aae182de262649440b8dd2218dfc01e9a17a7984f20cd9be"
94
+ },
95
+ {
96
+ "path": "dist/transport/wire-protocol.js",
97
+ "sha256": "bdec9f397c6ea4fbd9c4facf5ac6078b7a79eb438cf7eac03066f0a5d555609c"
98
+ },
99
+ {
100
+ "path": "package.json",
101
+ "sha256": "da7b6e33f330e6a15f3d26599ccbf100d4565a510e877876add6c8036a2c941b"
102
+ }
103
+ ]
104
+ }
@@ -0,0 +1,57 @@
1
+ import type { JsonValue } from "../core/wire.ts";
2
+ export type ClassificationVerdict = "by-value" | "by-reference";
3
+ export type ClassifyResult = {
4
+ verdict: "by-value"; /** The file's decoded UTF-8 content. */
5
+ content: string;
6
+ } | {
7
+ verdict: "by-reference";
8
+ };
9
+ export declare function decodeSniffableText(buf: Buffer): string | null;
10
+ export declare function isSniffableText(buf: Buffer): boolean;
11
+ interface ClassifyParams {
12
+ packageDir: string;
13
+ packageRoot: string;
14
+ relPath: string;
15
+ isTemplateMarked: boolean;
16
+ /**
17
+ * The `pathTemplate`/`options`/`force` the caller would put on the `create` directive
18
+ * IF this source classifies by-value — REQUIRED, never defaulted, so the budget check
19
+ * below can never silently regress to a content-only measure (REQ-CCL-02: the budget is
20
+ * evaluated against the PROSPECTIVE emitted directive, matching the emit authority
21
+ * exactly — see the `serializedBatchSize` call below).
22
+ */
23
+ destPath: string;
24
+ options: JsonValue;
25
+ force?: boolean;
26
+ /**
27
+ * Render-request mode (`create({templateFile})`, REQ-FEH-02): a failed gate throws
28
+ * `invalid-input` with THESE caller-pinned message texts instead of degrading to a
29
+ * by-reference verdict — the same fail-loud carve-out `.template`-marked entries get,
30
+ * with the caller's own message family.
31
+ */
32
+ failMessages?: {
33
+ binary: string;
34
+ oversized: string;
35
+ };
36
+ /** Precomputed `resolveRealCeiling(packageRoot)` — threaded by loop callers (`runScaffold`). */
37
+ realCeiling?: string;
38
+ }
39
+ /**
40
+ * Classifies ONE package-local source: stat-size gate before any content read
41
+ * (REQ-CCL-06) → whole-file UTF-8/null-byte sniff (REQ-CCL-01/03) → serialized-budget
42
+ * check (REQ-CCL-02) → verdict. A `.template`-marked source (`isTemplateMarked`, from the
43
+ * filename pipeline's post-translation check) NEVER degrades to by-reference on a failed
44
+ * gate — it fails loud instead (REQ-CCL-05), same posture `readTemplateFile` applies to
45
+ * `create({templateFile})` render requests via `failMessages` (REQ-FEH-02).
46
+ */
47
+ export declare function classifyTransport(params: ClassifyParams & {
48
+ failMessages: {
49
+ binary: string;
50
+ oversized: string;
51
+ };
52
+ }): {
53
+ verdict: "by-value";
54
+ content: string;
55
+ };
56
+ export declare function classifyTransport(params: ClassifyParams): ClassifyResult;
57
+ export {};
@@ -0,0 +1,123 @@
1
+ // src/scaffold/classify-transport.ts (ADR-0044): the by-value/by-reference classifier —
2
+ // stat-gate → whole-file sniff → serialized-budget → verdict (content-classification
3
+ // REQ-CCL-01/02/03/06), plus the `.template`/`templateFile` render-request fail-loud
4
+ // carve-out (REQ-CCL-05). PURE per-file decision (Executor Context §18) — it never throws
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).
8
+ //
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.
19
+ import { readFileSync } from "node:fs";
20
+ import { AuthoringError, invalidInput } from "../core/authoring-error.js";
21
+ import { EMIT_BATCH_BUDGET_BYTES, serializedBatchSize } from "../core/wire.js";
22
+ import { encodeOptions, forceEntry } from "../core/directive-factory.js";
23
+ import { validateSourceContainment } from "./containment.js";
24
+ // REQ-CCL-01's whole-file sniff, scoped to what a render REQUEST needs (S-000): valid UTF-8
25
+ // across the ENTIRE buffer (never a prefix sample — REQ-CCL-03) and no null byte anywhere.
26
+ // Lives here (the classify leaf) so the module graph stays acyclic — `index.ts` re-exports
27
+ // the boolean form for the historical `scaffold/index.ts` surface. A render request has no
28
+ // by-reference fallback (REQ-FEH-02), it fails loud. `ignoreBOM: true` is REQUIRED (judgment-
29
+ // day iteration 2 fix, REQ-FEH-01.1): `TextDecoder` defaults to stripping a leading UTF-8 BOM
30
+ // (`ignoreBOM: false`), which would silently drop bytes from a file's exact content — this
31
+ // decoded string becomes the `create` directive's `template` (both the by-value scaffold path
32
+ // and `readTemplateFile`), so a BOM-prefixed source must decode BOM-preserving to honor "exact
33
+ // content" (REQ-FEH-01.1). `ignoreBOM: true` still fatal-validates the whole buffer in one pass
34
+ // — no second decode at the caller.
35
+ export function decodeSniffableText(buf) {
36
+ if (buf.includes(0))
37
+ return null;
38
+ try {
39
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buf);
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ export function isSniffableText(buf) {
46
+ return decodeSniffableText(buf) !== null;
47
+ }
48
+ function templateSniffFailMessage(relPath, problem) {
49
+ return (`invalid input: source "${relPath}" is marked .template but ${problem} — ` +
50
+ "render requests never silently fall back to a copy");
51
+ }
52
+ export function classifyTransport(params) {
53
+ const { packageDir, packageRoot, relPath, isTemplateMarked, destPath, options, force, failMessages, realCeiling } = params;
54
+ // The fail-loud message pair for a render REQUEST (either kind); undefined ⇒ a failed
55
+ // gate is an ordinary by-reference verdict.
56
+ const renderFail = failMessages ??
57
+ (isTemplateMarked
58
+ ? {
59
+ binary: templateSniffFailMessage(relPath, "is not valid text (binary content)"),
60
+ oversized: templateSniffFailMessage(relPath, "is too large to render inline (over the 4 MiB limit)"),
61
+ }
62
+ : 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 });
69
+ // 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.
71
+ if (stat.size > EMIT_BATCH_BUDGET_BYTES) {
72
+ if (renderFail) {
73
+ throw invalidInput(renderFail.oversized);
74
+ }
75
+ return { verdict: "by-reference" };
76
+ }
77
+ let buf;
78
+ try {
79
+ buf = readFileSync(absPath);
80
+ }
81
+ 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 });
85
+ }
86
+ const content = decodeSniffableText(buf);
87
+ if (content === null) {
88
+ if (renderFail) {
89
+ throw invalidInput(renderFail.binary);
90
+ }
91
+ return { verdict: "by-reference" };
92
+ }
93
+ // Serialized-form budget (REQ-CCL-02): measured against the PROSPECTIVE `create`
94
+ // DIRECTIVE this source would emit if classified by-value — envelope, `create` wrapper,
95
+ // `pathTemplate`, and `options` all included, never the content string alone — via the
96
+ // SAME `serializedBatchSize` helper the fake's real batch-cap check applies at emit time
97
+ // (`core/wire.ts`). A lone over-budget directive can never fit any flush group (the
98
+ // expander flushes a solo directive as its own group, REQ-04.2), so measuring the
99
+ // single-directive batch here is exactly what the emit authority will measure later —
100
+ // against `EMIT_BATCH_BUDGET_BYTES`, the SAME boundary `exceedsEmitBatchBudget` enforces
101
+ // at emit (spec V4 REQ-WPS-04.1: the cap reserves the frame-envelope allowance).
102
+ // `>` (not `>=`) — exactly-at-budget still fits (REQ-CCL-02.3).
103
+ //
104
+ // REQ-CCL-02.4: `options` is run through the SAME shared `encodeOptions` (fit-39's one
105
+ // other sanctioned call site) real `create()` emission applies — never the caller's raw,
106
+ // pre-encode shape. A composite option value's JSON-string form carries its own
107
+ // quote/backslash-escaping inflation once re-embedded and serialized again here, closing
108
+ // the pre-encode/post-encode misclassification gap: measuring the raw shape would
109
+ // under-count and could wrongly classify by-value a directive that is actually over
110
+ // budget once the real encode step runs.
111
+ const prospectiveDirective = {
112
+ op: "create",
113
+ create: { pathTemplate: destPath, template: content, options: encodeOptions(options), ...forceEntry(force) },
114
+ };
115
+ const directiveSize = serializedBatchSize([prospectiveDirective]);
116
+ if (directiveSize > EMIT_BATCH_BUDGET_BYTES) {
117
+ if (renderFail) {
118
+ throw invalidInput(renderFail.oversized);
119
+ }
120
+ return { verdict: "by-reference" };
121
+ }
122
+ return { verdict: "by-value", content };
123
+ }
@@ -0,0 +1,54 @@
1
+ import { type Stats } from "node:fs";
2
+ export declare function isWithinCeiling(candidateAbs: string, ceilingAbs: string): boolean;
3
+ /**
4
+ * The realpath'd form of the containment ceiling — a RUN invariant (`packageRoot` is
5
+ * seeded once per run and always exists, so this realpath cannot ENOENT). Loop callers
6
+ * (`runScaffold`) compute it once and thread it through `classifyTransport` →
7
+ * `validateSourceContainment` instead of re-realpath'ing the same directory per entry.
8
+ */
9
+ export declare function resolveRealCeiling(packageRoot: string): string;
10
+ /**
11
+ * Validates ONE package-local SOURCE path against the dual-anchor containment model
12
+ * (REQ-PRC-01..08) and returns its realpath'd absolute path plus the `lstat` used to
13
+ * prove regular-file eligibility — callers (`classify-transport.ts`) reuse this `Stats`
14
+ * for the CCL-06 size gate instead of stat'ing again. Throws one of the four `source-*`
15
+ * `AuthoringError`s (REQ-AEC-10) on any failure; never reads file CONTENT.
16
+ * `realCeiling` (optional) is the precomputed `resolveRealCeiling(packageRoot)` — passed
17
+ * by per-entry loop callers; single-shot callers omit it and it is derived here.
18
+ */
19
+ export declare function validateSourceContainment(params: {
20
+ packageDir: string;
21
+ packageRoot: string;
22
+ relPath: string;
23
+ realCeiling?: string;
24
+ }): {
25
+ absPath: string;
26
+ stat: Stats;
27
+ };
28
+ /**
29
+ * Validates `scaffold`'s walk ROOT (`from`, a DIRECTORY — never file-checked) against the
30
+ * SAME lexical + realpath ceiling machinery `validateSourceContainment` uses (steps 1-3,
31
+ * via `resolveContainedRealpath` — no parallel check forked for the directory case).
32
+ * Rejects `source-outside-package` for an escaping or out-of-ceiling root; a
33
+ * legitimately ABSENT in-ceiling root is left alone (no-op) so `walkFolder`'s own
34
+ * existing not-found behavior is preserved unchanged — this function only ever narrows
35
+ * what `runScaffold` was already going to do, it never invents a new not-found path.
36
+ * MUST run before `walkFolder` so the 10k-entry bound can never fire on an out-of-ceiling
37
+ * tree (owner-ratified final-verify remediation, package-root-containment domain).
38
+ */
39
+ export declare function validateSourceRootContainment(params: {
40
+ packageDir: string;
41
+ packageRoot: string;
42
+ relPath: string;
43
+ realCeiling?: string;
44
+ }): void;
45
+ /**
46
+ * Validates a FINAL, SDK-computed DESTINATION path (`scaffold`'s computed `to`, or
47
+ * `copyIn`'s `to`) — LEXICAL ONLY, no realpath (the destination may not exist yet,
48
+ * REQ-PRC-09). Applied post-rename, post-token-translation, immediately pre-emit.
49
+ * Rejects with the EXISTING `invalid-input` reason (scaffold-family author misuse,
50
+ * REQ-AEC-12) — never a `source-*` reason, which is reserved for source READS. The
51
+ * engine's own post-render check (REQ-PRC-06/BRC-08) remains the real control for
52
+ * rendered forms the SDK cannot evaluate.
53
+ */
54
+ export declare function validateDestinationLexical(relPath: string): void;
@@ -0,0 +1,242 @@
1
+ // src/scaffold/containment.ts (ADR-0044, ADR-0045, ADR-0046): the dual-anchor
2
+ // containment enforcement (package-root-containment REQ-PRC-01..09) — REPLACES S-001's
3
+ // MINIMAL placeholder lexical guard that used to live inline in classify-transport.ts.
4
+ // Two DISTINCT checks, never conflated (REQ-PRC-01):
5
+ //
6
+ // 1. `validateSourceContainment` — realpath-based, segment-aware, case-fold ceiling
7
+ // check + regular-file allow-list for a SOURCE path (PRC-01..08). Mints the four
8
+ // `source-*` AuthoringReasons (REQ-AEC-10): `source-not-found`,
9
+ // `source-outside-package`, `source-not-regular-file`, `source-unreadable`.
10
+ // 2. `validateDestinationLexical` — lexical-only guard for a `to` destination
11
+ // (PRC-09) — no realpath (the destination may not exist yet). Reuses the EXISTING
12
+ // `invalid-input` reason (scaffold-family author misuse, REQ-AEC-12), never a
13
+ // `source-*` reason — this is about the emitted DIRECTIVE SHAPE, not a source read.
14
+ //
15
+ // Classification pipeline order (design §Data Model, pinned): lexical `../`/absolute
16
+ // screen → resolve + segment-aware ceiling check (pre-realpath) → (out-of-ceiling ⇒
17
+ // source-outside-package, NO existence probe, PRC-07) → realpath. ENOENT ordering (S1,
18
+ // closes the ancestor-symlink existence oracle, REQ-PRC-07.2): on realpath ENOENT,
19
+ // `source-not-found` may be concluded ONLY AFTER the nearest EXISTING ancestor's
20
+ // realpath is proven in-ceiling; an out-of-ceiling ancestor still answers
21
+ // `source-outside-package`, never differentiating existence beyond the boundary. Then
22
+ // `lstat` allow-list (`isFile()` only, else `source-not-regular-file` — never a
23
+ // directory-blacklist, PRC-04.4's FIFO kill). Only after ALL of this may content be read
24
+ // (PRC-08) — `source-unreadable` covers a LATER read failure of an already-proven
25
+ // in-ceiling regular file (permission/I/O error), surfaced by classify-transport.ts's
26
+ // own `readFileSync`, not by this module (this module never reads content).
27
+ import { lstatSync, readlinkSync, realpathSync, existsSync } from "node:fs";
28
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
29
+ import { AuthoringError, invalidInput } from "../core/authoring-error.js";
30
+ import { isErrnoException } from "../core/fs-errors.js";
31
+ const FOLD_CASE = process.platform === "win32" || process.platform === "darwin";
32
+ const fold = (p) => (FOLD_CASE ? p.toLowerCase() : p);
33
+ // Segment-aware ceiling comparison (REQ-PRC-04, kills the bare-`startsWith` mutant —
34
+ // REQ-PRC-04.5's sibling-prefix scenario: `/pkg-evil/x`.startsWith(`/pkg`) would wrongly
35
+ // admit it). `candidate` is within `ceiling` iff it EQUALS the ceiling or starts with the
36
+ // ceiling PLUS a path separator — never a bare string prefix. Case-folds on
37
+ // case-insensitive platforms ONLY (product ruling Q24 — win32/darwin); canonical-form
38
+ // hardening (UNC/device/reserved-DOS/drive-relative) stays engine-side (BRC-08).
39
+ export function isWithinCeiling(candidateAbs, ceilingAbs) {
40
+ const candidate = fold(candidateAbs);
41
+ const ceiling = fold(ceilingAbs);
42
+ const ceilingWithSep = ceiling.endsWith(sep) ? ceiling : ceiling + sep;
43
+ return candidate === ceiling || candidate.startsWith(ceilingWithSep);
44
+ }
45
+ // Lexical `../`/absolute screen shared by BOTH the source guard (REQ-PRC-04's first
46
+ // clause) and the destination guard (REQ-PRC-09, symmetric by design): a literal ".."
47
+ // segment or an absolute-looking path (POSIX leading `/` or a Windows drive letter)
48
+ // resolves outside any ceiling by construction — no filesystem touch needed to reject it.
49
+ function isLexicallyEscaping(relPath) {
50
+ const isAbsolute = relPath.startsWith("/") || /^[A-Za-z]:[\\/]/.test(relPath);
51
+ const segments = relPath.split(/[\\/]+/);
52
+ return isAbsolute || segments.includes("..");
53
+ }
54
+ function sourceRejection(reason, relPath) {
55
+ // No `message` override: messageFor() derives the AEC-11 neutral template from
56
+ // `reason` + `path` alone — `path` here is ALWAYS the package-relative `relPath`
57
+ // (REQ-PRC-05), never an absolute filesystem path.
58
+ return new AuthoringError({ verb: undefined, path: relPath, reason, appliedCount: 0 });
59
+ }
60
+ // Walks UP from `dirname(absPath)` to find the nearest EXISTING ancestor and returns its
61
+ // realpath — the GENUINELY-missing-entry half of the S1 ENOENT ordering fix (an entry
62
+ // that does not exist AT ALL, lstat included; no symlink indirection involved).
63
+ // Terminates at the filesystem root, which always exists.
64
+ function nearestExistingAncestorRealpath(absPath) {
65
+ let dir = dirname(absPath);
66
+ for (;;) {
67
+ if (existsSync(dir)) {
68
+ return realpathSync(dir);
69
+ }
70
+ const parent = dirname(dir);
71
+ if (parent === dir) {
72
+ return realpathSync(dir); // filesystem root — defensive terminator, always exists
73
+ }
74
+ dir = parent;
75
+ }
76
+ }
77
+ // The BROKEN-SYMLINK half of the S1 ENOENT ordering fix (REQ-PRC-07.2): `symlinkAbsPath`
78
+ // itself EXISTS (its `lstat` succeeded) and IS a symlink, but `realpath` failed because its
79
+ // target does not exist — so there is nothing to realpath TO directly. The returned value
80
+ // is compared against the REALPATH'D ceiling, so it MUST be in real space: the raw
81
+ // `readlink` target text is LEXICAL (verify-in-loop-4 CRITICAL — on macOS a raw absolute
82
+ // target under `/var/...` never string-matches a `/private/var/...` real ceiling), and even
83
+ // a relative target joined under a realpath'd parent stays partially lexical when an
84
+ // EXISTING intermediate directory of the target is itself a symlink. Both target forms are
85
+ // therefore normalized identically: lexical absolute form first (anchored on the symlink's
86
+ // realpath'd parent for a relative target — the containing directory exists, the symlink's
87
+ // own lstat succeeded), then `nearestExistingAncestorRealpath` brings the result into real
88
+ // space. The missing tail cannot alter ceiling membership (`resolve` already collapsed any
89
+ // `..`), and the target is never existence-probed beyond the same ancestor walk the
90
+ // plain-missing case already uses (REQ-PRC-07: the containment verdict precedes existence
91
+ // knowledge). Single-hop only (the symlink's immediate target); deeper multi-hop broken
92
+ // chains are not a scenario this domain pins.
93
+ function resolveBrokenSymlinkTargetRealAncestor(symlinkAbsPath) {
94
+ const target = readlinkSync(symlinkAbsPath);
95
+ const lexicalTargetAbs = isAbsolute(target)
96
+ ? resolve(target)
97
+ : resolve(join(realpathSync(dirname(symlinkAbsPath)), target));
98
+ return nearestExistingAncestorRealpath(lexicalTargetAbs);
99
+ }
100
+ /**
101
+ * The realpath'd form of the containment ceiling — a RUN invariant (`packageRoot` is
102
+ * seeded once per run and always exists, so this realpath cannot ENOENT). Loop callers
103
+ * (`runScaffold`) compute it once and thread it through `classifyTransport` →
104
+ * `validateSourceContainment` instead of re-realpath'ing the same directory per entry.
105
+ */
106
+ export function resolveRealCeiling(packageRoot) {
107
+ return realpathSync(resolve(packageRoot));
108
+ }
109
+ // Steps 1-3 of the containment pipeline (design §Classification pipeline order, pinned):
110
+ // lexical `../`/absolute screen → pre-realpath segment-aware ceiling check → realpath +
111
+ // ENOENT ordering (S1, REQ-PRC-07.2). Shared by `validateSourceContainment` (file source,
112
+ // adds step 4's regular-file allow-list) and `validateSourceRootContainment` (scaffold's
113
+ // walk ROOT — a directory, no step 4). Extracted so the ENOENT/symlink-ordering logic has
114
+ // exactly ONE implementation — never forked in parallel for the directory case.
115
+ function resolveContainedRealpath(params) {
116
+ const { packageDir, relPath, realCeiling } = params;
117
+ const lexicalCeiling = resolve(params.packageRoot);
118
+ // Step 1 (REQ-PRC-04 first clause): lexical `../`/absolute screen, independent of any
119
+ // realpath check — a literal ".." segment or an absolute path resolves outside the
120
+ // ceiling by construction (REQ-PRC-04.1/.6).
121
+ if (isLexicallyEscaping(relPath)) {
122
+ throw sourceRejection("source-outside-package", relPath);
123
+ }
124
+ const lexicalAbs = resolve(join(packageDir, relPath));
125
+ // Step 2 (design §Classification pipeline): pre-realpath segment-aware ceiling check
126
+ // on the lexically-resolved path — out-of-ceiling ⇒ source-outside-package, NO
127
+ // existence probe (REQ-PRC-07: containment precedes any existence/stat probing).
128
+ if (!isWithinCeiling(lexicalAbs, lexicalCeiling)) {
129
+ throw sourceRejection("source-outside-package", relPath);
130
+ }
131
+ // Step 3: realpath — resolves symlinks. ENOENT ordering (S1, REQ-PRC-07.2): a missing
132
+ // target may be classified not-found ONLY AFTER the location it would resolve TO
133
+ // is proven in-ceiling. Two distinct ENOENT shapes, both resolved into REAL space (the
134
+ // ceiling side of this comparison is `realCeiling` — never compare a lexical candidate
135
+ // against it):
136
+ // (a) `lexicalAbs` itself is a BROKEN SYMLINK (its own entry exists, lstat succeeds,
137
+ // but the target it points to does not) — the target's real-space nearest existing
138
+ // ancestor is checked against the ceiling.
139
+ // (b) `lexicalAbs` does not exist AT ALL (no symlink indirection) — walk up to the
140
+ // nearest EXISTING ancestor and check ITS realpath against the ceiling.
141
+ // Either way: out-of-ceiling ⇒ source-outside-package (never differentiates existence
142
+ // beyond the boundary, REQ-PRC-07.1); in-ceiling ⇒ notFound.
143
+ let realAbs;
144
+ try {
145
+ realAbs = realpathSync(lexicalAbs);
146
+ }
147
+ catch (err) {
148
+ if (isErrnoException(err) && err.code === "ENOENT") {
149
+ let selfIsBrokenSymlink = false;
150
+ try {
151
+ selfIsBrokenSymlink = lstatSync(lexicalAbs).isSymbolicLink();
152
+ }
153
+ catch {
154
+ selfIsBrokenSymlink = false; // lexicalAbs itself doesn't exist — case (b)
155
+ }
156
+ const resolvedRealAncestor = selfIsBrokenSymlink
157
+ ? resolveBrokenSymlinkTargetRealAncestor(lexicalAbs)
158
+ : nearestExistingAncestorRealpath(lexicalAbs);
159
+ if (!isWithinCeiling(resolvedRealAncestor, realCeiling)) {
160
+ throw sourceRejection("source-outside-package", relPath);
161
+ }
162
+ return { notFound: true };
163
+ }
164
+ throw sourceRejection("source-unreadable", relPath);
165
+ }
166
+ if (!isWithinCeiling(realAbs, realCeiling)) {
167
+ throw sourceRejection("source-outside-package", relPath);
168
+ }
169
+ return { realAbs };
170
+ }
171
+ /**
172
+ * Validates ONE package-local SOURCE path against the dual-anchor containment model
173
+ * (REQ-PRC-01..08) and returns its realpath'd absolute path plus the `lstat` used to
174
+ * prove regular-file eligibility — callers (`classify-transport.ts`) reuse this `Stats`
175
+ * for the CCL-06 size gate instead of stat'ing again. Throws one of the four `source-*`
176
+ * `AuthoringError`s (REQ-AEC-10) on any failure; never reads file CONTENT.
177
+ * `realCeiling` (optional) is the precomputed `resolveRealCeiling(packageRoot)` — passed
178
+ * by per-entry loop callers; single-shot callers omit it and it is derived here.
179
+ */
180
+ export function validateSourceContainment(params) {
181
+ const { packageDir, packageRoot, relPath } = params;
182
+ // `packageRoot` always exists (context.ts's ancestor walk proved it via `existsSync`),
183
+ // so this realpath cannot ENOENT.
184
+ const realCeiling = params.realCeiling ?? realpathSync(resolve(packageRoot));
185
+ const resolution = resolveContainedRealpath({ packageDir, packageRoot, relPath, realCeiling });
186
+ if ("notFound" in resolution) {
187
+ throw sourceRejection("source-not-found", relPath);
188
+ }
189
+ const { realAbs } = resolution;
190
+ // Step 4 (REQ-PRC-04): lstat ALLOW-LIST — isFile() only, never a directory-blacklist
191
+ // (PRC-04.4's FIFO kill: a FIFO/socket/device is equally ineligible).
192
+ let stat;
193
+ try {
194
+ stat = lstatSync(realAbs);
195
+ }
196
+ catch (err) {
197
+ if (isErrnoException(err) && err.code === "ENOENT") {
198
+ // TOCTOU: existed for realpath, vanished before lstat — treat as not-found rather
199
+ // than leaking a raw Node error.
200
+ throw sourceRejection("source-not-found", relPath);
201
+ }
202
+ throw sourceRejection("source-unreadable", relPath);
203
+ }
204
+ if (!stat.isFile()) {
205
+ throw sourceRejection("source-not-regular-file", relPath);
206
+ }
207
+ return { absPath: realAbs, stat };
208
+ }
209
+ /**
210
+ * Validates `scaffold`'s walk ROOT (`from`, a DIRECTORY — never file-checked) against the
211
+ * SAME lexical + realpath ceiling machinery `validateSourceContainment` uses (steps 1-3,
212
+ * via `resolveContainedRealpath` — no parallel check forked for the directory case).
213
+ * Rejects `source-outside-package` for an escaping or out-of-ceiling root; a
214
+ * legitimately ABSENT in-ceiling root is left alone (no-op) so `walkFolder`'s own
215
+ * existing not-found behavior is preserved unchanged — this function only ever narrows
216
+ * what `runScaffold` was already going to do, it never invents a new not-found path.
217
+ * MUST run before `walkFolder` so the 10k-entry bound can never fire on an out-of-ceiling
218
+ * tree (owner-ratified final-verify remediation, package-root-containment domain).
219
+ */
220
+ export function validateSourceRootContainment(params) {
221
+ const { packageDir, packageRoot, relPath } = params;
222
+ const realCeiling = params.realCeiling ?? realpathSync(resolve(packageRoot));
223
+ resolveContainedRealpath({ packageDir, packageRoot, relPath, realCeiling });
224
+ }
225
+ function destinationEscapeMessage(relPath) {
226
+ return (`invalid input: destination "${relPath}" escapes the workspace tree ` +
227
+ '(literal ".." segment or absolute path)');
228
+ }
229
+ /**
230
+ * Validates a FINAL, SDK-computed DESTINATION path (`scaffold`'s computed `to`, or
231
+ * `copyIn`'s `to`) — LEXICAL ONLY, no realpath (the destination may not exist yet,
232
+ * REQ-PRC-09). Applied post-rename, post-token-translation, immediately pre-emit.
233
+ * Rejects with the EXISTING `invalid-input` reason (scaffold-family author misuse,
234
+ * REQ-AEC-12) — never a `source-*` reason, which is reserved for source READS. The
235
+ * engine's own post-render check (REQ-PRC-06/BRC-08) remains the real control for
236
+ * rendered forms the SDK cannot evaluate.
237
+ */
238
+ export function validateDestinationLexical(relPath) {
239
+ if (isLexicallyEscaping(relPath)) {
240
+ throw invalidInput(destinationEscapeMessage(relPath));
241
+ }
242
+ }