@powerhousedao/ph-clint-cli 0.1.0-dev.8 → 0.1.0-dev.80

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 (99) hide show
  1. package/dist/cli.js +52 -10
  2. package/dist/codegen/actions.d.ts +46 -0
  3. package/dist/codegen/actions.js +424 -0
  4. package/dist/codegen/builders/agent-ts.d.ts +4 -4
  5. package/dist/codegen/builders/agent-ts.js +92 -2
  6. package/dist/codegen/builders/app-index-ts.d.ts +3 -10
  7. package/dist/codegen/builders/app-index-ts.js +30 -20
  8. package/dist/codegen/builders/cli-package-json.js +46 -14
  9. package/dist/codegen/builders/cli-ts.js +87 -49
  10. package/dist/codegen/builders/config-ts.d.ts +1 -1
  11. package/dist/codegen/builders/config-ts.js +2 -8
  12. package/dist/codegen/builders/demo-agent-ts.d.ts +8 -0
  13. package/dist/codegen/builders/demo-agent-ts.js +50 -0
  14. package/dist/codegen/builders/eslint-config-js.d.ts +1 -1
  15. package/dist/codegen/builders/eslint-config-js.js +7 -4
  16. package/dist/codegen/builders/framework-gen-ts.d.ts +11 -6
  17. package/dist/codegen/builders/framework-gen-ts.js +73 -21
  18. package/dist/codegen/builders/framework-ts.js +33 -7
  19. package/dist/codegen/builders/index.d.ts +10 -2
  20. package/dist/codegen/builders/index.js +30 -6
  21. package/dist/codegen/builders/manifest-json.d.ts +6 -0
  22. package/dist/codegen/builders/manifest-json.js +31 -0
  23. package/dist/codegen/builders/mastra-index-ts.d.ts +3 -0
  24. package/dist/codegen/builders/mastra-index-ts.js +47 -5
  25. package/dist/codegen/builders/publish-config-js.d.ts +8 -0
  26. package/dist/codegen/builders/publish-config-js.js +33 -0
  27. package/dist/codegen/builders/readme-md.js +7 -6
  28. package/dist/codegen/builders/root-package-json.js +11 -12
  29. package/dist/codegen/builders/smoke-test-ts.d.ts +2 -0
  30. package/dist/codegen/builders/smoke-test-ts.js +15 -0
  31. package/dist/codegen/exec.d.ts +0 -18
  32. package/dist/codegen/exec.js +0 -27
  33. package/dist/codegen/generated.d.ts +17 -0
  34. package/dist/codegen/generated.js +49 -0
  35. package/dist/codegen/index.d.ts +8 -36
  36. package/dist/codegen/index.js +6 -293
  37. package/dist/codegen/scaffold.d.ts +41 -3
  38. package/dist/codegen/scaffold.js +106 -16
  39. package/dist/commands/clint-project-build.d.ts +77 -1
  40. package/dist/commands/clint-project-build.js +11 -28
  41. package/dist/commands/clint-project-init.d.ts +128 -10
  42. package/dist/commands/clint-project-init.js +72 -47
  43. package/dist/commands/clint-project-publish.d.ts +78 -1
  44. package/dist/commands/clint-project-publish.js +6 -4
  45. package/dist/commands/clint-project-regen.d.ts +77 -1
  46. package/dist/commands/clint-project-regen.js +26 -2
  47. package/dist/commands/clint-skills-sync.d.ts +86 -0
  48. package/dist/commands/clint-skills-sync.js +56 -0
  49. package/dist/framework.d.ts +322 -60
  50. package/dist/framework.gen.d.ts +50 -10
  51. package/dist/framework.js +1 -5
  52. package/{prompts/agent-profiles/AgentBase.md → dist/gen/agent-profiles/PhClintDevAgent.md} +1 -1
  53. package/dist/gen/skills/cli-setup/.cli-docs.md +135 -0
  54. package/dist/gen/skills/cli-setup/SKILL.md +125 -0
  55. package/dist/gen/skills/cli-setup/references/00.assess-cli-needs.md +53 -0
  56. package/dist/gen/skills/cli-setup/references/01.define-config-schema.md +78 -0
  57. package/dist/gen/skills/cli-setup/references/02.wire-cli.md +141 -0
  58. package/dist/gen/skills/cli-setup/references/03.add-entrypoint.md +128 -0
  59. package/dist/gen/skills/cli-setup/references/expected-outcome.md +3 -0
  60. package/dist/gen/skills/command-definition/.cli-docs.md +84 -0
  61. package/dist/gen/skills/command-definition/SKILL.md +99 -0
  62. package/dist/gen/skills/command-definition/references/00.assess-requirements.md +58 -0
  63. package/dist/gen/skills/command-definition/references/01.define-schema.md +72 -0
  64. package/dist/gen/skills/command-definition/references/02.implement-execute.md +118 -0
  65. package/dist/gen/skills/command-definition/references/03.add-prompting.md +54 -0
  66. package/dist/gen/skills/command-definition/references/expected-outcome.md +3 -0
  67. package/dist/gen/skills/service-definition/.cli-docs.md +214 -0
  68. package/dist/gen/skills/service-definition/SKILL.md +148 -0
  69. package/dist/gen/skills/service-definition/references/00.assess-service.md +69 -0
  70. package/dist/gen/skills/service-definition/references/01.define-service.md +166 -0
  71. package/dist/gen/skills/service-definition/references/02.add-preflight.md +132 -0
  72. package/dist/gen/skills/service-definition/references/03.add-project-scanner.md +82 -0
  73. package/dist/gen/skills/service-definition/references/04.wire-events.md +120 -0
  74. package/dist/gen/skills/service-definition/references/expected-outcome.md +3 -0
  75. package/dist/main.js +0 -0
  76. package/dist/services/clint-project.js +21 -0
  77. package/dist/skills/sync.d.ts +40 -0
  78. package/dist/skills/sync.js +119 -0
  79. package/dist/spec/ensure-document.d.ts +17 -0
  80. package/dist/spec/ensure-document.js +56 -0
  81. package/dist/spec/file.d.ts +1 -4
  82. package/dist/spec/file.js +1 -34
  83. package/dist/spec/from-document.d.ts +4 -1
  84. package/dist/spec/from-document.js +4 -16
  85. package/dist/spec/types.d.ts +1 -62
  86. package/dist/spec/types.js +1 -112
  87. package/dist/triggers/publish-trigger.d.ts +81 -0
  88. package/dist/triggers/publish-trigger.js +137 -0
  89. package/dist/triggers/spec-change.d.ts +60 -18
  90. package/dist/triggers/spec-change.js +154 -101
  91. package/package.json +13 -18
  92. package/dist/codegen/builders/publish-config-ts.d.ts +0 -6
  93. package/dist/codegen/builders/publish-config-ts.js +0 -18
  94. package/dist/commands/init.d.ts +0 -57
  95. package/dist/commands/init.js +0 -168
  96. package/dist/commands/regen.d.ts +0 -18
  97. package/dist/commands/regen.js +0 -68
  98. package/prompts/skills-ext/.gitkeep +0 -0
  99. package/prompts/skills-tpl/.gitkeep +0 -0
