Skip to content
Open
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
6 changes: 6 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,12 @@ an unlinked file creates a new resource. Show the report and ask the human
to choose per file. Pass
`--allow-new-files` only once they confirm every file is genuinely new. For a
rename, see [Renaming](#naming-and-renaming); delete stale files.
Scoped pushes also check dependencies they would create, including squad
member assistants and those assistants' tools and structured outputs. Each
is marked "Needed by <selected file>", including transitive dependencies.
`--allow-new-files` approves creation throughout the selected scope and its
dependencies; the dependency paths need not also be listed. Ask for approval
for the whole reported creation plan, not just the selected file.
Same-named org resources are NOT linked automatically. Preview with
`npm run push -- <org> --dry-run --allow-new-files` only after approval for
those new files, and check the **Name collisions** list (read-only dashboard
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ More detail: [How the engine works](docs/guides/how-it-works.md).
| `npm run validate -- <org>` | Check resource files offline before deploying |
| `npm run apply -- <org>` | Deploy: pull, merge, then preflight and push (the default) |
| `npm run pull -- <org>` | Sync platform changes down without overwriting local edits; unknown UUIDs get separate files, never name-linked |
| `npm run push -- <org>` | Preflight the write plan, then push without pulling first (prefer `apply`); `--strict` also blocks validation errors outside the plan. Review `--dry-run` Name collisions, and use `--adopt <id>[=<uuid>]` only with explicit approval to take over a resource; unchanged alias files are removed, edited/unbaselined copies need review. Push/apply support `--json` for one grouped link-preflight report (exit 1 on blockers); see [Running in CI](docs/guides/commands.md#running-in-ci). |
| `npm run push -- <org>` | Preflight the write plan, then push without pulling first (prefer `apply`); `--strict` also blocks validation errors outside the plan. Review `--dry-run` Name collisions, and use `--adopt <id>[=<uuid>]` only with explicit approval to take over a resource; unchanged alias files are removed, edited/unbaselined copies need review. Scoped pushes also stop for unlinked dependencies; `--allow-new-files` approves creation in the selection and its dependencies. Push/apply support `--json` for one grouped link-preflight report (exit 1 on blockers); see [Running in CI](docs/guides/commands.md#running-in-ci). |
| `npm run rollback -- <org>` | Restore a pre-deploy snapshot |
| `npm run cleanup -- <org>` | Find, and optionally delete, platform resources with no file |
| `npm run audit -- <org>` | Report drift between files, state and the platform |
Expand Down
19 changes: 19 additions & 0 deletions docs/guides/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,25 @@ block and exits **1**, before API mutations, state writes or alias deletion.
"Not linked to any resource in <org> yet" means pushing would create a new
resource; the engine cannot infer new versus renamed/stale intent.

The same check covers dependencies a scoped push would auto-create: tools,
structured outputs, and squad member assistants (including their dependencies).
They are marked "Needed by <selected file>" in text and in JSON's `problem`
field. Already-linked dependencies and repo-owned mappings that can be safely
reused do not require creation approval. `--allow-new-files` authorizes new
resources across the selected scope **and its dependencies**; you do not need
to list the dependency paths separately. For example, after reviewing the
whole plan:

```bash
npm run push -- <org> assistants/receptionist.md --allow-new-files
# Or explicitly take over the existing tool instead of creating one:
npm run push -- <org> assistants/receptionist.md --adopt my-end-call
```

Without either approval, an unlinked dependency stops the run with exit 1
before API mutations or state writes. `--dry-run` reports the same blockers
and never creates resources.

Each file has exact commands: approve `--allow-new-files` for genuinely new
resources, approve `--adopt <id>[=<uuid>]` for a takeover, or merge needed edits
and remove a renamed/stale file. A single ready-to-run combined command appears
Expand Down
14 changes: 14 additions & 0 deletions docs/guides/how-it-works.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,20 @@ block and exits **1**, before API mutations, state writes or alias deletion.
"Not linked to any resource in <org> yet" means pushing would create a new
resource; the engine cannot infer new versus renamed/stale intent.

Before a scoped push writes anything, preflight also follows its auto-apply
paths: selected assistants' tools and structured outputs, and selected squads'
member assistants plus their tools/outputs. This includes dependencies of
already-linked member assistants. Any dependency that would need a POST is
included in the same grouped report, marked "Needed by <selected file>" (also
in JSON's `problem` field). Linked dependencies and safe reuse of repo-owned
mappings behave as before. References without an auto-apply path do not expand
the creation plan.

`--allow-new-files` approves the selected scope and all its new dependencies;
dependency paths do not need to be listed separately. Alternatively, explicitly
adopt the dependency with `--adopt <id>[=<uuid>]`. Without approval, preflight
stops with exit 1 before mutations, including during `--dry-run`.

Each file has exact commands: approve `--allow-new-files` for genuinely new
resources, approve `--adopt <id>[=<uuid>]` for a takeover, or merge needed edits
and remove a renamed/stale file. A single ready-to-run combined command appears
Expand Down
17 changes: 17 additions & 0 deletions improvements.md
Original file line number Diff line number Diff line change
Expand Up @@ -2116,3 +2116,20 @@ Alias cleanup now checks canonical file content against the UUID-keyed baseline,
removes unchanged copies, and requires approval for edited/unbaselined copies.
Link preflight groups all stop reasons with per-file commands (exit 1); `--json`
emits the machine-readable report. Apply runs this read-only check before pull.

## Scoped dependency creation approval (2026-11-21)

- **Problem:** a scoped assistant push could bypass the new-file check and
POST an unlinked tool or structured output without approval.
- **Current behavior:** link preflight follows the same scope selection and
auto-apply paths, including squad → assistant → tool/output, before writes.
All unlinked dependencies that would be created join the grouped stop report
with the selected file that needs them.
- **Risk:** unexpected new remote resources and changed assistant references.
- **Current mitigation:** review the whole plan, then explicitly approve
`--allow-new-files` or adopt the intended resource. Dependency paths need not
be listed separately; the flag applies throughout the selected scope.
- **Possible fix:** implemented in `src/push-dependencies.ts` and
`src/link-preflight.ts`, with shared selection in `src/push-scope.ts`.
- **Status:** resolved; local-HTTP tests cover blocked, approved, adopted,
linked, dry-run, JSON and transitive creation plans.
63 changes: 56 additions & 7 deletions src/link-preflight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ import {
} from "./config.ts";
import { extractResourceName, type RemoteResource } from "./dep-dedup.ts";
import { detectOrphanYamls } from "./new-file-gate.ts";
import { collectUnlinkedDependencies } from "./push-dependencies.ts";
import {
filterResourcesByPaths,
shouldApplyResourceType,
} from "./push-scope.ts";
import { extractBaseSlug, slugify } from "./slug-utils.ts";
import type { TouchedSets } from "./state-merge.ts";
import { type StopIssue, shellQuote } from "./stop-report.ts";
Expand Down Expand Up @@ -113,6 +118,37 @@ export async function prepareResourceLinks(opts: {
state: preview,
filePathFilter: APPLY_FILTER.filePaths,
});
const dependencies = collectUnlinkedDependencies(
opts.resources,
{
assistants: shouldApplyResourceType("assistants")
? filterResourcesByPaths(opts.resources.assistants, "assistants")
: [],
squads: shouldApplyResourceType("squads")
? filterResourcesByPaths(opts.resources.squads, "squads")
: [],
},
preview,
);
const neededBy = new Map(
dependencies.map((dependency) => [
`${dependency.type}:${dependency.resource.resourceId}`,
[...dependency.neededBy].map((path) => relative(BASE_DIR, path)),
]),
);
for (const { type, resource } of dependencies) {
if (
!report.orphans.some(
(entry) =>
entry.type === type && entry.resourceId === resource.resourceId,
)
)
report.orphans.push({
type,
resourceId: resource.resourceId,
relativePath: relative(BASE_DIR, resource.filePath),
});
}
for (const entry of report.orphans) {
if (removed.has(`${entry.type}:${entry.resourceId}`)) continue;
const file = opts.resources[entry.type].find(
Expand All @@ -124,6 +160,15 @@ export async function prepareResourceLinks(opts: {
)
continue;
const path = relative(BASE_DIR, file.filePath);
const parents = neededBy.get(`${entry.type}:${entry.resourceId}`);
const commandPaths = parents
? APPLY_FILTER.filePaths?.length
? APPLY_FILTER.filePaths
: APPLY_FILTER.resourceTypes?.length
? APPLY_FILTER.resourceTypes
: [path]
: [path];
const scope = commandPaths.map(shellQuote).join(" ");
const name = slugify(extractResourceName(file.data) ?? entry.resourceId);
const matches = new Set(
Object.entries(opts.state[entry.type])
Expand All @@ -141,24 +186,28 @@ export async function prepareResourceLinks(opts: {
const adopt = matches.size === 1 && !lookupError;
const args = [
`--adopt ${shellQuote(entry.resourceId)}`,
shellQuote(path),
...commandPaths.map(shellQuote),
];
const commands = [...matches]
.sort()
.map(
(uuid) =>
`${base} --adopt ${shellQuote(entry.resourceId + (matches.size > 1 ? "=" + uuid : ""))} ${shellQuote(path)}`,
`${base} --adopt ${shellQuote(entry.resourceId + (matches.size > 1 ? "=" + uuid : ""))} ${scope}`,
);
const issue: StopIssue = {
file: path,
resourceType: entry.type,
problem: `Not linked to any resource in ${VAPI_ENV} yet.${matches.size ? ` Same-named resource(s): ${[...matches].join(", ")}; NOT linked automatically.` : ""}${lookupError ? ` Inventory unavailable: ${lookupError}` : ""}`,
fix: matches.size
? "To take over a same-named resource, explicitly approve adoption. If genuinely new, approve --allow-new-files instead. If renamed/stale, delete the file."
: "If new, approve --allow-new-files. If renamed/stale, delete the file (merge any needed edits first).",
problem: `Not linked to any resource in ${VAPI_ENV} yet.${parents ? ` Needed by ${parents.join(", ")}.` : ""}${matches.size ? ` Same-named resource(s): ${[...matches].join(", ")}; NOT linked automatically.` : ""}${lookupError ? ` Inventory unavailable: ${lookupError}` : ""}`,
fix:
(matches.size
? "To take over a same-named resource, explicitly approve adoption. If genuinely new, approve --allow-new-files instead. If renamed/stale, delete the file."
: "If new, approve --allow-new-files. If renamed/stale, delete the file (merge any needed edits first).") +
(parents
? " If deleting it, also remove or replace its references in the files that need it."
: ""),
command: [
...commands,
`${base} --allow-new-files ${shellQuote(path)}`,
`${base} --allow-new-files ${scope}`,
`rm -- ${shellQuote(path)}`,
].join(" OR "),
needsChoice: !adopt,
Expand Down
71 changes: 71 additions & 0 deletions src/push-dependencies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { findExistingResourceByName } from "./dep-dedup.ts";
import { extractReferencedIds } from "./resolver.ts";
import type {
LoadedResources,
ResourceFile,
ResourceType,
StateFile,
} from "./types.ts";

export interface UnlinkedDependency {
type: ResourceType;
resource: ResourceFile;
neededBy: Set<string>;
}

export function collectUnlinkedDependencies(
resources: LoadedResources,
selected: Pick<LoadedResources, "assistants" | "squads">,
state: StateFile,
): UnlinkedDependency[] {
const dependencies = new Map<string, UnlinkedDependency>();
for (const rootType of ["assistants", "squads"] as const) {
for (const root of selected[rootType]) {
const visited = new Set<string>();
const visit = (type: ResourceType, resource: ResourceFile) => {
const key = `${type}:${resource.resourceId}`;
if (visited.has(key) || resource.data._platformDefault === true) return;
visited.add(key);
const refs = extractReferencedIds(resource.data);
const childTypes: ("assistants" | "tools" | "structuredOutputs")[] =
type === "squads"
? ["assistants"]
: type === "assistants"
? ["tools", "structuredOutputs"]
: [];
for (const childType of childTypes) {
for (const id of refs[childType]) {
if (/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id))
continue;
const child = resources[childType].find(
(file) => file.resourceId === id,
);
if (!child || child.data._platformDefault === true) continue;
if (
!state[childType][id] &&
!findExistingResourceByName({
localResourceId: id,
localPayload: child.data,
stateSection: state[childType],
})
) {
let dependency = dependencies.get(`${childType}:${id}`);
if (!dependency) {
dependency = {
type: childType,
resource: child,
neededBy: new Set(),
};
dependencies.set(`${childType}:${id}`, dependency);
}
dependency.neededBy.add(root.filePath);
}
visit(childType, child);
}
}
};
visit(rootType, root);
}
}
return [...dependencies.values()];
}
42 changes: 42 additions & 0 deletions src/push-scope.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { resolve } from "path";
import { APPLY_FILTER, BASE_DIR } from "./config.ts";
import { FOLDER_MAP, pathMatchesFolder } from "./resources.ts";
import type { ResourceFile, ResourceType } from "./types.ts";

export function shouldApplyResourceType(type: ResourceType): boolean {
if (APPLY_FILTER.filePaths?.length) {
const folder = FOLDER_MAP[type];
return APPLY_FILTER.filePaths.some((fp) => pathMatchesFolder(fp, folder));
}
if (APPLY_FILTER.resourceTypes?.length) {
return APPLY_FILTER.resourceTypes.includes(type);
}
return true;
}

export function filterResourcesByPaths<T>(
resources: ResourceFile<T>[],
_type: ResourceType,
): ResourceFile<T>[] {
if (!APPLY_FILTER.filePaths?.length) return resources;

const matchingIds = new Set<string>();
for (const filePath of APPLY_FILTER.filePaths) {
const resolvedInput = resolve(BASE_DIR, filePath);
for (const resource of resources) {
if (
resource.filePath === resolvedInput ||
resource.filePath.endsWith(filePath) ||
filePath.endsWith(resource.resourceId + ".yml") ||
filePath.endsWith(resource.resourceId + ".yaml") ||
filePath.endsWith(resource.resourceId + ".md") ||
filePath.endsWith(resource.resourceId + ".ts") ||
resource.filePath === filePath ||
resource.resourceId === filePath.replace(/\.(yml|yaml|md|ts)$/, "")
) {
matchingIds.add(resource.resourceId);
}
}
}
return resources.filter((resource) => matchingIds.has(resource.resourceId));
}
47 changes: 4 additions & 43 deletions src/push.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ import { prepareResourceLinks } from "./link-preflight.ts";
import { assertStateMigrated } from "./migrate-hash-store.ts";
import { NameCollisionReport } from "./name-collisions.ts";
import { computePushPlan, pushBlockingFindings } from "./push-plan.ts";
import {
filterResourcesByPaths,
shouldApplyResourceType,
} from "./push-scope.ts";
import { reconcileStateKeyForResource } from "./reconcile-state-key.ts";
import { writeSnapshot } from "./snapshot.ts";
import { mergeScoped } from "./state-merge.ts";
Expand Down Expand Up @@ -76,11 +80,9 @@ import {
resolveReferences,
} from "./resolver.ts";
import {
FOLDER_MAP,
loadResources,
loadSingleResource,
parseResourceFilePath,
pathMatchesFolder,
} from "./resources.ts";
import { hashPayload, loadState, saveState, upsertState } from "./state.ts";
import type {
Expand Down Expand Up @@ -1182,47 +1184,6 @@ function isPartialApply(): boolean {
);
}

function shouldApplyResourceType(type: ResourceType): boolean {
if (APPLY_FILTER.filePaths?.length) {
const folder = FOLDER_MAP[type];
return APPLY_FILTER.filePaths.some((fp) => pathMatchesFolder(fp, folder));
}
if (APPLY_FILTER.resourceTypes?.length) {
return APPLY_FILTER.resourceTypes.includes(type);
}
return true;
}

function filterResourcesByPaths<T>(
resources: ResourceFile<T>[],
type: ResourceType,
): ResourceFile<T>[] {
if (!APPLY_FILTER.filePaths?.length) return resources;

const matchingIds = new Set<string>();

for (const filePath of APPLY_FILTER.filePaths) {
const resolvedInput = resolve(BASE_DIR, filePath);

for (const resource of resources) {
if (
resource.filePath === resolvedInput ||
resource.filePath.endsWith(filePath) ||
filePath.endsWith(resource.resourceId + ".yml") ||
filePath.endsWith(resource.resourceId + ".yaml") ||
filePath.endsWith(resource.resourceId + ".md") ||
filePath.endsWith(resource.resourceId + ".ts") ||
resource.filePath === filePath ||
resource.resourceId === filePath.replace(/\.(yml|yaml|md|ts)$/, "")
) {
matchingIds.add(resource.resourceId);
}
}
}

return resources.filter((r) => matchingIds.has(r.resourceId));
}

function scopeLoadedResourcesForApply(
resources: LoadedResources,
): LoadedResources {
Expand Down
Loading
Loading