farna-bootstrapper 0.0.0-stage → 0.1.1

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 (80) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/LICENSE +30 -0
  3. package/NOTICE +42 -0
  4. package/README.md +1102 -2
  5. package/SECURITY.md +65 -0
  6. package/dist/cli/commands/check.d.ts +58 -0
  7. package/dist/cli/commands/check.js +198 -0
  8. package/dist/cli/commands/generate.d.ts +75 -0
  9. package/dist/cli/commands/generate.js +218 -0
  10. package/dist/cli/commands/init.d.ts +52 -0
  11. package/dist/cli/commands/init.js +271 -0
  12. package/dist/cli/main.d.ts +2 -0
  13. package/dist/cli/main.js +51 -0
  14. package/dist/cli/program.d.ts +23 -0
  15. package/dist/cli/program.js +183 -0
  16. package/dist/compose/resolve.d.ts +161 -0
  17. package/dist/compose/resolve.js +576 -0
  18. package/dist/config/load.d.ts +4 -0
  19. package/dist/config/load.js +45 -0
  20. package/dist/config/schema.d.ts +22 -0
  21. package/dist/config/schema.js +46 -0
  22. package/dist/core/constants.d.ts +279 -0
  23. package/dist/core/constants.js +351 -0
  24. package/dist/core/errors.d.ts +44 -0
  25. package/dist/core/errors.js +75 -0
  26. package/dist/core/fs.d.ts +31 -0
  27. package/dist/core/fs.js +169 -0
  28. package/dist/core/json.d.ts +22 -0
  29. package/dist/core/json.js +174 -0
  30. package/dist/core/paths.d.ts +45 -0
  31. package/dist/core/paths.js +110 -0
  32. package/dist/core/text.d.ts +10 -0
  33. package/dist/core/text.js +27 -0
  34. package/dist/index.d.ts +10 -0
  35. package/dist/index.js +1 -0
  36. package/dist/lock/lockfile.d.ts +230 -0
  37. package/dist/lock/lockfile.js +333 -0
  38. package/dist/materialise/source-tree.d.ts +77 -0
  39. package/dist/materialise/source-tree.js +267 -0
  40. package/dist/permissions/permissions.d.ts +128 -0
  41. package/dist/permissions/permissions.js +452 -0
  42. package/dist/render/commit.d.ts +59 -0
  43. package/dist/render/commit.js +279 -0
  44. package/dist/render/generate-lock.d.ts +9 -0
  45. package/dist/render/generate-lock.js +203 -0
  46. package/dist/render/identity.d.ts +23 -0
  47. package/dist/render/identity.js +396 -0
  48. package/dist/render/orphans.d.ts +59 -0
  49. package/dist/render/orphans.js +234 -0
  50. package/dist/render/port.d.ts +96 -0
  51. package/dist/render/port.js +1 -0
  52. package/dist/render/prepare.d.ts +33 -0
  53. package/dist/render/prepare.js +139 -0
  54. package/dist/render/root-cleanliness.d.ts +28 -0
  55. package/dist/render/root-cleanliness.js +76 -0
  56. package/dist/render/stage.d.ts +36 -0
  57. package/dist/render/stage.js +92 -0
  58. package/dist/render/staging.d.ts +16 -0
  59. package/dist/render/staging.js +94 -0
  60. package/dist/render/structured.d.ts +35 -0
  61. package/dist/render/structured.js +258 -0
  62. package/dist/render/upstream.d.ts +41 -0
  63. package/dist/render/upstream.js +179 -0
  64. package/dist/report/format.d.ts +7 -0
  65. package/dist/report/format.js +97 -0
  66. package/dist/report/warnings.d.ts +21 -0
  67. package/dist/report/warnings.js +24 -0
  68. package/dist/source/digest.d.ts +18 -0
  69. package/dist/source/digest.js +77 -0
  70. package/dist/source/frontmatter.d.ts +12 -0
  71. package/dist/source/frontmatter.js +29 -0
  72. package/dist/source/load.d.ts +103 -0
  73. package/dist/source/load.js +676 -0
  74. package/dist/source/schema.d.ts +154 -0
  75. package/dist/source/schema.js +292 -0
  76. package/dist/source/yaml.d.ts +10 -0
  77. package/dist/source/yaml.js +49 -0
  78. package/dist/verify/containment.d.ts +22 -0
  79. package/dist/verify/containment.js +753 -0
  80. package/package.json +79 -4