@@ -1,34 +1,7 @@
1
1
  /**
2
2
  * Small helpers for invoking external commands during code generation.
3
- *
4
- * We deliberately keep this separate from `ph-clint`'s process manager:
5
- * here we need synchronous-feeling prompt-forwarding (stdio inherited) so
6
- * the user can respond to interactive prompts from `ph init` or from a
7
- * package manager.
8
3
  */
9
4
  import { spawn } from 'node:child_process';
10
- /**
11
- * Run `command args` in `cwd`, forwarding stdio by default. Resolves to
12
- * the exit code. Does NOT throw on non-zero — callers decide how to react.
13
- */
14
- export async function runCommand(command, args, options) {
15
- return new Promise((resolve, reject) => {
16
- const child = spawn(command, args, {
17
- cwd: options.cwd,
18
- stdio: options.stdio ?? 'inherit',
19
- env: options.env ? { ...process.env, ...options.env } : process.env,
20
- });
21
- child.once('error', reject);
22
- child.once('close', (code) => {
23
- resolve({
24
- command,
25
- args,
26
- cwd: options.cwd,
27
- exitCode: code ?? 0,
28
- });
29
- });
30
- });
31
- }
32
5
  /** Returns true if `command` is on PATH. */
33
6
  export async function hasCommandOnPath(command) {
34
7
  return new Promise((resolve) => {
@@ -0,0 +1,17 @@
1
+ import { type ClintProjectSpec } from '../spec/types.js';
2
+ export interface GeneratedState {
3
+ name: string;
4
+ scope: string | undefined;
5
+ cliFolderName: string;
6
+ appFolderName: string;
7
+ /** True once `ph init` has run successfully in the app dir. */
8
+ appInitialized: boolean;
9
+ }
10
+ export declare function getGeneratedPath(targetDir: string): string;
11
+ export declare function readGeneratedState(targetDir: string): Promise<GeneratedState | null>;
12
+ export declare function writeGeneratedState(targetDir: string, state: GeneratedState): Promise<void>;
13
+ /**
14
+ * Derive a `GeneratedState` from a spec. The `appInitialized` flag must be
15
+ * supplied by the caller (it depends on filesystem state, not the spec).
16
+ */
17
+ export declare function generatedStateFromSpec(spec: ClintProjectSpec, appInitialized: boolean): GeneratedState;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Tracks the derived state from the last successful code generation.
3
+ *
4
+ * Stored at `{targetDir}/.ph/ph-clint-cli/generated.json`. Used to detect
5
+ * folder renames (name/scope changes) and re-apply patches that depend on
6
+ * the project identity.
7
+ */
8
+ import fs from 'node:fs/promises';
9
+ import path from 'node:path';
10
+ import { getAppFolderName, getCliFolderName, } from '../spec/types.js';
11
+ const GEN_DIR = path.join('.ph', 'ph-clint-cli');
12
+ const GEN_FILE = 'generated.json';
13
+ export function getGeneratedPath(targetDir) {
14
+ return path.join(targetDir, GEN_DIR, GEN_FILE);
15
+ }
16
+ export async function readGeneratedState(targetDir) {
17
+ try {
18
+ const raw = await fs.readFile(getGeneratedPath(targetDir), 'utf8');
19
+ return JSON.parse(raw);
20
+ }
21
+ catch (err) {
22
+ if (err &&
23
+ typeof err === 'object' &&
24
+ 'code' in err &&
25
+ err.code === 'ENOENT') {
26
+ return null;
27
+ }
28
+ throw err;
29
+ }
30
+ }
31
+ export async function writeGeneratedState(targetDir, state) {
32
+ const file = getGeneratedPath(targetDir);
33
+ await fs.mkdir(path.dirname(file), { recursive: true });
34
+ await fs.writeFile(file, JSON.stringify(state, null, 2) + '\n', 'utf8');
35
+ }
36
+ /**
37
+ * Derive a `GeneratedState` from a spec. The `appInitialized` flag must be
38
+ * supplied by the caller (it depends on filesystem state, not the spec).
39
+ */
40
+ export function generatedStateFromSpec(spec, appInitialized) {
41
+ const split = spec.features.powerhouse !== 'Disabled';
42
+ return {
43
+ name: spec.name,
44
+ scope: spec.scope,
45
+ cliFolderName: split ? getCliFolderName(spec) : '',
46
+ appFolderName: split ? getAppFolderName(spec) : '',
47
+ appInitialized,
48
+ };
49
+ }
@@ -1,39 +1,11 @@
1
- import { type ClintProjectSpec } from '../spec/types.js';
2
- export type GenerateMode = 'create' | 'update' | 'auto';
3
- export interface GenerateProjectOptions {
4
- /** Absolute path to the project root. */
5
- targetDir: string;
6
- spec: ClintProjectSpec;
7
- /** Defaults to `'auto'` — create if no persisted spec, else update. */
8
- mode?: GenerateMode;
9
- /** Create mode: allow writing into a non-empty directory. */
10
- allowNonEmpty?: boolean;
11
- /**
12
- * Update mode: overwrite user-edited files (hash-mismatch) anyway.
13
- * Also relaxes the git-dirty guard on flat → split migration.
14
- */
15
- force?: boolean;
16
- /** Optional warning sink (diagnostics, not errors). */
17
- onWarn?: (msg: string) => void;
18
- }
19
- export interface GeneratedFile {
20
- absolutePath: string;
21
- relativePath: string;
22
- }
23
- export interface GenerateProjectResult {
24
- mode: 'create' | 'update';
25
- /** Files newly written or rewritten. */
26
- files: GeneratedFile[];
27
- /** Files skipped because the user had edited them. */
28
- skipped: GeneratedFile[];
29
- /** Files removed because the new spec no longer emits them. */
30
- deleted: GeneratedFile[];
31
- /** True if a flat → split migration ran. */
32
- migrated: boolean;
33
- cliDir: string;
34
- appDir: string | null;
35
- }
36
1
  /**
37
- * Generate / reconcile a project at `targetDir` from the given spec.
2
+ * Re-exports from @powerhousedao/ph-clint-dev/codegen with CLI_VERSION default.
38
3
  */
4
+ import { type GenerateProjectOptions as DevGenerateProjectOptions, type GenerateProjectResult, type GenerateMode, type GeneratedFile } from '@powerhousedao/ph-clint-dev/codegen';
5
+ import type { CodegenContext } from '@powerhousedao/ph-clint-dev/codegen/types';
6
+ export type { GenerateProjectResult, GenerateMode, GeneratedFile, CodegenContext };
7
+ export interface GenerateProjectOptions extends Omit<DevGenerateProjectOptions, 'context'> {
8
+ /** Codegen context; defaults to CLI_VERSION when omitted. */
9
+ context?: CodegenContext;
10
+ }
39
11
  export declare function generateProject(options: GenerateProjectOptions): Promise<GenerateProjectResult>;
@@ -1,298 +1,11 @@
1
1
  /**
2
- * Code generator entry point.
3
- *
4
- * Takes a `ClintProjectSpec` + target directory and reconciles the on-disk
5
- * project tree with it.
6
- *
7
- * Two modes:
8
- *
9
- * - **create** — the target dir is empty (or only contains ignorable
10
- * artefacts). Every templated file is written fresh. Refuses to
11
- * overwrite existing non-empty state unless `allowNonEmpty`.
12
- *
13
- * - **update** — a previous run's spec exists at
14
- * `.ph/ph-clint-cli/project-spec.json`. Re-runs the builders, then for
15
- * each emitted file:
16
- * - files containing `@clint:begin/@clint:end` markers (today: just
17
- * `src/cli.ts`) have their marker regions spliced in-place, leaving
18
- * user code outside markers untouched;
19
- * - files without markers are overwritten iff their on-disk hash still
20
- * matches the hash stored from the previous write (user-edited files
21
- * are skipped and surfaced via `onWarn`);
22
- * - files the new spec no longer emits are removed if their hash still
23
- * matches.
24
- *
25
- * A spec flip of `features.powerhouse.enabled` from `false` to `true`
26
- * triggers the flat → split migration before the update flow runs.
27
- *
28
- * Mode is auto-detected by the presence of the persisted spec.
29
- */
30
- import fs from 'node:fs/promises';
31
- import path from 'node:path';
32
- import { getAppFolderName, getCliFolderName, } from '../spec/types.js';
33
- import { getSpecPath, readProjectSpec, writeProjectSpec, } from '../spec/file.js';
34
- import { hashContent, hashFile, readHashes, writeHashes, } from './hashes.js';
35
- import { hasMarkers, spliceMarkerRegions } from './markers.js';
36
- import { writeFileEnsuringDir, isDirEmptyEnough } from './write.js';
37
- import { migrateFlatToSplit } from './migrate/flat-to-split.js';
38
- import { CLI_FILE_BUILDERS, buildReadme, buildRootPackageJson, buildPublishConfigTs, buildAppIndexTs, } from './builders/index.js';
39
- /**
40
- * Generate / reconcile a project at `targetDir` from the given spec.
2
+ * Re-exports from @powerhousedao/ph-clint-dev/codegen with CLI_VERSION default.
41
3
  */
4
+ import { generateProject as _generateProject, } from '@powerhousedao/ph-clint-dev/codegen';
5
+ import { CLI_VERSION } from '../config.js';
42
6
  export async function generateProject(options) {
43
- const { targetDir, spec } = options;
44
- const warn = options.onWarn ?? (() => { });
45
- const existingSpec = await readProjectSpec(targetDir);
46
- const resolvedMode = resolveMode(options.mode ?? 'auto', existingSpec !== null);
47
- // Flat → split migration, if needed. Runs BEFORE we compute planned files
48
- // so the hash record and on-disk state are already in split-layout shape
49
- // by the time the normal reconciliation runs.
50
- let migrated = false;
51
- if (resolvedMode === 'update' &&
52
- existingSpec &&
53
- !existingSpec.features.powerhouse.enabled &&
54
- spec.features.powerhouse.enabled) {
55
- await migrateFlatToSplit({
56
- targetDir,
57
- spec,
58
- force: options.force,
59
- onWarn: warn,
60
- });
61
- migrated = true;
62
- }
63
- // Dispatch to the mode-specific flow.
64
- if (resolvedMode === 'create') {
65
- return runCreate(options, warn);
66
- }
67
- return runUpdate(options, warn, migrated);
68
- }
69
- function resolveMode(requested, specExists) {
70
- if (requested === 'create')
71
- return 'create';
72
- if (requested === 'update')
73
- return 'update';
74
- return specExists ? 'update' : 'create';
75
- }
76
- /** Build the list of files the new spec would emit, with their content. */
77
- function planFiles(spec, targetDir) {
78
- const split = spec.features.powerhouse.enabled;
79
- const cliDir = split ? path.join(targetDir, getCliFolderName(spec)) : targetDir;
80
- const appDir = split ? path.join(targetDir, getAppFolderName(spec)) : null;
81
- const planned = [];
82
- for (const builder of CLI_FILE_BUILDERS) {
83
- const content = builder.build(spec);
84
- if (content === null)
85
- continue;
86
- const abs = path.join(cliDir, builder.relativePath);
87
- planned.push({
88
- relativePath: path.relative(targetDir, abs),
89
- absolutePath: abs,
90
- content,
91
- initOnly: builder.initOnly,
92
- });
93
- }
94
- // Project-root README — always at the top level.
95
- const readmeAbs = path.join(targetDir, 'README.md');
96
- planned.push({
97
- relativePath: 'README.md',
98
- absolutePath: readmeAbs,
99
- content: buildReadme(spec),
7
+ return _generateProject({
8
+ ...options,
9
+ context: options.context ?? { toolVersion: CLI_VERSION },
100
10
  });
101
- // Split-layout only: root package.json + app placeholder files.
102
- if (split && appDir) {
103
- const rootPkg = path.join(targetDir, 'package.json');
104
- planned.push({
105
- relativePath: 'package.json',
106
- absolutePath: rootPkg,
107
- content: buildRootPackageJson(spec),
108
- });
109
- const publishConfig = path.join(targetDir, 'publish.config.ts');
110
- planned.push({
111
- relativePath: 'publish.config.ts',
112
- absolutePath: publishConfig,
113
- content: buildPublishConfigTs(spec),
114
- });
115
- const appGitkeep = path.join(appDir, '.gitkeep');
116
- planned.push({
117
- relativePath: path.relative(targetDir, appGitkeep),
118
- absolutePath: appGitkeep,
119
- content: '',
120
- });
121
- const appReadme = path.join(appDir, 'README.md');
122
- planned.push({
123
- relativePath: path.relative(targetDir, appReadme),
124
- absolutePath: appReadme,
125
- content: buildAppReadmeContent(spec),
126
- });
127
- // Top-level barrel for the reactor package — lets impl code import from
128
- // `{name}-app` instead of drilling into `document-models/<slug>/v1/gen`.
129
- const appIndex = buildAppIndexTs(spec);
130
- if (appIndex !== null) {
131
- const appIndexAbs = path.join(appDir, 'index.ts');
132
- planned.push({
133
- relativePath: path.relative(targetDir, appIndexAbs),
134
- absolutePath: appIndexAbs,
135
- content: appIndex,
136
- });
137
- }
138
- }
139
- return { planned, cliDir, appDir };
140
- }
141
- function buildAppReadmeContent(spec) {
142
- return [
143
- `# ${spec.name}-app`,
144
- '',
145
- 'Powerhouse reactor-package for this project. Scaffold it with:',
146
- '',
147
- '```sh',
148
- `cd ${spec.name}-app`,
149
- 'ph init',
150
- '```',
151
- '',
152
- 'Then run `pnpm install` at the project root.',
153
- '',
154
- ].join('\n');
155
- }
156
- /** Create mode — empty target dir, write everything fresh. */
157
- async function runCreate(options, _warn) {
158
- const { targetDir, spec } = options;
159
- if (!options.allowNonEmpty) {
160
- const empty = await isDirEmptyEnough(targetDir);
161
- if (!empty) {
162
- throw new Error(`target directory ${targetDir} is not empty (pass allowNonEmpty or --force to override)`);
163
- }
164
- }
165
- const { planned, cliDir, appDir } = planFiles(spec, targetDir);
166
- const hashes = {};
167
- const files = [];
168
- for (const p of planned) {
169
- await writeFileEnsuringDir(p.absolutePath, p.content);
170
- hashes[p.relativePath] = hashContent(p.content);
171
- files.push({ absolutePath: p.absolutePath, relativePath: p.relativePath });
172
- }
173
- await writeProjectSpec(targetDir, spec);
174
- files.push({
175
- absolutePath: getSpecPath(targetDir),
176
- relativePath: path.relative(targetDir, getSpecPath(targetDir)),
177
- });
178
- await writeHashes(targetDir, hashes);
179
- return {
180
- mode: 'create',
181
- files,
182
- skipped: [],
183
- deleted: [],
184
- migrated: false,
185
- cliDir,
186
- appDir,
187
- };
188
- }
189
- /** Update mode — reconcile against an existing project. */
190
- async function runUpdate(options, warn, migrated) {
191
- const { targetDir, spec } = options;
192
- const force = !!options.force;
193
- const { planned, cliDir, appDir } = planFiles(spec, targetDir);
194
- const plannedByKey = new Map(planned.map((p) => [p.relativePath, p]));
195
- const previous = await readHashes(targetDir);
196
- const next = {};
197
- const files = [];
198
- const skipped = [];
199
- const deleted = [];
200
- // Step 1: write / patch / skip each planned file.
201
- for (const p of planned) {
202
- if (p.initOnly) {
203
- // User-owned files (e.g. `src/framework.ts` with its `configSchema`)
204
- // are emitted only on create. In update mode we never overwrite them
205
- // and never re-create them if missing — the user may have deliberately
206
- // deleted or inlined them. Keep whatever hash the previous run stored
207
- // so the deletion pass (step 2) still considers them "ours".
208
- const stored = previous[p.relativePath];
209
- if (stored !== undefined)
210
- next[p.relativePath] = stored;
211
- continue;
212
- }
213
- const existing = await hashFile(p.absolutePath);
214
- if (existing === null) {
215
- // Not yet on disk — fresh write.
216
- await writeFileEnsuringDir(p.absolutePath, p.content);
217
- next[p.relativePath] = hashContent(p.content);
218
- files.push({
219
- absolutePath: p.absolutePath,
220
- relativePath: p.relativePath,
221
- });
222
- continue;
223
- }
224
- // File exists. Decide how to update it.
225
- if (hasMarkers(p.content)) {
226
- const existingContent = await fs.readFile(p.absolutePath, 'utf8');
227
- const patched = hasMarkers(existingContent)
228
- ? spliceMarkerRegions(existingContent, p.content)
229
- : p.content;
230
- if (patched === existingContent) {
231
- // No-op: regions already match.
232
- next[p.relativePath] = hashContent(patched);
233
- continue;
234
- }
235
- await writeFileEnsuringDir(p.absolutePath, patched);
236
- next[p.relativePath] = hashContent(patched);
237
- files.push({
238
- absolutePath: p.absolutePath,
239
- relativePath: p.relativePath,
240
- });
241
- continue;
242
- }
243
- // No markers — hash-protected overwrite.
244
- const stored = previous[p.relativePath];
245
- const pristine = stored !== undefined && stored === existing;
246
- if (!pristine && !force) {
247
- // User edited a managed file. Leave it alone.
248
- warn(`skipped ${p.relativePath} — modified since last generation. Use --force to overwrite.`);
249
- skipped.push({
250
- absolutePath: p.absolutePath,
251
- relativePath: p.relativePath,
252
- });
253
- // Preserve the previous hash so the file stays on our ledger.
254
- if (stored !== undefined)
255
- next[p.relativePath] = stored;
256
- continue;
257
- }
258
- if (existing === hashContent(p.content)) {
259
- // Already up to date.
260
- next[p.relativePath] = existing;
261
- continue;
262
- }
263
- await writeFileEnsuringDir(p.absolutePath, p.content);
264
- next[p.relativePath] = hashContent(p.content);
265
- files.push({
266
- absolutePath: p.absolutePath,
267
- relativePath: p.relativePath,
268
- });
269
- }
270
- // Step 2: delete files that the new spec no longer emits, IF we still
271
- // recognise their content (hash match). Otherwise warn and keep.
272
- for (const [relPath, storedHash] of Object.entries(previous)) {
273
- if (plannedByKey.has(relPath))
274
- continue;
275
- const abs = path.join(targetDir, relPath);
276
- const onDisk = await hashFile(abs);
277
- if (onDisk === null)
278
- continue; // already gone
279
- if (onDisk !== storedHash && !force) {
280
- warn(`kept ${relPath} — modified since last generation; new spec no longer emits it.`);
281
- next[relPath] = storedHash;
282
- continue;
283
- }
284
- await fs.rm(abs, { force: true });
285
- deleted.push({ absolutePath: abs, relativePath: relPath });
286
- }
287
- await writeProjectSpec(targetDir, spec);
288
- await writeHashes(targetDir, next);
289
- return {
290
- mode: 'update',
291
- files,
292
- skipped,
293
- deleted,
294
- migrated,
295
- cliDir,
296
- appDir,
297
- };
298
11
  }
@@ -1,4 +1,13 @@
1
1
  import type { ClintProjectSpec } from '../spec/types.js';
2
+ import type { ProcessRunOptions } from '@powerhousedao/ph-clint';
3
+ /**
4
+ * Signature for the subprocess runner — matches CommandContext.runProcess.
5
+ */
6
+ type RunProcess = (command: string, opts?: Omit<ProcessRunOptions, 'onOutput'>) => Promise<{
7
+ success: boolean;
8
+ output: string;
9
+ }>;
10
+ export type { RunProcess };
2
11
  export interface PhInitOptions {
3
12
  /** Absolute path to the project root. */
4
13
  targetDir: string;
@@ -9,22 +18,51 @@ export interface PhInitOptions {
9
18
  log?: (msg: string) => void;
10
19
  /** Override `ph` binary name (for tests). */
11
20
  binName?: string;
12
- /** Stdio passthrough (tests pass 'ignore'). */
13
- stdio?: 'inherit' | 'ignore';
21
+ /** Subprocess runner — matches CommandContext.runProcess. */
22
+ runProcess: RunProcess;
23
+ /** Explicit Powerhouse version to pin `ph init` to (tag or semver). */
24
+ phVersion?: string;
14
25
  }
15
26
  export interface PhInitResult {
16
27
  ran: boolean;
17
28
  exitCode?: number;
18
29
  reason?: string;
19
30
  }
31
+ /**
32
+ * Detect the installed `ph` CLI version by parsing `ph --version` output.
33
+ * Returns the version string (e.g. '6.0.0-dev.194') or undefined if
34
+ * detection fails.
35
+ */
36
+ export declare function getPhVersion(binName: string): string | undefined;
20
37
  export declare function runPhInit(options: PhInitOptions): Promise<PhInitResult>;
38
+ /**
39
+ * Patch the app `package.json` name to the scoped form (`@scope/name-app`).
40
+ * Called after `ph init` and after name/scope renames.
41
+ *
42
+ * Returns `true` if the file was actually changed.
43
+ */
44
+ export declare function patchAppPackageName(appDir: string, spec: {
45
+ name: string;
46
+ scope?: string;
47
+ }, log?: (msg: string) => void): Promise<boolean>;
48
+ /**
49
+ * Run `ph install <packages> --local --pnpm` in the app directory to register
50
+ * external packages in `powerhouse.config.json`.
51
+ */
52
+ export declare function runPhInstallPackages(options: {
53
+ appDir: string;
54
+ packages: string[];
55
+ log?: (msg: string) => void;
56
+ runProcess: RunProcess;
57
+ }): Promise<boolean>;
21
58
  export interface PnpmInstallOptions {
22
59
  /** Directories to run `pnpm install` in, in order. */
23
60
  dirs: string[];
24
61
  log?: (msg: string) => void;
25
62
  /** Override `pnpm` binary name (for tests). */
26
63
  binName?: string;
27
- stdio?: 'inherit' | 'ignore';
64
+ /** Subprocess runner — matches CommandContext.runProcess. */
65
+ runProcess: RunProcess;
28
66
  }
29
67
  export interface PnpmInstallResult {
30
68
  ran: string[];
@@ -7,32 +7,123 @@
7
7
  */
8
8
  import fs from 'node:fs/promises';
9
9
  import path from 'node:path';
10
- import { hasCommandOnPath, runCommand } from './exec.js';
10
+ import { execFileSync } from 'node:child_process';
11
+ import { hasCommandOnPath } from './exec.js';
12
+ /**
13
+ * Detect the installed `ph` CLI version by parsing `ph --version` output.
14
+ * Returns the version string (e.g. '6.0.0-dev.194') or undefined if
15
+ * detection fails.
16
+ */
17
+ export function getPhVersion(binName) {
18
+ try {
19
+ const output = execFileSync(binName, ['--version'], {
20
+ encoding: 'utf-8',
21
+ timeout: 5_000,
22
+ });
23
+ const match = output.match(/PH CMD version:\s*(\S+)/);
24
+ return match?.[1];
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
11
30
  export async function runPhInit(options) {
12
31
  const log = options.log ?? (() => { });
13
32
  const binName = options.binName ?? 'ph';
14
33
  const appFolder = path.basename(options.appDir);
34
+ // Guard: never re-init an already-initialized app directory.
35
+ try {
36
+ await fs.access(path.join(options.appDir, 'package.json'));
37
+ log(`App directory ${appFolder} already initialized — skipping ph init.`);
38
+ return { ran: false, reason: 'already-initialized' };
39
+ }
40
+ catch {
41
+ // No package.json — proceed with init.
42
+ }
15
43
  if (!(await hasCommandOnPath(binName))) {
16
44
  log(`Skipping \`${binName} init\` — \`${binName}\` is not on PATH. ` +
17
45
  `Install @powerhousedao/ph-cli and re-run manually inside ${appFolder}/.`);
18
46
  return { ran: false, reason: 'ph-not-on-path' };
19
47
  }
48
+ // Pin ph init to the same version as the installed ph CLI, so the
49
+ // generated app uses matching Powerhouse packages.
50
+ const phVersion = options.phVersion ?? getPhVersion(binName);
51
+ const tags = ['dev', 'staging', 'latest'];
52
+ const versionArgs = phVersion
53
+ ? tags.includes(phVersion)
54
+ ? [`--${phVersion}`]
55
+ : ['--version', phVersion]
56
+ : ['--dev']; // fallback if detection fails
20
57
  // `ph init {name}` creates a fresh directory beside the cwd. Our generator
21
58
  // placed a `.gitkeep` + README.md placeholder there; clear it out so
22
59
  // ph init has a blank slate to work with.
23
60
  await fs.rm(options.appDir, { recursive: true, force: true });
24
- log(`Running \`${binName} init ${appFolder}\` in ${options.targetDir} …`);
25
- const result = await runCommand(binName, [
26
- 'init',
27
- appFolder,
28
- '--pnpm',
29
- '--dev',
30
- ], { cwd: options.targetDir, stdio: options.stdio ?? 'inherit' });
31
- if (result.exitCode !== 0) {
32
- log(`\`${binName} init\` exited with code ${result.exitCode}. ` +
61
+ const args = ['init', appFolder, ...versionArgs, '--pnpm'];
62
+ log(`Running \`${binName} init ${appFolder}\` (version: ${phVersion ?? 'auto'}) in ${options.targetDir} …`);
63
+ const result = await options.runProcess(`${binName} ${args.join(' ')}`, {
64
+ cwd: options.targetDir,
65
+ timeout: 300_000,
66
+ });
67
+ const exitCode = result.success ? 0 : 1;
68
+ if (!result.success) {
69
+ log(`\`${binName} init\` failed. ` +
33
70
  'You can re-run it manually after resolving the issue.');
34
71
  }
35
- return { ran: true, exitCode: result.exitCode };
72
+ await patchScopedName(options, appFolder, log);
73
+ return { ran: true, exitCode };
74
+ }
75
+ /**
76
+ * Patch the app `package.json` name to the scoped form (`@scope/name-app`).
77
+ * Called after `ph init` and after name/scope renames.
78
+ *
79
+ * Returns `true` if the file was actually changed.
80
+ */
81
+ export async function patchAppPackageName(appDir, spec, log) {
82
+ const appFolder = path.basename(appDir);
83
+ const scopedName = spec.scope
84
+ ? `${spec.scope}/${appFolder}`
85
+ : appFolder;
86
+ const appPkgJsonPath = path.join(appDir, 'package.json');
87
+ try {
88
+ const raw = await fs.readFile(appPkgJsonPath, 'utf8');
89
+ const pkg = JSON.parse(raw);
90
+ if (pkg.name !== scopedName) {
91
+ pkg.name = scopedName;
92
+ if (spec.scope) {
93
+ pkg.publishConfig = { access: 'public' };
94
+ }
95
+ await fs.writeFile(appPkgJsonPath, JSON.stringify(pkg, null, 2) + '\n');
96
+ log?.(`Patched app package name to ${scopedName}`);
97
+ return true;
98
+ }
99
+ return false;
100
+ }
101
+ catch (err) {
102
+ log?.(`Warning: could not patch app package name: ${err instanceof Error ? err.message : String(err)}`);
103
+ return false;
104
+ }
105
+ }
106
+ async function patchScopedName(options, _appFolder, log) {
107
+ await patchAppPackageName(options.appDir, options.spec, log);
108
+ }
109
+ /**
110
+ * Run `ph install <packages> --local --pnpm` in the app directory to register
111
+ * external packages in `powerhouse.config.json`.
112
+ */
113
+ export async function runPhInstallPackages(options) {
114
+ const { appDir, packages, log = () => { }, runProcess } = options;
115
+ const binName = 'ph';
116
+ if (!(await hasCommandOnPath(binName))) {
117
+ log(`Skipping — \`${binName}\` is not on PATH.`);
118
+ return false;
119
+ }
120
+ const args = ['install', ...packages, '--local', '--pnpm'];
121
+ log(`Running \`${binName} install ${packages.join(' ')} --local\` in ${path.basename(appDir)} …`);
122
+ const result = await runProcess(`${binName} ${args.join(' ')}`, {
123
+ cwd: appDir,
124
+ timeout: 300_000,
125
+ });
126
+ return result.success;
36
127
  }
37
128
  export async function runPnpmInstall(options) {
38
129
  const log = options.log ?? (() => { });
@@ -45,14 +136,13 @@ export async function runPnpmInstall(options) {
45
136
  const ran = [];
46
137
  for (const dir of options.dirs) {
47
138
  log(`Running \`${binName} install\` in ${dir} …`);
48
- const result = await runCommand(binName, ['install'], {
139
+ const result = await options.runProcess(`${binName} install`, {
49
140
  cwd: dir,
50
- stdio: options.stdio ?? 'inherit',
141
+ timeout: 300_000,
51
142
  });
52
- if (result.exitCode !== 0) {
53
- log(`\`${binName} install\` exited with code ${result.exitCode} in ${dir}. ` +
143
+ if (!result.success) {
144
+ log(`\`${binName} install\` failed in ${dir}. ` +
54
145
  'Retry manually once the underlying issue is resolved.');
55
- // Don't abort the whole chain — subsequent dirs may still work.
56
146
  }
57
147
  ran.push(dir);
58
148
  }