Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/apply-warns-missing-specs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@fission-ai/openspec': minor
---

Apply now says when a change has no delta specs. Apply gates on the schema's `apply.requires` alone, so a change whose `tasks.md` was written ahead of its specs read as ready to implement even though it had no spec deltas at all — the state `openspec validate` rejects. `openspec instructions apply` now reports that gap as a warning (text and `--json`), naming both ways out: write the specs, or declare `skip_specs: true`. Changes that have specs, declare `skip_specs`, or are still blocked on their own required artifacts are unaffected.

A blocked apply also names the whole chain now, not just the first hop: a change holding only a proposal reported `Missing artifacts: tasks` while the specs that `tasks` depends on were missing too, which reads as an instruction to write the tracking file straight from the proposal. The full build order is reported as `missingPrerequisites` in `--json`. The remedies these messages give are CLI commands (`openspec instructions <artifact> --change <name>`) rather than the `openspec-continue-change` skill, which the `core` profile never installs.
2 changes: 1 addition & 1 deletion docs/agent-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ Change: `{ "id", "title", "deltaCount", "deltas": [...], "root" }`. Spec: `{ "id
`ReferenceIndexEntry`: `{ "store_id", "root"?, "specs"?: [{id,summary}], "fetch"?, "status": [] }` — resolved entries carry root/specs/fetch; unresolved carry store_id + warning status. Index capped at 50KB (`reference_index_truncated`).

### 4.6 `instructions apply --json`
`{ "changeName", "changeDir", "schemaName", "contextFiles": { "<artifactId>": ["/abs", ...] }, "progress": {total,complete,remaining}, "tasks": [{id,description,done}], "state": "blocked"|"all_done"|"ready", "missingArtifacts"?, "instruction", "references"?, "context"?, "operationGuidance"?, "root" }`. Both optional fields are read from the selected root on every invocation. `context` is a required prompt-level input whose relevant project facts, conventions, and constraints must be applied; `operationGuidance` is advisory input whose entries are followed only when applicable and compatible with the built-in workflow. Both remain separate from state, tasks, progress, context files, and the built-in instruction.
`{ "changeName", "changeDir", "schemaName", "contextFiles": { "<artifactId>": ["/abs", ...] }, "progress": {total,complete,remaining}, "tasks": [{id,description,done}], "state": "blocked"|"all_done"|"ready", "missingArtifacts"?, "missingPrerequisites"?, "warnings"?, "instruction", "references"?, "context"?, "operationGuidance"?, "root" }`. `missingArtifacts` is what apply blocks on (the schema's `apply.requires`); `missingPrerequisites` is everything still to build before apply can run, in build order - the transitive closure of those requires, so it can be the longer list. `warnings` lists non-blocking problems with the change itself - today, a change that is ready to implement with no delta specs and no `skip_specs: true`, the state `openspec validate` rejects. Both optional root fields (`context`, `operationGuidance`) are read from the selected root on every invocation. `context` is a required prompt-level input whose relevant project facts, conventions, and constraints must be applied; `operationGuidance` is advisory input whose entries are followed only when applicable and compatible with the built-in workflow. Both remain separate from state, tasks, progress, context files, and the built-in instruction.

### 4.7 `instructions archive --json`
`{ "changeName", "context"?, "operationGuidance"?, "root" }`. Requires a valid `--change` in the resolved repo/store root and uses the same required-context/advisory-guidance semantics as apply. This is a read-only runtime-input surface: it does not return the static archive workflow, inspect or merge delta specs, write main specs, or move the change.
Expand Down
183 changes: 178 additions & 5 deletions src/commands/workflow/instructions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
resolveArtifactOutputs,
type ArtifactInstructions,
} from '../../core/artifact-graph/index.js';
import { isSpecsArtifactPath } from '../../core/artifact-graph/outputs.js';
import {
getChangeDir,
resolveCurrentPlanningHomeSync,
Expand Down Expand Up @@ -48,6 +49,7 @@ import {
type ArchiveInstructions,
} from './shared.js';
import { parseTaskLines, type ParsedTask } from '../../utils/task-progress.js';
import { METADATA_FILENAME } from '../../utils/change-metadata.js';

// -----------------------------------------------------------------------------
// Types
Expand Down Expand Up @@ -350,6 +352,126 @@ function toTaskItems(parsed: ParsedTask[]): TaskItem[] {
return tasks;
}

/**
* The command that builds one artifact.
*
* Every earlier remedy here named the `openspec-continue-change` skill, which
* the `core` profile never installs - the advice was a dead end for the default
* install. The CLI verb exists on every profile and is what the skill runs.
*/
function describeArtifactRemedy(
changeName: string,
artifactId?: string,
options: { many?: boolean } = {}
): string {
const target = artifactId ?? '<artifact>';
const verb = options.many ? 'Create each with' : 'Create it with';
return (
`${verb} \`openspec instructions ${target} --change ${changeName}\`` +
` (\`openspec status --change ${changeName}\` shows what is left).`
);
}

