anhedral 0.19.0 → 0.20.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.
- package/README.md +4 -0
- package/dist/capability-command.d.ts +8 -0
- package/dist/capability-command.js +3 -3
- package/dist/capability-editor.js +21 -1
- package/dist/cli-commands.js +3 -0
- package/dist/command-schema.js +35 -2
- package/dist/credential-helper.d.ts +2 -0
- package/dist/credential-helper.js +44 -0
- package/dist/platform-state.d.ts +2 -1
- package/dist/platform-state.js +5 -4
- package/dist/registry/usage.js +2 -1
- package/dist/release-artifact.d.ts +18 -0
- package/dist/release-artifact.js +169 -0
- package/dist/stack-update.d.ts +39 -0
- package/dist/stack-update.js +346 -0
- package/dist/transaction.d.ts +1 -0
- package/dist/transaction.js +2 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/software-factory.md +28 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -30,6 +30,10 @@ After adding backend, configure `apps/api/.dev.vars` from its example, review th
|
|
|
30
30
|
|
|
31
31
|
Use `anhedral stack list`, `status` and `doctor` to inspect the Anhedral Stack and its additions. These checks describe source completeness, not live provider readiness. Current public generation is web-only. OJ runs development and builds. Historical generators and framework aliases are removed.
|
|
32
32
|
|
|
33
|
+
## Update an existing project
|
|
34
|
+
|
|
35
|
+
Update your agent plugin through its host and select the matching published CLI version. Preview `anhedral stack update --dry-run --json`, review the returned diffs/conflicts, then apply `anhedral stack update --expect-plan <planId> --json`. Updates preserve authored source and stop on customized-file conflicts or a changed plan. They refresh generated runtime/configuration and deployment provenance without running project scripts or installing dependencies. Validate dependencies and the application separately before upload/deployment. See [the operating workflow](docs/software-factory.md).
|
|
36
|
+
|
|
33
37
|
## Source-owned UI
|
|
34
38
|
|
|
35
39
|
```sh
|
|
@@ -1,3 +1,11 @@
|
|
|
1
1
|
import { type OutputOptions } from './cli-output.js';
|
|
2
|
+
import { CapabilityEditor } from './capability-editor.js';
|
|
2
3
|
import type { CommandRunner } from './command-types.js';
|
|
4
|
+
export declare function projectRoot(cwd: string, allowRecovery?: boolean): string;
|
|
5
|
+
export declare function readState(e: CapabilityEditor): {
|
|
6
|
+
installed: ("hono" | "database-auth" | "r2" | "stripe")[];
|
|
7
|
+
managedFiles: Record<string, string>;
|
|
8
|
+
};
|
|
9
|
+
/** Identify the source before any recovery or source mutation. One missing manifest can be an interrupted add. */
|
|
10
|
+
export declare function assertPublicWorkspace(root: string, allowRecovery?: boolean, command?: 'add' | 'stack'): void;
|
|
3
11
|
export declare function runCapabilityCommand(command: 'add' | 'stack', args: string[], output: OutputOptions, run?: CommandRunner): Promise<void>;
|
|
@@ -13,7 +13,7 @@ import { execFile } from './util.js';
|
|
|
13
13
|
import { capabilityReferences } from './capability-references.js';
|
|
14
14
|
import { configureDependencyPatches } from './dependency-patches.js';
|
|
15
15
|
import { composeSourceProvenance } from './composition.js';
|
|
16
|
-
function projectRoot(cwd, allowRecovery = false) {
|
|
16
|
+
export function projectRoot(cwd, allowRecovery = false) {
|
|
17
17
|
let root = realpathSync(cwd);
|
|
18
18
|
for (;;) {
|
|
19
19
|
if (existsSync(path.join(root, 'anhedral.json')) ||
|
|
@@ -28,7 +28,7 @@ function projectRoot(cwd, allowRecovery = false) {
|
|
|
28
28
|
}
|
|
29
29
|
throw Error('No Anhedral workspace found. Select a generated project with --cwd.');
|
|
30
30
|
}
|
|
31
|
-
function readState(e) {
|
|
31
|
+
export function readState(e) {
|
|
32
32
|
const project = e.json('anhedral.json');
|
|
33
33
|
const state = project.capabilities ?? { schemaVersion: 1, installed: [], managedFiles: {} };
|
|
34
34
|
if (state.schemaVersion !== 1 ||
|
|
@@ -54,7 +54,7 @@ function publicScopeError(command = 'add') {
|
|
|
54
54
|
return commandArgumentError(command, 'The CLI edits only the Anhedral Stack: TanStack Start with OJ and shadcn.');
|
|
55
55
|
}
|
|
56
56
|
/** Identify the source before any recovery or source mutation. One missing manifest can be an interrupted add. */
|
|
57
|
-
function assertPublicWorkspace(root, allowRecovery = false, command = 'add') {
|
|
57
|
+
export function assertPublicWorkspace(root, allowRecovery = false, command = 'add') {
|
|
58
58
|
const editor = new CapabilityEditor(root, {});
|
|
59
59
|
const recovering = allowRecovery && existsSync(path.join(root, '.anhedral-journal.json'));
|
|
60
60
|
const hasWeb = existsSync(path.join(root, 'apps/web/package.json'));
|
|
@@ -2,7 +2,7 @@ import { readBoundedFile, MAX_PROJECT_JSON_BYTES } from './bounded-file.js';
|
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
3
|
import { existsSync, lstatSync } from 'node:fs';
|
|
4
4
|
import path from 'node:path';
|
|
5
|
-
import { parse, modify, applyEdits } from 'jsonc-parser';
|
|
5
|
+
import { parse, visit, modify, applyEdits } from 'jsonc-parser';
|
|
6
6
|
export const fingerprint = (source) => createHash('sha256').update(source).digest('hex');
|
|
7
7
|
/** A bounded, read-only overlay until every capability has passed preflight. */
|
|
8
8
|
export class CapabilityEditor {
|
|
@@ -52,6 +52,26 @@ export class CapabilityEditor {
|
|
|
52
52
|
const value = parse(source, errors, { allowTrailingComma: true });
|
|
53
53
|
if (errors.length || !value || typeof value !== 'object' || Array.isArray(value))
|
|
54
54
|
throw Error(`Invalid JSON/JSONC in ${relative}.`);
|
|
55
|
+
// JSON modification targets the first property while runtime parsers use the last.
|
|
56
|
+
// Compare decoded keys in each object so escaped aliases cannot bypass this guard.
|
|
57
|
+
const objects = [];
|
|
58
|
+
let duplicate = false;
|
|
59
|
+
visit(source, {
|
|
60
|
+
onObjectBegin() {
|
|
61
|
+
objects.push(new Set());
|
|
62
|
+
},
|
|
63
|
+
onObjectProperty(property) {
|
|
64
|
+
const keys = objects.at(-1);
|
|
65
|
+
if (keys.has(property))
|
|
66
|
+
duplicate = true;
|
|
67
|
+
keys.add(property);
|
|
68
|
+
},
|
|
69
|
+
onObjectEnd() {
|
|
70
|
+
objects.pop();
|
|
71
|
+
},
|
|
72
|
+
}, { allowTrailingComma: true });
|
|
73
|
+
if (duplicate)
|
|
74
|
+
throw Error(`Duplicate JSON object keys in ${relative}; preserve and reconcile them before editing source.`);
|
|
55
75
|
return value;
|
|
56
76
|
}
|
|
57
77
|
create(relative, source) {
|
package/dist/cli-commands.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { runPlatformCommand } from './platform-command.js';
|
|
2
|
+
import { runStackUpdate } from './stack-update.js';
|
|
2
3
|
import { runCapabilityCommand } from './capability-command.js';
|
|
3
4
|
import { runAnhedralUiCommand } from './ui-command.js';
|
|
4
5
|
import { commandArgumentError } from './cli-arguments.js';
|
|
@@ -29,6 +30,8 @@ export async function runCommand(command, args, output) {
|
|
|
29
30
|
'logs',
|
|
30
31
|
].includes(command))
|
|
31
32
|
return runPlatformCommand(command, args, output);
|
|
33
|
+
if (command === 'stack' && commandArguments('stack', args).positional[0] === 'update')
|
|
34
|
+
return runStackUpdate(args, output);
|
|
32
35
|
if (command === 'add' || command === 'stack')
|
|
33
36
|
return runCapabilityCommand(command, args, output);
|
|
34
37
|
if (command === 'ui')
|
package/dist/command-schema.js
CHANGED
|
@@ -463,9 +463,42 @@ export const COMMANDS = {
|
|
|
463
463
|
},
|
|
464
464
|
stack: {
|
|
465
465
|
description: 'Inspect the Anhedral Stack and its three optional additions.',
|
|
466
|
-
usage: 'stack <list|status|doctor>',
|
|
467
|
-
options: [
|
|
466
|
+
usage: 'stack <list|status|doctor|update>',
|
|
467
|
+
options: [
|
|
468
|
+
{ flag: '--dry-run', description: 'Preview bounded source updates without writes.' },
|
|
469
|
+
{
|
|
470
|
+
flag: '--offline',
|
|
471
|
+
description: 'Update source without resolving a published deployment artifact.',
|
|
472
|
+
},
|
|
473
|
+
{
|
|
474
|
+
flag: '--expect-plan',
|
|
475
|
+
arity: 'required',
|
|
476
|
+
value: 'sha256',
|
|
477
|
+
description: 'Apply only the reviewed source update plan.',
|
|
478
|
+
},
|
|
479
|
+
],
|
|
468
480
|
children: {
|
|
481
|
+
update: {
|
|
482
|
+
description: 'Preview or apply bounded source updates without executing project scripts.',
|
|
483
|
+
usage: 'stack update [--dry-run] [--expect-plan <sha256>]',
|
|
484
|
+
options: [
|
|
485
|
+
{
|
|
486
|
+
flag: '--dry-run',
|
|
487
|
+
description: 'Show exact source changes and conflicts without writes.',
|
|
488
|
+
},
|
|
489
|
+
{
|
|
490
|
+
flag: '--offline',
|
|
491
|
+
description: 'Skip published artifact resolution; leave deployment provenance pending.',
|
|
492
|
+
},
|
|
493
|
+
{
|
|
494
|
+
flag: '--expect-plan',
|
|
495
|
+
arity: 'required',
|
|
496
|
+
value: 'sha256',
|
|
497
|
+
description: 'Apply only if the reviewed update plan still matches.',
|
|
498
|
+
},
|
|
499
|
+
],
|
|
500
|
+
examples: ['stack update --dry-run --json', 'stack update --json'],
|
|
501
|
+
},
|
|
469
502
|
list: {
|
|
470
503
|
description: 'Show the Anhedral Stack foundation and optional additions.',
|
|
471
504
|
usage: 'stack list',
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { lstat, realpath } from 'node:fs/promises';
|
|
2
|
+
import { dirname, isAbsolute, join, parse } from 'node:path';
|
|
3
|
+
import { CliFailure } from './cli-errors.js';
|
|
4
|
+
const unavailable = () => new CliFailure('A trusted Linux Secret Service helper is unavailable.', 'PLATFORM_ACCESS_FAILED', 'Install a system-owned secret-tool, explicitly select a trusted system helper with ANHEDRAL_CLI_SECRET_TOOL_PATH, or use --credential-file.', 'context', false);
|
|
5
|
+
async function safePath(path, executable) {
|
|
6
|
+
// Validate the original chain as well as the canonical chain: an untrusted
|
|
7
|
+
// symlink or writable parent must not redirect a privileged helper lookup.
|
|
8
|
+
let current = parse(path).root;
|
|
9
|
+
const parts = path.slice(current.length).split('/').filter(Boolean);
|
|
10
|
+
for (const [index, part] of parts.entries()) {
|
|
11
|
+
current = join(current, part);
|
|
12
|
+
const entry = await lstat(current);
|
|
13
|
+
if (entry.uid !== 0 || (!entry.isSymbolicLink() && (entry.mode & 0o022) !== 0))
|
|
14
|
+
throw unavailable();
|
|
15
|
+
const last = index === parts.length - 1;
|
|
16
|
+
if (!entry.isSymbolicLink() && !(last && executable ? entry.isFile() : entry.isDirectory()))
|
|
17
|
+
throw unavailable();
|
|
18
|
+
if (last && executable && !entry.isSymbolicLink() && (entry.mode & 0o111) === 0)
|
|
19
|
+
throw unavailable();
|
|
20
|
+
}
|
|
21
|
+
const root = await lstat(parse(path).root);
|
|
22
|
+
if (root.uid !== 0 || (root.mode & 0o022) !== 0)
|
|
23
|
+
throw unavailable();
|
|
24
|
+
}
|
|
25
|
+
/** Never resolve credential infrastructure from project/package-manager PATH. */
|
|
26
|
+
export async function trustedLinuxCredentialHelper(explicit = process.env.ANHEDRAL_CLI_SECRET_TOOL_PATH) {
|
|
27
|
+
const candidates = explicit === undefined ? ['/usr/bin/secret-tool', '/bin/secret-tool'] : [explicit];
|
|
28
|
+
for (const candidate of candidates) {
|
|
29
|
+
try {
|
|
30
|
+
if (!isAbsolute(candidate) || /[\0\r\n]/.test(candidate) || dirname(candidate) === candidate)
|
|
31
|
+
throw unavailable();
|
|
32
|
+
await safePath(candidate, true);
|
|
33
|
+
const canonical = await realpath(candidate);
|
|
34
|
+
await safePath(canonical, true);
|
|
35
|
+
return canonical;
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// An explicit selection never silently falls back to a different helper.
|
|
39
|
+
if (explicit !== undefined)
|
|
40
|
+
throw unavailable();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
throw unavailable();
|
|
44
|
+
}
|
package/dist/platform-state.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CliFailure } from './cli-errors.js';
|
|
2
|
+
import { trustedLinuxCredentialHelper } from './credential-helper.js';
|
|
2
3
|
export type PlatformFailureCategory = ConstructorParameters<typeof CliFailure>[3];
|
|
3
4
|
export declare const platformFailure: (message: string, nextAction?: string, category?: PlatformFailureCategory, retryable?: boolean) => CliFailure;
|
|
4
5
|
export declare function platformOrigin(value?: string): string;
|
|
@@ -12,4 +13,4 @@ export interface SecretStore {
|
|
|
12
13
|
clear(): Promise<void>;
|
|
13
14
|
}
|
|
14
15
|
export declare function runCredentialProcess(binary: string, args: string[], input?: string, timeoutMs?: number): Promise<string>;
|
|
15
|
-
export declare function secretStore(origin: string, file?: string, runProcess?: typeof runCredentialProcess, platform?: NodeJS.Platform): SecretStore;
|
|
16
|
+
export declare function secretStore(origin: string, file?: string, runProcess?: typeof runCredentialProcess, platform?: NodeJS.Platform, linuxHelper?: typeof trustedLinuxCredentialHelper): SecretStore;
|
package/dist/platform-state.js
CHANGED
|
@@ -4,6 +4,7 @@ import { dirname, join } from 'node:path';
|
|
|
4
4
|
import { lstat, mkdir, open, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
5
5
|
import { CliArgumentError } from './cli-arguments.js';
|
|
6
6
|
import { CliFailure } from './cli-errors.js';
|
|
7
|
+
import { trustedLinuxCredentialHelper } from './credential-helper.js';
|
|
7
8
|
export const platformFailure = (message, nextAction = 'Run anhedral login --help.', category = 'context', retryable = false) => new CliFailure(message, 'PLATFORM_ACCESS_FAILED', nextAction, category, retryable);
|
|
8
9
|
export function platformOrigin(value = 'https://platform.anhedral.com') {
|
|
9
10
|
let url;
|
|
@@ -140,7 +141,7 @@ export function runCredentialProcess(binary, args, input = '', timeoutMs = 30000
|
|
|
140
141
|
child.stdin.end(input);
|
|
141
142
|
});
|
|
142
143
|
}
|
|
143
|
-
export function secretStore(origin, file, runProcess = runCredentialProcess, platform = process.platform) {
|
|
144
|
+
export function secretStore(origin, file, runProcess = runCredentialProcess, platform = process.platform, linuxHelper = trustedLinuxCredentialHelper) {
|
|
144
145
|
if (file && platform === 'win32')
|
|
145
146
|
throw platformFailure('Secure Windows credential storage is not implemented. Use macOS Keychain or Linux Secret Service for this preview.');
|
|
146
147
|
if (file)
|
|
@@ -203,7 +204,7 @@ export function secretStore(origin, file, runProcess = runCredentialProcess, pla
|
|
|
203
204
|
if (platform === 'linux')
|
|
204
205
|
return {
|
|
205
206
|
read: async () => {
|
|
206
|
-
const value = await runProcess(
|
|
207
|
+
const value = await runProcess(await linuxHelper(), [
|
|
207
208
|
'lookup',
|
|
208
209
|
'service',
|
|
209
210
|
'dev.anhedral.cli.v1',
|
|
@@ -213,10 +214,10 @@ export function secretStore(origin, file, runProcess = runCredentialProcess, pla
|
|
|
213
214
|
return value ? JSON.parse(value) : null;
|
|
214
215
|
},
|
|
215
216
|
write: async (data) => {
|
|
216
|
-
await runProcess(
|
|
217
|
+
await runProcess(await linuxHelper(), ['store', '--label=Anhedral CLI', 'service', 'dev.anhedral.cli.v1', 'origin', account], JSON.stringify(data));
|
|
217
218
|
},
|
|
218
219
|
clear: async () => {
|
|
219
|
-
await runProcess(
|
|
220
|
+
await runProcess(await linuxHelper(), [
|
|
220
221
|
'clear',
|
|
221
222
|
'service',
|
|
222
223
|
'dev.anhedral.cli.v1',
|
package/dist/registry/usage.js
CHANGED
|
@@ -35,7 +35,7 @@ Start a project:
|
|
|
35
35
|
add Add backend, private storage or payments.
|
|
36
36
|
|
|
37
37
|
Inspect source and UI:
|
|
38
|
-
stack Inspect the Anhedral Stack
|
|
38
|
+
stack Inspect, update or diagnose the Anhedral Stack.
|
|
39
39
|
ui Initialize, add, list, diff or check UI components.
|
|
40
40
|
|
|
41
41
|
Optional Platform access:
|
|
@@ -47,6 +47,7 @@ Optional Platform access:
|
|
|
47
47
|
deploy Plan, prepare or inspect a candidate; never activates it.
|
|
48
48
|
env Import private configuration or list variable metadata.
|
|
49
49
|
staging Deploy verified candidates to persistent staging.
|
|
50
|
+
production Publish ready candidates with current project permissions.
|
|
50
51
|
logs Read redacted runtime logs for a linked project.
|
|
51
52
|
|
|
52
53
|
Shell setup:
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type CliArtifact } from './contracts/deployment.js';
|
|
2
|
+
declare const publishedArtifact: unique symbol;
|
|
3
|
+
export type PublishedCliArtifact = Readonly<CliArtifact> & {
|
|
4
|
+
readonly [publishedArtifact]: true;
|
|
5
|
+
};
|
|
6
|
+
export type ReleaseArtifactOptions = {
|
|
7
|
+
fetch?: typeof globalThis.fetch;
|
|
8
|
+
signal?: AbortSignal;
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
};
|
|
11
|
+
export declare class ArtifactUnavailableError extends Error {
|
|
12
|
+
readonly code = "ARTIFACT_UNAVAILABLE";
|
|
13
|
+
constructor();
|
|
14
|
+
}
|
|
15
|
+
export declare function isPublishedCliArtifact(value: unknown): value is PublishedCliArtifact;
|
|
16
|
+
/** Only fixed official public release endpoints may supply provenance. No project context is read. */
|
|
17
|
+
export declare function resolvePublishedCliArtifact(options?: ReleaseArtifactOptions): Promise<PublishedCliArtifact>;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { cliArtifactSchema } from './contracts/deployment.js';
|
|
2
|
+
import { GENERATOR_VERSION } from './version.js';
|
|
3
|
+
const MAX_JSON_BYTES = 256 * 1024;
|
|
4
|
+
const MAX_TIMEOUT_MS = 15000;
|
|
5
|
+
const sourceRevision = /^[a-f0-9]{40}$/;
|
|
6
|
+
const releaseVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
|
|
7
|
+
const verified = new WeakSet();
|
|
8
|
+
export class ArtifactUnavailableError extends Error {
|
|
9
|
+
code = 'ARTIFACT_UNAVAILABLE';
|
|
10
|
+
constructor() {
|
|
11
|
+
super('The running CLI release artifact could not be verified from official GitHub and npm metadata. Retry after publication or use --offline for a source-only update; deployment will remain unavailable.');
|
|
12
|
+
this.name = 'ArtifactUnavailableError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export function isPublishedCliArtifact(value) {
|
|
16
|
+
return typeof value === 'object' && value !== null && verified.has(value);
|
|
17
|
+
}
|
|
18
|
+
function object(value) {
|
|
19
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
20
|
+
throw new ArtifactUnavailableError();
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
function abortable(signal, operation) {
|
|
24
|
+
signal.throwIfAborted();
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const abort = () => reject(new ArtifactUnavailableError());
|
|
27
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
28
|
+
Promise.resolve()
|
|
29
|
+
.then(operation)
|
|
30
|
+
.then((value) => {
|
|
31
|
+
signal.removeEventListener('abort', abort);
|
|
32
|
+
resolve(value);
|
|
33
|
+
}, (error) => {
|
|
34
|
+
signal.removeEventListener('abort', abort);
|
|
35
|
+
reject(error);
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
async function readJson(response, signal) {
|
|
40
|
+
if (!response.ok || !response.body) {
|
|
41
|
+
void response.body?.cancel().catch(() => undefined);
|
|
42
|
+
throw new ArtifactUnavailableError();
|
|
43
|
+
}
|
|
44
|
+
const length = response.headers.get('content-length');
|
|
45
|
+
if (length !== null && Number(length) > MAX_JSON_BYTES) {
|
|
46
|
+
void response.body.cancel().catch(() => undefined);
|
|
47
|
+
throw new ArtifactUnavailableError();
|
|
48
|
+
}
|
|
49
|
+
const reader = response.body.getReader();
|
|
50
|
+
const chunks = [];
|
|
51
|
+
let size = 0;
|
|
52
|
+
try {
|
|
53
|
+
for (;;) {
|
|
54
|
+
signal.throwIfAborted();
|
|
55
|
+
const result = await abortable(signal, () => reader.read());
|
|
56
|
+
if (result.done)
|
|
57
|
+
break;
|
|
58
|
+
size += result.value.byteLength;
|
|
59
|
+
if (size > MAX_JSON_BYTES)
|
|
60
|
+
throw new ArtifactUnavailableError();
|
|
61
|
+
chunks.push(result.value);
|
|
62
|
+
}
|
|
63
|
+
const bytes = new Uint8Array(size);
|
|
64
|
+
let offset = 0;
|
|
65
|
+
for (const chunk of chunks) {
|
|
66
|
+
bytes.set(chunk, offset);
|
|
67
|
+
offset += chunk.byteLength;
|
|
68
|
+
}
|
|
69
|
+
return object(JSON.parse(new TextDecoder('utf8', { fatal: true }).decode(bytes)));
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
void reader.cancel().catch(() => undefined);
|
|
73
|
+
reader.releaseLock();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** Only fixed official public release endpoints may supply provenance. No project context is read. */
|
|
77
|
+
export async function resolvePublishedCliArtifact(options = {}) {
|
|
78
|
+
const timeout = options.timeoutMs ?? MAX_TIMEOUT_MS;
|
|
79
|
+
if (!Number.isInteger(timeout) ||
|
|
80
|
+
timeout < 1 ||
|
|
81
|
+
timeout > MAX_TIMEOUT_MS ||
|
|
82
|
+
!releaseVersion.test(GENERATOR_VERSION))
|
|
83
|
+
throw new ArtifactUnavailableError();
|
|
84
|
+
const controller = new AbortController();
|
|
85
|
+
const timer = setTimeout(() => controller.abort(), timeout);
|
|
86
|
+
const signal = AbortSignal.any([controller.signal, ...(options.signal ? [options.signal] : [])]);
|
|
87
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
88
|
+
async function request(url, redirects = false) {
|
|
89
|
+
for (let count = 0;; count++) {
|
|
90
|
+
signal.throwIfAborted();
|
|
91
|
+
const response = await abortable(signal, () => fetcher(url.href, {
|
|
92
|
+
method: 'GET',
|
|
93
|
+
redirect: 'manual',
|
|
94
|
+
credentials: 'omit',
|
|
95
|
+
cache: 'no-store',
|
|
96
|
+
referrerPolicy: 'no-referrer',
|
|
97
|
+
signal,
|
|
98
|
+
headers: { accept: 'application/json', 'user-agent': 'anhedral-cli' },
|
|
99
|
+
}));
|
|
100
|
+
if (response.redirected || (response.url && new URL(response.url).href !== url.href))
|
|
101
|
+
throw new ArtifactUnavailableError();
|
|
102
|
+
if (response.status >= 300 && response.status < 400) {
|
|
103
|
+
const location = response.headers.get('location');
|
|
104
|
+
void response.body?.cancel().catch(() => undefined);
|
|
105
|
+
if (!redirects || count >= 2 || !location)
|
|
106
|
+
throw new ArtifactUnavailableError();
|
|
107
|
+
const next = new URL(location, url);
|
|
108
|
+
if (next.protocol !== 'https:' ||
|
|
109
|
+
next.hostname !== 'release-assets.githubusercontent.com' ||
|
|
110
|
+
next.port ||
|
|
111
|
+
next.username ||
|
|
112
|
+
next.password ||
|
|
113
|
+
next.hash)
|
|
114
|
+
throw new ArtifactUnavailableError();
|
|
115
|
+
url = next;
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
return readJson(response, signal);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const version = GENERATOR_VERSION;
|
|
123
|
+
const metadata = await request(new URL(`https://github.com/anhedral/anhedral-cli/releases/download/v${version}/metadata.json`), true);
|
|
124
|
+
if (metadata.schemaVersion !== 1 ||
|
|
125
|
+
metadata.name !== 'anhedral' ||
|
|
126
|
+
metadata.version !== version ||
|
|
127
|
+
metadata.filename !== `anhedral-${version}.tgz` ||
|
|
128
|
+
typeof metadata.sourceRevision !== 'string' ||
|
|
129
|
+
!sourceRevision.test(metadata.sourceRevision))
|
|
130
|
+
throw new ArtifactUnavailableError();
|
|
131
|
+
const artifact = cliArtifactSchema.parse({
|
|
132
|
+
version,
|
|
133
|
+
sourceRevision: metadata.sourceRevision,
|
|
134
|
+
packageIntegrity: metadata.integrity,
|
|
135
|
+
});
|
|
136
|
+
const registry = await request(new URL(`https://registry.npmjs.org/anhedral/${version}`));
|
|
137
|
+
const dist = object(registry.dist);
|
|
138
|
+
if (registry.name !== 'anhedral' ||
|
|
139
|
+
registry.version !== version ||
|
|
140
|
+
dist.integrity !== artifact.packageIntegrity ||
|
|
141
|
+
dist.tarball !== `https://registry.npmjs.org/anhedral/-/anhedral-${version}.tgz`)
|
|
142
|
+
throw new ArtifactUnavailableError();
|
|
143
|
+
if (registry.gitHead !== undefined && registry.gitHead !== artifact.sourceRevision)
|
|
144
|
+
throw new ArtifactUnavailableError();
|
|
145
|
+
const ref = await request(new URL(`https://api.github.com/repos/anhedral/anhedral-cli/git/ref/tags/v${version}`));
|
|
146
|
+
if (ref.ref !== `refs/tags/v${version}`)
|
|
147
|
+
throw new ArtifactUnavailableError();
|
|
148
|
+
let target = object(ref.object);
|
|
149
|
+
if (target.type === 'tag') {
|
|
150
|
+
if (typeof target.sha !== 'string' || !sourceRevision.test(target.sha))
|
|
151
|
+
throw new ArtifactUnavailableError();
|
|
152
|
+
const tag = await request(new URL(`https://api.github.com/repos/anhedral/anhedral-cli/git/tags/${target.sha}`));
|
|
153
|
+
if (tag.tag !== `v${version}`)
|
|
154
|
+
throw new ArtifactUnavailableError();
|
|
155
|
+
target = object(tag.object);
|
|
156
|
+
}
|
|
157
|
+
if (target.type !== 'commit' || target.sha !== artifact.sourceRevision)
|
|
158
|
+
throw new ArtifactUnavailableError();
|
|
159
|
+
const result = Object.freeze(artifact);
|
|
160
|
+
verified.add(result);
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
throw new ArtifactUnavailableError();
|
|
165
|
+
}
|
|
166
|
+
finally {
|
|
167
|
+
clearTimeout(timer);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { resolvePublishedCliArtifact, type PublishedCliArtifact } from './release-artifact.js';
|
|
2
|
+
import { type OutputOptions } from './cli-output.js';
|
|
3
|
+
import { CapabilityEditor } from './capability-editor.js';
|
|
4
|
+
/** One exact replacement hunk without unchanged project configuration context. */
|
|
5
|
+
export declare function updateDiff(file: string, before: string | null, after: string): string;
|
|
6
|
+
export declare function planStackUpdate(root: string, artifact?: PublishedCliArtifact): {
|
|
7
|
+
editor: CapabilityEditor;
|
|
8
|
+
entries: [string, string][];
|
|
9
|
+
plan: {
|
|
10
|
+
planId: string;
|
|
11
|
+
schemaVersion: number;
|
|
12
|
+
root: string;
|
|
13
|
+
fromVersion: any;
|
|
14
|
+
toVersion: string;
|
|
15
|
+
changes: {
|
|
16
|
+
path: string;
|
|
17
|
+
beforeDigest: string | null;
|
|
18
|
+
afterDigest: string;
|
|
19
|
+
diff: string;
|
|
20
|
+
}[];
|
|
21
|
+
conflicts: {
|
|
22
|
+
code: string;
|
|
23
|
+
message: string;
|
|
24
|
+
}[];
|
|
25
|
+
sourceOnly: boolean;
|
|
26
|
+
dependenciesInstalled: boolean;
|
|
27
|
+
resourcesProvisionedByCli: boolean;
|
|
28
|
+
deployment: {
|
|
29
|
+
provenanceReady: boolean;
|
|
30
|
+
artifactRequired: boolean;
|
|
31
|
+
artifact: PublishedCliArtifact | null;
|
|
32
|
+
message: string;
|
|
33
|
+
};
|
|
34
|
+
nextAction: string;
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
export declare function runStackUpdate(args: string[], output: OutputOptions, dependencies?: {
|
|
38
|
+
resolveArtifact?: typeof resolvePublishedCliArtifact;
|
|
39
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
import { chmodSync, existsSync, statSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { isDeepStrictEqual, stripVTControlCharacters } from 'node:util';
|
|
4
|
+
import { deploymentManifestSchema } from './contracts/deployment.js';
|
|
5
|
+
import { ArtifactUnavailableError, resolvePublishedCliArtifact, isPublishedCliArtifact, } from './release-artifact.js';
|
|
6
|
+
import { isMap, parseDocument } from 'yaml';
|
|
7
|
+
import { commandArgumentError, commandArguments } from './cli-arguments.js';
|
|
8
|
+
import { CliFailure } from './cli-errors.js';
|
|
9
|
+
import { createReporter } from './cli-output.js';
|
|
10
|
+
import { assertPublicWorkspace, projectRoot, readState } from './capability-command.js';
|
|
11
|
+
import { CapabilityEditor, fingerprint } from './capability-editor.js';
|
|
12
|
+
import { normalizeOjFoundation } from './platforms/tanstack.js';
|
|
13
|
+
import { composeSourceProvenance } from './composition.js';
|
|
14
|
+
import { GENERATOR_VERSION } from './version.js';
|
|
15
|
+
import { runStagedTransaction } from './transaction.js';
|
|
16
|
+
import { put } from './scaffold/files.js';
|
|
17
|
+
const MAX_UPDATE_BYTES = 256 * 1024;
|
|
18
|
+
const MAX_UPDATE_FILES = 32;
|
|
19
|
+
/** One exact replacement hunk without unchanged project configuration context. */
|
|
20
|
+
export function updateDiff(file, before, after) {
|
|
21
|
+
const old = before === null || before === '' ? [] : before.split('\n');
|
|
22
|
+
const next = after === '' ? [] : after.split('\n');
|
|
23
|
+
if (old.at(-1) === '')
|
|
24
|
+
old.pop();
|
|
25
|
+
if (next.at(-1) === '')
|
|
26
|
+
next.pop();
|
|
27
|
+
const newlineChanged = before !== null && before.endsWith('\n') !== after.endsWith('\n');
|
|
28
|
+
let prefix = 0;
|
|
29
|
+
while (prefix < old.length && prefix < next.length && old[prefix] === next[prefix])
|
|
30
|
+
prefix++;
|
|
31
|
+
if (newlineChanged && prefix === old.length && prefix === next.length && prefix > 0)
|
|
32
|
+
prefix--;
|
|
33
|
+
let suffix = 0;
|
|
34
|
+
while (suffix < old.length - prefix &&
|
|
35
|
+
suffix < next.length - prefix &&
|
|
36
|
+
old[old.length - suffix - 1] === next[next.length - suffix - 1] &&
|
|
37
|
+
!(newlineChanged && suffix === 0))
|
|
38
|
+
suffix++;
|
|
39
|
+
const oldEnd = old.length - suffix;
|
|
40
|
+
const nextEnd = next.length - suffix;
|
|
41
|
+
const oldCount = oldEnd - prefix;
|
|
42
|
+
const nextCount = nextEnd - prefix;
|
|
43
|
+
const lines = [
|
|
44
|
+
`--- ${before === null ? '/dev/null' : `a/${file}`}`,
|
|
45
|
+
`+++ b/${file}`,
|
|
46
|
+
`@@ -${oldCount ? prefix + 1 : prefix},${oldCount} +${nextCount ? prefix + 1 : prefix},${nextCount} @@`,
|
|
47
|
+
];
|
|
48
|
+
for (let index = prefix; index < oldEnd; index++) {
|
|
49
|
+
lines.push(`-${old[index]}`);
|
|
50
|
+
if (index === old.length - 1 && before !== null && !before.endsWith('\n'))
|
|
51
|
+
lines.push('\');
|
|
52
|
+
}
|
|
53
|
+
for (let index = prefix; index < nextEnd; index++) {
|
|
54
|
+
lines.push(`+${next[index]}`);
|
|
55
|
+
if (index === next.length - 1 && !after.endsWith('\n'))
|
|
56
|
+
lines.push('\');
|
|
57
|
+
}
|
|
58
|
+
return lines.join('\n') + '\n';
|
|
59
|
+
}
|
|
60
|
+
function updatePnpmPolicy(e) {
|
|
61
|
+
const file = 'pnpm-workspace.yaml';
|
|
62
|
+
const source = e.read(file);
|
|
63
|
+
if (source === null)
|
|
64
|
+
throw Error('Missing pnpm-workspace.yaml; preserve and reconcile workspace policy.');
|
|
65
|
+
const document = parseDocument(source);
|
|
66
|
+
if (document.errors.length || !isMap(document.contents))
|
|
67
|
+
throw Error('Invalid pnpm-workspace.yaml; preserve existing policy.');
|
|
68
|
+
let policy;
|
|
69
|
+
try {
|
|
70
|
+
policy = document.toJS();
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
throw Error('Invalid or ambiguous pnpm workspace aliases; preserve existing policy.');
|
|
74
|
+
}
|
|
75
|
+
const expected = { esbuild: true, workerd: true };
|
|
76
|
+
if (policy.dangerouslyAllowAllBuilds !== undefined ||
|
|
77
|
+
policy.ignoredBuiltDependencies !== undefined ||
|
|
78
|
+
policy.neverBuiltDependencies !== undefined ||
|
|
79
|
+
policy.onlyBuiltDependenciesFile !== undefined)
|
|
80
|
+
throw Error('Customized pnpm build policy requires review; no source was changed.');
|
|
81
|
+
const previous = policy.onlyBuiltDependencies;
|
|
82
|
+
if (previous !== undefined &&
|
|
83
|
+
(!Array.isArray(previous) ||
|
|
84
|
+
previous.length !== 2 ||
|
|
85
|
+
new Set(previous).size !== 2 ||
|
|
86
|
+
!previous.includes('esbuild') ||
|
|
87
|
+
!previous.includes('workerd')))
|
|
88
|
+
throw Error('Customized onlyBuiltDependencies requires review; no source was changed.');
|
|
89
|
+
const allowed = policy.allowBuilds;
|
|
90
|
+
if (allowed !== undefined &&
|
|
91
|
+
(allowed === null ||
|
|
92
|
+
typeof allowed !== 'object' ||
|
|
93
|
+
Array.isArray(allowed) ||
|
|
94
|
+
Object.keys(allowed).length !== 2 ||
|
|
95
|
+
Reflect.get(allowed, 'esbuild') !== true ||
|
|
96
|
+
Reflect.get(allowed, 'workerd') !== true))
|
|
97
|
+
throw Error('Customized allowBuilds requires review; no source was changed.');
|
|
98
|
+
if (previous === undefined && allowed !== undefined)
|
|
99
|
+
return;
|
|
100
|
+
// Missing policy is not permission to enable lifecycle scripts.
|
|
101
|
+
if (previous === undefined && allowed === undefined)
|
|
102
|
+
throw Error('Missing reviewed pnpm build policy; reconcile it explicitly before updating.');
|
|
103
|
+
const pair = document.contents.items.find((item) => item.key &&
|
|
104
|
+
typeof item.key === 'object' &&
|
|
105
|
+
'value' in item.key &&
|
|
106
|
+
item.key.value === 'onlyBuiltDependencies');
|
|
107
|
+
const key = pair?.key;
|
|
108
|
+
const value = pair?.value;
|
|
109
|
+
if (!key?.range || !value?.range)
|
|
110
|
+
throw Error('Cannot safely locate canonical pnpm build policy.');
|
|
111
|
+
const replacement = allowed === undefined ? `allowBuilds: ${JSON.stringify(expected)}\n` : '';
|
|
112
|
+
const updated = source.slice(0, key.range[0]) + replacement + source.slice(value.range[2]);
|
|
113
|
+
const updatedDocument = parseDocument(updated);
|
|
114
|
+
const expectedPolicy = { ...policy, allowBuilds: expected };
|
|
115
|
+
delete expectedPolicy.onlyBuiltDependencies;
|
|
116
|
+
let validPolicy = false;
|
|
117
|
+
try {
|
|
118
|
+
validPolicy =
|
|
119
|
+
!updatedDocument.errors.length && isDeepStrictEqual(updatedDocument.toJS(), expectedPolicy);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
/* Never expose untrusted YAML alias details in a conflict. */
|
|
123
|
+
}
|
|
124
|
+
if (!validPolicy)
|
|
125
|
+
throw Error('The pnpm policy uses aliases or custom syntax that cannot be safely upgraded; preserve and reconcile it explicitly.');
|
|
126
|
+
e.writes.set(file, updated);
|
|
127
|
+
}
|
|
128
|
+
/** Remove only the previous canonical CSS URL adapter, retaining the authored document. */
|
|
129
|
+
function updateRootStylesheet(e) {
|
|
130
|
+
const file = 'apps/web/src/routes/__root.tsx';
|
|
131
|
+
const source = e.read(file);
|
|
132
|
+
if (source === null || !/\bfrom\s*(['"])\.\.\/styles\.css\?url\1/.test(source))
|
|
133
|
+
return;
|
|
134
|
+
const imports = [
|
|
135
|
+
...source.matchAll(/^import[ \t]+styles[ \t]+from[ \t]+(['"])\.\.\/styles\.css\?url\1;[ \t]*\r?$/gm),
|
|
136
|
+
];
|
|
137
|
+
const links = [
|
|
138
|
+
...source.matchAll(/^[ \t]*links:[ \t]*\[[ \t]*\{[ \t]*rel:[ \t]*(['"])stylesheet\1[ \t]*,[ \t]*href:[ \t]*styles[ \t]*\}[ \t]*\],[ \t]*\r?\n/gm),
|
|
139
|
+
];
|
|
140
|
+
const head = source.indexOf('head: () => ({');
|
|
141
|
+
const component = source.indexOf('component: Root', head);
|
|
142
|
+
if (imports.length !== 1 ||
|
|
143
|
+
links.length !== 1 ||
|
|
144
|
+
head < 0 ||
|
|
145
|
+
component < 0 ||
|
|
146
|
+
links[0].index < head ||
|
|
147
|
+
links[0].index > component ||
|
|
148
|
+
source.split('export const Route = createRootRoute({').length !== 2)
|
|
149
|
+
throw Error('Customized root stylesheet adapter needs review; preserve the authored root document.');
|
|
150
|
+
const imported = imports[0];
|
|
151
|
+
const linked = links[0];
|
|
152
|
+
const remainder = source.replace(imported[0], '').replace(linked[0], '');
|
|
153
|
+
if (/\bstyles\b/.test(remainder))
|
|
154
|
+
throw Error('The root stylesheet URL has additional uses; preserve and reconcile them explicitly.');
|
|
155
|
+
const updated = source
|
|
156
|
+
.replace(imported[0], `import ${imported[1]}../styles.css${imported[1]};`)
|
|
157
|
+
.replace(linked[0], '');
|
|
158
|
+
e.writes.set(file, updated);
|
|
159
|
+
}
|
|
160
|
+
export function planStackUpdate(root, artifact) {
|
|
161
|
+
if (artifact !== undefined &&
|
|
162
|
+
(!isPublishedCliArtifact(artifact) || artifact.version !== GENERATOR_VERSION))
|
|
163
|
+
throw Error('Only a verified published artifact matching this CLI can update deployment provenance.');
|
|
164
|
+
assertPublicWorkspace(root, false, 'stack');
|
|
165
|
+
const e = new CapabilityEditor(root, {});
|
|
166
|
+
const state = readState(e);
|
|
167
|
+
Object.assign(e.managed, state.managedFiles);
|
|
168
|
+
const configuration = e.json('anhedral.json');
|
|
169
|
+
const previousVersion = configuration.composition.generatorVersion;
|
|
170
|
+
const conflicts = [];
|
|
171
|
+
if (typeof previousVersion === 'string') {
|
|
172
|
+
const old = previousVersion.split(/[.-]/).slice(0, 3).map(Number);
|
|
173
|
+
const current = GENERATOR_VERSION.split(/[.-]/).slice(0, 3).map(Number);
|
|
174
|
+
const differing = old.findIndex((value, index) => value !== current[index]);
|
|
175
|
+
if (differing >= 0 && old[differing] > current[differing])
|
|
176
|
+
conflicts.push({
|
|
177
|
+
code: 'NEWER_SOURCE',
|
|
178
|
+
message: 'This source was generated by a newer CLI. Use that version or a newer published CLI; source downgrades are not supported.',
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
const attempt = (action) => {
|
|
182
|
+
try {
|
|
183
|
+
action();
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
conflicts.push({
|
|
187
|
+
code: 'SOURCE_CONFLICT',
|
|
188
|
+
message: (error instanceof Error ? error.message : String(error)).slice(0, 1000),
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
if (existsSync(path.join(root, '.anhedral-journal.json')))
|
|
193
|
+
conflicts.push({
|
|
194
|
+
code: 'RECOVERY_REQUIRED',
|
|
195
|
+
message: 'An interrupted source transaction exists. Recover the original command before updating.',
|
|
196
|
+
});
|
|
197
|
+
attempt(() => {
|
|
198
|
+
updateRootStylesheet(e);
|
|
199
|
+
normalizeOjFoundation(e, state.installed, true);
|
|
200
|
+
});
|
|
201
|
+
attempt(() => updatePnpmPolicy(e));
|
|
202
|
+
let artifactRequired = true;
|
|
203
|
+
attempt(() => {
|
|
204
|
+
const source = e.read('deployment.json');
|
|
205
|
+
const composition = composeSourceProvenance(configuration.composition, state.installed, []);
|
|
206
|
+
if (source !== null) {
|
|
207
|
+
const manifest = deploymentManifestSchema.parse(e.json('deployment.json'));
|
|
208
|
+
if (manifest.foundation !== composition.foundation ||
|
|
209
|
+
manifest.identity !== composition.identity ||
|
|
210
|
+
JSON.stringify([...manifest.capabilities].sort()) !==
|
|
211
|
+
JSON.stringify([...state.installed].sort()))
|
|
212
|
+
throw Error('Deployment identity or capabilities disagree with installed source; preserve and reconcile deployment.json.');
|
|
213
|
+
if (artifact) {
|
|
214
|
+
artifactRequired = false;
|
|
215
|
+
if (JSON.stringify(manifest.cliArtifact) !== JSON.stringify(artifact))
|
|
216
|
+
e.set('deployment.json', ['cliArtifact'], artifact);
|
|
217
|
+
if (JSON.stringify(deploymentManifestSchema.parse(e.json('deployment.json')).cliArtifact) !==
|
|
218
|
+
JSON.stringify(artifact))
|
|
219
|
+
throw Error('Deployment artifact has ambiguous source keys; preserve and reconcile deployment.json.');
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
else if (artifact) {
|
|
223
|
+
const manifest = deploymentManifestSchema.parse({
|
|
224
|
+
contractVersion: 1,
|
|
225
|
+
foundation: composition.foundation,
|
|
226
|
+
capabilities: state.installed,
|
|
227
|
+
identity: composition.identity,
|
|
228
|
+
cliArtifact: artifact,
|
|
229
|
+
intent: {
|
|
230
|
+
contractVersion: 1,
|
|
231
|
+
runtimeProfile: 'anhedral-stack',
|
|
232
|
+
environment: 'preview',
|
|
233
|
+
visibility: 'protected',
|
|
234
|
+
},
|
|
235
|
+
});
|
|
236
|
+
e.create('deployment.json', JSON.stringify(manifest, null, 2) + '\n');
|
|
237
|
+
artifactRequired = false;
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
if (!conflicts.length)
|
|
241
|
+
attempt(() => {
|
|
242
|
+
const composition = composeSourceProvenance(configuration.composition, state.installed, []);
|
|
243
|
+
if (configuration.setup.cliVersion !== GENERATOR_VERSION)
|
|
244
|
+
e.set('anhedral.json', ['setup', 'cliVersion'], GENERATOR_VERSION);
|
|
245
|
+
if (JSON.stringify(composition) !== JSON.stringify(configuration.composition))
|
|
246
|
+
e.set('anhedral.json', ['composition'], composition);
|
|
247
|
+
if (JSON.stringify(e.managed) !== JSON.stringify(state.managedFiles))
|
|
248
|
+
e.set('anhedral.json', ['capabilities', 'managedFiles'], e.managed);
|
|
249
|
+
const updatedConfiguration = e.json('anhedral.json');
|
|
250
|
+
if (updatedConfiguration.setup.cliVersion !== GENERATOR_VERSION ||
|
|
251
|
+
!isDeepStrictEqual(updatedConfiguration.composition, composition) ||
|
|
252
|
+
!isDeepStrictEqual(updatedConfiguration.capabilities.managedFiles, e.managed))
|
|
253
|
+
throw Error('Ambiguous source provenance keys; preserve and reconcile anhedral.json before updating.');
|
|
254
|
+
});
|
|
255
|
+
const entries = [...e.writes]
|
|
256
|
+
.filter(([file, after]) => e.before.get(file) !== after)
|
|
257
|
+
.sort(([a], [b]) => a.localeCompare(b));
|
|
258
|
+
const total = entries.reduce((bytes, [file, after]) => bytes + Buffer.byteLength(e.before.get(file) ?? '') + Buffer.byteLength(after), 0);
|
|
259
|
+
if (entries.length > MAX_UPDATE_FILES || total > MAX_UPDATE_BYTES)
|
|
260
|
+
conflicts.push({
|
|
261
|
+
code: 'PREVIEW_LIMIT',
|
|
262
|
+
message: `Update exceeds the bounded preview (${MAX_UPDATE_FILES} files/${MAX_UPDATE_BYTES} bytes); preserve source and reconcile it explicitly.`,
|
|
263
|
+
});
|
|
264
|
+
let changes = total > MAX_UPDATE_BYTES || entries.length > MAX_UPDATE_FILES
|
|
265
|
+
? []
|
|
266
|
+
: entries.map(([file, after]) => ({
|
|
267
|
+
path: file,
|
|
268
|
+
beforeDigest: e.before.get(file) === null ? null : fingerprint(e.before.get(file)),
|
|
269
|
+
afterDigest: fingerprint(after),
|
|
270
|
+
diff: updateDiff(file, e.before.get(file) ?? null, after),
|
|
271
|
+
}));
|
|
272
|
+
if (changes.some((change) => /["']?[A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PRIVATE_KEY|API_KEY|AUTHORIZATION)[A-Z0-9_]*["']?\s*[:=]/i.test(change.diff))) {
|
|
273
|
+
conflicts.push({
|
|
274
|
+
code: 'SENSITIVE_PREVIEW',
|
|
275
|
+
message: 'A changed configuration block may contain private values. Preserve it and reconcile that owned configuration before updating.',
|
|
276
|
+
});
|
|
277
|
+
changes = [];
|
|
278
|
+
}
|
|
279
|
+
const plan = {
|
|
280
|
+
schemaVersion: 1,
|
|
281
|
+
root,
|
|
282
|
+
fromVersion: previousVersion,
|
|
283
|
+
toVersion: GENERATOR_VERSION,
|
|
284
|
+
changes,
|
|
285
|
+
conflicts,
|
|
286
|
+
sourceOnly: true,
|
|
287
|
+
dependenciesInstalled: false,
|
|
288
|
+
resourcesProvisionedByCli: false,
|
|
289
|
+
deployment: {
|
|
290
|
+
provenanceReady: !artifactRequired && conflicts.length === 0,
|
|
291
|
+
artifactRequired,
|
|
292
|
+
artifact: artifact ?? null,
|
|
293
|
+
message: artifactRequired
|
|
294
|
+
? 'Resolve the published CLI artifact before refreshing deployment provenance. Rerun without --offline when online.'
|
|
295
|
+
: 'CLI artifact verified against official release metadata and npm. Hosting and build admission remain server-owned.',
|
|
296
|
+
},
|
|
297
|
+
nextAction: 'Review the diff, apply with --expect-plan, then install dependencies and validate the application separately.',
|
|
298
|
+
};
|
|
299
|
+
return { editor: e, entries, plan: { ...plan, planId: fingerprint(JSON.stringify(plan)) } };
|
|
300
|
+
}
|
|
301
|
+
export async function runStackUpdate(args, output, dependencies = {}) {
|
|
302
|
+
const parsed = commandArguments('stack', args);
|
|
303
|
+
const expected = parsed.value('--expect-plan');
|
|
304
|
+
if (expected !== undefined && !/^[a-f0-9]{64}$/.test(expected))
|
|
305
|
+
throw commandArgumentError('stack', '--expect-plan requires a SHA-256 plan ID.');
|
|
306
|
+
const root = projectRoot(process.cwd());
|
|
307
|
+
assertPublicWorkspace(root, false, 'stack');
|
|
308
|
+
let artifact;
|
|
309
|
+
if (!parsed.has('--offline')) {
|
|
310
|
+
try {
|
|
311
|
+
artifact = await (dependencies.resolveArtifact ?? resolvePublishedCliArtifact)();
|
|
312
|
+
}
|
|
313
|
+
catch (error) {
|
|
314
|
+
if (error instanceof ArtifactUnavailableError)
|
|
315
|
+
throw new CliFailure(error.message, 'ARTIFACT_UNAVAILABLE', 'Retry after publication or preview with stack update --offline --dry-run --json. Deployment provenance stays pending offline.', 'network', true);
|
|
316
|
+
throw error;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
const { editor, entries, plan } = planStackUpdate(root, artifact);
|
|
320
|
+
if (expected !== undefined && expected !== plan.planId)
|
|
321
|
+
throw new CliFailure('The source update plan changed. Review a fresh --dry-run before applying.', 'UPDATE_PLAN_CHANGED', 'Run anhedral stack update --dry-run --json and review the new plan before applying.', 'conflict', false);
|
|
322
|
+
let applied = false;
|
|
323
|
+
if (!parsed.has('--dry-run') && !plan.conflicts.length) {
|
|
324
|
+
if (entries.length)
|
|
325
|
+
await runStagedTransaction(root, {
|
|
326
|
+
commitPaths: entries.map(([file]) => file),
|
|
327
|
+
recover: false,
|
|
328
|
+
prepare: () => editor.verify(),
|
|
329
|
+
build: async (stage) => {
|
|
330
|
+
for (const [file, source] of entries) {
|
|
331
|
+
put(stage, file, source);
|
|
332
|
+
if (editor.before.get(file) !== null)
|
|
333
|
+
chmodSync(path.join(stage, file), statSync(path.join(root, file)).mode & 0o777);
|
|
334
|
+
}
|
|
335
|
+
editor.verify();
|
|
336
|
+
},
|
|
337
|
+
});
|
|
338
|
+
else
|
|
339
|
+
editor.verify();
|
|
340
|
+
applied = true;
|
|
341
|
+
}
|
|
342
|
+
if (plan.conflicts.length)
|
|
343
|
+
process.exitCode = 1;
|
|
344
|
+
const terminalSafe = (value) => stripVTControlCharacters(value.replace(/\r\n/g, '\n')).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, '');
|
|
345
|
+
createReporter(output, () => terminalSafe(`${applied ? 'Applied' : 'Preview'} source update ${plan.fromVersion ?? 'unknown'} → ${plan.toVersion}\nPlan: ${plan.planId}\n${plan.changes.map((change) => change.diff).join('\n')}${plan.conflicts.map((conflict) => conflict.message).join('\n')}\n${plan.nextAction}`)).result({ ...plan, dryRun: parsed.has('--dry-run'), applied });
|
|
346
|
+
}
|
package/dist/transaction.d.ts
CHANGED
|
@@ -15,6 +15,7 @@ export declare function runStagedTransaction(root: string, options: {
|
|
|
15
15
|
deletePaths?: string[];
|
|
16
16
|
seedPaths?: string[];
|
|
17
17
|
dryRun?: boolean;
|
|
18
|
+
recover?: boolean;
|
|
18
19
|
prepare?: () => boolean | void | Promise<boolean | void>;
|
|
19
20
|
afterCommit?: () => void | Promise<void>;
|
|
20
21
|
onPlan?: (paths: readonly string[]) => void;
|
package/dist/transaction.js
CHANGED
|
@@ -642,6 +642,8 @@ export async function runStagedTransaction(root, options) {
|
|
|
642
642
|
if (options.dryRun && pathEntryExists(path.join(root, JOURNAL_FILE))) {
|
|
643
643
|
throw new Error('Dry-run cannot recover an interrupted transaction. Re-run the original command without --dry-run first.');
|
|
644
644
|
}
|
|
645
|
+
if (options.recover === false && pathEntryExists(path.join(root, JOURNAL_FILE)))
|
|
646
|
+
throw new Error('An interrupted transaction requires recovery before this operation.');
|
|
645
647
|
recoverInterruptedTransactionUnlocked(root);
|
|
646
648
|
if (!options.dryRun)
|
|
647
649
|
cleanupOrphanTransactionRoots(root);
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const GENERATOR_VERSION = "0.
|
|
1
|
+
export declare const GENERATOR_VERSION = "0.20.0";
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const GENERATOR_VERSION = '0.
|
|
1
|
+
export const GENERATOR_VERSION = '0.20.0';
|
package/docs/software-factory.md
CHANGED
|
@@ -74,11 +74,36 @@ Backend server entries call TanStack’s `createStartHandler(defaultStreamHandle
|
|
|
74
74
|
|
|
75
75
|
OJ dev commands attach an explicit host value with `--host=<hostname>`, as required by the pinned runtime. Generated workspaces explicitly allow dependency build scripts only for esbuild and workerd through the pnpm `allowBuilds` map. This keeps installation noninteractive under the pinned pnpm release and pnpm11 without allowing arbitrary dependency scripts.
|
|
76
76
|
|
|
77
|
+
## Updating existing source
|
|
78
|
+
|
|
79
|
+
Plugin updates refresh agent guidance; select its matching published CLI separately.
|
|
80
|
+
Use the host's configured marketplace: Codex refreshes its marketplace with
|
|
81
|
+
`codex plugin marketplace upgrade <marketplace>` and installs the refreshed
|
|
82
|
+
`codex plugin add anhedral@<marketplace>`; Claude Code uses
|
|
83
|
+
`claude plugin marketplace update <marketplace>` and
|
|
84
|
+
`claude plugin update anhedral@<marketplace>`. Verify the installed manifest version
|
|
85
|
+
and reload/restart the host when required before relying on its new guidance.
|
|
86
|
+
Run `stack update --dry-run --json`, inspect the bounded file diffs and conflicts,
|
|
87
|
+
then apply `stack update --expect-plan <planId> --json`. The plan binds source
|
|
88
|
+
preimages, target generator and resolved release artifact. Changed plans and
|
|
89
|
+
customized generated files stop the update; authored routes and assets remain
|
|
90
|
+
owned by the application. This operation uses the existing journaled transaction
|
|
91
|
+
without installing dependencies or running project scripts. Resolve source
|
|
92
|
+
conflicts before another preview, then install dependencies and run application
|
|
93
|
+
checks/build separately. It never changes authentication or deployment authority.
|
|
94
|
+
Official release metadata and npm integrity establish deployment provenance;
|
|
95
|
+
project-supplied metadata cannot select another registry, credential destination
|
|
96
|
+
or executable. Offline source inspection cannot attest a newly published artifact.
|
|
97
|
+
|
|
77
98
|
## Platform CLI access and source upload
|
|
78
99
|
|
|
79
100
|
`login --start` prints browser approval instructions; `login --resume` redeems the
|
|
80
101
|
saved approval. Interactive `login` polls after showing the URL and confirmation
|
|
81
102
|
code. Tokens and device secrets use macOS Keychain or Linux Secret Service;
|
|
103
|
+
Linux selects a validated root-owned system helper without searching project
|
|
104
|
+
`PATH`. `ANHEDRAL_CLI_SECRET_TOOL_PATH` can select an absolute trusted system
|
|
105
|
+
installation; its executable and path ownership/permissions are validated.
|
|
106
|
+
Untrusted or unavailable helpers fail closed.
|
|
82
107
|
`--credential-file <path>` explicitly selects an owner-only file. Credential
|
|
83
108
|
storage is currently unsupported on Windows. Credentials are
|
|
84
109
|
bound to the explicit `--api-url` origin (HTTPS, with literal loopback for fixtures).
|
|
@@ -193,6 +218,9 @@ reviewed skills, references, assets and host manifests, and rejects connection f
|
|
|
193
218
|
or executable declarations. `tests/test-plugin-codex.test.mjs` installs the exact
|
|
194
219
|
archive in an isolated Codex home and verifies both skills with no MCP, app or hook
|
|
195
220
|
registration when Codex is available (`ANHEDRAL_CODEX_BIN` overrides the binary).
|
|
221
|
+
`ANHEDRAL_CLAUDE_BIN` selects an explicitly installed Claude validator; use a current
|
|
222
|
+
version supporting `plugin validate --strict`. Installed older validators fail the
|
|
223
|
+
gate rather than silently dropping strict validation.
|
|
196
224
|
|
|
197
225
|
One distribution directory, `plugin/`, serves Codex and Claude Code. Codex reads
|
|
198
226
|
`plugin.json` and `skills/*/agents/openai.yaml`; Claude Code reads
|