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.
- package/CHANGELOG.md +107 -0
- package/LICENSE +30 -0
- package/NOTICE +42 -0
- package/README.md +1102 -2
- package/SECURITY.md +65 -0
- package/dist/cli/commands/check.d.ts +58 -0
- package/dist/cli/commands/check.js +198 -0
- package/dist/cli/commands/generate.d.ts +75 -0
- package/dist/cli/commands/generate.js +218 -0
- package/dist/cli/commands/init.d.ts +52 -0
- package/dist/cli/commands/init.js +271 -0
- package/dist/cli/main.d.ts +2 -0
- package/dist/cli/main.js +51 -0
- package/dist/cli/program.d.ts +23 -0
- package/dist/cli/program.js +183 -0
- package/dist/compose/resolve.d.ts +161 -0
- package/dist/compose/resolve.js +576 -0
- package/dist/config/load.d.ts +4 -0
- package/dist/config/load.js +45 -0
- package/dist/config/schema.d.ts +22 -0
- package/dist/config/schema.js +46 -0
- package/dist/core/constants.d.ts +279 -0
- package/dist/core/constants.js +351 -0
- package/dist/core/errors.d.ts +44 -0
- package/dist/core/errors.js +75 -0
- package/dist/core/fs.d.ts +31 -0
- package/dist/core/fs.js +169 -0
- package/dist/core/json.d.ts +22 -0
- package/dist/core/json.js +174 -0
- package/dist/core/paths.d.ts +45 -0
- package/dist/core/paths.js +110 -0
- package/dist/core/text.d.ts +10 -0
- package/dist/core/text.js +27 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +1 -0
- package/dist/lock/lockfile.d.ts +230 -0
- package/dist/lock/lockfile.js +333 -0
- package/dist/materialise/source-tree.d.ts +77 -0
- package/dist/materialise/source-tree.js +267 -0
- package/dist/permissions/permissions.d.ts +128 -0
- package/dist/permissions/permissions.js +452 -0
- package/dist/render/commit.d.ts +59 -0
- package/dist/render/commit.js +279 -0
- package/dist/render/generate-lock.d.ts +9 -0
- package/dist/render/generate-lock.js +203 -0
- package/dist/render/identity.d.ts +23 -0
- package/dist/render/identity.js +396 -0
- package/dist/render/orphans.d.ts +59 -0
- package/dist/render/orphans.js +234 -0
- package/dist/render/port.d.ts +96 -0
- package/dist/render/port.js +1 -0
- package/dist/render/prepare.d.ts +33 -0
- package/dist/render/prepare.js +139 -0
- package/dist/render/root-cleanliness.d.ts +28 -0
- package/dist/render/root-cleanliness.js +76 -0
- package/dist/render/stage.d.ts +36 -0
- package/dist/render/stage.js +92 -0
- package/dist/render/staging.d.ts +16 -0
- package/dist/render/staging.js +94 -0
- package/dist/render/structured.d.ts +35 -0
- package/dist/render/structured.js +258 -0
- package/dist/render/upstream.d.ts +41 -0
- package/dist/render/upstream.js +179 -0
- package/dist/report/format.d.ts +7 -0
- package/dist/report/format.js +97 -0
- package/dist/report/warnings.d.ts +21 -0
- package/dist/report/warnings.js +24 -0
- package/dist/source/digest.d.ts +18 -0
- package/dist/source/digest.js +77 -0
- package/dist/source/frontmatter.d.ts +12 -0
- package/dist/source/frontmatter.js +29 -0
- package/dist/source/load.d.ts +103 -0
- package/dist/source/load.js +676 -0
- package/dist/source/schema.d.ts +154 -0
- package/dist/source/schema.js +292 -0
- package/dist/source/yaml.d.ts +10 -0
- package/dist/source/yaml.js +49 -0
- package/dist/verify/containment.d.ts +22 -0
- package/dist/verify/containment.js +753 -0
- package/package.json +79 -4
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, open, rename, rm, rmdir, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { COMMAND_FILE_EXT, COMMANDS_DIR, CONFIG_FILE, CONFIG_PATH, DEFAULT_TARGET, GITATTRIBUTES_LINES, GITIGNORE_LINES, HOOKS_DIR, MANAGED_FILE_MAX_BYTES, MCP_DIR, OPENCODE_SUPPORTED_MAJOR, OPENCODE_V1_SUPPORTED_MAJOR, PERMISSION_FILE_EXT, PERMISSIONS_DIR, PERSONA_FILE_EXT, PERSONAS_DIR, PRODUCT_NAME, RESOURCES_DIR, ROOT_DIR, RULE_FILE_EXT, RULES_DIR, SCHEMA_VERSION, SKILL_FILE_NAME, SKILLS_DIR, STAGING_INFIX, STRUCTURED_RESOURCE_FILE_EXT, } from '../../core/constants.js';
|
|
5
|
+
import { FarnaError, invalidConfig } from '../../core/errors.js';
|
|
6
|
+
import { describeFsError, readBoundedBytes } from '../../core/fs.js';
|
|
7
|
+
import { assertRealDirectory, lstatOrUndefined } from '../../core/paths.js';
|
|
8
|
+
/**
|
|
9
|
+
* The config `init` writes. Derived from the constants the schema validates, so
|
|
10
|
+
* the template cannot drift from the version or target this build supports. It
|
|
11
|
+
* carries no `$schema` URL: a URL that 404s is a dangling claim, and no schema
|
|
12
|
+
* is published yet.
|
|
13
|
+
*/
|
|
14
|
+
export function configTemplate() {
|
|
15
|
+
return `{
|
|
16
|
+
// Farna Bootstrapper source root. Generated files are committed.
|
|
17
|
+
"schemaVersion": ${SCHEMA_VERSION},
|
|
18
|
+
"targets": {
|
|
19
|
+
"${DEFAULT_TARGET}": {}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
`;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Append the lines a shared text file is missing, preserving every byte already
|
|
26
|
+
* there. The existing file is decoded with `latin1` only to find line boundaries
|
|
27
|
+
* and compare ASCII lines: that map is byte-for-byte reversible, so a
|
|
28
|
+
* `.gitignore` in Latin-1 (or any other encoding) keeps its original bytes and
|
|
29
|
+
* only the new ASCII lines are added. Decoding as UTF-8 would replace an invalid
|
|
30
|
+
* byte with U+FFFD and write the lossy text back.
|
|
31
|
+
*/
|
|
32
|
+
export function appendMissingLines(existing, lines) {
|
|
33
|
+
const text = existing.toString('latin1');
|
|
34
|
+
const crlf = (text.match(/\r\n/g) ?? []).length;
|
|
35
|
+
const lf = (text.match(/\n/g) ?? []).length - crlf;
|
|
36
|
+
const eol = crlf > lf ? '\r\n' : '\n';
|
|
37
|
+
const present = new Set(text.split(/\r?\n/).map((line) => line.trim()));
|
|
38
|
+
const missing = lines.filter((line) => !present.has(line));
|
|
39
|
+
if (missing.length === 0) {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
const endsWithNewline = existing.length === 0 || existing[existing.length - 1] === 0x0a;
|
|
43
|
+
const prefix = endsWithNewline ? existing : Buffer.concat([existing, Buffer.from(eol, 'latin1')]);
|
|
44
|
+
return Buffer.concat([prefix, Buffer.from(`${missing.join(eol)}${eol}`, 'latin1')]);
|
|
45
|
+
}
|
|
46
|
+
/** An unpredictable sibling name: a pre-planted symlink cannot guess it. */
|
|
47
|
+
export function defaultTemporaryName(path) {
|
|
48
|
+
return `${path}${STAGING_INFIX}${process.pid}-${randomUUID()}`;
|
|
49
|
+
}
|
|
50
|
+
/** The mode an existing file had, or the umask-implied mode for a new file. */
|
|
51
|
+
async function targetMode(path, subject) {
|
|
52
|
+
const stats = await lstatOrUndefined(path, subject);
|
|
53
|
+
return stats?.isFile() === true ? stats.mode & 0o777 : 0o666 & ~process.umask();
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Replace a file atomically. The temporary is created with `O_EXCL`, so a path
|
|
57
|
+
* an attacker planted (a symlink to a victim file, or any other object) makes
|
|
58
|
+
* the create fail instead of being followed; the `stat` of the opened handle
|
|
59
|
+
* proves the opened object is a regular file (the path may have been swapped
|
|
60
|
+
* since). The rename then moves a file this call created over the target, never
|
|
61
|
+
* a link. The target's existing mode is preserved; a new file uses the umask.
|
|
62
|
+
*
|
|
63
|
+
* A failed CREATE removes nothing: the object at the temporary name was not
|
|
64
|
+
* created by this call, so deleting it would delete something the caller did not
|
|
65
|
+
* own.
|
|
66
|
+
*/
|
|
67
|
+
export async function writeAtomicFile(path, contents, subject, action, temporaryName = defaultTemporaryName) {
|
|
68
|
+
const temporary = temporaryName(path);
|
|
69
|
+
const mode = await targetMode(path, subject);
|
|
70
|
+
let handle;
|
|
71
|
+
try {
|
|
72
|
+
handle = await open(temporary, 'wx', mode);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
throw invalidConfig(`cannot update ${subject} (${describeFsError(error)})`, {
|
|
76
|
+
subject,
|
|
77
|
+
action,
|
|
78
|
+
cause: error,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
const stats = await handle.stat();
|
|
83
|
+
if (stats.isSymbolicLink() || !stats.isFile()) {
|
|
84
|
+
throw new Error('staging path is not a regular file');
|
|
85
|
+
}
|
|
86
|
+
await handle.writeFile(contents);
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
await handle.close().catch(() => undefined);
|
|
90
|
+
await rm(temporary, { force: true });
|
|
91
|
+
throw invalidConfig(`cannot update ${subject} (${describeFsError(error)})`, {
|
|
92
|
+
subject,
|
|
93
|
+
action,
|
|
94
|
+
cause: error,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
await handle.close();
|
|
98
|
+
try {
|
|
99
|
+
await rename(temporary, path);
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
await rm(temporary, { force: true });
|
|
103
|
+
throw invalidConfig(`cannot update ${subject} (${describeFsError(error)})`, {
|
|
104
|
+
subject,
|
|
105
|
+
action,
|
|
106
|
+
cause: error,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** Replace `.gitignore` atomically, preserving its bytes and mode. */
|
|
111
|
+
export async function writeGitignore(path, contents, temporaryName = defaultTemporaryName) {
|
|
112
|
+
await writeAtomicFile(path, contents, '.gitignore', 'make .gitignore writable and re-run init', temporaryName);
|
|
113
|
+
}
|
|
114
|
+
/** Read a shared text file as raw bytes, refusing a link or a non-file. */
|
|
115
|
+
async function preflightSharedFile(path, subject) {
|
|
116
|
+
const stats = await lstatOrUndefined(path, subject);
|
|
117
|
+
if (stats === undefined) {
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
if (stats.isSymbolicLink()) {
|
|
121
|
+
throw invalidConfig(`cannot update ${subject}: it is a symbolic link`, {
|
|
122
|
+
subject,
|
|
123
|
+
action: 'replace the symbolic link with a regular file',
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
if (!stats.isFile()) {
|
|
127
|
+
throw invalidConfig(`cannot update ${subject}: it is not a regular file`, {
|
|
128
|
+
subject,
|
|
129
|
+
action: 'replace it with a regular file, or remove it',
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
return await readBoundedBytes(path, subject, {
|
|
133
|
+
action: `make ${subject} readable and re-run init`,
|
|
134
|
+
maxBytes: MANAGED_FILE_MAX_BYTES,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Create the source root. Refuses to overwrite an existing config: `init` is
|
|
139
|
+
* never destructive. The whole command is atomic: the writes that can fail on
|
|
140
|
+
* an ordinary filesystem state (`.gitignore`, `.gitattributes`) are preflighted
|
|
141
|
+
* before anything is created, and a failure after creation removes what this
|
|
142
|
+
* invocation created and restores the shared files byte for byte.
|
|
143
|
+
*/
|
|
144
|
+
export async function runInit(repoRoot) {
|
|
145
|
+
const rootRelative = ROOT_DIR;
|
|
146
|
+
const configRelative = `${ROOT_DIR}/${CONFIG_FILE}`;
|
|
147
|
+
const configAbsolute = join(repoRoot, ROOT_DIR, CONFIG_FILE);
|
|
148
|
+
const gitignorePath = join(repoRoot, '.gitignore');
|
|
149
|
+
const gitattributesPath = join(repoRoot, '.gitattributes');
|
|
150
|
+
// Check `.farna` itself before probing anything below it: when it is a
|
|
151
|
+
// regular file, lstat of `.farna/config.jsonc` raises ENOTDIR.
|
|
152
|
+
await assertRealDirectory(join(repoRoot, ROOT_DIR), ROOT_DIR);
|
|
153
|
+
const existingConfig = await lstatOrUndefined(configAbsolute, configRelative);
|
|
154
|
+
if (existingConfig !== undefined) {
|
|
155
|
+
throw invalidConfig('a source root already exists', {
|
|
156
|
+
subject: configRelative,
|
|
157
|
+
action: 'edit the existing config, or remove it deliberately before re-initialising',
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
// Preflight every remaining path this invocation will touch before creating
|
|
161
|
+
// anything.
|
|
162
|
+
const gitignoreOriginal = await preflightSharedFile(gitignorePath, '.gitignore');
|
|
163
|
+
const gitignoreNext = gitignoreOriginal === undefined
|
|
164
|
+
? Buffer.from(`${GITIGNORE_LINES.join('\n')}\n`)
|
|
165
|
+
: appendMissingLines(gitignoreOriginal, GITIGNORE_LINES);
|
|
166
|
+
const gitattributesOriginal = await preflightSharedFile(gitattributesPath, '.gitattributes');
|
|
167
|
+
const gitattributesNext = gitattributesOriginal === undefined
|
|
168
|
+
? Buffer.from(`${GITATTRIBUTES_LINES.join('\n')}\n`)
|
|
169
|
+
: appendMissingLines(gitattributesOriginal, GITATTRIBUTES_LINES);
|
|
170
|
+
const createdDirectories = [];
|
|
171
|
+
const createdDirectorySubjects = [];
|
|
172
|
+
const createdFiles = [];
|
|
173
|
+
const created = new Set();
|
|
174
|
+
const updated = new Set();
|
|
175
|
+
const sharedWrites = [];
|
|
176
|
+
const ensureDirectory = async (path, subject) => {
|
|
177
|
+
const stats = await assertRealDirectory(path, subject);
|
|
178
|
+
if (stats === undefined) {
|
|
179
|
+
try {
|
|
180
|
+
await mkdir(path);
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
const now = describeFsError(error) === 'EEXIST' ? await lstatOrUndefined(path, subject) : undefined;
|
|
184
|
+
if (now?.isDirectory() !== true) {
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
createdDirectories.push(path);
|
|
190
|
+
createdDirectorySubjects.push(subject);
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
const rollback = async () => {
|
|
194
|
+
for (const entry of [...sharedWrites].reverse()) {
|
|
195
|
+
try {
|
|
196
|
+
if (entry.original === undefined) {
|
|
197
|
+
await rm(entry.path, { force: true });
|
|
198
|
+
}
|
|
199
|
+
else {
|
|
200
|
+
// Raw bytes: the file may not be UTF-8, and a text round-trip would
|
|
201
|
+
// write back a replaced U+FFFD instead of the original byte.
|
|
202
|
+
await writeFile(entry.path, entry.original);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
// Best effort: the typed error below still names the failing path.
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
for (const file of [...createdFiles].reverse()) {
|
|
210
|
+
try {
|
|
211
|
+
await rm(file, { force: true });
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
// Best effort.
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
for (const directory of [...createdDirectories].reverse()) {
|
|
218
|
+
try {
|
|
219
|
+
await rmdir(directory);
|
|
220
|
+
}
|
|
221
|
+
catch {
|
|
222
|
+
// A non-empty directory means something other than init wrote to it.
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
const recordStage = async (path, subject, original, next) => {
|
|
227
|
+
sharedWrites.push({ path, subject, original, next });
|
|
228
|
+
await writeAtomicFile(path, next, subject, `make ${subject} writable and re-run init`);
|
|
229
|
+
(original === undefined ? created : updated).add(subject);
|
|
230
|
+
};
|
|
231
|
+
try {
|
|
232
|
+
await ensureDirectory(join(repoRoot, ROOT_DIR), ROOT_DIR);
|
|
233
|
+
await ensureDirectory(join(repoRoot, ROOT_DIR, PERSONAS_DIR), `${ROOT_DIR}/${PERSONAS_DIR}`);
|
|
234
|
+
await ensureDirectory(join(repoRoot, ROOT_DIR, RESOURCES_DIR), `${ROOT_DIR}/${RESOURCES_DIR}`);
|
|
235
|
+
await ensureDirectory(join(repoRoot, ROOT_DIR, RESOURCES_DIR, RULES_DIR), `${ROOT_DIR}/${RESOURCES_DIR}/${RULES_DIR}`);
|
|
236
|
+
await ensureDirectory(join(repoRoot, ROOT_DIR, RESOURCES_DIR, PERMISSIONS_DIR), `${ROOT_DIR}/${RESOURCES_DIR}/${PERMISSIONS_DIR}`);
|
|
237
|
+
await ensureDirectory(join(repoRoot, ROOT_DIR, RESOURCES_DIR, MCP_DIR), `${ROOT_DIR}/${RESOURCES_DIR}/${MCP_DIR}`);
|
|
238
|
+
await ensureDirectory(join(repoRoot, ROOT_DIR, RESOURCES_DIR, SKILLS_DIR), `${ROOT_DIR}/${RESOURCES_DIR}/${SKILLS_DIR}`);
|
|
239
|
+
await ensureDirectory(join(repoRoot, ROOT_DIR, RESOURCES_DIR, COMMANDS_DIR), `${ROOT_DIR}/${RESOURCES_DIR}/${COMMANDS_DIR}`);
|
|
240
|
+
await ensureDirectory(join(repoRoot, ROOT_DIR, RESOURCES_DIR, HOOKS_DIR), `${ROOT_DIR}/${RESOURCES_DIR}/${HOOKS_DIR}`);
|
|
241
|
+
createdFiles.push(configAbsolute);
|
|
242
|
+
await writeFile(configAbsolute, configTemplate(), 'utf8');
|
|
243
|
+
created.add(configRelative);
|
|
244
|
+
if (gitignoreNext !== undefined) {
|
|
245
|
+
await recordStage(gitignorePath, '.gitignore', gitignoreOriginal, gitignoreNext);
|
|
246
|
+
}
|
|
247
|
+
if (gitattributesNext !== undefined) {
|
|
248
|
+
await recordStage(gitattributesPath, '.gitattributes', gitattributesOriginal, gitattributesNext);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
await rollback();
|
|
253
|
+
if (error instanceof FarnaError) {
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
throw invalidConfig(`init could not complete (${describeFsError(error)})`, {
|
|
257
|
+
subject: ROOT_DIR,
|
|
258
|
+
cause: error,
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
return {
|
|
262
|
+
ok: true,
|
|
263
|
+
root: rootRelative,
|
|
264
|
+
configPath: configRelative,
|
|
265
|
+
// Only directories this invocation actually created. A source root that
|
|
266
|
+
// already has `resources/` must not be reported as though `init` made it.
|
|
267
|
+
created: [...created, ...createdDirectorySubjects.map((directory) => `${directory}/`)],
|
|
268
|
+
updated: [...updated],
|
|
269
|
+
nextStep: `Add personas to ${ROOT_DIR}/${PERSONAS_DIR}/*${PERSONA_FILE_EXT}, rules to ${ROOT_DIR}/${RESOURCES_DIR}/${RULES_DIR}/*${RULE_FILE_EXT}, permissions to ${ROOT_DIR}/${RESOURCES_DIR}/${PERMISSIONS_DIR}/*${PERMISSION_FILE_EXT}, MCP servers to ${ROOT_DIR}/${RESOURCES_DIR}/${MCP_DIR}/*${STRUCTURED_RESOURCE_FILE_EXT}, skills to ${ROOT_DIR}/${RESOURCES_DIR}/${SKILLS_DIR}/<id>/${SKILL_FILE_NAME}, commands to ${ROOT_DIR}/${RESOURCES_DIR}/${COMMANDS_DIR}/*${COMMAND_FILE_EXT} and hooks to ${ROOT_DIR}/${RESOURCES_DIR}/${HOOKS_DIR}/*${STRUCTURED_RESOURCE_FILE_EXT}, then run "${PRODUCT_NAME} generate". Two OpenCode targets are supported: "opencode" for OpenCode ${OPENCODE_SUPPORTED_MAJOR}.x (@opencode/cli) and "opencodev1" for OpenCode ${OPENCODE_V1_SUPPORTED_MAJOR}.x (opencode-ai). For OpenCode profile mode, replace the "targets" block in ${CONFIG_PATH} with { "opencode": { "active": "<persona-id>" } } (or the same for "opencodev1"; exactly one target is configured per run, so this replaces the claudecode target rather than adding to it), or pass --persona <id> to generate and check. The active persona then owns the workspace: opencode.jsonc is written at the repository root, and its skills, commands and hooks under .opencode/. Agent mode is the default when no active persona is set.`,
|
|
270
|
+
};
|
|
271
|
+
}
|
package/dist/cli/main.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { CommanderError } from 'commander';
|
|
3
|
+
import { FarnaError } from '../core/errors.js';
|
|
4
|
+
import { UpstreamRenderTarget } from '../render/upstream.js';
|
|
5
|
+
import { formatJson } from '../report/format.js';
|
|
6
|
+
import { buildProgram, failureObject, redactRoot, unexpectedFailureObject } from './program.js';
|
|
7
|
+
/**
|
|
8
|
+
* Process entry point. This is the only place where a concrete renderer is
|
|
9
|
+
* bound to the `RenderTarget` port. `--json` is detected here as well as in
|
|
10
|
+
* the command wrapper, so a failure before a command action runs (an
|
|
11
|
+
* unreadable installed renderer, for example) still produces one object.
|
|
12
|
+
*/
|
|
13
|
+
const json = process.argv.includes('--json');
|
|
14
|
+
const command = process.argv.slice(2).find((argument) => !argument.startsWith('-')) ?? null;
|
|
15
|
+
try {
|
|
16
|
+
const program = buildProgram({
|
|
17
|
+
cwd: process.cwd(),
|
|
18
|
+
renderer: new UpstreamRenderTarget(),
|
|
19
|
+
stdout: (text) => process.stdout.write(text),
|
|
20
|
+
argv: process.argv,
|
|
21
|
+
});
|
|
22
|
+
await program.parseAsync(process.argv);
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (error instanceof CommanderError) {
|
|
26
|
+
// Commander has already written the usage message. A usage error gets the
|
|
27
|
+
// machine-readable object too; help and version (exit 0) do not.
|
|
28
|
+
if (json && error.exitCode !== 0) {
|
|
29
|
+
process.stdout.write(formatJson(unexpectedFailureObject(command, error.message)));
|
|
30
|
+
}
|
|
31
|
+
process.exitCode = error.exitCode;
|
|
32
|
+
}
|
|
33
|
+
else if (error instanceof FarnaError) {
|
|
34
|
+
if (json) {
|
|
35
|
+
process.stdout.write(formatJson(failureObject(command, error)));
|
|
36
|
+
}
|
|
37
|
+
process.stderr.write(`${error.format()}\n`);
|
|
38
|
+
process.exitCode = error.exitCode;
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
const raw = error instanceof Error ? error.message : String(error);
|
|
42
|
+
// Never print a raw absolute path from the one branch with no diagnostic
|
|
43
|
+
// code; every typed path already carries a repository-relative subject.
|
|
44
|
+
const message = redactRoot(raw, process.cwd());
|
|
45
|
+
if (json) {
|
|
46
|
+
process.stdout.write(formatJson(unexpectedFailureObject(command, message)));
|
|
47
|
+
}
|
|
48
|
+
process.stderr.write(`farna-bootstrapper: unexpected error\n ${message}\n`);
|
|
49
|
+
process.exitCode = 1;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Command } from 'commander';
|
|
2
|
+
import { FarnaError } from '../core/errors.js';
|
|
3
|
+
import type { RenderTarget } from '../render/port.js';
|
|
4
|
+
export type CliContext = {
|
|
5
|
+
cwd: string;
|
|
6
|
+
renderer: RenderTarget;
|
|
7
|
+
stdout: (text: string) => void;
|
|
8
|
+
/** The process argv, so a pre-command `--json` can still be honoured. */
|
|
9
|
+
argv: readonly string[];
|
|
10
|
+
};
|
|
11
|
+
/** The one machine-readable failure object: the same keys for every command. */
|
|
12
|
+
export declare function failureObject(command: string | null, error: FarnaError): Record<string, unknown>;
|
|
13
|
+
/** The same failure object for a throw that carries no diagnostic code. */
|
|
14
|
+
export declare function unexpectedFailureObject(command: string | null, message: string): Record<string, unknown>;
|
|
15
|
+
/**
|
|
16
|
+
* Strip the repository root from a message that escaped as an untyped error, so
|
|
17
|
+
* the one failure with no diagnostic code still names a repository-relative
|
|
18
|
+
* subject rather than leaking an absolute path. Both separators are handled:
|
|
19
|
+
* the message may come from a platform library or from a tool.
|
|
20
|
+
*/
|
|
21
|
+
export declare function redactRoot(message: string, root: string): string;
|
|
22
|
+
/** Commander wiring for the three commands this slice implements. */
|
|
23
|
+
export declare function buildProgram(context: CliContext): Command;
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { Command } from 'commander';
|
|
2
|
+
import { CONFIG_PATH, DRIFT_CODE, EXIT, OPENCODE_SUPPORTED_MAJOR, OPENCODE_V1_SUPPORTED_MAJOR, PRODUCT_NAME, PRODUCT_VERSION, SCHEMA_VERSION, } from '../core/constants.js';
|
|
3
|
+
import { FarnaError } from '../core/errors.js';
|
|
4
|
+
import { RENDERER_PIN } from '../render/upstream.js';
|
|
5
|
+
import { formatCheck, formatGenerate, formatInit, formatJson } from '../report/format.js';
|
|
6
|
+
import { runCheck } from './commands/check.js';
|
|
7
|
+
import { runGenerate } from './commands/generate.js';
|
|
8
|
+
import { runInit } from './commands/init.js';
|
|
9
|
+
/** The one machine-readable failure object: the same keys for every command. */
|
|
10
|
+
export function failureObject(command, error) {
|
|
11
|
+
return {
|
|
12
|
+
schemaVersion: SCHEMA_VERSION,
|
|
13
|
+
command,
|
|
14
|
+
ok: false,
|
|
15
|
+
exitCode: error.exitCode,
|
|
16
|
+
code: error.code,
|
|
17
|
+
subject: error.subject ?? null,
|
|
18
|
+
message: error.message,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/** The same failure object for a throw that carries no diagnostic code. */
|
|
22
|
+
export function unexpectedFailureObject(command, message) {
|
|
23
|
+
return {
|
|
24
|
+
schemaVersion: SCHEMA_VERSION,
|
|
25
|
+
command,
|
|
26
|
+
ok: false,
|
|
27
|
+
exitCode: EXIT.invalidConfig,
|
|
28
|
+
code: null,
|
|
29
|
+
subject: null,
|
|
30
|
+
message,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Strip the repository root from a message that escaped as an untyped error, so
|
|
35
|
+
* the one failure with no diagnostic code still names a repository-relative
|
|
36
|
+
* subject rather than leaking an absolute path. Both separators are handled:
|
|
37
|
+
* the message may come from a platform library or from a tool.
|
|
38
|
+
*/
|
|
39
|
+
export function redactRoot(message, root) {
|
|
40
|
+
const withoutTrailing = root.endsWith('/') || root.endsWith('\\') ? root.slice(0, -1) : root;
|
|
41
|
+
return message
|
|
42
|
+
.replaceAll(`${withoutTrailing}/`, '')
|
|
43
|
+
.replaceAll(`${withoutTrailing}\\`, '')
|
|
44
|
+
.replaceAll(withoutTrailing, '.');
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Run one command and marshal its result. `--json` emits an object on stdout
|
|
48
|
+
* for a typed failure as well as for success; the human line always goes to
|
|
49
|
+
* stderr, and the exit code is always the diagnostic's own code.
|
|
50
|
+
*/
|
|
51
|
+
async function emit(command, json, context, run) {
|
|
52
|
+
try {
|
|
53
|
+
const outcome = await run();
|
|
54
|
+
context.stdout(json ? formatJson(outcome.payload) : outcome.text);
|
|
55
|
+
if (outcome.exitCode !== 0) {
|
|
56
|
+
process.exitCode = outcome.exitCode;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
if (!(error instanceof FarnaError)) {
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
if (json) {
|
|
64
|
+
context.stdout(formatJson(failureObject(command, error)));
|
|
65
|
+
}
|
|
66
|
+
process.stderr.write(`${error.format()}\n`);
|
|
67
|
+
process.exitCode = error.exitCode;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** Commander wiring for the three commands this slice implements. */
|
|
71
|
+
export function buildProgram(context) {
|
|
72
|
+
const program = new Command();
|
|
73
|
+
program
|
|
74
|
+
.name(PRODUCT_NAME)
|
|
75
|
+
.description('Compile named agent personas and resources into harness configuration, and prove the output still matches the source.')
|
|
76
|
+
.addHelpText('after', `\nTwo OpenCode targets are supported, one per run: "opencode" for OpenCode ${OPENCODE_SUPPORTED_MAJOR}.x
|
|
77
|
+
(@opencode/cli) and "opencodev1" for OpenCode ${OPENCODE_V1_SUPPORTED_MAJOR}.x (opencode-ai). They write the same
|
|
78
|
+
paths in each major's own shapes; configuring both at once is refused.
|
|
79
|
+
\nProfile mode: pass --persona <id> to generate or check, or set "active" under a target
|
|
80
|
+
in .farna/config.jsonc. Exactly one persona is live and owns the workspace: its
|
|
81
|
+
opencode.jsonc is written at the repository root, and its skills, commands and hooks
|
|
82
|
+
under .opencode/. Profile mode is supported for both OpenCode targets; agent mode
|
|
83
|
+
remains the default.`)
|
|
84
|
+
.version(
|
|
85
|
+
// The compiled-in pin, never the installed renderer: `--version` and
|
|
86
|
+
// `init` must work when the renderer is missing or broken.
|
|
87
|
+
`${PRODUCT_NAME} ${PRODUCT_VERSION} (renderer ${RENDERER_PIN.name} ${RENDERER_PIN.version})`, '-v, --version')
|
|
88
|
+
.showSuggestionAfterError()
|
|
89
|
+
.showHelpAfterError()
|
|
90
|
+
// Throw instead of calling process.exit, so main can emit the same JSON
|
|
91
|
+
// failure object for a usage error (an unknown option, a missing value).
|
|
92
|
+
.exitOverride();
|
|
93
|
+
program
|
|
94
|
+
.command('init')
|
|
95
|
+
.exitOverride()
|
|
96
|
+
.description(`create ${CONFIG_PATH} and the empty source directories`)
|
|
97
|
+
.option('--json', 'print one JSON object')
|
|
98
|
+
.action(async (options) => {
|
|
99
|
+
await emit('init', options.json === true, context, async () => {
|
|
100
|
+
const result = await runInit(context.cwd);
|
|
101
|
+
return {
|
|
102
|
+
payload: {
|
|
103
|
+
schemaVersion: SCHEMA_VERSION,
|
|
104
|
+
command: 'init',
|
|
105
|
+
...result,
|
|
106
|
+
exitCode: EXIT.ok,
|
|
107
|
+
},
|
|
108
|
+
text: formatInit(result),
|
|
109
|
+
exitCode: EXIT.ok,
|
|
110
|
+
};
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
program
|
|
114
|
+
.command('generate')
|
|
115
|
+
.exitOverride()
|
|
116
|
+
.description('render every live persona and write the verified files into the repository')
|
|
117
|
+
.option('--dry-run', 'print the plan without writing anything')
|
|
118
|
+
.option('--adopt', 'take ownership of every existing planned managed output (required when the lockfile is missing)')
|
|
119
|
+
.option('--persona <id>', 'run profile mode as this persona (overrides the configured active)')
|
|
120
|
+
.option('--json', 'print one JSON object')
|
|
121
|
+
.action(async (options) => {
|
|
122
|
+
await emit('generate', options.json === true, context, async () => {
|
|
123
|
+
const result = await runGenerate({
|
|
124
|
+
cwd: context.cwd,
|
|
125
|
+
dryRun: options.dryRun === true,
|
|
126
|
+
...(options.adopt === true ? { adopt: true } : {}),
|
|
127
|
+
...(options.persona === undefined ? {} : { persona: options.persona }),
|
|
128
|
+
}, context.renderer);
|
|
129
|
+
return {
|
|
130
|
+
payload: {
|
|
131
|
+
schemaVersion: SCHEMA_VERSION,
|
|
132
|
+
command: 'generate',
|
|
133
|
+
...result,
|
|
134
|
+
exitCode: EXIT.ok,
|
|
135
|
+
},
|
|
136
|
+
text: formatGenerate(result),
|
|
137
|
+
exitCode: EXIT.ok,
|
|
138
|
+
};
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
program
|
|
142
|
+
.command('check')
|
|
143
|
+
.exitOverride()
|
|
144
|
+
.description('regenerate into a temporary directory and compare with the repository')
|
|
145
|
+
.option('--persona <id>', 'run profile mode as this persona (overrides the configured active)')
|
|
146
|
+
.option('--json', 'print one JSON object')
|
|
147
|
+
.action(async (options) => {
|
|
148
|
+
await emit('check', options.json === true, context, async () => {
|
|
149
|
+
const result = await runCheck(context.cwd, context.renderer, {
|
|
150
|
+
...(options.persona === undefined ? {} : { persona: options.persona }),
|
|
151
|
+
});
|
|
152
|
+
const payload = {
|
|
153
|
+
schemaVersion: SCHEMA_VERSION,
|
|
154
|
+
command: 'check',
|
|
155
|
+
...result,
|
|
156
|
+
};
|
|
157
|
+
if (!result.ok) {
|
|
158
|
+
// The same failure keys the typed-error path carries, so a consumer
|
|
159
|
+
// never has to special-case drift to learn it failed. The top-level
|
|
160
|
+
// code is always the drift code; an item's own code (`W107` for
|
|
161
|
+
// content outside ownership) stays in the `drift` array, because a
|
|
162
|
+
// path that sorts first must not decide what kind of failure the run
|
|
163
|
+
// is.
|
|
164
|
+
payload['code'] = DRIFT_CODE;
|
|
165
|
+
payload['subject'] = result.drift[0]?.path ?? null;
|
|
166
|
+
payload['message'] = 'managed output drifted from a fresh render';
|
|
167
|
+
}
|
|
168
|
+
return { payload, text: formatCheck(result), exitCode: result.exitCode };
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
// A listener here replaces Commander's default "unknown command" error and
|
|
172
|
+
// process exit, so the same machine-readable object can be emitted.
|
|
173
|
+
program.on('command:*', (operands) => {
|
|
174
|
+
const attempted = operands[0] ?? '';
|
|
175
|
+
const message = `unknown command "${attempted}"`;
|
|
176
|
+
if (context.argv.includes('--json')) {
|
|
177
|
+
context.stdout(formatJson(unexpectedFailureObject(attempted === '' ? null : attempted, message)));
|
|
178
|
+
}
|
|
179
|
+
process.stderr.write(`${PRODUCT_NAME}: ${message}\n`);
|
|
180
|
+
process.exitCode = EXIT.invalidConfig;
|
|
181
|
+
});
|
|
182
|
+
return program;
|
|
183
|
+
}
|