/**
* Finds the artifact a schema path is generated by, so a remedy can name it.
*/
function findArtifactIdFor(
schema: { artifacts: { id: string; generates: string }[] },
generates: string
): string | undefined {
return schema.artifacts.find((artifact) => artifact.generates === generates)?.id;
}

/**
* Everything still to build before apply can run, in build order.
*
* Apply blocks on the schema's `apply.requires` alone, so its own list stops at
* the first hop: a change with only a proposal is told "Missing artifacts:
* tasks" while the specs `tasks` depends on are missing too. An agent that
* takes that literally writes the tracking file straight from the proposal and
* skips the artifacts in between - the failure reported in #834 and #869.
* Walking `requires` names the whole chain, the same set and order
* `openspec status` already prints, without changing what apply blocks on.
*/
function collectMissingPrerequisites(input: {
requiredArtifactIds: string[];
schema: { artifacts: { id: string; requires: string[] }[] };
buildOrder: string[];
completed: Set<string>;
}): string[] {
const { requiredArtifactIds, schema, buildOrder, completed } = input;
const byId = new Map(schema.artifacts.map((artifact) => [artifact.id, artifact]));
const missing = new Set<string>();
const queue = [...requiredArtifactIds];
const seen = new Set<string>(queue);

while (queue.length > 0) {
const id = queue.shift() as string;
const artifact = byId.get(id);
if (!artifact) continue;
if (!completed.has(id)) missing.add(id);
for (const dependency of artifact.requires) {
if (seen.has(dependency)) continue;
seen.add(dependency);
queue.push(dependency);
}
}

const order = new Map(buildOrder.map((id, index) => [id, index]));
return [...missing].sort(
(a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0)
);
}

/**
* Warnings apply reports alongside its instruction.
*
* Apply gates on the schema's `apply.requires` only, so a change whose tasks
* file was written ahead of its specs reads as ready even though no delta spec
* exists - the state `openspec validate` rejects. Blocking here would be a
* policy change; naming the gap is not, and it is what keeps apply from being
* the one surface that green-lights a change every other surface flags.
*
* Only reported once apply is past its own gate: for a change that has not
* reached tasks yet, the missing specs are the next step rather than a warning.
* Schemas that declare no spec-producing artifact carry `skip_specs` from
* creation, so this never fires on them.
*/
function collectApplyWarnings(input: {
state: ApplyInstructions['state'];
schema: { artifacts: { id: string; generates: string }[] };
changeDir: string;
changeName: string;
skippedArtifacts?: Set<string>;
}): string[] {
const { state, schema, changeDir, changeName, skippedArtifacts } = input;
if (state === 'blocked') return [];

const specArtifacts = schema.artifacts.filter((artifact) =>
isSpecsArtifactPath(artifact.generates)
);
if (specArtifacts.length === 0) return [];
if (specArtifacts.some((artifact) => skippedArtifacts?.has(artifact.id))) return [];
const hasDeltas = specArtifacts.some(
(artifact) => resolveArtifactOutputs(changeDir, artifact.generates).length > 0
);
if (hasDeltas) return [];

const metadataPath = path.join(changeDir, METADATA_FILENAME);
// The command names the artifact this schema actually declares, never the
// literal `specs`. A schema whose spec-producing artifact is `contracts` was
// told to run `openspec instructions specs`, an artifact it does not have,
// so the warning dead-ended at the exact step meant to resolve it. With more
// than one such artifact there is no single right answer, so the id becomes
// a placeholder rather than a guess.
const specTarget = specArtifacts.length === 1 ? specArtifacts[0].id : '<artifact-id>';
return [
`This change has no delta specs and does not declare \`skip_specs: true\`, so \`openspec validate ${changeName}\` fails on it. ` +
`Write the delta specs before implementing (\`openspec instructions ${specTarget} --change ${changeName}\`), ` +
`or add \`skip_specs: true\` to ${metadataPath} if this change really changes no specified behavior.`,
];
}

export interface GenerateApplyInstructionsOptions {
planningHome?: PlanningHome;
references?: ReferenceIndexEntry[];
Expand Down Expand Up @@ -403,6 +525,14 @@ export async function generateApplyInstructions(
}
}

// Everything still to build, not just the first hop apply blocks on.
const missingPrerequisites = collectMissingPrerequisites({
requiredArtifactIds: [...requiredArtifactIds],
schema,
buildOrder: context.graph.getBuildOrder(),
completed: context.completed,
});

