Skip to content

Commit cc51570

Browse files
committed
Prompt for and validate resources added because others require them
addRequiredResources() now runs before the missing parameters are prompted and the config is validated, so a required type with mandatory parameters is asked for like a declared resource instead of reaching the plugin's plan without them. The prompt says why the resource is there ("Added automatically · required by cursor"), and the non-interactive errors (JSON reporter, agent) name the resources that required it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016QnBk1brshJrHGEkhMFR29
1 parent d0e11d0 commit cc51570

11 files changed

Lines changed: 94 additions & 8 deletions

File tree

‎CLAUDE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ The `test` command spins up a Tart VM to test Codify configs in isolation:
7575
- Explicit: `dependsOn` field in config
7676
- Implicit: Extracted from parameter references (e.g., `${other-resource.param}`)
7777
- Plugin-level: Plugins declare type dependencies (soft: only order resources that are present)
78-
- Required: `requires` in a resource definition (ex: `homebrew`, `xcode-tools` on macOS). `Project.addRequiredResources()` adds a default config for missing required types, transitively, before dependencies are resolved. Added resources keep `ResourceConfig.requiredBy` and get a `✦ AUTO-ADDED` badge plus "required by ..." in the plan (`src/ui/required-by.ts`, `requiredBy` in JSON output and in the agent's `codify_plan` result)
78+
- Required: `requires` in a resource definition (ex: `homebrew`, `xcode-tools` on macOS). `Project.addRequiredResources()` adds a default config for missing required types, transitively, before missing parameters are prompted and the config is validated (so added resources are asked and validated like declared ones; `codify test` doesn't add them on the host, the VM's plan does). Added resources keep `ResourceConfig.requiredBy` and get a `✦ AUTO-ADDED` badge plus "required by ..." in the plan (`src/ui/required-by.ts`, `requiredBy` in JSON output and in the agent's `codify_plan` result)
7979
- Topological sort ensures correct evaluation order (`src/utils/dependency-graph-resolver.ts`)
8080

8181
### Key Directory Structure

‎src/orchestrators/plan.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,11 +57,13 @@ export class PlanOrchestrator {
5757

5858
await createStartupShellScriptsIfNotExists();
5959

60+
// Ex: homebrew for resources installed with brew, xcode-tools for resources that need git or a compiler on macOS.
61+
// Added first so they are prompted for and validated like the resources of the config.
62+
project.addRequiredResources(resourceDefinitions);
63+
6064
// Prompt for missing required values and dashboard placeholders. Must happen before validation.
6165
await MissingParametersResolver.run(initializationResult, reporter, args.presetParameterValues);
6266
await ValidateOrchestrator.run({ existing: initializationResult, noProgress: args.noProgress }, reporter);
63-
// Ex: homebrew for resources installed with brew, xcode-tools for resources that need git or a compiler on macOS
64-
project.addRequiredResources(resourceDefinitions);
6567
project.resolveDependenciesAndCalculateEvalOrder(resourceDefinitions);
6668

6769
// Also validates the dependsOn of every notice before planning

‎src/prompt/tools/codify-tools.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { ApplyOrchestrator } from '../../orchestrators/apply.js';
88
import { PlanOrchestrator } from '../../orchestrators/plan.js';
99
import { applyEntryLabel } from '../../ui/apply-result-formatter.js';
1010
import { prettyFormatResourcePlan } from '../../ui/plan-pretty-printer.js';
11-
import { requiredByOf } from '../../ui/required-by.js';
11+
import { formatRequiredBy, requiredByOf } from '../../ui/required-by.js';
1212
import { Reporter } from '../../ui/reporters/reporter.js';
1313
import { StubReporter } from '../../ui/reporters/stub-reporter.js';
1414
import { SessionStore } from '../session-store.js';
@@ -45,7 +45,7 @@ export interface CodifyApplyResult {
4545
*/
4646
class NonInteractiveReporter extends StubReporter {
4747
async promptMissingParameters(requests: ResourceMissingParameters[]): Promise<unknown[][]> {
48-
const missing = requests.map((r) => `${r.resource.id}: ${r.parameters.map((p) => p.label).join(', ')}`);
48+
const missing = requests.map((r) => `${r.resource.id}${r.resource.requiredBy.length > 0 ? ` (added automatically, ${formatRequiredBy(r.resource.requiredBy)})` : ''}: ${r.parameters.map((p) => p.label).join(', ')}`);
4949
throw new Error(`The config is missing required values (${missing.join('; ')}). Fill them in or ask the user.`);
5050
}
5151
}

‎src/ui/components/parameter-list/parameter-list.tsx‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Box, Text, useInput } from 'ink';
22
import React, { useMemo, useState } from 'react';
33

44
import { setValueAtPath } from '../../../utils/missing-parameters.js';
5+
import { AUTO_ADDED_COLOR, formatRequiredBy } from '../../required-by.js';
56

67
export interface ParameterListField {
78
/** Location of the value inside the resource. Strings are object keys, numbers are array indices. */
@@ -25,6 +26,8 @@ export interface ParameterListResource {
2526
config: Record<string, unknown>;
2627
/** Top level keys whose existing values are masked. '*' masks every value. */
2728
sensitiveKeys?: string[];
29+
/** Set when the CLI added the resource because these resources require it. Shown under the header. */
30+
requiredBy?: string[];
2831
fields: ParameterListField[];
2932
}
3033

@@ -217,6 +220,16 @@ function layoutResources(resources: ParameterListResource[]): Line[] {
217220
isHeader: true,
218221
});
219222

223+
if (resource.requiredBy && resource.requiredBy.length > 0) {
224+
lines.push({
225+
kind: 'text',
226+
key: `${resource.id}-${resourceIdx}-required-by`,
227+
indent: 0,
228+
text: `✦ Added automatically · ${formatRequiredBy(resource.requiredBy)}`,
229+
color: AUTO_ADDED_COLOR,
230+
});
231+
}
232+
220233
// Insert a marker at every field path so missing keys show up in the right place
221234
const fieldIdxByPath = new Map(resource.fields.map((f, idx) => [pathKey(f.path), fieldOffset + idx]));
222235
const config = resource.fields.reduce<Record<string, unknown>>((result, field) => {

‎src/ui/reporters/default-reporter.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,7 @@ export class DefaultReporter implements Reporter {
299299
id: resource.id,
300300
config: { ...resource.core(), ...resource.parameters },
301301
sensitiveKeys: sensitiveParameters,
302+
requiredBy: resource.requiredBy,
302303
fields: parameters.map((parameter) => ({
303304
path: parameter.path,
304305
type: parameter.type,

‎src/ui/reporters/json-reporter.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { ResourceMissingParameters } from '../../entities/missing-parameter.js';
77
import { Plan } from '../../entities/plan.js';
88
import { ResourceConfig } from '../../entities/resource-config.js';
99
import { ImportResult } from '../../orchestrators/import.js';
10-
import { requiredByOf } from '../required-by.js';
10+
import { formatRequiredBy, requiredByOf } from '../required-by.js';
1111
import { Reporter } from './reporter.js';
1212
import type { TemplateCommandApprovalRequest } from '../../templates/template-command-approval.js';
1313
import type { SecretsApprovalRequest } from '../../variables/secrets-approval.js';
@@ -73,7 +73,8 @@ export class JsonReporter implements Reporter {
7373
}
7474

7575
async promptMissingParameters(requests: ResourceMissingParameters[]): Promise<unknown[][]> {
76-
const missing = requests.flatMap(({ resource, parameters }) => parameters.map((p) => `${resource.id}.${p.label}`));
76+
const missing = requests.flatMap(({ resource, parameters }) => parameters.map((p) =>
77+
`${resource.id}.${p.label}${resource.requiredBy.length > 0 ? ` (${formatRequiredBy(resource.requiredBy)})` : ''}`));
7778
throw new Error(`Json reporter error: the following values are missing from the config and cannot be prompted while using the Json reporter: ${stringifyRedacted(missing)}`);
7879
}
7980

‎src/ui/reporters/plain-reporter.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import type { SecretsApprovalRequest } from '../../variables/secrets-approval.js
2323
import { VariableValueType } from '@codifycli/schemas';
2424
import type { VariablePromptRequest } from '../../variables/variable-resolver.js';
2525
import { formatVariableDefault, formatVariableHint, formatVariableLabel, formatVariableQuestion } from '../variable-prompt-formatter.js';
26+
import { AUTO_ADDED_COLOR, formatRequiredBy } from '../required-by.js';
2627

2728
export class PlainReporter implements Reporter {
2829
private readonly rl = readline.createInterface(process.stdin, process.stdout);
@@ -141,6 +142,9 @@ export class PlainReporter implements Reporter {
141142
const answers: unknown[][] = [];
142143
for (const { resource, parameters } of requests) {
143144
ctx.log(`Resource: "${resource.id}"`);
145+
if (resource.requiredBy.length > 0) {
146+
ctx.log(chalk.hex(AUTO_ADDED_COLOR)(`✦ Added automatically · ${formatRequiredBy(resource.requiredBy)}`));
147+
}
144148

145149
const resourceAnswers: unknown[] = [];
146150
for (const parameter of parameters) {

‎test/orchestrator/mocks/plugin.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ import { OsUtils } from '../../../src/utils/os-utils.js';
1111
import { getMockResources } from './get-mock-resources.js';
1212

1313
export class MockPlugin implements IPlugin {
14+
/** Test-only: replaces the requires sent for these types (ex: { action: ['mock'] }). Reset after each test. */
15+
static requiresOverride: Record<string, string[]> = {};
16+
1417
name = 'default';
1518
version = '0.0.0'
1619
path = '/'
@@ -30,7 +33,7 @@ export class MockPlugin implements IPlugin {
3033
...response,
3134
resourceDefinitions: response.resourceDefinitions.map((d) => ({
3235
...d,
33-
requires: d.type === 'mock' && OsUtils.isMacOS() ? ['xcode-tools'] : [],
36+
requires: MockPlugin.requiresOverride[d.type] ?? (d.type === 'mock' && OsUtils.isMacOS() ? ['xcode-tools'] : []),
3437
})),
3538
};
3639
}

‎test/orchestrator/plan/plan.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { MockOs } from '../mocks/system.js';
55
import { Plan } from '../../../src/entities/plan.js';
66
import { ResourceOperation } from '@codifycli/schemas';
77
import { MockReporter } from '../mocks/reporter.js';
8+
import { MockPlugin } from '../mocks/plugin.js';
89
import { PlanOrchestrator } from '../../../src/orchestrators/plan';
910
import {OsUtils} from "../../../src/utils/os-utils.js";
1011
import fs from 'node:fs/promises';
@@ -212,6 +213,43 @@ describe('Plan orchestrator tests', () => {
212213
expect(await fs.readFile(configPath, 'utf8')).to.eq(originalFile);
213214
});
214215

216+
it('Prompts for the missing values of resources added because another resource requires them', async () => {
217+
// action requires mock, which has required parameters (propA, propB)
218+
MockPlugin.requiresOverride = { action: ['mock'] };
219+
220+
const reporter = new MockReporter({
221+
promptMissingParameters(requests) {
222+
expect(requests).toHaveLength(1);
223+
expect(requests[0].resource.id).to.eq('mock');
224+
expect(requests[0].resource.requiredBy).toEqual(['action']);
225+
expect(requests[0].parameters.map((p) => [p.label, p.reason])).toEqual([
226+
['propA', 'missing'],
227+
['propB', 'missing'],
228+
]);
229+
230+
return [['abc', '123']];
231+
},
232+
validatePlan(plan: Plan) {
233+
expect(plan.getResourcePlan('mock')).toMatchObject({
234+
operation: ResourceOperation.CREATE,
235+
parameters: expect.arrayContaining([
236+
expect.objectContaining({ name: 'propA', newValue: 'abc' }),
237+
expect.objectContaining({ name: 'propB', newValue: 123 }),
238+
]),
239+
});
240+
},
241+
promptConfirmation(): boolean {
242+
return true;
243+
},
244+
});
245+
246+
const { project } = await PlanOrchestrator.run({ path: path.join(__dirname, 'requires-mock.codify.json') }, reporter);
247+
248+
// Applied before the resource that requires it
249+
const order = project.evaluationOrder!;
250+
expect(order.indexOf('mock')).toBeLessThan(order.indexOf('action'));
251+
});
252+
215253
it('Throws a validation error if a prompted value is invalid', async () => {
216254
const reporter = new MockReporter({
217255
promptMissingParameters: () => [['abc', 'b', 'not-a-number']],
@@ -234,6 +272,7 @@ describe('Plan orchestrator tests', () => {
234272
afterEach(() => {
235273
vi.resetAllMocks();
236274
MockOs.reset();
275+
MockPlugin.requiresOverride = {};
237276
})
238277

239278
})
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[
2+
{ "type": "project", "plugins": { "default": "./test/orchestrator/mocks/plugin.ts" } },
3+
{ "type": "action", "action": "echo hello" }
4+
]

0 commit comments

Comments
 (0)