package/SECURITY.md ADDED
@@ -0,0 +1,65 @@
1
+ # Security policy
2
+
3
+ ## Supported versions
4
+
5
+ `farna-bootstrapper` is pre-1.0. Only the latest published release receives fixes; the project does
6
+ not maintain security backports for earlier releases.
7
+
8
+ | Version | Supported |
9
+ |---|---|
10
+ | the latest published release | yes |
11
+ | every earlier release | no |
12
+
13
+ ## Reporting a vulnerability
14
+
15
+ Do **not** open a public issue, pull request or discussion for a security problem.
16
+
17
+ Report it privately by email to **security@farnalabs.com** with:
18
+
19
+ - the affected version (`farna-bootstrapper --version`);
20
+ - the operating system and Node.js version;
21
+ - a minimal reproduction, or the exact steps and the source tree that triggers it;
22
+ - what you observed and what you expected;
23
+ - whether the report can be disclosed publicly, and after when.
24
+
25
+ The maintainers aim to acknowledge a report within five working days and to agree a disclosure
26
+ timeline with the reporter. Please give the project a reasonable window to ship a fix before public
27
+ disclosure. Credit is offered unless the reporter asks otherwise.
28
+
29
+ Never include live credentials, tokens or customer data in a report. Use synthetic values. If a
30
+ secret may already be exposed, rotate it first and say so in the report; do not send the value.
31
+
32
+ ## Scope
33
+
34
+ In scope, because these are the properties the product claims:
35
+
36
+ - **Path handling** — traversal, escaping the repository root, writing through a symlink, or
37
+ following a symlinked source, output or ancestor;
38
+ - **Secret handling** — a literal credential in `env`, `headers` or a URL being accepted, echoed in
39
+ a diagnostic, or written into an emitted file; a credential-shaped value being echoed by
40
+ `W115` or `W116`;
41
+ - **Ownership and deletion** — removing or overwriting a file the lockfile does not record, or
42
+ deleting outside a managed location;
43
+ - **Containment** — a persona's content or permission reaching another persona's artefact, or a
44
+ renderer drop being written rather than refused;
45
+ - **Renderer identity** — a renderer other than the pinned version, or a different tarball
46
+ integrity, being accepted;
47
+ - **Supply chain** — a production dependency that makes a network call or collects telemetry, or a
48
+ published tarball that contains repository-only files.
49
+
50
+ Out of scope:
51
+
52
+ - a vulnerability in `rulesync`, Claude Code, OpenCode or another harness — report it to that
53
+ project (you may also tell us, but the fix belongs upstream);
54
+ - anything that requires an attacker to already control the machine, the repository or the
55
+ developer's account;
56
+ - findings that only restate a limitation documented in the README's
57
+ [Residual risks and known gaps](README.md#residual-risks-and-known-gaps) — those are known and
58
+ stated, not new vulnerabilities;
59
+ - social engineering, physical access and denial of service against a third-party registry.
60
+
61
+ ## What the product does and does not do
62
+
63
+ `farna-bootstrapper` is a build-time compiler. It makes no network request of its own while
64
+ generating or checking, sends no telemetry, has no Farna Control dependency, and never executes a
65
+ hook, MCP server or command it writes. A report that shows otherwise is a security report.
@@ -0,0 +1,58 @@
1
+ import { DRIFT_CODE, EXIT, OUTSIDE_OWNERSHIP_CODE, type RenderMode } from '../../core/constants.js';
2
+ import type { RenderTarget } from '../../render/port.js';
3
+ import type { Warning } from '../../report/warnings.js';
4
+ export type DriftKind = 'missing' | 'modified' | 'unexpected';
5
+ export type DriftItem = {
6
+ /** `F007_DRIFT` for our own byte, `W107_OUTSIDE_OWNERSHIP` for something we do not own. */
7
+ code: typeof DRIFT_CODE | typeof OUTSIDE_OWNERSHIP_CODE;
8
+ path: string;
9
+ kind: DriftKind;
10
+ detail: string;
11
+ };
12
+ export type CheckOptions = {
13
+ /** The `--persona` override. It selects profile mode and wins over the config. */
14
+ persona?: string;
15
+ };
16
+ export type CheckResult = {
17
+ ok: boolean;
18
+ target: string;
19
+ mode: RenderMode;
20
+ activePersona: string | null;
21
+ /** Personas resolved but not live. Empty in agent mode. */
22
+ notLive: string[];
23
+ exitCode: 0 | typeof EXIT.drift;
24
+ checked: string[];
25
+ drift: DriftItem[];
26
+ warnings: Warning[];
27
+ };
28
+ /**
29
+ * Regenerate into a disposable stage and compare the result with the working
30
+ * tree. Never writes. Exit 0 when identical, 1 when anything drifted.
31
+ *
32
+ * Ownership is explicit, never inferred from a file name. When `.farna/lock.json`
33
+ * is absent and a planned managed output already exists, there is no record of
34
+ * what this tool wrote, so `check` refuses with the same `F007` and the action
35
+ * `run generate --adopt`. `check` never adopts.
36
+ *
37
+ * Drift is scoped to what this tool owns: every path in the fresh plan (a
38
+ * missing or changed managed file) and every path the committed lockfile
39
+ * records (an output the source no longer produces). An unrecorded file in a
40
+ * managed directory or at the repository root belongs to the user and is not
41
+ * reported, so a repository may legitimately keep its own `opencode.jsonc` or
42
+ * its own `.opencode/commands/custom.md`.
43
+ *
44
+ * A `structured` file (`opencode.jsonc`) is compared by its owned keys only: a
45
+ * user's `theme`, `$schema` or comment is theirs, so editing it is not drift;
46
+ * editing the `mcp` value this tool wrote is.
47
+ *
48
+ * The one unrecorded path `check` does report is an extra file inside a skill
49
+ * directory this tool owns (recorded or planned), as `W107_OUTSIDE_OWNERSHIP`.
50
+ * It is reported and never deleted.
51
+ *
52
+ * The source root is validated before the lockfile is read, so a broken source
53
+ * tree is reported as itself rather than after a lockfile read. The renderer
54
+ * identity recorded in the lockfile is checked next: a renderer that is not the
55
+ * one that produced the committed bytes fails F010 (exit 5) before any byte
56
+ * comparison, so drift is never blamed on the wrong cause.
57
+ */
58
+ export declare function runCheck(repoRoot: string, renderer: RenderTarget, options?: CheckOptions): Promise<CheckResult>;
@@ -0,0 +1,198 @@
1
+ import { join } from 'node:path';
2
+ import { DRIFT_CODE, EXIT, LOCK_PATH, MANAGED_FILE_MAX_BYTES, MODE_PROFILE, OUTSIDE_OWNERSHIP_CODE, ROOT_DIR, } from '../../core/constants.js';
3
+ import { FarnaError } from '../../core/errors.js';
4
+ import { decodeUtf8, readBoundedBytes } from '../../core/fs.js';
5
+ import { compareCodepoints } from '../../core/json.js';
6
+ import { assertRealDirectory, containedTarget, lstatOrUndefined } from '../../core/paths.js';
7
+ import { readLockfile } from '../../lock/lockfile.js';
8
+ import { verifyRendererIdentity } from '../../render/identity.js';
9
+ import { prepareRender } from '../../render/prepare.js';
10
+ import { findSkillTreeExtras } from '../../render/root-cleanliness.js';
11
+ import { canonicalOwnedSubset, parseStructuredDocument, structuredOwnedKeys, } from '../../render/structured.js';
12
+ /** The detail `check` prints for a whole file whose bytes changed. */
13
+ const MODIFIED_DETAIL = 'content differs from a fresh render';
14
+ const MISSING_DETAIL = 'managed file is missing';
15
+ const NOT_A_FILE_DETAIL = 'managed path is not a regular file';
16
+ /**
17
+ * Regenerate into a disposable stage and compare the result with the working
18
+ * tree. Never writes. Exit 0 when identical, 1 when anything drifted.
19
+ *
20
+ * Ownership is explicit, never inferred from a file name. When `.farna/lock.json`
21
+ * is absent and a planned managed output already exists, there is no record of
22
+ * what this tool wrote, so `check` refuses with the same `F007` and the action
23
+ * `run generate --adopt`. `check` never adopts.
24
+ *
25
+ * Drift is scoped to what this tool owns: every path in the fresh plan (a
26
+ * missing or changed managed file) and every path the committed lockfile
27
+ * records (an output the source no longer produces). An unrecorded file in a
28
+ * managed directory or at the repository root belongs to the user and is not
29
+ * reported, so a repository may legitimately keep its own `opencode.jsonc` or
30
+ * its own `.opencode/commands/custom.md`.
31
+ *
32
+ * A `structured` file (`opencode.jsonc`) is compared by its owned keys only: a
33
+ * user's `theme`, `$schema` or comment is theirs, so editing it is not drift;
34
+ * editing the `mcp` value this tool wrote is.
35
+ *
36
+ * The one unrecorded path `check` does report is an extra file inside a skill
37
+ * directory this tool owns (recorded or planned), as `W107_OUTSIDE_OWNERSHIP`.
38
+ * It is reported and never deleted.
39
+ *
40
+ * The source root is validated before the lockfile is read, so a broken source
41
+ * tree is reported as itself rather than after a lockfile read. The renderer
42
+ * identity recorded in the lockfile is checked next: a renderer that is not the
43
+ * one that produced the committed bytes fails F010 (exit 5) before any byte
44
+ * comparison, so drift is never blamed on the wrong cause.
45
+ */
46
+ export async function runCheck(repoRoot, renderer, options = {}) {
47
+ await assertRealDirectory(join(repoRoot, ROOT_DIR), ROOT_DIR);
48
+ const lockfile = await readLockfile(repoRoot);
49
+ if (lockfile !== undefined) {
50
+ verifyRendererIdentity(lockfile.renderer, renderer.identity(), LOCK_PATH);
51
+ }
52
+ const prepared = await prepareRender(repoRoot, renderer, {
53
+ ...(options.persona === undefined ? {} : { persona: options.persona }),
54
+ });
55
+ if (lockfile === undefined) {
56
+ // With no record, an existing planned output could be this tool's earlier
57
+ // render or the user's file. `check` cannot tell, so it refuses and asks for
58
+ // the explicit adoption `generate --adopt` performs.
59
+ const existing = [];
60
+ for (const file of prepared.files) {
61
+ if (file.path === LOCK_PATH) {
62
+ continue;
63
+ }
64
+ const absolute = await containedTarget(repoRoot, file.path);
65
+ if ((await lstatOrUndefined(absolute, file.path)) !== undefined) {
66
+ existing.push(file.path);
67
+ }
68
+ }
69
+ if (existing.length > 0) {
70
+ existing.sort(compareCodepoints);
71
+ throw new FarnaError(DRIFT_CODE, `refusing to check: ${LOCK_PATH} is missing but ${existing.length} managed output(s) from this plan already exist (${existing.join(', ')})`, {
72
+ ...(existing[0] === undefined ? {} : { subject: existing[0] }),
73
+ action: 'run generate --adopt to take ownership of every existing managed output; check never adopts',
74
+ });
75
+ }
76
+ }
77
+ const drift = [];
78
+ // A source change that renders no different byte — an edit to a persona that
79
+ // is not live, a rule only that persona declares — is still a change to the
80
+ // committed record. Comparing the digest is what makes it visible.
81
+ const digestChanged = lockfile?.configDigest !== undefined && lockfile.configDigest !== prepared.configDigest;
82
+ for (const file of prepared.files) {
83
+ if (file.path === LOCK_PATH && digestChanged) {
84
+ // Reported below as the source-digest item, which names the cause.
85
+ continue;
86
+ }
87
+ const absolute = await containedTarget(repoRoot, file.path);
88
+ const stats = await lstatOrUndefined(absolute, file.path);
89
+ if (stats === undefined) {
90
+ drift.push({ code: DRIFT_CODE, path: file.path, kind: 'missing', detail: MISSING_DETAIL });
91
+ continue;
92
+ }
93
+ if (!stats.isFile() || stats.isSymbolicLink()) {
94
+ drift.push({
95
+ code: DRIFT_CODE,
96
+ path: file.path,
97
+ kind: 'modified',
98
+ detail: NOT_A_FILE_DETAIL,
99
+ });
100
+ continue;
101
+ }
102
+ const ownedKeys = structuredOwnedKeys(file.path);
103
+ if (ownedKeys !== undefined) {
104
+ const existing = await readBoundedBytes(absolute, file.path, {
105
+ action: 'make the managed file readable and re-run check',
106
+ maxBytes: MANAGED_FILE_MAX_BYTES,
107
+ });
108
+ let existingOwned;
109
+ try {
110
+ existingOwned = canonicalOwnedSubset(parseStructuredDocument(decodeUtf8(existing, file.path), file.path), ownedKeys);
111
+ }
112
+ catch (error) {
113
+ if (!(error instanceof FarnaError)) {
114
+ throw error;
115
+ }
116
+ drift.push({
117
+ code: DRIFT_CODE,
118
+ path: file.path,
119
+ kind: 'modified',
120
+ detail: 'structured file no longer parses as a JSON object',
121
+ });
122
+ continue;
123
+ }
124
+ const generated = parseStructuredDocument(file.bytes, file.path);
125
+ if (existingOwned !== canonicalOwnedSubset(generated, ownedKeys)) {
126
+ drift.push({
127
+ code: DRIFT_CODE,
128
+ path: file.path,
129
+ kind: 'modified',
130
+ detail: `owned key(s) ${ownedKeys.join(', ')} differ from a fresh render`,
131
+ });
132
+ }
133
+ continue;
134
+ }
135
+ const existing = await readBoundedBytes(absolute, file.path, {
136
+ action: 'make the managed file readable and re-run check',
137
+ maxBytes: MANAGED_FILE_MAX_BYTES,
138
+ });
139
+ if (!existing.equals(Buffer.from(file.bytes, 'utf8'))) {
140
+ drift.push({
141
+ code: DRIFT_CODE,
142
+ path: file.path,
143
+ kind: 'modified',
144
+ detail: MODIFIED_DETAIL,
145
+ });
146
+ }
147
+ }
148
+ if (digestChanged) {
149
+ drift.push({
150
+ code: DRIFT_CODE,
151
+ path: LOCK_PATH,
152
+ kind: 'modified',
153
+ detail: 'the source or config changed since the lockfile was written; re-run generate',
154
+ });
155
+ }
156
+ const expected = new Set(prepared.files.map((file) => file.path));
157
+ // A recorded path the current source no longer produces is drift whether or
158
+ // not it is still on disk: removing the last declaration must not leave a
159
+ // live config that `check` calls clean. Only the lockfile can name it; the
160
+ // on-disk scan is deliberately gone, because an unrecorded path is not ours.
161
+ const recorded = new Set(lockfile?.files.map((file) => file.path) ?? []);
162
+ for (const path of recorded) {
163
+ if (expected.has(path)) {
164
+ continue;
165
+ }
166
+ drift.push({
167
+ code: DRIFT_CODE,
168
+ path,
169
+ kind: 'unexpected',
170
+ detail: 'path is recorded in the lockfile but no longer produced by this source',
171
+ });
172
+ }
173
+ if (prepared.source.mode === MODE_PROFILE) {
174
+ const recordedEntries = lockfile?.files ?? [];
175
+ for (const extra of await findSkillTreeExtras(repoRoot, expected, recordedEntries)) {
176
+ drift.push({
177
+ code: OUTSIDE_OWNERSHIP_CODE,
178
+ path: extra.path,
179
+ kind: 'unexpected',
180
+ detail: extra.symbolicLink
181
+ ? 'an unrecorded symbolic link is inside a managed skill directory'
182
+ : 'an unrecorded file is inside a managed skill directory',
183
+ });
184
+ }
185
+ }
186
+ drift.sort((a, b) => compareCodepoints(a.path, b.path));
187
+ return {
188
+ ok: drift.length === 0,
189
+ target: prepared.source.target,
190
+ mode: prepared.source.mode,
191
+ activePersona: prepared.source.active,
192
+ notLive: prepared.source.notLive,
193
+ exitCode: drift.length === 0 ? EXIT.ok : EXIT.drift,
194
+ checked: prepared.files.map((file) => file.path),
195
+ drift,
196
+ warnings: prepared.warnings,
197
+ };
198
+ }
@@ -0,0 +1,75 @@
1
+ import { type RenderMode } from '../../core/constants.js';
2
+ import { type CommitOperations, type FileStatus } from '../../render/commit.js';
3
+ import type { RenderTarget } from '../../render/port.js';
4
+ import type { Warning } from '../../report/warnings.js';
5
+ export type GenerateOptions = {
6
+ cwd: string;
7
+ dryRun: boolean;
8
+ /** The `--persona` override. It selects profile mode and wins over the config. */
9
+ persona?: string;
10
+ /**
11
+ * Take ownership of every existing planned managed output. Required when the
12
+ * lockfile is absent and a planned output exists: without it the tool cannot
13
+ * tell its own render from a file the user wrote.
14
+ */
15
+ adopt?: boolean;
16
+ /**
17
+ * The filesystem seam the commit uses. Production never sets it; a failure
18
+ * test injects a rename or write failure to prove the recovery path.
19
+ */
20
+ commitOperations?: Partial<CommitOperations>;
21
+ };
22
+ export type OrphanStatus = 'removed' | 'would-remove' | 'updated' | 'would-update' | 'missing';
23
+ export type GenerateResult = {
24
+ ok: true;
25
+ target: string;
26
+ mode: RenderMode;
27
+ activePersona: string | null;
28
+ /** Personas resolved but not live. Empty in agent mode. */
29
+ notLive: string[];
30
+ dryRun: boolean;
31
+ /** Paths taken over by `--adopt` (or, in a dry run, that would be). */
32
+ adopted: string[];
33
+ personas: string[];
34
+ files: Array<{
35
+ path: string;
36
+ status: FileStatus | 'would-write';
37
+ }>;
38
+ /**
39
+ * Recorded paths this run no longer produces. A whole file is removed; a
40
+ * structured file that still carries user keys is updated in place (its
41
+ * owned key deleted) and the record dropped.
42
+ */
43
+ removed: Array<{
44
+ path: string;
45
+ status: OrphanStatus;
46
+ }>;
47
+ warnings: Warning[];
48
+ };
49
+ /**
50
+ * Render the source tree, verify containment, then write the verified set.
51
+ * In dry-run mode nothing is written, and every path is compared with the
52
+ * working tree so the plan distinguishes `unchanged` from `would-write`.
53
+ *
54
+ * The whole read → plan → remove → commit sequence runs under an exclusive
55
+ * `.farna/.generate.lock` directory, so two concurrent runs cannot each plan
56
+ * from the same lockfile and delete each other's output.
57
+ *
58
+ * Ownership is explicit, never inferred from a file name. When the lockfile is
59
+ * absent and a planned output already exists, this refuses (`F007`) and names
60
+ * `generate --adopt`; `check` refuses the same tree and never adopts. With
61
+ * `--adopt` every existing planned managed output is taken over: `opencode.jsonc`
62
+ * keeps the user's other keys (only the owned `mcp` key is merged), every other
63
+ * planned file is overwritten with the fresh render, and the lockfile records
64
+ * the result. A file not in the plan is neither adopted nor removed.
65
+ *
66
+ * A recorded path the new plan no longer produces is an orphan (a persona
67
+ * switch, a removed resource). It is preflighted with the same rigour and
68
+ * removed before the new set is committed. Removing before the commit means a
69
+ * failed commit leaves the tree visibly missing the old artefacts, which
70
+ * `check` reports; writing first would leave an unrecorded orphan behind, which
71
+ * nothing could ever find again. Only a recorded regular file in a managed
72
+ * location whose bytes still match its recorded digest is removed; a symlink,
73
+ * a directory, an edited file or an unrecorded user file is never touched.
74
+ */
75
+ export declare function runGenerate(options: GenerateOptions, renderer: RenderTarget): Promise<GenerateResult>;
@@ -0,0 +1,218 @@
1
+ import { LOCK_PATH } from '../../core/constants.js';
2
+ import { driftRefused, FarnaError } from '../../core/errors.js';
3
+ import { decodeUtf8 } from '../../core/fs.js';
4
+ import { compareCodepoints } from '../../core/json.js';
5
+ import { readLockfile } from '../../lock/lockfile.js';
6
+ import { commitFiles, inspectManagedTarget, } from '../../render/commit.js';
7
+ import { withGenerateLock } from '../../render/generate-lock.js';
8
+ import { planOrphans, removeOrphans } from '../../render/orphans.js';
9
+ import { prepareRender } from '../../render/prepare.js';
10
+ import { mergeStructuredText, structuredOwnedKeys } from '../../render/structured.js';
11
+ async function recordedState(cwd) {
12
+ const lockfile = await readLockfile(cwd);
13
+ return {
14
+ lockfile,
15
+ paths: new Set([LOCK_PATH, ...(lockfile?.files.map((file) => file.path) ?? [])]),
16
+ entries: lockfile?.files ?? [],
17
+ };
18
+ }
19
+ /** The planned managed outputs that already exist on disk. */
20
+ function existingOutputs(files, inspected) {
21
+ return files
22
+ .filter((file) => file.path !== LOCK_PATH)
23
+ .filter((file) => inspected.get(file.path)?.existing !== undefined)
24
+ .map((file) => file.path)
25
+ .sort(compareCodepoints);
26
+ }
27
+ /**
28
+ * A missing lockfile with outputs already on disk is not proof of ownership.
29
+ * The tool cannot tell its own earlier render from a file the user wrote, so it
30
+ * refuses and asks for an explicit `--adopt` rather than guessing from names.
31
+ */
32
+ function lockfileMissing(existing) {
33
+ return driftRefused(`refusing to continue: ${LOCK_PATH} is missing but ${existing.length} managed output(s) from this plan already exist (${existing.join(', ')})`, {
34
+ ...(existing[0] === undefined ? {} : { subject: existing[0] }),
35
+ action: 'run generate --adopt to take ownership of every existing managed output; a file not in the plan is never adopted or removed',
36
+ });
37
+ }
38
+ /** Resolve every planned target to its current bytes, or `undefined` when absent. */
39
+ async function inspectPlan(cwd, files) {
40
+ const inspected = new Map();
41
+ for (const file of files) {
42
+ inspected.set(file.path, await inspectManagedTarget(cwd, file.path));
43
+ }
44
+ return inspected;
45
+ }
46
+ /**
47
+ * Refuse an unrecorded path this tool cannot prove it owns, unless its bytes are
48
+ * exactly what this run would write or the caller explicitly adopted it.
49
+ *
50
+ * An unrecorded path is adoptable when it already holds the fresh render: that
51
+ * is the recovery path after a deleted lockfile, where the outputs are this
52
+ * tool's own and only the record was lost. An unrecorded path that differs is
53
+ * refused (F007) unless `--adopt` was passed, because taking it over would
54
+ * destroy bytes this tool did not write.
55
+ */
56
+ function assertOwnership(files, inspected, recorded, adopt) {
57
+ if (adopt) {
58
+ return;
59
+ }
60
+ for (const file of files) {
61
+ const current = inspected.get(file.path)?.existing;
62
+ if (current === undefined || recorded.has(file.path)) {
63
+ continue;
64
+ }
65
+ if (!current.equals(Buffer.from(file.bytes, 'utf8'))) {
66
+ throw driftRefused(`refusing to overwrite ${file.path}: it exists but is not recorded in the committed lockfile and its bytes differ from a fresh render`, {
67
+ subject: file.path,
68
+ action: 'run generate --adopt to take ownership of the existing managed output, or move it aside deliberately',
69
+ });
70
+ }
71
+ }
72
+ }
73
+ /**
74
+ * The bytes this run will write for a structured file: the owned keys merged
75
+ * into the user's document **in place**, preserving every other byte including
76
+ * comments and whitespace.
77
+ *
78
+ * The merge applies to a path in the committed lockfile and, with `--adopt`, to
79
+ * an existing planned file the lockfile does not record. Any other file is
80
+ * either absent (the fresh render is written) or was refused by
81
+ * `assertOwnership`.
82
+ */
83
+ function mergeStructuredFiles(files, inspected, recorded, adopt) {
84
+ return files.map((file) => {
85
+ const ownedKeys = structuredOwnedKeys(file.path);
86
+ const existing = inspected.get(file.path)?.existing;
87
+ const owned = recorded.has(file.path) || adopt;
88
+ if (ownedKeys === undefined || existing === undefined || !owned) {
89
+ return { path: file.path, bytes: file.bytes };
90
+ }
91
+ return {
92
+ path: file.path,
93
+ bytes: mergeStructuredText(decodeUtf8(existing, file.path), file.bytes, ownedKeys, file.path),
94
+ };
95
+ });
96
+ }
97
+ /**
98
+ * Re-throw a commit failure with the removals this run already made named. The
99
+ * commit's own message ("nothing was written") is true of the commit and false
100
+ * of the run: the orphan removal happened first, so the tree is partially
101
+ * updated and the reader must be told which paths are gone.
102
+ */
103
+ function commitFailure(error, removed) {
104
+ const paths = removed.filter((entry) => entry.status === 'removed').map((entry) => entry.path);
105
+ const updated = removed.filter((entry) => entry.status === 'updated').map((entry) => entry.path);
106
+ if (!(error instanceof FarnaError) || (paths.length === 0 && updated.length === 0)) {
107
+ return error;
108
+ }
109
+ const details = [];
110
+ if (paths.length > 0) {
111
+ details.push(`this run already removed ${paths.length} recorded path(s) (${paths.join(', ')})`);
112
+ }
113
+ if (updated.length > 0) {
114
+ details.push(`this run already updated ${updated.length} recorded path(s) (${updated.join(', ')})`);
115
+ }
116
+ return new FarnaError(error.code, `${error.message}; ${details.join('; ')} before the write failed, so the tree is partially updated`, {
117
+ ...(error.subject === undefined ? {} : { subject: error.subject }),
118
+ action: 're-run generate after fixing the filesystem; the lockfile still records the affected paths',
119
+ cause: error,
120
+ });
121
+ }
122
+ /**
123
+ * Render the source tree, verify containment, then write the verified set.
124
+ * In dry-run mode nothing is written, and every path is compared with the
125
+ * working tree so the plan distinguishes `unchanged` from `would-write`.
126
+ *
127
+ * The whole read → plan → remove → commit sequence runs under an exclusive
128
+ * `.farna/.generate.lock` directory, so two concurrent runs cannot each plan
129
+ * from the same lockfile and delete each other's output.
130
+ *
131
+ * Ownership is explicit, never inferred from a file name. When the lockfile is
132
+ * absent and a planned output already exists, this refuses (`F007`) and names
133
+ * `generate --adopt`; `check` refuses the same tree and never adopts. With
134
+ * `--adopt` every existing planned managed output is taken over: `opencode.jsonc`
135
+ * keeps the user's other keys (only the owned `mcp` key is merged), every other
136
+ * planned file is overwritten with the fresh render, and the lockfile records
137
+ * the result. A file not in the plan is neither adopted nor removed.
138
+ *
139
+ * A recorded path the new plan no longer produces is an orphan (a persona
140
+ * switch, a removed resource). It is preflighted with the same rigour and
141
+ * removed before the new set is committed. Removing before the commit means a
142
+ * failed commit leaves the tree visibly missing the old artefacts, which
143
+ * `check` reports; writing first would leave an unrecorded orphan behind, which
144
+ * nothing could ever find again. Only a recorded regular file in a managed
145
+ * location whose bytes still match its recorded digest is removed; a symlink,
146
+ * a directory, an edited file or an unrecorded user file is never touched.
147
+ */
148
+ export async function runGenerate(options, renderer) {
149
+ const adopt = options.adopt === true;
150
+ return await withGenerateLock(options.cwd, async () => {
151
+ const prepared = await prepareRender(options.cwd, renderer, {
152
+ ...(options.persona === undefined ? {} : { persona: options.persona }),
153
+ });
154
+ const personas = prepared.source.personas.map((persona) => persona.id);
155
+ const recorded = await recordedState(options.cwd);
156
+ const inspected = await inspectPlan(options.cwd, prepared.files);
157
+ const existing = existingOutputs(prepared.files, inspected);
158
+ if (recorded.lockfile === undefined && existing.length > 0 && !adopt) {
159
+ throw lockfileMissing(existing);
160
+ }
161
+ assertOwnership(prepared.files, inspected, recorded.paths, adopt);
162
+ const adopted = existing.filter((path) => !recorded.paths.has(path));
163
+ const expected = new Set(prepared.files.map((file) => file.path));
164
+ const orphans = await planOrphans(options.cwd, recorded.entries, expected);
165
+ const planned = mergeStructuredFiles(prepared.files, inspected, recorded.paths, adopt);
166
+ if (options.dryRun) {
167
+ const files = [];
168
+ for (const file of planned) {
169
+ // Compare bytes: decoded text can collapse an invalid byte and a genuine
170
+ // U+FFFD to the same string, reporting "unchanged" for a file that needs
171
+ // repair.
172
+ const current = inspected.get(file.path)?.existing;
173
+ const matches = current?.equals(Buffer.from(file.bytes, 'utf8')) === true;
174
+ files.push({
175
+ path: file.path,
176
+ status: matches ? 'unchanged' : 'would-write',
177
+ });
178
+ }
179
+ return {
180
+ ok: true,
181
+ target: prepared.source.target,
182
+ mode: prepared.source.mode,
183
+ activePersona: prepared.source.active,
184
+ notLive: prepared.source.notLive,
185
+ dryRun: true,
186
+ adopted,
187
+ personas,
188
+ files,
189
+ removed: orphans.map((orphan) => ({
190
+ path: orphan.entry.path,
191
+ status: orphan.action === 'remove' ? 'would-remove' : 'would-update',
192
+ })),
193
+ warnings: prepared.warnings,
194
+ };
195
+ }
196
+ const removed = await removeOrphans(options.cwd, orphans);
197
+ let committed;
198
+ try {
199
+ committed = await commitFiles(options.cwd, planned, options.commitOperations ?? {});
200
+ }
201
+ catch (error) {
202
+ throw commitFailure(error, removed);
203
+ }
204
+ return {
205
+ ok: true,
206
+ target: prepared.source.target,
207
+ mode: prepared.source.mode,
208
+ activePersona: prepared.source.active,
209
+ notLive: prepared.source.notLive,
210
+ dryRun: false,
211
+ adopted,
212
+ personas,
213
+ files: committed.statuses,
214
+ removed: removed.sort((a, b) => compareCodepoints(a.path, b.path)),
215
+ warnings: prepared.warnings,
216
+ };
217
+ });
218
+ }
@@ -0,0 +1,52 @@
1
+ export type InitResult = {
2
+ ok: true;
3
+ root: string;
4
+ configPath: string;
5
+ /** Paths this invocation created, including the two shared ignore/attribute files. */
6
+ created: string[];
7
+ /** Existing shared files this invocation appended to. */
8
+ updated: string[];
9
+ nextStep: string;
10
+ };
11
+ /**
12
+ * The config `init` writes. Derived from the constants the schema validates, so
13
+ * the template cannot drift from the version or target this build supports. It
14
+ * carries no `$schema` URL: a URL that 404s is a dangling claim, and no schema
15
+ * is published yet.
16
+ */
17
+ export declare function configTemplate(): string;
18
+ /**
19
+ * Append the lines a shared text file is missing, preserving every byte already
20
+ * there. The existing file is decoded with `latin1` only to find line boundaries
21
+ * and compare ASCII lines: that map is byte-for-byte reversible, so a
22
+ * `.gitignore` in Latin-1 (or any other encoding) keeps its original bytes and
23
+ * only the new ASCII lines are added. Decoding as UTF-8 would replace an invalid
24
+ * byte with U+FFFD and write the lossy text back.
25
+ */
26
+ export declare function appendMissingLines(existing: Buffer, lines: readonly string[]): Buffer | undefined;
27
+ export type TemporaryName = (path: string) => string;
28
+ /** An unpredictable sibling name: a pre-planted symlink cannot guess it. */
29
+ export declare function defaultTemporaryName(path: string): string;
30
+ /**
31
+ * Replace a file atomically. The temporary is created with `O_EXCL`, so a path
32
+ * an attacker planted (a symlink to a victim file, or any other object) makes
33
+ * the create fail instead of being followed; the `stat` of the opened handle
34
+ * proves the opened object is a regular file (the path may have been swapped
35
+ * since). The rename then moves a file this call created over the target, never
36
+ * a link. The target's existing mode is preserved; a new file uses the umask.
37
+ *
38
+ * A failed CREATE removes nothing: the object at the temporary name was not
39
+ * created by this call, so deleting it would delete something the caller did not
40
+ * own.
41
+ */
42
+ export declare function writeAtomicFile(path: string, contents: string | Uint8Array, subject: string, action: string, temporaryName?: TemporaryName): Promise<void>;
43
+ /** Replace `.gitignore` atomically, preserving its bytes and mode. */
44
+ export declare function writeGitignore(path: string, contents: string | Uint8Array, temporaryName?: TemporaryName): Promise<void>;
45
+ /**
46
+ * Create the source root. Refuses to overwrite an existing config: `init` is
47
+ * never destructive. The whole command is atomic: the writes that can fail on
48
+ * an ordinary filesystem state (`.gitignore`, `.gitattributes`) are preflighted
49
+ * before anything is created, and a failure after creation removes what this
50
+ * invocation created and restores the shared files byte for byte.
51
+ */
52
+ export declare function runInit(repoRoot: string): Promise<InitResult>;