// Build context files from all existing artifacts in schema
const contextFiles: Record<string, string[]> = {};
for (const artifact of schema.artifacts) {
Expand Down Expand Up @@ -437,18 +567,35 @@ export async function generateApplyInstructions(

if (missingArtifacts.length > 0) {
state = 'blocked';
instruction = `Cannot apply this change yet. Missing artifacts: ${missingArtifacts.join(', ')}.\nUse the openspec-continue-change skill to create the missing artifacts first.`;
const chain =
missingPrerequisites.length > missingArtifacts.length
? `\nNot created yet, in build order: ${missingPrerequisites.join(', ')}.` +
` Build the ones this change needs before applying - the schema says which are conditional.`
: '';
instruction =
`Cannot apply this change yet. Missing artifacts: ${missingArtifacts.join(', ')}.${chain}` +
`\n${describeArtifactRemedy(
changeName,
// Only name one when one is left: the first of several would be the
// schema's conditional artifact as often as not.
missingPrerequisites.length === 1 ? missingPrerequisites[0] : undefined,
{ many: missingPrerequisites.length > 1 }
)}`;
} else if (tracksFile && !tracksFileExists) {
// Tracking file configured but doesn't exist yet
const tracksFilename = path.basename(tracksFile);
state = 'blocked';
instruction = `The ${tracksFilename} file is missing and must be created.\nUse openspec-continue-change to generate the tracking file.`;
instruction =
`The ${tracksFilename} file is missing and must be created.` +
`\n${describeArtifactRemedy(changeName, findArtifactIdFor(schema, tracksFile))}`;
} else if (tracksFile && tracksFileExists && tasks.length === 0) {
// Tracking file exists but lists nothing an agent can work on: either no
// checkboxes at all, or only checkboxes with no text after them.
const tracksFilename = path.basename(tracksFile);
state = 'blocked';
instruction = `The ${tracksFilename} file exists but contains no tasks to work on.\nAdd tasks to ${tracksFilename} or regenerate it with openspec-continue-change.`;
instruction =
`The ${tracksFilename} file exists but contains no tasks to work on.` +
`\nAdd tasks to ${tracksFilename}, or rebuild it: ${describeArtifactRemedy(changeName, findArtifactIdFor(schema, tracksFile))}`;
} else if (tracksFile && remaining === 0 && total > 0) {
state = 'all_done';
instruction = 'All tasks are complete! This change is ready to be archived.\nConsider running tests and reviewing the changes before archiving.';
Expand All @@ -461,6 +608,14 @@ export async function generateApplyInstructions(
instruction = schemaInstruction?.trim() ?? 'Read context files, work through pending tasks, mark complete as you go.\nPause if you hit blockers or need clarification.';
}

const warnings = collectApplyWarnings({
state,
schema,
changeDir,
changeName,
skippedArtifacts: context.skippedArtifacts,
});

return {
changeName,
changeDir,
Expand All @@ -470,6 +625,8 @@ export async function generateApplyInstructions(
tasks,
state,
missingArtifacts: missingArtifacts.length > 0 ? missingArtifacts : undefined,
...(missingPrerequisites.length > 0 ? { missingPrerequisites } : {}),
...(warnings.length > 0 ? { warnings } : {}),
instruction,
...(references !== undefined ? { references } : {}),
...operationInputs,
Expand Down Expand Up @@ -524,7 +681,7 @@ export async function applyInstructionsCommand(options: ApplyInstructionsOptions
}

export function printApplyInstructionsText(instructions: ApplyInstructions): void {
const { changeName, schemaName, contextFiles, progress, tasks, state, missingArtifacts, instruction } = instructions;
const { changeName, schemaName, contextFiles, progress, tasks, state, missingArtifacts, warnings, instruction } = instructions;

console.log(`## Apply: ${changeName}`);
console.log(`Schema: ${schemaName}`);
Expand All @@ -540,7 +697,23 @@ export function printApplyInstructionsText(instructions: ApplyInstructions): voi
console.log('### ⚠️ Blocked');
console.log();
console.log(`Missing artifacts: ${missingArtifacts.join(', ')}`);
console.log('Use the openspec-continue-change skill to create these first.');
if (
instructions.missingPrerequisites &&
instructions.missingPrerequisites.length > missingArtifacts.length
) {
console.log(
`Not created yet, in build order: ${instructions.missingPrerequisites.join(', ')}`
);
}
console.log();
}

if (warnings && warnings.length > 0) {
console.log('### ⚠️ Warnings');
console.log();
for (const warning of warnings) {
console.log(`- ${warning}`);
}
console.log();
}

Expand Down
8 changes: 8 additions & 0 deletions src/commands/workflow/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ export interface ApplyInstructions {
tasks: TaskItem[];
state: 'blocked' | 'all_done' | 'ready';
missingArtifacts?: string[];
/**
* Everything still to build before apply can run, in build order - the
* transitive closure of the schema's `apply.requires`, so it can be longer
* than `missingArtifacts`, which stops at the first hop apply blocks on.
*/
missingPrerequisites?: string[];
/** Non-blocking problems with the change, reported alongside the instruction. */
warnings?: string[];
instruction: string;
/** Referenced-store index (read-only upstream context; omitted when none declared) */
references?: ReferenceIndexEntry[];
Expand Down
Loading
Loading