diff --git a/AGENTS.md b/AGENTS.md index 1a4c96d..ccdb627 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,6 +42,7 @@ change, before running: | `npm run rollback -- --to …` | Reverts live resources | | `npm run cleanup -- --force --confirm ` | Deletes platform resources | | `npm run pull -- --force` | Overwrites local edits | +| `--adopt [=]` | Takes over an existing org resource; requires an explicit yes for that resource | | `--allow-new-files`, `--overwrite`, `--resolve=ours\|theirs` | Bypass a safety check (see rule 6) | | `npm run call`, `npm run sim`, live `npm run check` | Place calls or run simulations that cost minutes | @@ -147,7 +148,10 @@ precisely. `.vapi-org.json` to make a reference resolve: fix the name, or pull. 4. **Build PR checks offline** if `vapi-checks.yml` exists: `npm run check -- --all --dry-run`. Fix anything it reports. -5. **Deploy only with a yes** (safety rule 1): `npm run apply -- `, or +5. **Review the dry-run Name collisions list**, then **deploy only with a yes** + (safety rule 1). Same-named org resources are never taken over automatically; + `--adopt [=]` requires explicit human approval to take one over. + Deploy: `npm run apply -- `, or scoped to files: `npm run apply -- resources//assistants/my-agent.md`. 6. **Verify** with the human's agreement: `npm run call -- -a ` or `npm run sim -- --suite --target `. @@ -161,11 +165,34 @@ the dashboard, `apply` asks about that resource alone in a terminal; in CI or piped runs it's blocked unless `--resolve=ours|theirs|fail` is passed — ask the human which. -**When a deploy stops at the new-file check** ("no state-file UUID mapping"), -the engine can't tell whether each listed file is new, a rename, or stale. -Show the list to the human and ask them to classify each file. Pass +**When a deploy stops at the new-file check** ("Not linked to any resource +in yet"), the grouped report lists every blocking file with exact fix +commands. The engine cannot tell new / renamed / stale files apart; pushing +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. +Same-named org resources are NOT linked automatically. Preview with +`npm run push -- --dry-run --allow-new-files` only after approval for +those new files, and check the **Name collisions** list (read-only dashboard +GETs). To take over an existing resource instead, get an explicit yes for +`--adopt [=]`; use the UUID form when candidates are ambiguous. +Never auto-pass adoption or new-file approval to make a deploy succeed. +Adoption removes unchanged alias files automatically using the last-synced +baseline. Edited aliases or missing baselines require per-file y/N approval; +headless runs stop before changing files/state or the platform. Merge edits +into the adopted file or remove the alias manually, then rerun. + +**Running in CI:** link/adoption preflight stops with exit code **1**, before +file deletion, state writes or API mutations. It groups unlinked files, invalid +adoptions and unsafe alias deletions once. `--json` prints one array of +`{file, resourceType, problem, fix, command}` to stdout (other logs go to stderr); +`[]` means this preflight found no blockers, not that deployment cannot fail. +A combined command is suggested only when every file has an unambiguous +suggestion; otherwise the report names files needing human choice. No flags +are needed to remove a verified unchanged leftover of an already-adopted +resource. The engine never auto-adopts, auto-allows new files or deletes edited +files without approval. If something goes wrong: `npm run rollback -- --list`, then (with a yes) `--to `. Details for every workflow: diff --git a/README.md b/README.md index 9984b3d..e7a7d6f 100644 --- a/README.md +++ b/README.md @@ -208,8 +208,8 @@ More detail: [How the engine works](docs/guides/how-it-works.md). | `npm run setup` | Connect an org: create `.env.` and `resources//` | | `npm run validate -- ` | Check resource files offline before deploying | | `npm run apply -- ` | Deploy: pull, merge, then push (the default) | -| `npm run pull -- ` | Sync platform changes down without overwriting local edits | -| `npm run push -- ` | Push without pulling first (prefer `apply`) | +| `npm run pull -- ` | Sync platform changes down without overwriting local edits; unknown UUIDs get separate files, never name-linked | +| `npm run push -- ` | Push without pulling first (prefer `apply`); review `--dry-run` Name collisions, and use `--adopt [=]` 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 rollback -- ` | Restore a pre-deploy snapshot | | `npm run cleanup -- ` | Find, and optionally delete, platform resources with no file | | `npm run audit -- ` | Report drift between files, state and the platform | diff --git a/docs/guides/commands.md b/docs/guides/commands.md index 299b12f..fc64295 100644 --- a/docs/guides/commands.md +++ b/docs/guides/commands.md @@ -11,9 +11,9 @@ The other commands are direct only. | --- | --- | --- | | `npm run setup` | `npm run setup [-- ]` | Connect an org: creates `.env.` and `resources//`. | | `npm run validate` | `npm run validate -- ` | Check resource files offline: API shape rules, and that every reference names a file or a state entry. `apply` runs it first. On GitHub Actions, findings are also shown on the files in the pull request. | -| `npm run apply` | `npm run apply -- [types or paths]` | **The default deploy:** pull, merge, then push. See [workflows](workflows.md). | +| `npm run apply` | `npm run apply -- [types or paths] [--adopt [=]]` | **The default deploy:** pull, merge, then push. See [workflows](workflows.md). | | `npm run pull` | `npm run pull -- [--force] [--bootstrap]` | Sync platform changes down; never overwrites local edits unless `--force`. | -| `npm run push` | `npm run push -- [--dry-run] [--strict]` | Push without pulling first. Prefer `apply`. `--strict` aborts before any API call if validation finds an error. | +| `npm run push` | `npm run push -- [--dry-run] [--json] [--strict] [--adopt [=]]` | Push without pulling first. Prefer `apply`. `--strict` aborts before any API call if validation finds an error. | | `npm run rollback` | `npm run rollback -- --list` or `--to ` | Restore a pre-deploy snapshot from `.vapi-state..snapshots/`. | | `npm run cleanup` | `npm run cleanup -- [--force --confirm ]` | List platform resources with no file; delete them only with both flags. | | `npm run audit` | `npm run audit -- [--type ]` | Report drift between files, state and the platform. Exits 1 on any finding, so it can run in CI. | @@ -24,6 +24,77 @@ The other commands are direct only. | `npm run build` | `npm run build` | Type-check the code and tests. | | `npm test` | `npm test` | Run the test suite. | +Pull and push never automatically rename UUID-suffixed state keys to match +local files. A local file without a UUID mapping remains subject to the +new-file gate even if the org has a same-name resource. The gate reports +same-name candidates without linking them. Existing mappings, including +legacy entries without provenance, remain linked. New pull mappings record +`origin: pulled`; push-created resources record `origin: pushed`. + +Dry-run push/apply ends with **Name collisions**, listing same-name state and +live dashboard resources for every planned POST, including dependency creates. +Read-only GETs run in dry-run. No matches prints `Name collisions: none`; +unavailable inventories are reported as an incomplete check, not a clean result. +Check this list before deploying; taking over a resource requires explicit +human approval for `--adopt`, just as `--allow-new-files` requires approval. + +### Running in CI + +Push/apply link preflight reports all blocking files in one **Push stopped** +block and exits **1**, before API mutations, state writes or alias deletion. +"Not linked to any resource in yet" means pushing would create a new +resource; the engine cannot infer new versus renamed/stale intent. + +Each file has exact commands: approve `--allow-new-files` for genuinely new +resources, approve `--adopt [=]` for a takeover, or merge needed edits +and remove a renamed/stale file. A single ready-to-run combined command appears +only when every file has an unambiguous suggestion; otherwise the report lists +which files need human choice. Suggestions are not authorization to execute. + +`--json` on push or apply prints one stdout array of +`{file, resourceType, problem, fix, command}`; ordinary logs go to stderr. +The exit code stays 1 for blockers. `[]` means no link-preflight blockers, +not a guarantee that later network/validation/deployment steps will succeed. +Use `--dry-run --json` for a read-only preview. When invoking through npm, +use `npm run -s push -- --dry-run --json` to suppress npm's own +command banner on stdout. + +Safe, unchanged leftover alias files are removed automatically, including +UUID-suffixed leftovers of an already-adopted mapping on a later plain push. +Edited/unbaselined files need per-file y/N approval in a terminal and stop CI. +The engine never auto-adopts, auto-passes the new-file flag or silently deletes +edited files. + +### Explicit resource adoption + +`--adopt ` opts a local file into taking over an existing org +resource. It is repeatable; `--adopt=` also works. The file must +exist and have no state mapping. Candidates are same-base-slug state entries +and live resources of that type matching the file's name (or ID when unnamed). +One distinct candidate is required. If several exist, use +`--adopt =`; that UUID must exist remotely for the file's type. +Missing files, already-linked files, and zero/ambiguous candidates are errors. + +Adoption records `origin: adopted`, removes other state keys for that UUID, and +uses the normal PATCH path. Scoped saves include both sides of the re-key. +`--dry-run --adopt ` performs live GET lookups and prints +`would adopt → `, but does not write state or mutate the platform. +`apply` forwards adoption to its push stage; its preceding pull remains a +normal pull except in `--dry-run`, which skips pull to avoid local writes. +Adoption deletes leftover alias files only when they match the last-synced +baseline. Edited files or missing baselines need per-file y/N approval in a +terminal; headless runs stop before changing files, state or the platform. +Merge those edits into the adopted file or delete the alias manually and rerun. +Dry-run reports would-delete/would-fail without deleting. Baselines are keyed +by remote UUID, not alias; adoption drops the shared old baseline and the normal +PATCH records a fresh one for the adopted resource. + +Dependencies are automatically reused by name only when an existing state +entry records `origin: pushed` or `origin: adopted`. Pulled and legacy entries, +and dashboard-only name matches, are not authorization: a missing dependency +is POST-created with a warning naming the existing resources. Use explicit +adoption before dependency resolution to take one over instead. + ## Interactive Mode When you run a command without arguments, you get a fully interactive experience: diff --git a/docs/guides/how-it-works.md b/docs/guides/how-it-works.md index 5e1c969..83ebce1 100644 --- a/docs/guides/how-it-works.md +++ b/docs/guides/how-it-works.md @@ -5,7 +5,7 @@ Resources are scoped by organization, with names you choose (not fixed `dev`/`stg`/`prod`). Each org gets: - `.env.` — private API key and base URL -- `.vapi-state..json` — resource name ↔ UUID mappings (nothing else — committed) +- `.vapi-state..json` — resource ID ↔ UUID mappings and optional origin (committed) - `.vapi-state-hash//` — last-seen platform content hash per resource, used for drift detection (per-developer, gitignored) - `resources//` — all resource files @@ -42,7 +42,52 @@ files **`push`** — reads local files and syncs them to the platform: creates and updates. It deletes platform resources whose files you removed only when you pass `--force`. -**`apply`** — runs `pull` then `push` in sequence. +**`apply`** — runs `pull` then `push` in sequence. With `--dry-run`, it skips +pull (which writes local files/state) and previews push with read-only GETs. + +### Running in CI + +Push/apply link preflight reports all blocking files in one **Push stopped** +block and exits **1**, before API mutations, state writes or alias deletion. +"Not linked to any resource in yet" means pushing would create a new +resource; the engine cannot infer new versus renamed/stale intent. + +Each file has exact commands: approve `--allow-new-files` for genuinely new +resources, approve `--adopt [=]` for a takeover, or merge needed edits +and remove a renamed/stale file. A single ready-to-run combined command appears +only when every file has an unambiguous suggestion; otherwise the report lists +which files need human choice. Suggestions are not authorization to execute. + +`--json` on push or apply prints one stdout array of +`{file, resourceType, problem, fix, command}`; ordinary logs go to stderr. +The exit code stays 1 for blockers. `[]` means no link-preflight blockers, +not a guarantee that later network/validation/deployment steps will succeed. +Use `--dry-run --json` for a read-only preview. With npm, use +`npm run -s push -- --dry-run --json` to suppress npm's banner. + +Safe, unchanged leftover alias files are removed automatically, including +UUID-suffixed leftovers of an already-adopted mapping on a later plain push. +Edited/unbaselined files need per-file y/N approval in a terminal and stop CI. +The engine never auto-adopts, auto-passes the new-file flag or silently deletes +edited files. + +### Names never authorize taking over org resources + +Pull keeps existing UUID mappings and filenames stable. An unknown UUID always +gets a separate `-` ID, even if a same-named local file exists. +Neither pull nor push automatically collapses that key onto a local filename. + +A file without a state mapping remains subject to the new-file gate. After +confirming it is genuinely new, preview `--dry-run --allow-new-files` and review +the final **Name collisions** list. It compares every planned POST, including +auto-created dependencies, with state and live dashboard names. Matching names +do not change the plan into a takeover. GETs run; platform mutations do not. + +To take over a resource intentionally, obtain explicit human approval and use +`--adopt [=]`. Adoption links an untracked local file before the gate +and normal PATCH flow. Dependency alias reuse is restricted to state entries +with `origin: pushed` or `origin: adopted`; pulled and legacy entries do not +authorize new name-based links. Existing exact-key legacy links remain intact. ## Conflicts and the drift gate @@ -53,7 +98,7 @@ Before updating a resource, push GETs its current dashboard payload, hashes it, - **Hashes match** → your local edit is the natural next step in the change chain → pushed silently, and the baseline is refreshed from the PATCH **response** (what the platform actually stored). - **Hashes differ** → someone else published changes since your last sync. In a terminal, push asks **for that resource only**: ① push my local version (take ownership) ② keep the dashboard version (skip, local untouched) ③ save the dashboard version as `..bkp.` beside your file and skip, for a manual merge. In CI / piped runs the resource is blocked instead (use `--overwrite` to push unconditionally). -Backup copies (`*.bkp.*`, gitignored) are merge reference material only — invisible to the loader, the orphan gate, audit, the interactive picker, and explicit CLI paths. +Backup copies (`*.bkp.*`, gitignored) are merge reference material only — invisible to the loader, the new-file check, audit, the interactive picker, and explicit CLI paths. ## Reading pull and push output @@ -77,7 +122,7 @@ Mental model: `⬆️` flows UP (push), `⬇️` flows DOWN (pull), `📝` is th ## Listing completeness -Vapi list endpoints cap a response at 100 items and expose no page cursor — only `createdAt` comparison filters. The engine pages backwards through `createdAt` until it gets a short page, so pull, push's invalid-mapping detection, `delete`'s orphan sweep, `audit`, and the credential reverse-map all see the whole type instead of the first hundred. When completeness cannot be proven — an endpoint that ignores the cursor params, a payload with no `createdAt`, or the page-count backstop — the engine says so on stderr. Treat that warning as "do not infer deletion from absence for this type". +Vapi list endpoints cap a response at 100 items and expose no page cursor — only `createdAt` comparison filters. The engine pages backwards through `createdAt` until it gets a short page, so pull, push's invalid-mapping detection, `delete`'s missing-file sweep, `audit`, and the credential reverse-map all see the whole type instead of the first hundred. When completeness cannot be proven — an endpoint that ignores the cursor params, a payload with no `createdAt`, or the page-count backstop — the engine says so on stderr. Treat that warning as "do not infer deletion from absence for this type". ## Processing Order @@ -144,6 +189,8 @@ Tracks resource ID ↔ Vapi UUID mappings per org: ``` Every resource type has a section. Keys are sorted, so diffs stay readable. +New entries record `origin: pushed`, `pulled`, or `adopted`. Updates preserve +that provenance, and legacy entries without an origin are not backfilled. ## What Vapi sees diff --git a/docs/guides/workflows.md b/docs/guides/workflows.md index 6e56d2e..78ccecc 100644 --- a/docs/guides/workflows.md +++ b/docs/guides/workflows.md @@ -109,6 +109,33 @@ When the files are genuinely new resources: npm run apply -- --allow-new-files ``` +Before deploying, review the collision preview (the flag still needs approval +for every genuinely new file): + +```bash +npm run push -- --dry-run --allow-new-files +``` + +The final **Name collisions** section includes same-name state and dashboard +resources for every planned create, including dependencies. Names alone never +take over an org resource. The plan POSTs a new one unless you explicitly adopt: + +```bash +npm run apply -- --adopt my-agent assistants/my-agent.md +# If multiple candidates exist: +npm run apply -- --adopt my-agent= assistants/my-agent.md +``` + +Adoption needs the human's explicit yes for that resource, just like new-file +approval. It requires a local file with no state mapping. Pull never links +unknown remote UUIDs to local files by name, and dependency aliases are reused +only when state records pushed/adopted ownership. Adoption removes unchanged alias files automatically. Edited aliases or +missing baselines require per-file approval in a terminal; headless runs stop +so you can merge their edits into the adopted file or remove them manually. + +Both `push --dry-run` and `apply --dry-run` perform read-only dashboard GETs +for the collision preview; apply skips its pull stage to avoid local writes. + Check each listed file before you pass the flag: it confirms every one is new. If a coding agent runs your deploys, it should show you the list rather than pass the flag itself; [`AGENTS.md`](../../AGENTS.md) instructs it to. @@ -202,7 +229,7 @@ npm run cleanup -- --force --confirm ``` Cleanup treats every platform resource that isn't in -`.vapi-state..json` as an orphan, except those matched by +`.vapi-state..json` as unmanaged, except those matched by `resources//.vapi-ignore`: it lists those as retained and never deletes them. Still read the dry-run list before a destructive run. @@ -213,7 +240,7 @@ through the API, then refresh state: ```bash curl -X DELETE -H "Authorization: Bearer $VAPI_PRIVATE_API_KEY" \ - https://api.vapi.ai/assistant/ + https://api.vapi.ai/assistant/ npm run pull -- --bootstrap ``` diff --git a/docs/learnings/sync-behavior.md b/docs/learnings/sync-behavior.md index b7532ad..60501a2 100644 --- a/docs/learnings/sync-behavior.md +++ b/docs/learnings/sync-behavior.md @@ -143,7 +143,7 @@ stale pointer. Never blocks, never prompts. | Command | Behavior | |---|---| | `validate` | schema-checked like any resource | -| `push` | **orphan-YAML gate**: refuses with exit 1, listing the file and possible rename-source candidates. Intentional — the engine can't tell "new resource" from "renamed file" from "stale cruft". After confirming it's genuinely new: `push --allow-new-files` → POST create → state entry + baseline (from response). If a dashboard resource with the **same name** already exists, the engine adopts its UUID instead of creating a duplicate (dep-dedup). | +| `push` | **orphan-YAML gate**: refuses with exit 1, listing the file and possible rename-source candidates. Intentional — the engine can't tell "new resource" from "renamed file" from "stale cruft". After confirming it's genuinely new: `push --allow-new-files` → POST create → state entry + baseline (from response). Same-name resources are never taken over automatically: review dry-run Name collisions, then use `--adopt [=]` only with explicit approval to take one over. Dependency alias reuse requires pushed/adopted provenance. | | `pull` | untouched — pull only visits resources the dashboard has | | `apply` | pull stage no-op for it; push stage hits the gate (pass `--allow-new-files` through apply) | @@ -282,7 +282,7 @@ push: the content is already live. | `--force` | push/apply/cleanup | enable deletions of dashboard orphans | | `--allow-new-files` | push/apply | bypass the orphan-YAML gate (confirm each orphan is genuinely new first) | | `--bootstrap` | pull | refresh state + baselines without writing resource files | -| `--dry-run` | push | print would-be calls; no API calls, no baseline writes, no prompts | +| `--dry-run` | push, apply | print would-be calls and Name collisions; read-only GETs, no baseline/state writes or prompts; apply skips pull | ## Interactivity rule diff --git a/improvements.md b/improvements.md index ef4ca0e..51eac4e 100644 --- a/improvements.md +++ b/improvements.md @@ -2076,3 +2076,24 @@ dependency check, as `check-payload.ts` already does. `AGENTS.md`. Don't conflate that with drift detection. - **Renaming `npm run eval` to disambiguate from `npm run sim`.** Backwards-incompatible script change; raise as a separate issue. + +## Implicit name-based takeover during pull/bootstrap recovery + +**Problem:** A matching name is not authorization to overwrite an org resource. +**Current behavior:** Pull generates UUID-suffixed IDs for unknown remote UUIDs; +pull and push no longer collapse these mappings onto local name matches. +The new-file gate reports same-name candidates without linking them. +**Risk:** Names are not globally unique; adoption needs an explicit UUID when ambiguous. +**Current mitigation:** Stop at the new-file gate, review each orphan and the +dry-run Name collisions list (state plus read-only dashboard GETs). Apply dry-run +skips pull to preserve local files/state while previewing the push. +**Possible fix:** Require explicit adoption for all name-based takeover paths. +**Status:** Pull/recanonicalization paths fixed. Dependency reuse now requires +pushed/adopted provenance; `--adopt [=]` explicitly claims remote UUIDs. +Dry-run reports planned POST collisions, including dependencies; failed inventory +lookups are reported as incomplete checks instead of falsely reporting none. + +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. diff --git a/src/adopt-alias-files.ts b/src/adopt-alias-files.ts new file mode 100644 index 0000000..e3b0a18 --- /dev/null +++ b/src/adopt-alias-files.ts @@ -0,0 +1,65 @@ +import { confirm } from "@inquirer/prompts"; +import { rm } from "fs/promises"; +import { relative } from "path"; +import type { AdoptionAlias } from "./adopt.ts"; +import { BASE_DIR, DRY_RUN, VAPI_ENV } from "./config.ts"; +import { deleteBaseline, readBaseline } from "./hash-store.ts"; +import { parseResourceDataFromFile } from "./resource-parse.ts"; +import { hashPayload } from "./state-serialize.ts"; +import type { LoadedResources } from "./types.ts"; + +export async function prepareAliasCleanup( + aliases: AdoptionAlias[], + resources: LoadedResources, +) { + const files = aliases.flatMap((alias) => + resources[alias.type] + .filter((file) => file.resourceId === alias.resourceId) + .map((file) => ({ ...alias, file })), + ); + const problems: { + file: string; + type: AdoptionAlias["type"]; + message: string; + }[] = []; + for (const { file, uuid, adoptedAs, type } of files) { + const path = relative(BASE_DIR, file.filePath); + let hash: string | undefined; + try { + hash = hashPayload(parseResourceDataFromFile(file.filePath)); + } catch {} + const baseline = readBaseline(VAPI_ENV, uuid); + if (!baseline || hash !== baseline) { + const message = `${path}: local edits or no baseline. Delete it by hand (or merge its edits into ${adoptedAs}) and rerun.`; + if ( + DRY_RUN || + process.argv.includes("--json") || + !process.stdin.isTTY || + !(await confirm({ + message: `Delete ${path}? Local edits may be lost.`, + default: false, + })) + ) { + problems.push({ file: path, type, message }); + } + } + } + return { + problems, + async run() { + for (const { file, adoptedAs, type } of files) { + const path = relative(BASE_DIR, file.filePath); + if (DRY_RUN) console.log(`would delete ${path}`); + else { + await rm(file.filePath); + console.log( + `Deleted ${path}: same remote resource, now adopted as ${adoptedAs}`, + ); + } + resources[type].splice(resources[type].indexOf(file), 1); + } + if (!DRY_RUN) + for (const { uuid } of aliases) await deleteBaseline(VAPI_ENV, uuid); + }, + }; +} diff --git a/src/adopt-apply-preflight.ts b/src/adopt-apply-preflight.ts new file mode 100644 index 0000000..5e7a539 --- /dev/null +++ b/src/adopt-apply-preflight.ts @@ -0,0 +1,48 @@ +import { VAPI_ENV } from "./config.ts"; +import type { RemoteResource } from "./dep-dedup.ts"; +import { prepareResourceLinks } from "./link-preflight.ts"; +import { fetchAllResources } from "./pull.ts"; +import { loadResources } from "./resources.ts"; +import { loadState } from "./state.ts"; +import type { TouchedSets } from "./state-merge.ts"; +import { formatStopReport, jsonStopReport } from "./stop-report.ts"; +import { type LoadedResources, VALID_RESOURCE_TYPES } from "./types.ts"; + +export async function preflightApplyLinks( + output: (value: string) => void, +): Promise { + const state = loadState(); + const resources = Object.fromEntries( + await Promise.all( + VALID_RESOURCE_TYPES.map(async (type) => [ + type, + await loadResources(type, { quiet: true }), + ]), + ), + ) as unknown as LoadedResources; + const touched = Object.fromEntries( + ["credentials", ...VALID_RESOURCE_TYPES].map((type) => [ + type, + new Set(), + ]), + ) as unknown as TouchedSets; + const inventories = new Map>(); + const links = await prepareResourceLinks({ + state, + resources, + touched, + getRemoteList: (type) => { + let inventory = inventories.get(type); + if (!inventory) { + inventory = fetchAllResources(type) as Promise; + inventories.set(type, inventory); + } + return inventory; + }, + }); + if (links.issues.length) { + if (process.argv.includes("--json")) output(jsonStopReport(links.issues)); + else console.error(formatStopReport(links.issues, VAPI_ENV)); + process.exit(1); + } +} diff --git a/src/adopt.ts b/src/adopt.ts new file mode 100644 index 0000000..d201edf --- /dev/null +++ b/src/adopt.ts @@ -0,0 +1,136 @@ +import { extractResourceName, type RemoteResource } from "./dep-dedup.ts"; +import { extractBaseSlug, slugify } from "./slug-utils.ts"; +import type { TouchedSets } from "./state-merge.ts"; +import type { LoadedResources, ResourceType, StateFile } from "./types.ts"; +import { VALID_RESOURCE_TYPES } from "./types.ts"; + +export interface AdoptionAlias { + type: ResourceType; + resourceId: string; + uuid: string; + adoptedAs: string; +} + +export function parseAdoptArgs(args: string[]): string[] { + const targets: string[] = []; + for (let i = 0; i < args.length; i++) { + const arg = args[i]!; + if (arg !== "--adopt" && !arg.startsWith("--adopt=")) continue; + const target = arg === "--adopt" ? args[++i] : arg.slice("--adopt=".length); + if ( + !target || + target.startsWith("--") || + !/^[^=\s]+(?:=[^=\s]+)?$/.test(target) + ) { + throw new Error("--adopt requires or ="); + } + targets.push(target); + } + return targets; +} + +export async function adoptResources(opts: { + targets: string[]; + resources: LoadedResources; + state: StateFile; + touched: TouchedSets; + getRemoteList: (type: ResourceType) => Promise; + dryRun: boolean; + errors?: { target: string; message: string }[]; + quiet?: boolean; + cleanupAliases?: (aliases: AdoptionAlias[]) => Promise; +}): Promise { + const state = opts.dryRun ? structuredClone(opts.state) : opts.state; + const plans: { type: ResourceType; resourceId: string; uuid: string }[] = []; + const inventories = new Map(); + for (const target of opts.targets) { + try { + const [resourceId, requestedUuid] = target.split("=") as [ + string, + string?, + ]; + const files = VALID_RESOURCE_TYPES.flatMap((type) => + opts.resources[type] + .filter((r) => r.resourceId === resourceId) + .map((resource) => ({ type, resource })), + ); + if (!files.length) throw new Error(`--adopt ${resourceId}: no such file`); + if (files.length !== 1) + throw new Error( + `--adopt ${resourceId}: file ID exists in multiple resource types`, + ); + const { type, resource } = files[0]!; + if (state[type][resourceId]) + throw new Error(`--adopt ${resourceId}: already linked`); + let remote = inventories.get(type); + if (!remote) { + remote = await opts.getRemoteList(type); + inventories.set(type, remote); + } + const candidates = new Set(); + for (const [key, entry] of Object.entries(state[type])) { + if (extractBaseSlug(key) === resourceId) candidates.add(entry.uuid); + } + const name = slugify(extractResourceName(resource.data) ?? resourceId); + for (const entry of remote) { + if (slugify(extractResourceName(entry) ?? "") === name) + candidates.add(entry.id); + } + let uuid = requestedUuid; + if (uuid) { + if (!remote.some((entry) => entry.id === uuid)) { + throw new Error( + `--adopt ${resourceId}=${uuid}: UUID does not exist remotely for ${type}`, + ); + } + } else { + if (!candidates.size) + throw new Error(`--adopt ${resourceId}: no candidates`); + if (candidates.size !== 1) { + throw new Error( + `--adopt ${resourceId}: ambiguous candidates: ${[...candidates].sort().join(", ")}. Use --adopt ${resourceId}=`, + ); + } + uuid = [...candidates][0]!; + } + if ( + plans.some( + (p) => + p.type === type && (p.resourceId === resourceId || p.uuid === uuid), + ) + ) { + throw new Error( + `--adopt ${resourceId}: duplicate adoption target or UUID`, + ); + } + plans.push({ type, resourceId, uuid }); + } catch (error) { + if (!opts.errors) throw error; + opts.errors.push({ + target, + message: error instanceof Error ? error.message : String(error), + }); + } + } + const aliases = plans.flatMap(({ type, resourceId, uuid }) => + Object.entries(state[type]) + .filter(([key, entry]) => key !== resourceId && entry.uuid === uuid) + .map(([key]) => ({ type, resourceId: key, uuid, adoptedAs: resourceId })), + ); + await opts.cleanupAliases?.(aliases); + for (const { type, resourceId, uuid } of plans) { + if (!opts.quiet) + console.log( + ` ${opts.dryRun ? "would adopt" : "Adopting"} ${resourceId} → ${uuid}`, + ); + state[type][resourceId] = { uuid, origin: "adopted" }; + if (!opts.dryRun) opts.touched[type].add(resourceId); + for (const [key, entry] of Object.entries(state[type])) { + if (key !== resourceId && entry.uuid === uuid) { + delete state[type][key]; + if (!opts.dryRun) opts.touched[type].add(key); + } + } + } + return state; +} diff --git a/src/apply.ts b/src/apply.ts index 5650408..b50057f 100644 --- a/src/apply.ts +++ b/src/apply.ts @@ -1,6 +1,7 @@ import { execSync } from "child_process"; import { dirname, join, resolve } from "path"; import { fileURLToPath } from "url"; +import { parseAdoptArgs } from "./adopt.ts"; import { assertStateMigrated } from "./migrate-hash-store.ts"; // Pins this command's User-Agent label for the pull and push it spawns. import "./user-agent.ts"; @@ -18,9 +19,12 @@ const BASE_DIR = join(__dirname, ".."); const SLUG_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/; -function runPassthrough(cmd: string): number { +function runPassthrough(cmd: string, quiet = false): number { try { - execSync(cmd, { cwd: BASE_DIR, stdio: "inherit" }); + execSync(cmd, { + cwd: BASE_DIR, + stdio: quiet ? ["inherit", 2, 2] : "inherit", + }); return 0; } catch (error: unknown) { return (error as { status?: number }).status ?? 1; @@ -28,9 +32,14 @@ function runPassthrough(cmd: string): number { } export async function runApply(): Promise { + const output = console.log.bind(console); + const json = process.argv.includes("--json"); + if (json) console.log = console.error.bind(console); const env = process.argv[2]; const allArgs = process.argv.slice(3); + parseAdoptArgs(allArgs); const hasForce = allArgs.includes("--force"); + const dryRun = allArgs.includes("--dry-run"); // Fail fast with one clear message if this org's state file is still legacy, // rather than letting the spawned pull/push subprocess surface it later. @@ -67,7 +76,9 @@ export async function runApply(): Promise { const pushArgs = pushArgsList.join(" "); if (!env || !SLUG_RE.test(env)) { - console.error("Usage: npm run apply [--force] [--allow-new-files] [--resolve=defer|ours|theirs|fail] []"); + console.error( + "Usage: npm run apply [--force] [--allow-new-files] [--resolve=defer|ours|theirs|fail] []", + ); console.error(""); console.error(" Pull → Merge → Push (safe bidirectional sync)"); console.error(""); @@ -81,7 +92,7 @@ export async function runApply(): Promise { " will also be deleted from the platform.", ); console.error( - " --allow-new-files Bypass the orphan-YAML pre-flight gate (push stage).", + " --allow-new-files Approve creating resources for unlinked files (push stage).", ); console.error( " Use only after confirming every local file without a", @@ -89,6 +100,12 @@ export async function runApply(): Promise { console.error( " state entry is genuinely new — see src/new-file-gate.ts.", ); + console.error( + " --adopt [=] Explicitly take over a remote resource (repeatable).", + ); + console.error( + " --json Print the link-preflight report as a JSON array on stdout.", + ); console.error( " --resolve=defer On 3-way drift, ask per resource at push time (default).", ); @@ -121,7 +138,7 @@ export async function runApply(): Promise { // this is the same check as `npm run validate`, just built in. It stays // available standalone for CI / pre-flight use. const validateCmd = `npx tsx src/validate-cmd.ts ${env}`; - const validateExit = runPassthrough(validateCmd); + const validateExit = runPassthrough(validateCmd, json); if (validateExit !== 0) { console.error( "\n❌ Validation failed — fix the schema errors above before applying.", @@ -130,7 +147,13 @@ export async function runApply(): Promise { } const pullCmd = `npx tsx src/pull.ts ${env} ${pullArgs}`.trim(); - const pullExit = runPassthrough(pullCmd); + const { preflightApplyLinks } = await import("./adopt-apply-preflight.ts"); + await preflightApplyLinks(output); + if (dryRun) + console.log( + "\n🧪 Dry-run: skipping pull to preserve local files and state.", + ); + const pullExit = dryRun ? 0 : runPassthrough(pullCmd, json); if (pullExit !== 0) { console.error("\n❌ Pull had issues. Resolve conflicts before pushing."); process.exit(1); @@ -140,10 +163,11 @@ export async function runApply(): Promise { const pushCmd = `npx tsx src/push.ts ${env} ${pushArgs}`.trim(); const pushExit = runPassthrough(pushCmd); if (pushExit !== 0) { - console.error("\n❌ Push failed!"); process.exit(1); } + if (dryRun) return; + console.log( "\n═══════════════════════════════════════════════════════════════", ); diff --git a/src/config.ts b/src/config.ts index 7ee5460..047960f 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,13 +1,14 @@ -import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { existsSync, readFileSync } from "fs"; import { basename, dirname, join, relative, resolve } from "path"; import { fileURLToPath } from "url"; -import type { Environment, ResourceType } from "./types.ts"; +import { parseAdoptArgs } from "./adopt.ts"; +import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts"; import { ignorePatternsRead, matchesIgnore as matchesIgnorePatterns, } from "./resource-parse.ts"; import { resolveResourceTypes, VALID_TYPE_ARGS } from "./resource-type-args.ts"; +import type { Environment, ResourceType } from "./types.ts"; // ───────────────────────────────────────────────────────────────────────────── // CLI Argument Parsing @@ -52,7 +53,6 @@ function parseEnvironment(): Environment { return envArg; } - function parseFlags(): { forceDelete: boolean; bootstrapSync: boolean; @@ -93,11 +93,18 @@ function parseFlags(): { arg === "--bootstrap" || arg === "--dry-run" || arg === "--strict" || + arg === "--json" || arg === "--overwrite" || arg === "--allow-new-files" ) continue; + if (arg === "--adopt") { + i++; + continue; + } + if (arg.startsWith("--adopt=")) continue; + // --confirm : consumed by cleanup.ts directly. Eat the value here so // parseFlags' strict-arg check below doesn't trip on the slug. if (arg === "--confirm" && args[i + 1]) { @@ -215,7 +222,9 @@ function loadEnvFile(env: string, baseDir: string): Record { process.env[key] = value; } } - console.log(`📁 Loaded env file: ${basename(envFile)}`); + (process.argv.includes("--json") ? console.error : console.log)( + `📁 Loaded env file: ${basename(envFile)}`, + ); } } return fileVars; @@ -231,6 +240,7 @@ export const BASE_DIR = join(__dirname, ".."); // Parse environment, flags, and load env files export const VAPI_ENV = parseEnvironment(); +export const ADOPT_TARGETS = parseAdoptArgs(process.argv.slice(3)); export const { forceDelete: FORCE_DELETE, bootstrapSync: BOOTSTRAP_SYNC, @@ -262,7 +272,9 @@ if (!VAPI_TOKEN) { } if (API_KEY?.warning) console.warn(`⚠️ ${API_KEY.warning}`); else if (API_KEY && API_KEY.source !== `.env.${VAPI_ENV}`) - console.log(`🔑 Using the API key from ${API_KEY.source}`); + (process.argv.includes("--json") ? console.error : console.log)( + `🔑 Using the API key from ${API_KEY.source}`, + ); // Some call sites read the variables directly; keep them on the key chosen // above, so code reading the generic name can't see another org's key. process.env.VAPI_PRIVATE_API_KEY = VAPI_TOKEN; diff --git a/src/delete.ts b/src/delete.ts index 702cfa3..a5c9da7 100644 --- a/src/delete.ts +++ b/src/delete.ts @@ -238,7 +238,7 @@ export async function deleteOrphanedResources( const loadedIds = loadedResources[type].map((r) => r.resourceId); if (!loadedIds.includes(id)) { retainedLogLines.push( - ` 🚫 ${type}/${id} retained (matched .vapi-ignore — orphan-protected)`, + ` 🚫 ${type}/${id} retained (matched .vapi-ignore — protected from deletion)`, ); } } @@ -373,7 +373,7 @@ export async function deleteOrphanedResources( // No orphaned resources - nothing to do if (allOrphaned.length === 0) { - console.log(" ✅ No orphaned resources found\n"); + console.log(" ✅ No tracked resources are missing local files\n"); return; } @@ -447,7 +447,9 @@ export async function deleteOrphanedResources( } // Force mode: actually delete (already in reverse dependency order) - console.log(" ⚠️ DELETING ORPHANED RESOURCES (--force enabled):\n"); + console.log( + " ⚠️ DELETING RESOURCES WITHOUT LOCAL FILES (--force enabled):\n", + ); let deleted = 0; for (const { resourceId, uuid, type, stateKey } of safeToDelete) { @@ -470,7 +472,7 @@ export async function deleteOrphanedResources( } } - console.log(`\n ✅ Deleted ${deleted} orphaned resource(s)`); + console.log(`\n ✅ Deleted ${deleted} resource(s) without local files`); if (blocked.length > 0) { console.log(` ⛔ Skipped ${blocked.length} resource(s) still referenced`); } diff --git a/src/dep-dedup.ts b/src/dep-dedup.ts index 556044d..e516bec 100644 --- a/src/dep-dedup.ts +++ b/src/dep-dedup.ts @@ -1,28 +1,4 @@ -// Dependency deduplication helpers for the push pipeline. -// -// On a targeted assistant push, `ensureToolExists` / `ensureStructuredOutputExists` -// previously skipped auto-create only when (a) the dep id was UUID-shaped, -// (b) `state.tools[depId]` was an exact key match, or (c) we'd already -// auto-applied this id in the current run. Bootstrap pull stores resources -// under `-` keys (e.g. `end-call-67aea057`), so a local file -// referencing `my-end-call` would miss the exact-key check and POST a -// duplicate dashboard tool. Repeated targeted pushes accumulated orphans -// on the dashboard. -// -// This module's helpers detect those collisions BEFORE create: -// - `findExistingResourceByName` — match local payload's canonical name -// against existing state entries (renamed/state-only keys) and the live -// dashboard list. Returns the UUID to adopt, plus an `ambiguous` flag -// when multiple distinct UUIDs share the same name (real on-dashboard -// duplicates from prior bug runs — the caller should warn and surface -// the loser UUIDs so a follow-up `npm run cleanup` can prune them). -// -// `slugify` and `extractBaseSlug` previously lived inline here as a -// deliberate copy of pull.ts's definitions — pull.ts imports config.ts -// which `process.exit(1)`s under unit tests, blocking direct reuse. They -// now live in `./slug-utils.ts` (config-free, side-effect-free) and are -// re-exported below so any existing test importing them from this module -// keeps working unchanged. +// Dependency reuse requires recorded ownership; names alone are not authorization. import { extractBaseSlug, slugify } from "./slug-utils.ts"; import type { ResourceState } from "./types.ts"; @@ -37,7 +13,8 @@ export interface RemoteResource { export interface DedupMatch { uuid: string; - source: "state" | "dashboard" | "both"; + origin: "pushed" | "adopted"; + source: "state"; ambiguous: boolean; // Other distinct UUIDs we saw under the same canonical name. Empty when // `ambiguous` is false. Caller should surface these in a warning so the @@ -72,20 +49,7 @@ export function extractResourceName( return undefined; } -// Find an existing resource (in state or dashboard) whose canonical name -// matches the local payload's canonical name. Used by ensureToolExists / -// ensureStructuredOutputExists to avoid creating a duplicate when bootstrap -// pull has already stored the same dashboard resource under a different -// state key. -// -// `localResourceId` is the key the engine WANTS to use in state. If a state -// entry already exists under that exact key, the caller short-circuits BEFORE -// calling this — so we exclude it here as a safety belt. -// -// Tiebreaker for >1 distinct UUID matching the same slugified name (i.e. -// real on-dashboard duplicates from prior bug runs): pick lexically smallest -// UUID for stable, deterministic adoption. Set `ambiguous=true` and surface -// the loser UUIDs in `duplicateUuids` so the caller can warn. +// Only repo-created or explicitly adopted state entries can be reused. export function findExistingResourceByName(args: { localResourceId: string; localPayload: NameablePayload; @@ -96,26 +60,15 @@ export function findExistingResourceByName(args: { if (!localName) return undefined; const localSlug = slugify(localName); - // uuid -> set of source labels (state:, dashboard:) - const matches = new Map>(); + const matches = new Map(); for (const [stateKey, entry] of Object.entries(args.stateSection)) { if (stateKey === args.localResourceId) continue; - if (extractBaseSlug(stateKey) === localSlug) { - const set = matches.get(entry.uuid) ?? new Set(); - set.add(`state:${stateKey}`); - matches.set(entry.uuid, set); - } - } - - for (const remote of args.remoteList ?? []) { - const remoteName = - (typeof remote.name === "string" && remote.name) || remote.function?.name; - if (!remoteName) continue; - if (slugify(remoteName) === localSlug) { - const set = matches.get(remote.id) ?? new Set(); - set.add(`dashboard:${remote.id}`); - matches.set(remote.id, set); + if ( + extractBaseSlug(stateKey) === localSlug && + (entry.origin === "pushed" || entry.origin === "adopted") + ) { + matches.set(entry.uuid, entry.origin); } } @@ -123,18 +76,39 @@ export function findExistingResourceByName(args: { const sorted = [...matches.keys()].sort(); const winner = sorted[0]!; - const winnerSources = matches.get(winner)!; - const hasState = [...winnerSources].some((s) => s.startsWith("state:")); - const hasDashboard = [...winnerSources].some((s) => - s.startsWith("dashboard:"), - ); - const source: DedupMatch["source"] = - hasState && hasDashboard ? "both" : hasState ? "state" : "dashboard"; return { uuid: winner, - source, + origin: matches.get(winner)!, + source: "state", ambiguous: matches.size > 1, duplicateUuids: sorted.slice(1), }; } + +export function warnUnownedNameMatches(args: { + resourceType: string; + localResourceId: string; + localPayload: NameablePayload; + stateSection: Record; + remoteList: RemoteResource[]; + reusedUuid?: string; +}): void { + const name = extractResourceName(args.localPayload) ?? args.localResourceId; + const slug = slugify(name); + const matches = new Map(); + for (const [key, entry] of Object.entries(args.stateSection)) { + if (extractBaseSlug(key) === slug) matches.set(entry.uuid, name); + } + for (const remote of args.remoteList) { + const remoteName = extractResourceName(remote); + if (remoteName && slugify(remoteName) === slug) + matches.set(remote.id, remoteName); + } + for (const [uuid, remoteName] of matches) { + if (uuid === args.reusedUuid) continue; + console.warn( + ` ⚠️ Existing ${args.resourceType} "${remoteName}" (${uuid}) was NOT linked by name. --adopt ${args.localResourceId} takes it over instead.`, + ); + } +} diff --git a/src/link-preflight.ts b/src/link-preflight.ts new file mode 100644 index 0000000..dd56858 --- /dev/null +++ b/src/link-preflight.ts @@ -0,0 +1,244 @@ +import { relative } from "path"; +import { type AdoptionAlias, adoptResources } from "./adopt.ts"; +import { prepareAliasCleanup } from "./adopt-alias-files.ts"; +import { + ADOPT_TARGETS, + ALLOW_NEW_FILES, + APPLY_FILTER, + BASE_DIR, + BOOTSTRAP_SYNC, + DRY_RUN, + VAPI_ENV, +} from "./config.ts"; +import { extractResourceName, type RemoteResource } from "./dep-dedup.ts"; +import { detectOrphanYamls } from "./new-file-gate.ts"; +import { extractBaseSlug, slugify } from "./slug-utils.ts"; +import type { TouchedSets } from "./state-merge.ts"; +import { type StopIssue, shellQuote } from "./stop-report.ts"; +import type { LoadedResources, ResourceType, StateFile } from "./types.ts"; +import { VALID_RESOURCE_TYPES } from "./types.ts"; + +export async function prepareResourceLinks(opts: { + resources: LoadedResources; + state: StateFile; + touched: TouchedSets; + getRemoteList: (type: ResourceType) => Promise; +}) { + const issues: StopIssue[] = []; + const errors: { target: string; message: string }[] = []; + let aliases: AdoptionAlias[] = []; + const preview = await adoptResources({ + ...opts, + targets: ADOPT_TARGETS, + dryRun: true, + quiet: true, + errors, + cleanupAliases: async (entries) => { + aliases = entries; + }, + }); + const base = `npm run push -- ${shellQuote(VAPI_ENV)}`; + for (const type of VALID_RESOURCE_TYPES) { + for (const file of opts.resources[type]) { + if (preview[type][file.resourceId]) continue; + const owners = Object.entries(preview[type]).filter( + ([id, entry]) => + entry.origin === "adopted" && + file.resourceId.endsWith(`-${entry.uuid.slice(0, 8)}`) && + extractBaseSlug(file.resourceId) === extractBaseSlug(id) && + opts.resources[type].some((resource) => resource.resourceId === id), + ); + if ( + owners.length === 1 && + !aliases.some( + (alias) => + alias.type === type && alias.resourceId === file.resourceId, + ) + ) { + const [adoptedAs, { uuid }] = owners[0]!; + aliases.push({ type, resourceId: file.resourceId, uuid, adoptedAs }); + } + } + } + for (const { target, message } of errors) { + const id = target.split("=")[0]!; + const type = VALID_RESOURCE_TYPES.find((type) => + opts.resources[type].some((file) => file.resourceId === id), + ); + const file = type + ? opts.resources[type].find((file) => file.resourceId === id) + : undefined; + const path = file ? relative(BASE_DIR, file.filePath) : id; + const alreadyLinked = message.includes("already linked"); + const noCandidates = message.includes("no candidates"); + const missing = message.includes("no such file"); + issues.push({ + file: path, + resourceType: type ?? "unknown", + problem: message, + fix: missing + ? "Remove this --adopt argument, or restore the intended local file and rerun." + : noCandidates + ? "If genuinely new, remove this --adopt argument and approve --allow-new-files. If renamed/stale, delete the file." + : alreadyLinked + ? "Already linked: remove this --adopt argument and retry." + : "Check the file and candidate UUIDs; choose a resource explicitly or remove this adoption request.", + command: missing + ? base + : noCandidates + ? `${base} --allow-new-files ${shellQuote(path)} OR rm -- ${shellQuote(path)}` + : alreadyLinked + ? `${base} ${shellQuote(path)}` + : `${base} --adopt ${shellQuote(id)}= ${shellQuote(path)}`, + needsChoice: !alreadyLinked, + ...(alreadyLinked ? { args: [shellQuote(path)] } : {}), + }); + } + const suggestedOwners = new Map(); + const cleanup = await prepareAliasCleanup(aliases, opts.resources); + for (const issue of cleanup.problems) + issues.push({ + file: issue.file, + resourceType: issue.type, + problem: issue.message, + fix: "Merge its edits into the adopted file, or delete this file by hand, then rerun.", + command: `rm -- ${shellQuote(issue.file)}`, + needsChoice: true, + }); + const removed = new Set( + aliases.map((alias) => `${alias.type}:${alias.resourceId}`), + ); + if (!BOOTSTRAP_SYNC && !ALLOW_NEW_FILES) { + const report = detectOrphanYamls({ + state: preview, + filePathFilter: APPLY_FILTER.filePaths, + }); + for (const entry of report.orphans) { + if (removed.has(`${entry.type}:${entry.resourceId}`)) continue; + const file = opts.resources[entry.type].find( + (file) => file.resourceId === entry.resourceId, + ); + if ( + !file || + errors.some((error) => error.target.split("=")[0] === entry.resourceId) + ) + continue; + const path = relative(BASE_DIR, file.filePath); + const name = slugify(extractResourceName(file.data) ?? entry.resourceId); + const matches = new Set( + Object.entries(opts.state[entry.type]) + .filter(([key]) => extractBaseSlug(key) === name) + .map(([, value]) => value.uuid), + ); + let lookupError: string | undefined; + try { + for (const remote of await opts.getRemoteList(entry.type)) + if (slugify(extractResourceName(remote) ?? "") === name) + matches.add(remote.id); + } catch (error) { + lookupError = error instanceof Error ? error.message : String(error); + } + const adopt = matches.size === 1 && !lookupError; + const args = [ + `--adopt ${shellQuote(entry.resourceId)}`, + shellQuote(path), + ]; + const commands = [...matches] + .sort() + .map( + (uuid) => + `${base} --adopt ${shellQuote(entry.resourceId + (matches.size > 1 ? "=" + uuid : ""))} ${shellQuote(path)}`, + ); + 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).", + command: [ + ...commands, + `${base} --allow-new-files ${shellQuote(path)}`, + `rm -- ${shellQuote(path)}`, + ].join(" OR "), + needsChoice: !adopt, + ...(adopt ? { args } : {}), + }; + issues.push(issue); + if (adopt) { + const uuid = [...matches][0]!; + const key = `${entry.type}:${uuid}`; + suggestedOwners.set(key, [...(suggestedOwners.get(key) ?? []), issue]); + } + } + } + for (const shared of suggestedOwners.values()) { + if (shared.length < 2) continue; + for (const issue of shared) { + issue.needsChoice = true; + issue.problem += + " Another file has the same proposed remote UUID; choose which file should own it."; + } + } + const approvedTargets = ADOPT_TARGETS.filter( + (target) => !errors.some((error) => error.target === target), + ).flatMap((target) => [ + `--adopt ${shellQuote(target)}`, + ...VALID_RESOURCE_TYPES.flatMap((type) => + opts.resources[type] + .filter((file) => file.resourceId === target.split("=")[0]) + .map((file) => shellQuote(relative(BASE_DIR, file.filePath))), + ), + ]); + for (const issue of issues) { + if (issue.args) + issue.args = [ + ...approvedTargets, + ...(ALLOW_NEW_FILES ? ["--allow-new-files"] : []), + ...issue.args, + ]; + } + const grouped = new Map(); + for (const issue of issues) { + const key = `${issue.resourceType}:${issue.file}`; + const existing = grouped.get(key); + if (!existing) grouped.set(key, issue); + else { + if (!existing.problem.includes(issue.problem)) + existing.problem += ` ${issue.problem}`; + if (!existing.command.includes(issue.command)) + existing.command += ` OR ${issue.command}`; + existing.needsChoice ||= issue.needsChoice; + } + } + return { + issues: [...grouped.values()], + preview, + async commit() { + await cleanup.run(); + for (const type of VALID_RESOURCE_TYPES) { + for (const id of new Set([ + ...Object.keys(opts.state[type]), + ...Object.keys(preview[type]), + ])) { + if ( + JSON.stringify(opts.state[type][id]) !== + JSON.stringify(preview[type][id]) && + !DRY_RUN + ) + opts.touched[type].add(id); + } + } + for (const target of ADOPT_TARGETS) { + const id = target.split("=")[0]!; + const type = VALID_RESOURCE_TYPES.find( + (type) => preview[type][id]?.origin === "adopted", + ); + if (type) + console.log( + ` ${DRY_RUN ? "would adopt" : "Adopting"} ${id} → ${preview[type][id]!.uuid}`, + ); + } + }, + }; +} diff --git a/src/migrate-hash-store.ts b/src/migrate-hash-store.ts index a8cf1bc..94ce990 100644 --- a/src/migrate-hash-store.ts +++ b/src/migrate-hash-store.ts @@ -14,7 +14,8 @@ import { existsSync, readdirSync, readFileSync } from "fs"; import { rename, writeFile } from "fs/promises"; import { basename, dirname, join } from "path"; import { HASH_STORE_ROOT, readBaseline, writeBaseline } from "./hash-store.ts"; -import { sortedKeysReplacer } from "./state-serialize.ts"; +import { asResourceState, sortedKeysReplacer } from "./state-serialize.ts"; +import type { ResourceState } from "./types.ts"; // Repo root, derived from the hash store's known location (single source). const BASE_DIR = dirname(HASH_STORE_ROOT); @@ -40,7 +41,7 @@ function isLegacyEntry(value: unknown): boolean { if (typeof value === "string") return true; if (value && typeof value === "object" && !Array.isArray(value)) { const keys = Object.keys(value as Record); - return keys.some((k) => k !== "uuid"); + return keys.some((k) => k !== "uuid" && k !== "origin"); } return false; } @@ -71,7 +72,9 @@ function isSection(value: unknown): value is Record { return !!value && typeof value === "object" && !Array.isArray(value); } -function discoverStateFiles(baseDir: string): Array<{ org: string; path: string }> { +function discoverStateFiles( + baseDir: string, +): Array<{ org: string; path: string }> { const out: Array<{ org: string; path: string }> = []; for (const name of readdirSync(baseDir)) { const m = STATE_FILE_RE.exec(name); @@ -93,7 +96,7 @@ async function migrateOne( let seeded = 0; let skipped = 0; let needsSlim = false; - const slim: Record> = {}; + const slim: Record> = {}; for (const [sectionKey, section] of Object.entries(raw)) { if (!isSection(section)) { @@ -102,7 +105,7 @@ async function migrateOne( (slim as Record)[sectionKey] = section; continue; } - const slimSection: Record = {}; + const slimSection: Record = {}; for (const [resourceId, value] of Object.entries(section)) { if (isLegacyEntry(value)) needsSlim = true; const uuid = uuidOf(value); @@ -118,7 +121,7 @@ async function migrateOne( skipped++; } } - slimSection[resourceId] = { uuid }; + slimSection[resourceId] = asResourceState(value)!; } slim[sectionKey] = slimSection; } @@ -132,7 +135,13 @@ async function migrateOne( await rename(tmpPath, stateFilePath); } - return { org, stateFile: basename(stateFilePath), seeded, skipped, slimmed: needsSlim }; + return { + org, + stateFile: basename(stateFilePath), + seeded, + skipped, + slimmed: needsSlim, + }; } // Migrate every `.vapi-state..json` in the repo root: seed missing diff --git a/src/name-collisions.ts b/src/name-collisions.ts new file mode 100644 index 0000000..d4c03a8 --- /dev/null +++ b/src/name-collisions.ts @@ -0,0 +1,91 @@ +import { + extractResourceName, + type NameablePayload, + type RemoteResource, +} from "./dep-dedup.ts"; +import { extractBaseSlug, slugify } from "./slug-utils.ts"; +import type { ResourceState, ResourceType } from "./types.ts"; + +export class NameCollisionReport { + private inventories = new Map>(); + private posts = new Map< + string, + { + type: ResourceType; + resourceId: string; + name: string; + stateMatches: RemoteResource[]; + } + >(); + + constructor( + private fetchRemote: (type: ResourceType) => Promise, + ) {} + + getRemoteList(type: ResourceType): Promise { + let inventory = this.inventories.get(type); + if (!inventory) { + inventory = this.fetchRemote(type); + this.inventories.set(type, inventory); + } + return inventory; + } + + recordPost( + type: ResourceType, + resourceId: string, + payload: NameablePayload, + section: Record, + ): void { + const name = extractResourceName(payload) ?? resourceId; + const stateMatches = Object.entries(section) + .filter( + ([key, entry]) => + extractBaseSlug(key) === slugify(name) && + !entry.uuid.startsWith("dry-run-"), + ) + .map(([, entry]) => ({ id: entry.uuid, name })); + this.posts.set(`${type}:${resourceId}`, { + type, + resourceId, + name, + stateMatches, + }); + } + + async format(): Promise { + const lines: string[] = []; + const unavailable = new Set(); + for (const post of this.posts.values()) { + const matches = new Map( + post.stateMatches.map((entry) => [entry.id, entry]), + ); + try { + for (const remote of await this.getRemoteList(post.type)) { + if (slugify(extractResourceName(remote) ?? "") === slugify(post.name)) + matches.set(remote.id, remote); + } + } catch (error) { + unavailable.add(post.type); + lines.push( + ` Inventory unavailable for ${post.type}: ${error instanceof Error ? error.message : String(error)}`, + ); + } + for (const remote of matches.values()) { + lines.push( + ` - ${post.type} "${extractResourceName(remote) ?? post.name}" (${remote.id}): ${post.resourceId} would create a new resource; --adopt ${post.resourceId} to take this over`, + ); + } + } + if (!lines.length) return "Name collisions: none"; + return [ + "Name collisions:", + ...lines, + ...(unavailable.size + ? [ + " Collision check incomplete: review unavailable inventories before deploying.", + ] + : []), + ].join("\n"); + } +} diff --git a/src/new-file-gate.ts b/src/new-file-gate.ts index f0fe0f5..8fb3cf0 100644 --- a/src/new-file-gate.ts +++ b/src/new-file-gate.ts @@ -29,6 +29,7 @@ import { matchesIgnore, VAPI_ENV } from "./config.ts"; import { listExistingResourceIds } from "./pull.ts"; import { FOLDER_MAP } from "./resources.ts"; import { extractBaseSlug } from "./slug-utils.ts"; +import { formatStopReport, shellQuote } from "./stop-report.ts"; import type { ResourceType, StateFile } from "./types.ts"; import { VALID_RESOURCE_TYPES } from "./types.ts"; @@ -40,6 +41,7 @@ export interface OrphanFile { type: ResourceType; resourceId: string; relativePath: string; + sameNameResourceIds?: string[]; } export interface RenameSource { @@ -178,7 +180,20 @@ export function detectOrphanYamls( ) { continue; } - orphans.push({ type, resourceId: localId, relativePath }); + const sameNameResourceIds = Object.entries(state[type]) + .filter( + ([id, entry]) => + id.toLowerCase() === + `${localId}-${entry.uuid.slice(0, 8)}`.toLowerCase() && + /^[a-f0-9]{8}$/i.test(entry.uuid.slice(0, 8)), + ) + .map(([id]) => id); + orphans.push({ + type, + resourceId: localId, + relativePath, + ...(sameNameResourceIds.length ? { sameNameResourceIds } : {}), + }); const baseSet = orphanBaseSlugsByType.get(type) ?? new Set(); baseSet.add(baseSlugFn(localId)); orphanBaseSlugsByType.set(type, baseSet); @@ -222,96 +237,21 @@ export function detectOrphanYamls( // AI-agent stdout captures get plain text. // ───────────────────────────────────────────────────────────────────────────── -interface AnsiPalette { - red: string; - yellow: string; - bold: string; - reset: string; -} - -function buildPalette(color: boolean): AnsiPalette { - if (!color) { - return { red: "", yellow: "", bold: "", reset: "" }; - } - return { - red: "\x1b[31m", - yellow: "\x1b[33m", - bold: "\x1b[1m", - reset: "\x1b[0m", - }; -} - export function formatGateMessage( report: OrphanReport, env: string, options: { color?: boolean } = {}, ): string { - const ansi = buildPalette(options.color === true); - const { red, yellow, bold, reset } = ansi; - - const lines: string[] = []; - const count = report.orphans.length; - const scopeNote = report.scopedToPaths - ? " (scoped to the selective-push file set)" - : ""; - - lines.push(""); - lines.push( - `${red}${bold}❌ Push refused${reset}${red}: ${count} file(s) on disk have no state-file UUID mapping for env "${env}"${scopeNote}.${reset}`, + const text = formatStopReport( + report.orphans.map((file) => ({ + file: file.relativePath, + resourceType: file.type, + problem: `Not linked to any resource in ${env} yet.`, + fix: "If new, approve --allow-new-files. If same-named, approve --adopt. If renamed/stale, delete the file after preserving needed edits.", + command: `npm run push -- ${shellQuote(env)} --allow-new-files ${shellQuote(file.relativePath)} OR npm run push -- ${shellQuote(env)} --adopt ${shellQuote(file.resourceId)} ${shellQuote(file.relativePath)} OR rm -- ${shellQuote(file.relativePath)}`, + needsChoice: true, + })), + env, ); - lines.push(""); - lines.push("The engine cannot tell whether each is:"); - lines.push(" - A NEW resource you intentionally want to create"); - lines.push( - " - A RENAME of an existing resource (state has the old slug; YAML has new name)", - ); - lines.push(" - A MOVED file (file copied without state updated)"); - lines.push(""); - lines.push(`${bold}Files without state entry:${reset}`); - for (const orphan of report.orphans) { - lines.push(` - ${orphan.relativePath}`); - } - - lines.push(""); - lines.push( - `${bold}State entries with no matching local file (possible rename SOURCES):${reset}`, - ); - if (report.possibleRenameSources.length === 0) { - lines.push(" (none — no plausible rename pairings found)"); - } else { - for (const src of report.possibleRenameSources) { - const shortUuid = `${src.uuid.slice(0, 8)}…`; - lines.push( - ` - ${src.type}/${src.resourceId} → ${shortUuid} (no ${src.resourceId} on disk)`, - ); - } - } - - lines.push(""); - lines.push( - `${yellow}${bold}⚠️ FOR AI AGENTS reading this:${reset} do NOT auto-pass --allow-new-files. Pause`, - ); - lines.push( - "and ask the human to confirm, for EACH file above, whether it is:", - ); - lines.push(" (a) intentionally new (then pass --allow-new-files)"); - lines.push( - " (b) a rename (then rename it back and use `npm run pull` to re-key", - ); - lines.push(" state, or apply the rename explicitly)"); - lines.push(" (c) stale cruft (then delete the local file)"); - lines.push(""); - lines.push( - "If the user is reachable, surface this gate to them. If running headless,", - ); - lines.push( - "abort. Silent --allow-new-files defeats the entire purpose of this gate.", - ); - lines.push(""); - lines.push( - `To proceed (after confirming intent for every file above): re-run with ${bold}--allow-new-files${reset}.`, - ); - lines.push(""); - - return lines.join("\n"); + return options.color ? `\x1b[31m\x1b[33m\x1b[1m${text}\x1b[0m` : text; } diff --git a/src/pull.ts b/src/pull.ts index 62b487f..f032294 100644 --- a/src/pull.ts +++ b/src/pull.ts @@ -35,10 +35,6 @@ import { } from "./drift.ts"; import { readBaseline, writeBaseline } from "./hash-store.ts"; import { assertStateMigrated } from "./migrate-hash-store.ts"; -import { - formatRecanonicalizeReport, - recanonicalizeStateKeys, -} from "./recanonicalize.ts"; import { FOLDER_MAP, hashLocalResource, @@ -226,7 +222,8 @@ async function fetchPagedList( // A short first page proves we saw everything in one request — the common case // pays nothing for paging. - if (first.length < LIST_PAGE_SIZE) return { resources: first, complete: true }; + if (first.length < LIST_PAGE_SIZE) + return { resources: first, complete: true }; // A full page means the response was capped. Walk backwards through // `createdAt`, the only cursor these endpoints offer. @@ -342,7 +339,9 @@ async function pullCredentials(state: StateFile): Promise { if (!slug) { slug = credentialSlug(cred); } - newSection[slug] = { uuid: cred.id }; + newSection[slug] = existingReverse.has(cred.id) + ? state.credentials[slug]! + : { uuid: cred.id, origin: "pulled" }; console.log(` 🔑 ${slug} -> ${cred.id}`); } @@ -408,49 +407,6 @@ export function listExistingResourceIds(resourceType: ResourceType): string[] { return walk(dir, []); } -// When pulling a new environment, a resource may already exist on disk under a -// different UUID suffix (e.g., `end-call-tool-8102e715` from dev). Match by -// name-slug so we reuse the existing file instead of creating a duplicate. -// -// State-awareness guard: if a name-matching file is already claimed in state -// by a *different* UUID, refuse adoption. Without this guard, two dashboard -// resources sharing a name (e.g. a Duplicate-Assistant click, or any -// platform auto-seed of a same-named twin) collapse onto the same file — -// the second pull silently overwrites the first's content and reassigns -// the slug's state mapping to the new UUID, orphaning the original. -// Falling through to `generateResourceId` (caller) produces a deterministic -// `-` slug per UUID, so the second resource gets its own file. -export function findExistingResourceId( - existingResourceIds: string[], - resource: VapiResource, - stateSection: Record, -): string | undefined { - const name = extractName(resource); - if (!name) return undefined; - - const nameSlug = slugify(name); - const matches = existingResourceIds.filter( - (id) => extractBaseSlug(id) === nameSlug, - ); - if (matches.length === 0) return undefined; - - // A file is adoptable when it is either unclaimed in state (cross-env - // pull: file shipped from dev, this env has no prior state for it) or - // already claimed by THIS resource's UUID. The same-UUID branch is - // defensive — in the production code path the caller's - // `reverseMap.get(resource.id)` short-circuits this case, so we only - // reach this function when the UUID is unknown to state. Keep the - // branch anyway so the helper is correct in isolation. - // A file claimed by a *different* UUID is not adoptable — adopting it - // would clobber the existing resource's content and state mapping. - const adoptable = matches.filter((id) => { - const claim = stateSection[id]?.uuid; - return claim === undefined || claim === resource.id; - }); - - return adoptable.length === 1 ? adoptable[0] : undefined; -} - function removeUuidMappings( stateSection: Record, uuid: string, @@ -826,9 +782,6 @@ export async function pullResourceType( const newStateSection: Record = resourceIds?.length ? { ...state[resourceType] } : {}; - const existingResourceIds = bootstrap - ? [] - : listExistingResourceIds(resourceType); let created = 0; let updated = 0; @@ -840,35 +793,21 @@ export async function pullResourceType( // dashboard `name`. If this UUID is already tracked in state, keep its // existing resourceId verbatim — a dashboard rename only changes the // resource's content, never its local filename. We only mint a new slug - // when the UUID is unknown to state (genuinely new or cross-env adoption). + // when the UUID is unknown to state. const trackedResourceId = reverseMap.get(resource.id); let resourceId = trackedResourceId; if (!resourceId) { - // Reuse an existing file's resourceId if the name matches (cross-env - // pull). The adoption guard needs both prior-pull claims AND - // intra-pull claims so the fix is iteration-order-independent: - // - `state[resourceType]` carries prior-pull claims loaded from - // disk. Without this, if the dashboard returns the new same-name - // twin BEFORE the tracked one, the new twin sees `newStateSection` - // empty and clobbers the tracked file. A customer's production - // 5-Rileys investigation surfaced this ordering dependency. - // - `newStateSection` carries intra-pull claims from earlier - // iterations. Handles the converse (tracked-then-twin order). - // Spread `newStateSection` last so it wins when both have the same - // slug — the in-flight value is the more authoritative claim during - // this pull (e.g. an earlier iteration rekeyed the slug to a new UUID). - const claimView = { ...state[resourceType], ...newStateSection }; - resourceId = bootstrap - ? generateResourceId(resource) - : (findExistingResourceId(existingResourceIds, resource, claimView) ?? - generateResourceId(resource)); + resourceId = generateResourceId(resource); } // New only when the UUID was not previously tracked. A dashboard rename // of an already-tracked resource is an UPDATE to the existing file, not // a new resource — the local filename stays put. const isNew = !trackedResourceId; + if (trackedResourceId && state[resourceType][trackedResourceId]) { + newStateSection[resourceId] = state[resourceType][trackedResourceId]; + } removeUuidMappings(newStateSection, resource.id, resourceId); const folderPath = FOLDER_MAP[resourceType]; @@ -964,7 +903,10 @@ export async function pullResourceType( console.log( ` ⬆️ ${resourceId} (local ahead of dashboard) ${formatDriftLabel(direction)}`, ); - upsertState(newStateSection, resourceId, { uuid: resource.id }); + upsertState(newStateSection, resourceId, { + uuid: resource.id, + origin: "pulled", + }); skipped++; continue; } @@ -1002,7 +944,10 @@ export async function pullResourceType( changedFiles.has(yamlPath) ) { console.log(` ✏️ ${resourceId} (locally modified, preserving)`); - upsertState(newStateSection, resourceId, { uuid: resource.id }); + upsertState(newStateSection, resourceId, { + uuid: resource.id, + origin: "pulled", + }); skipped++; continue; } @@ -1029,7 +974,10 @@ export async function pullResourceType( const stateMtime = statSync(stateFilePath).mtimeMs; if (localMtime > stateMtime) { console.log(` ✏️ ${resourceId} (locally modified, preserving)`); - upsertState(newStateSection, resourceId, { uuid: resource.id }); + upsertState(newStateSection, resourceId, { + uuid: resource.id, + origin: "pulled", + }); skipped++; continue; } @@ -1051,7 +999,10 @@ export async function pullResourceType( console.log( ` 🗑️ ${resourceId} (deleted locally, intent in state — add to .vapi-ignore to stop tracking)`, ); - upsertState(newStateSection, resourceId, { uuid: resource.id }); + upsertState(newStateSection, resourceId, { + uuid: resource.id, + origin: "pulled", + }); skipped++; continue; } @@ -1113,7 +1064,10 @@ export async function pullResourceType( ` ⚠️ ${resourceType}/${resourceId}: failed to hash post-write disk form; falling back to in-memory hash (may produce phantom drift on next pull)`, ); } - upsertState(newStateSection, resourceId, { uuid: resource.id }); + upsertState(newStateSection, resourceId, { + uuid: resource.id, + origin: "pulled", + }); await writeBaseline( VAPI_ENV, resource.id, @@ -1209,7 +1163,10 @@ async function resolveBothDivergedResources(options: { // No file write — local is preserved. Set the baseline to the platform // state at resolve time so the next classifyDrift correctly reports // `local-ahead` instead of re-flagging `both-diverged`. - upsertState(section, entry.resourceId, { uuid: entry.resource.id }); + upsertState(section, entry.resourceId, { + uuid: entry.resource.id, + origin: "pulled", + }); await writeBaseline(VAPI_ENV, entry.resource.id, entry.platformHash); continue; } @@ -1235,7 +1192,10 @@ async function resolveBothDivergedResources(options: { ` ⚠️ ${entry.resourceType}/${entry.resourceId}: failed to hash post-write disk form; falling back to in-memory hash (may produce phantom drift on next pull)`, ); } - upsertState(section, entry.resourceId, { uuid: entry.resource.id }); + upsertState(section, entry.resourceId, { + uuid: entry.resource.id, + origin: "pulled", + }); await writeBaseline( VAPI_ENV, entry.resource.id, @@ -1533,26 +1493,6 @@ export async function runPull(options: PullOptions = {}): Promise { if (shouldPull("evals")) stats.evals = await pullResourceType("evals", state, pullOptsFor("evals")); - // Collapse UUID-suffixed state keys back to canonical when the underlying - // name-collision has resolved (the conflicting twin was deleted, etc.). - // Skipped during bootstrap because bootstrap is supposed to populate state - // from scratch — there is no prior rekey to undo. Also skipped on targeted - // ID pulls so we don't sweep types we haven't fully refreshed. When the - // pull is scoped by typeFilter, the pass is restricted to those types so - // we don't touch sections this pull didn't refresh — preserves the stated - // safety boundary even though the preconditions themselves are safe. - // Pull's saveState writes wholesale, so `touched` isn't needed here. - if (!bootstrap && !isScopedPull) { - const report = recanonicalizeStateKeys({ - state, - types: typeFilter?.length ? (typeFilter as ResourceType[]) : undefined, - }); - const summary = formatRecanonicalizeReport(report); - if (summary) { - console.log(`\n${summary}`); - } - } - const resolveResult = await resolveBothDivergedResources({ state, bothDiverged: bothDivergedResources, diff --git a/src/push.ts b/src/push.ts index c22f41d..0067b27 100644 --- a/src/push.ts +++ b/src/push.ts @@ -4,10 +4,8 @@ import { fileURLToPath } from "url"; import { getDryRunCounts, VapiApiError, vapiRequest } from "./api.ts"; import { canonicalizeForHash, type VapiResource } from "./canonical.ts"; import { - ALLOW_NEW_FILES, APPLY_FILTER, BASE_DIR, - BOOTSTRAP_SYNC, DRY_RUN, FORCE_DELETE, loadIgnorePatterns, @@ -20,21 +18,19 @@ import { VAPI_ENV, } from "./config.ts"; import { - extractResourceName, findExistingResourceByName, type RemoteResource, + warnUnownedNameMatches, } from "./dep-dedup.ts"; import { checkDriftForUpdate, type DriftCheckResult } from "./drift.ts"; import { deleteBaseline, writeBaseline } from "./hash-store.ts"; +import { prepareResourceLinks } from "./link-preflight.ts"; import { assertStateMigrated } from "./migrate-hash-store.ts"; -import { detectOrphanYamls, formatGateMessage } from "./new-file-gate.ts"; -import { - formatRecanonicalizeReport, - recanonicalizeStateKeys, -} from "./recanonicalize.ts"; +import { NameCollisionReport } from "./name-collisions.ts"; import { reconcileStateKeyForResource } from "./reconcile-state-key.ts"; import { writeSnapshot } from "./snapshot.ts"; import { mergeScoped } from "./state-merge.ts"; +import { formatStopReport, jsonStopReport } from "./stop-report.ts"; import { userAgentGet, vapiClientGet } from "./user-agent.ts"; import { summarizeFindings, @@ -212,6 +208,8 @@ async function writeAssistantVersionMetadata(options: { } } +let dryRunCollisions: NameCollisionReport | undefined; + async function upsertResourceWithStateRecovery(options: { resourceLabel: string; resourceId: string; @@ -241,8 +239,20 @@ async function upsertResourceWithStateRecovery(options: { } = options; if (!existingUuid) { + const resourceType = RESOURCE_LABEL_TO_TYPE[resourceLabel]; + if (resourceType) + dryRunCollisions?.recordPost( + resourceType, + resourceId, + createPayload, + stateSection, + ); console.log(` ✨ Creating ${resourceLabel}: ${resourceId}`); const result = await vapiRequest("POST", createEndpoint, createPayload); + upsertState(stateSection, resourceId, { + uuid: result.id, + origin: "pushed", + }); await writeBaselineFromResponse(result.id, result, fullState); if (resourceLabel === "assistant") { await writeAssistantVersionMetadata({ @@ -1024,8 +1034,10 @@ export async function applyEval( await writeBaselineFromResponse(existingUuid, result, state); return existingUuid; } else { + dryRunCollisions?.recordPost("evals", resourceId, payload, state.evals); console.log(` ✨ Creating eval: ${resourceId}`); const result = await vapiRequest("POST", "/eval", payload); + upsertState(state.evals, resourceId, { uuid: result.id, origin: "pushed" }); await writeBaselineFromResponse(result.id, result, state); return result.id; } @@ -1316,20 +1328,15 @@ interface DependencyContext { touched: TouchedSets; } -// Lazy-fetch the live dashboard inventory for a given resource type. Used by -// the auto-apply path to detect existing dashboard resources before minting -// a duplicate POST. Honors dry-run by skipping the API call entirely -// (empty list → state-only dedup). +// Lazy-fetch inventory for same-name warnings, not name-based adoption. +// Dry-run inventories are shared with the collision report. async function getExistingRemoteTools( ctx: DependencyContext, ): Promise { if (ctx.existingRemoteTools !== undefined) return ctx.existingRemoteTools; - if (DRY_RUN) { - ctx.existingRemoteTools = []; - return ctx.existingRemoteTools; - } try { - const remote = await fetchAllResources("tools"); + const remote = await (dryRunCollisions?.getRemoteList("tools") ?? + fetchAllResources("tools")); ctx.existingRemoteTools = remote as unknown as RemoteResource[]; } catch (err) { console.warn( @@ -1347,12 +1354,10 @@ async function getExistingRemoteStructuredOutputs( ): Promise { if (ctx.existingRemoteStructuredOutputs !== undefined) return ctx.existingRemoteStructuredOutputs; - if (DRY_RUN) { - ctx.existingRemoteStructuredOutputs = []; - return ctx.existingRemoteStructuredOutputs; - } try { - const remote = await fetchAllResources("structuredOutputs"); + const remote = await (dryRunCollisions?.getRemoteList( + "structuredOutputs", + ) ?? fetchAllResources("structuredOutputs")); ctx.existingRemoteStructuredOutputs = remote as unknown as RemoteResource[]; } catch (err) { console.warn( @@ -1370,12 +1375,9 @@ async function getExistingRemoteAssistants( ): Promise { if (ctx.existingRemoteAssistants !== undefined) return ctx.existingRemoteAssistants; - if (DRY_RUN) { - ctx.existingRemoteAssistants = []; - return ctx.existingRemoteAssistants; - } try { - const remote = await fetchAllResources("assistants"); + const remote = await (dryRunCollisions?.getRemoteList("assistants") ?? + fetchAllResources("assistants")); ctx.existingRemoteAssistants = remote as unknown as RemoteResource[]; } catch (err) { console.warn( @@ -1518,19 +1520,22 @@ async function ensureAssistantExists( stateSection: ctx.state.assistants, remoteList, }); + warnUnownedNameMatches({ + resourceType: "assistants", + localResourceId: assistantId, + localPayload: assistant.data, + stateSection: ctx.state.assistants, + remoteList, + reusedUuid: match?.uuid, + }); if (match) { - if (match.ambiguous) { - const displayName = extractResourceName(assistant.data) ?? assistantId; - console.warn( - ` ⚠️ Multiple dashboard assistants share the name "${displayName}" — adopting ${match.uuid} (lex-smallest). Other UUIDs: ${match.duplicateUuids.join(", ")}. Run \`npm run cleanup -- ${VAPI_ENV}\` to prune duplicates.`, - ); - } console.log( ` 🔁 Reusing existing assistant: ${assistantId} → ${match.uuid} (matched via ${match.source})`, ); upsertState(ctx.state.assistants, assistant.resourceId, { uuid: match.uuid, + origin: match.origin, }); // Orphan-deletion guard — drop other state keys pointing at the SAME @@ -1584,7 +1589,16 @@ async function ensureAssistantExists( // Main Apply Engine // ───────────────────────────────────────────────────────────────────────────── +const reportOutput = console.log.bind(console); + async function main(): Promise { + const json = process.argv.includes("--json"); + if (json) console.log = console.error.bind(console); + dryRunCollisions = DRY_RUN + ? new NameCollisionReport( + async (type) => (await fetchAllResources(type)) as RemoteResource[], + ) + : undefined; // Guard here (not only in runPush): apply spawns `tsx src/push.ts` directly, // which enters via the isMainModule block below and never calls runPush. assertStateMigrated(STATE_FILE_PATH); @@ -1614,6 +1628,7 @@ async function main(): Promise { // Load current state (needed for reference resolution even in partial apply) let state = loadState(); + let preflightComplete = false; // Track which resourceIds we actually mutate so the end-of-run save can // merge into existing on-disk state instead of rewriting wholesale. @@ -1705,68 +1720,42 @@ async function main(): Promise { evals: allEvalsRaw, }; - state = await maybeBootstrapState(loadedResources, state); - - // Recanonicalize stale UUID-suffixed state keys back to canonical slugs - // before the orphan-YAML gate runs. This is the safe collapse of the - // pull-side rekey-on-name-collision behavior (src/pull.ts) once the - // underlying collision has resolved (e.g. the conflicting twin was - // deleted on the dashboard). Without this pass, the orphan-YAML gate - // sees the canonical-slug local file as "new" — the recurring - // duplicate-creation root cause documented in improvements.md. - // - // Gating: `BOOTSTRAP_SYNC` (the user's explicit `--bootstrap` flag) - // skips this pass because state is being rebuilt from scratch. Note - // that the *internal* bootstrap-recovery pull triggered by - // `maybeBootstrapState` above does NOT set `BOOTSTRAP_SYNC` — so - // recanonicalize still runs after that recovery, which is intentional: - // bootstrap freshly generates UUID-suffixed keys for unresolved - // collisions, and recanonicalize collapses any that no longer have a - // live conflict. - // - // `touched` is plumbed through so scoped pushes flush the rename via - // `mergeScoped` at save time. Without this, the on-disk stale key - // would silently re-overwrite the in-memory canonical rename — H1 in - // the code review. - if (!BOOTSTRAP_SYNC) { - const recanonReport = recanonicalizeStateKeys({ state, touched }); - const recanonSummary = formatRecanonicalizeReport(recanonReport); - if (recanonSummary) { - console.log(`\n${recanonSummary}`); - } + const inventories = new Map>(); + const links = await prepareResourceLinks({ + resources: loadedResources, + state, + touched, + getRemoteList: (type) => { + let inventory = inventories.get(type); + if (!inventory) { + inventory = (dryRunCollisions?.getRemoteList(type) ?? + fetchAllResources(type)) as Promise; + inventories.set(type, inventory); + } + return inventory; + }, + }); + if (links.issues.length) { + if (json) reportOutput(jsonStopReport(links.issues)); + else console.error(formatStopReport(links.issues, VAPI_ENV)); + process.exit(1); } - - // Orphan-YAML pre-flight gate. Runs ONCE for ALL resource types after - // bootstrap (so state-recovery has a chance to rekey first) and BEFORE - // any apply phase. Halts push when local files exist with no state entry - // — the duplicate-creation pattern we surfaced in a customer fork's - // working session 2026-05-13 (see src/new-file-gate.ts for context). - // - // Skipped during explicit `--bootstrap` runs: a bootstrap is supposed to - // populate state from scratch, so every local file legitimately lacks a - // state entry at that point. - if (!BOOTSTRAP_SYNC) { - const orphanReport = detectOrphanYamls({ - state, - filePathFilter: APPLY_FILTER.filePaths, - }); - if (orphanReport.orphans.length > 0) { - if (ALLOW_NEW_FILES) { - const verb = DRY_RUN ? "would create" : "creating"; - console.log( - ` ⚠️ bypassing new-file gate: ${verb} ${orphanReport.orphans.length} new resource(s) on the dashboard`, - ); - } else { - console.error( - formatGateMessage(orphanReport, VAPI_ENV, { - color: process.stderr.isTTY === true, - }), - ); - process.exit(1); + await links.commit(); + state = links.preview; + state = await maybeBootstrapState(loadedResources, state); + for (const type of ALL_RESOURCE_TYPES) { + for (const [id, entry] of Object.entries(links.preview[type])) { + if (entry.origin !== "adopted") continue; + for (const [key, value] of Object.entries(state[type])) { + if (key !== id && value.uuid === entry.uuid) { + delete state[type][key]; + if (!DRY_RUN) touched[type].add(key); + } } + state[type][id] = entry; } } - + preflightComplete = true; // Run client-side validators against the loaded resource set. In default // mode, errors are surfaced as warnings so a single bad spec doesn't block // an otherwise-good push. With --strict, any error-severity finding aborts @@ -2202,7 +2191,7 @@ async function main(): Promise { if (DRY_RUN) { const counts = getDryRunCounts(); console.log( - `🧪 Would create ${counts.POST}, would update ${counts.PATCH}, would delete ${counts.DELETE} (no API calls fired)`, + `🧪 Would create ${counts.POST}, would update ${counts.PATCH}, would delete ${counts.DELETE} (no API mutations fired)`, ); } @@ -2264,18 +2253,20 @@ async function main(): Promise { process.exit(1); } } finally { + if (json && preflightComplete) reportOutput("[]"); // Always flush state, even on partial failure — resources that already // received UUIDs from the API must be recorded so the next run does not // re-create them. // - // EXCEPT in dry-run mode: no real API calls fired, so the state file + // EXCEPT in dry-run mode: no API mutations fired, so the state file // would be polluted with synthetic dry-run UUIDs. Skip the save entirely. if (DRY_RUN) { console.log( "\n🧪 [dry-run] Skipping state file write (would have written to " + `.vapi-state.${VAPI_ENV}.json)`, ); - } else { + console.log(`\n${await dryRunCollisions!.format()}`); + } else if (preflightComplete) { try { // For scoped pushes, only persist entries we actually mutated. // Re-load disk state and merge our touched entries on top so diff --git a/src/recanonicalize.ts b/src/recanonicalize.ts deleted file mode 100644 index 88ace2c..0000000 --- a/src/recanonicalize.ts +++ /dev/null @@ -1,274 +0,0 @@ -// ───────────────────────────────────────────────────────────────────────────── -// State key recanonicalization — generic across all resource types. -// -// The pull engine generates UUID-suffixed state keys (`-`) when -// name-collision adoption is refused (src/pull.ts:findExistingResourceId / -// generateResourceId). That rekey is fire-and-forget: once the underlying -// collision resolves (e.g. the conflicting twin is deleted on the dashboard), -// nothing ever collapses the UUID-suffixed entry back to its canonical slug. -// -// Without this collapse, subsequent pushes treat the canonical-slug local -// file as a brand-new resource (orphan-YAML), and the operator either hits -// the orphan-YAML gate (#30) and bypasses with `--allow-new-files`, or — in -// older engine versions — silently creates a third dashboard duplicate. -// -// This module runs a safe collapse pass at end-of-pull and start-of-push. -// The pass is resource-type-agnostic: it walks every section of StateFile -// uniformly, so adding a new ResourceType doesn't need a code change here. -// -// SAFETY MODEL — every rekey must satisfy all five preconditions: -// 1. Key matches `^(.+)-([0-9a-f]{8})$` — the engine's generated shape. -// 2. The captured `` matches the entry's UUID prefix. This rules -// out resources whose user-given names legitimately end in -// `-abcd1234`. We only touch keys we can prove the engine wrote. -// 3. Canonical slug `` is unclaimed in the SAME state section. -// Prevents collision when a same-name twin is intentionally tracked. -// 4. A local file exists at `` with any extension recognized by -// the resource loader (`VALID_EXTENSIONS` in src/resources.ts — -// .yml/.yaml/.ts/.md). Prevents creating phantom state mappings to -// slugs that have no source file. The extension set is imported, not -// hardcoded here, so the precondition stays in lockstep with the -// loader; any future loader extension is automatically respected. -// 5. NO local file exists at `-` under any -// `VALID_EXTENSIONS` shape. The UUID-suffixed file represents a -// different content snapshot; rekeying state without consolidating -// files would silently reassign which file PATCHes which dashboard -// UUID — the data-loss shape we are explicitly refusing to introduce. -// -// When (5) fails we surface a CONFLICT (both files exist, ambiguous which -// owns the dashboard UUID) so the operator can resolve it manually. We -// never auto-pick a winner — silent data loss is worse than a duplicate. -// ───────────────────────────────────────────────────────────────────────────── - -import { existsSync } from "fs"; -import { join } from "path"; -import { RESOURCES_DIR } from "./config.ts"; -import { FOLDER_MAP, VALID_EXTENSIONS } from "./resources.ts"; -import { isEngineSuffixedSlug } from "./slug-utils.ts"; -import type { TouchedSets } from "./state-merge.ts"; -import type { ResourceType, StateFile } from "./types.ts"; -import { VALID_RESOURCE_TYPES } from "./types.ts"; - -export interface RecanonicalizeRekey { - type: ResourceType; - fromKey: string; - toKey: string; - uuid: string; -} - -export interface RecanonicalizeConflict { - type: ResourceType; - uuidSuffixedKey: string; - canonicalKey: string; - reason: - | "canonical-slug-claimed-by-different-uuid" - | "both-local-files-exist" - | "canonical-local-file-missing"; - uuid: string; -} - -export interface RecanonicalizeReport { - rekeys: RecanonicalizeRekey[]; - conflicts: RecanonicalizeConflict[]; -} - -export interface RecanonicalizeOptions { - state: StateFile; - // DI seam — defaults to filesystem check rooted at `RESOURCES_DIR`. Tests - // pass a stub so they don't need a fixture tree. - fileExists?: (relativePath: string) => boolean; - // Restrict the pass to specific types (default: all). - types?: ResourceType[]; - // Optional `touched` set for scoped pushes. When provided, both the - // deleted UUID-suffixed key AND the new canonical key are marked so - // `mergeScoped` flushes the rename instead of silently re-persisting the - // on-disk stale key. Pull doesn't pass this — it saves wholesale. - touched?: TouchedSets; -} - -function defaultFileExists(relativePath: string): boolean { - return existsSync(join(RESOURCES_DIR, relativePath)); -} - -function localFileExistsForId( - type: ResourceType, - resourceId: string, - fileExists: (relativePath: string) => boolean, -): boolean { - const folder = FOLDER_MAP[type]; - for (const ext of VALID_EXTENSIONS) { - if (fileExists(`${folder}/${resourceId}${ext}`)) return true; - } - return false; -} - -// Mutates `state` in place. Returns the list of changes for logging and the -// list of unresolved conflicts the operator should see. Callers decide -// whether conflicts halt the run (push) or are advisory (pull). -export function recanonicalizeStateKeys( - opts: RecanonicalizeOptions, -): RecanonicalizeReport { - const { - state, - fileExists = defaultFileExists, - types = [...VALID_RESOURCE_TYPES], - touched, - } = opts; - - const rekeys: RecanonicalizeRekey[] = []; - const conflicts: RecanonicalizeConflict[] = []; - - const markTouched = (type: ResourceType, key: string): void => { - if (touched) touched[type].add(key); - }; - - for (const type of types) { - const section = state[type]; - if (!section) continue; - - // Snapshot keys upfront so we can mutate the section during iteration. - for (const stateKey of Object.keys(section)) { - const entry = section[stateKey]; - if (!entry) continue; - - // Preconditions 1 + 2 — the key must match the engine-generated - // shape `-` AND the captured 8-hex must match the - // entry's UUID prefix. `isEngineSuffixedSlug` returns `null` on - // either failure, ruling out user-named resources that - // coincidentally end in `-abcd1234`. - const parsed = isEngineSuffixedSlug(stateKey, entry.uuid); - if (!parsed) continue; - const canonicalSlug = parsed.base; - - // Precondition 3 — canonical slot must be unclaimed in state. - // - // Special case: if the canonical slot is claimed by the SAME UUID, - // both keys are aliases for one dashboard resource. This shape is - // produced by older engine versions that wrote duplicate-aliased - // state, or by a `mergeScoped` round-trip before recanonicalize was - // touched-aware. Safe action: drop the redundant UUID-suffixed key - // (canonical wins; its metadata is presumed more authoritative). - // This is auto-resolved as a rekey for reporting purposes. - const claimedEntry = section[canonicalSlug]; - if (claimedEntry !== undefined) { - if (claimedEntry.uuid === entry.uuid) { - delete section[stateKey]; - markTouched(type, stateKey); - markTouched(type, canonicalSlug); - rekeys.push({ - type, - fromKey: stateKey, - toKey: canonicalSlug, - uuid: entry.uuid, - }); - continue; - } - // Genuinely a different UUID — same-name twin tracked legitimately. - conflicts.push({ - type, - uuidSuffixedKey: stateKey, - canonicalKey: canonicalSlug, - reason: "canonical-slug-claimed-by-different-uuid", - uuid: entry.uuid, - }); - continue; - } - - // Precondition 4 — canonical local file must exist. Otherwise we'd - // be inventing a state mapping that has no source on disk. - const canonicalFileExists = localFileExistsForId( - type, - canonicalSlug, - fileExists, - ); - if (!canonicalFileExists) { - // Post-pull layout: only the UUID-suffixed file exists and its name - // matches the state key — already consistent, nothing to collapse. - const uuidSuffixedOnly = localFileExistsForId( - type, - stateKey, - fileExists, - ); - if (uuidSuffixedOnly) continue; - - conflicts.push({ - type, - uuidSuffixedKey: stateKey, - canonicalKey: canonicalSlug, - reason: "canonical-local-file-missing", - uuid: entry.uuid, - }); - continue; - } - - // Precondition 5 — UUID-suffixed local file must NOT exist. If both - // files exist they represent different content snapshots; silently - // rekeying would change which file PATCHes which dashboard UUID. - const uuidSuffixedFileExists = localFileExistsForId( - type, - stateKey, - fileExists, - ); - if (uuidSuffixedFileExists) { - conflicts.push({ - type, - uuidSuffixedKey: stateKey, - canonicalKey: canonicalSlug, - reason: "both-local-files-exist", - uuid: entry.uuid, - }); - continue; - } - - // All preconditions met — collapse. Mark BOTH the deleted UUID-suffixed - // key AND the new canonical key as touched, so scoped pushes flush the - // rename via `mergeScoped` instead of silently re-persisting the - // on-disk stale key. - section[canonicalSlug] = entry; - delete section[stateKey]; - markTouched(type, stateKey); - markTouched(type, canonicalSlug); - rekeys.push({ - type, - fromKey: stateKey, - toKey: canonicalSlug, - uuid: entry.uuid, - }); - } - } - - return { rekeys, conflicts }; -} - -// Human-readable summary for stdout. Empty report renders nothing — callers -// can unconditionally log. -export function formatRecanonicalizeReport( - report: RecanonicalizeReport, -): string { - if (report.rekeys.length === 0 && report.conflicts.length === 0) return ""; - - const lines: string[] = []; - if (report.rekeys.length > 0) { - lines.push( - `🔧 Recanonicalized ${report.rekeys.length} state key(s) — collapsed UUID-suffixed slug back to canonical:`, - ); - for (const r of report.rekeys) { - lines.push(` ${r.type}/${r.fromKey} → ${r.type}/${r.toKey}`); - } - } - if (report.conflicts.length > 0) { - lines.push( - `⚠️ ${report.conflicts.length} UUID-suffixed state key(s) NOT recanonicalized (manual resolution required):`, - ); - for (const c of report.conflicts) { - const hint = - c.reason === "canonical-slug-claimed-by-different-uuid" - ? `canonical slug ${c.canonicalKey} already claimed by a different dashboard UUID (legitimate same-name twin)` - : c.reason === "both-local-files-exist" - ? `both ${c.canonicalKey}.{yml,yaml,ts,md} and ${c.uuidSuffixedKey}.{yml,yaml,ts,md} exist — pick one and delete the other before next push` - : `no local file at ${c.canonicalKey}.{yml,yaml,ts,md} — state entry is stale; either restore the file or remove the state entry`; - lines.push(` ${c.type}/${c.uuidSuffixedKey}: ${hint}`); - } - } - return lines.join("\n"); -} diff --git a/src/reconcile-state-key.ts b/src/reconcile-state-key.ts index 6aba897..aca922f 100644 --- a/src/reconcile-state-key.ts +++ b/src/reconcile-state-key.ts @@ -1,36 +1,9 @@ -// Generic state-key reconciliation for auto-applied dependencies. -// -// Both `ensureToolExists` and `ensureStructuredOutputExists` in `push.ts` -// share a 94-line body that: -// -// 1. Probes for an existing dashboard / state resource whose canonical -// name matches the local payload (`findExistingResourceByName`), so a -// bootstrap-renamed state entry (`-`) or a live dashboard -// twin isn't shadowed by a brand-new POST. -// 2. On match: rekeys state to the adopted UUID, runs the orphan-deletion -// guard (drop OTHER state keys pointing at the same UUID so a -// subsequent push doesn't DELETE the freshly-adopted dashboard -// resource), and PATCHes via the standard apply path so drift -// detection fires. -// 3. On no match: logs the auto-apply line and runs the standard apply -// path (which creates). -// 4. In BOTH branches: records `autoApplied` even when the apply returns -// `null` (the apply-path short-circuit that signals "skipped"), then -// conditionally updates state with the post-PATCH hash, increments the -// applied counter, pushes onto the per-type bookkeeping array, and -// marks the local resourceId touched. -// -// The two functions differ only in: resource type label (singular + plural -// for log lines), state section, remote list fetcher, the per-type counter -// in `applied`, the per-type bookkeeping array, and the apply function. -// This module extracts the shared body — narrowed to `tools` / -// `structuredOutputs` because those are the only two auto-apply paths in -// the engine today. +// Reuse repo-owned dependency mappings; all other name matches require adoption. import type { RemoteResource } from "./dep-dedup.ts"; import { - extractResourceName, findExistingResourceByName, + warnUnownedNameMatches, } from "./dep-dedup.ts"; import { upsertState } from "./state.ts"; import type { TouchedSets } from "./state-merge.ts"; @@ -112,11 +85,10 @@ export async function reconcileStateKeyForResource( pushToAutoAppliedList, getRemoteList, applyFn, - vapiEnv, formatError, } = opts; - const { singular, plural } = LABELS[resourceType]; + const { singular } = LABELS[resourceType]; const stateSection = state[resourceType]; const touchedSection = touched[resourceType]; const resourceId = resource.resourceId; @@ -134,13 +106,16 @@ export async function reconcileStateKeyForResource( remoteList, }); + warnUnownedNameMatches({ + resourceType, + localResourceId: resourceId, + localPayload: resource.data, + stateSection, + remoteList, + reusedUuid: match?.uuid, + }); + if (match) { - if (match.ambiguous) { - const displayName = extractResourceName(resource.data) ?? resourceId; - console.warn( - ` ⚠️ Multiple ${plural} share the name "${displayName}" — adopting ${match.uuid} (lex-smallest). Other UUIDs: ${match.duplicateUuids.join(", ")}. Run \`npm run cleanup -- ${vapiEnv}\` to prune duplicates.`, - ); - } console.log( ` 🔁 Reusing existing ${singular}: ${resourceId} → ${match.uuid} (matched via ${match.source})`, ); @@ -148,7 +123,10 @@ export async function reconcileStateKeyForResource( // Re-key state to point at the adopted UUID under the local resourceId. // No hash yet — `applyFn` below will PATCH with the local payload and // record the post-PATCH hash, exercising the standard drift-check flow. - upsertState(stateSection, resourceId, { uuid: match.uuid }); + upsertState(stateSection, resourceId, { + uuid: match.uuid, + origin: match.origin, + }); // Orphan-deletion guard — drop other state keys pointing at the SAME // uuid so a subsequent full push doesn't see them as "tracked but no diff --git a/src/state-serialize.ts b/src/state-serialize.ts index 9320fff..4e7285f 100644 --- a/src/state-serialize.ts +++ b/src/state-serialize.ts @@ -58,7 +58,7 @@ export function hashPayload(payload: unknown): string { return createHash("sha256").update(JSON.stringify(canonical)).digest("hex"); } -// Normalize a state value to the slim `{ uuid }` shape. Accepts a bare string +// Normalize a state value, preserving optional provenance. Accepts a bare string // (oldest legacy form) or an object with a `uuid` field, and discards any other // fields a legacy file may still carry (lastPulledHash, lastPulledAt, // lastPushedHash). Returns undefined if no uuid can be recovered — at load time @@ -72,20 +72,27 @@ export function asResourceState(value: unknown): ResourceState | undefined { typeof value === "object" && typeof (value as { uuid?: unknown }).uuid === "string" ) { - return { uuid: (value as { uuid: string }).uuid }; + const { uuid, origin } = value as ResourceState; + return { + uuid, + ...(origin === "pushed" || origin === "pulled" || origin === "adopted" + ? { origin } + : {}), + }; } return undefined; } -// Set the `{ uuid }` mapping for a resource. The state file no longer carries -// any per-resource field beyond the UUID, so this is a plain assignment — the -// drift baseline now lives in the hash store, not here. +// Preserve provenance on existing entries, including legacy entries without it. export function upsertState( section: Record, resourceId: string, patch: ResourceState, ): void { - section[resourceId] = { uuid: patch.uuid }; + const existing = section[resourceId]; + section[resourceId] = asResourceState( + existing ? { uuid: patch.uuid, origin: existing.origin } : patch, + )!; } // Pronunciation-dictionary drop check. Detects when a dictionary attachment diff --git a/src/stop-report.ts b/src/stop-report.ts new file mode 100644 index 0000000..3a2547e --- /dev/null +++ b/src/stop-report.ts @@ -0,0 +1,60 @@ +export interface StopIssue { + file: string; + resourceType: string; + problem: string; + fix: string; + command: string; + args?: string[]; + needsChoice?: boolean; +} + +export const shellQuote = (value: string): string => + /^[a-zA-Z0-9_./=-]+$/.test(value) + ? value + : `'${value.replaceAll("'", "'\\''")}'`; + +export function formatStopReport(issues: StopIssue[], org: string): string { + const lines = [ + `Push stopped: review ${issues.length} file(s) for ${org}. Exit code: 1.`, + "The engine cannot tell new / renamed / stale files apart; pushing an unlinked file would create a new resource.", + "Nothing has been changed by this preflight check.", + "", + ]; + for (const issue of issues) + lines.push( + `- ${issue.file} (${issue.resourceType})`, + ` ${issue.problem}`, + ` Fix: ${issue.fix}`, + ` Command: ${issue.command}`, + ); + const choices = issues.filter((issue) => issue.needsChoice || !issue.args); + if (choices.length) + lines.push( + "", + `Human choice needed: ${choices.map((issue) => issue.file).join(", ")}`, + ); + else { + const args = [...new Set(issues.flatMap((issue) => issue.args!))]; + lines.push( + "", + `Suggested command (review and approve first): npm run push -- ${shellQuote(org)} ${args.join(" ")}`, + ); + } + lines.push( + "", + "Do not auto-pass --adopt or --allow-new-files; get explicit approval.", + ); + return lines.join("\n"); +} + +export function jsonStopReport(issues: StopIssue[]): string { + return JSON.stringify( + issues.map(({ file, resourceType, problem, fix, command }) => ({ + file, + resourceType, + problem, + fix, + command, + })), + ); +} diff --git a/src/types.ts b/src/types.ts index 6b8cd1c..8da6fba 100644 --- a/src/types.ts +++ b/src/types.ts @@ -20,6 +20,7 @@ // store from the old hashes. export interface ResourceState { uuid: string; + origin?: "pushed" | "pulled" | "adopted"; } // `StateFile` is the on-disk shape of `.vapi-state..json`. Each section diff --git a/tests/adopt.test.ts b/tests/adopt.test.ts new file mode 100644 index 0000000..cf15b55 --- /dev/null +++ b/tests/adopt.test.ts @@ -0,0 +1,156 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { adoptResources, parseAdoptArgs } from "../src/adopt.ts"; +import type { RemoteResource } from "../src/dep-dedup.ts"; +import type { TouchedSets } from "../src/state-merge.ts"; +import type { LoadedResources, ResourceType, StateFile } from "../src/types.ts"; +import { VALID_RESOURCE_TYPES } from "../src/types.ts"; + +function fixture() { + const state = Object.fromEntries( + ["credentials", ...VALID_RESOURCE_TYPES].map((t) => [t, {}]), + ) as unknown as StateFile; + const resources = Object.fromEntries( + VALID_RESOURCE_TYPES.map((t) => [t, []]), + ) as unknown as LoadedResources; + resources.tools.push({ + resourceId: "stop", + filePath: "tools/stop.yml", + data: { function: { name: "End Call" } }, + }); + const touched = Object.fromEntries( + ["credentials", ...VALID_RESOURCE_TYPES].map((t) => [t, new Set()]), + ) as unknown as TouchedSets; + return { + state, + resources, + touched, + targets: ["stop"], + dryRun: false, + getRemoteList: async (_type: ResourceType): Promise => [ + { id: "remote", function: { name: "End Call" } }, + ], + }; +} + +test("adopt argument forms are repeatable and malformed values fail", () => { + assert.deepEqual( + parseAdoptArgs([ + "--adopt", + "stop", + "--adopt=agent=id", + "--adopt", + "other=uuid", + ]), + ["stop", "agent=id", "other=uuid"], + ); + for (const args of [ + ["--adopt"], + ["--adopt="], + ["--adopt", "--dry-run"], + ["--adopt=x="], + ["--adopt=x=y=z"], + ]) { + assert.throws(() => parseAdoptArgs(args), /requires/); + } + assert.deepEqual(parseAdoptArgs(["--dry-run", "tools"]), []); +}); + +test("single candidate is adopted, aliases removed, and scoped touched sets populated", async () => { + const f = fixture(); + f.state.tools["stop-abcd1234"] = { uuid: "remote", origin: "pulled" }; + f.state.tools.alias = { uuid: "remote" }; + f.state.tools.unrelated = { uuid: "other" }; + await adoptResources(f); + assert.deepEqual(f.state.tools.stop, { uuid: "remote", origin: "adopted" }); + assert.equal(f.state.tools["stop-abcd1234"], undefined); + assert.equal(f.state.tools.alias, undefined); + assert.deepEqual([...f.touched.tools].sort(), [ + "alias", + "stop", + "stop-abcd1234", + ]); + assert.deepEqual(f.state.tools.unrelated, { uuid: "other" }); +}); + +test("explicit UUID selects an existing remote even with a different name", async () => { + const f = fixture(); + f.targets = ["stop=chosen"]; + f.getRemoteList = async () => [ + { id: "remote", name: "End Call" }, + { id: "chosen", name: "Different" }, + ]; + await adoptResources(f); + assert.deepEqual(f.state.tools.stop, { uuid: "chosen", origin: "adopted" }); +}); + +test("ambiguous, missing, already linked, nonexistent UUID, and absent file all fail without linking", async () => { + const cases = [ + { + setup: (f: ReturnType) => { + f.getRemoteList = async () => [ + { id: "a", name: "End Call" }, + { id: "b", name: "End Call" }, + ]; + }, + error: /ambiguous candidates: a, b.*--adopt stop=/, + }, + { + setup: (f: ReturnType) => { + f.getRemoteList = async () => []; + }, + error: /no candidates/, + }, + { + setup: (f: ReturnType) => { + f.state.tools.stop = { uuid: "linked" }; + }, + error: /already linked/, + }, + { + setup: (f: ReturnType) => { + f.targets = ["stop=absent"]; + }, + error: /does not exist remotely/, + }, + { + setup: (f: ReturnType) => { + f.targets = ["absent"]; + }, + error: /no such file/, + }, + ]; + for (const { setup, error } of cases) { + const f = fixture(); + setup(f); + const before = structuredClone(f.state); + await assert.rejects(adoptResources(f), error); + assert.deepEqual(f.state, before); + } +}); + +test("dry run looks up candidates and returns a preview without mutating state or touched", async () => { + const f = fixture(); + f.dryRun = true; + let lookups = 0; + f.getRemoteList = async () => { + lookups++; + return [{ id: "remote", name: "End Call" }]; + }; + const preview = await adoptResources(f); + assert.equal(lookups, 1); + assert.deepEqual(f.state.tools, {}); + assert.equal(f.touched.tools.size, 0); + assert.deepEqual(preview.tools.stop, { uuid: "remote", origin: "adopted" }); +}); + +test("empty targets do not query; lookup errors fail closed", async () => { + const f = fixture(); + f.getRemoteList = async () => { + throw new Error("lookup failed"); + }; + f.targets = []; + await adoptResources(f); + f.targets = ["stop"]; + await assert.rejects(adoptResources(f), /lookup failed/); +}); diff --git a/tests/dep-dedup.test.ts b/tests/dep-dedup.test.ts index 40db393..f7319f5 100644 --- a/tests/dep-dedup.test.ts +++ b/tests/dep-dedup.test.ts @@ -43,157 +43,54 @@ test("extractResourceName: top-level name wins over function.name", () => { ); }); -test("findExistingResourceByName: assistant payload (top-level name only)", () => { - // Assistants use top-level `name` and have no nested `function`. The - // squad → assistant auto-apply path hits this shape via - // ensureAssistantExists. Bootstrap may store the same dashboard assistant - // under `-` (e.g., `support-bot-1234abcd`); a squad - // referencing the original local key (`support-bot`) must adopt rather - // than mint a duplicate. - const m = findExistingResourceByName({ - localResourceId: "support-bot", - localPayload: { name: "support-bot" }, - stateSection: { - "support-bot-1234abcd": { uuid: "uuid-asst-aaa" }, - }, - remoteList: [{ id: "uuid-asst-aaa", name: "support-bot" }], +for (const origin of ["pushed", "adopted"] as const) { + test(`owned ${origin} state match can be reused without dashboard authorization`, () => { + const match = findExistingResourceByName({ + localResourceId: "stop", + localPayload: { name: "Stop" }, + stateSection: { "stop-abcd1234": { uuid: "abcd1234", origin } }, + remoteList: [{ id: "different", name: "Stop" }], + }); + assert.equal(match?.uuid, "abcd1234"); + assert.equal(match?.origin, origin); + assert.equal(match?.source, "state"); }); - assert.equal(m?.uuid, "uuid-asst-aaa"); - assert.equal(m?.source, "both"); - assert.equal(m?.ambiguous, false); -}); - -test("findExistingResourceByName: state-only match", () => { - const m = findExistingResourceByName({ - localResourceId: "b2b-invoice-end-call", - localPayload: { function: { name: "end-call" } }, - stateSection: { - "end-call-67aea057": { uuid: "uuid-aaa" }, - }, - }); - assert.deepEqual(m, { - uuid: "uuid-aaa", - source: "state", - ambiguous: false, - duplicateUuids: [], +} +for (const origin of ["pulled", undefined] as const) { + test(`unowned ${origin} state and dashboard name matches cannot be reused`, () => { + assert.equal( + findExistingResourceByName({ + localResourceId: "stop", + localPayload: { name: "Stop" }, + stateSection: { + "stop-abcd1234": { uuid: "abcd1234", ...(origin ? { origin } : {}) }, + }, + remoteList: [{ id: "abcd1234", name: "Stop" }], + }), + undefined, + ); }); +} +test("dashboard alone never authorizes reuse", () => { + assert.equal( + findExistingResourceByName({ + localResourceId: "stop", + localPayload: { function: { name: "Stop" } }, + stateSection: {}, + remoteList: [{ id: "remote", function: { name: "Stop" } }], + }), + undefined, + ); }); - -test("findExistingResourceByName: dashboard-only match", () => { - const m = findExistingResourceByName({ - localResourceId: "end-call", - localPayload: { function: { name: "end-call" } }, - stateSection: {}, - remoteList: [{ id: "uuid-bbb", function: { name: "end-call" } }], - }); - assert.deepEqual(m, { - uuid: "uuid-bbb", - source: "dashboard", - ambiguous: false, - duplicateUuids: [], - }); -}); - -test("findExistingResourceByName: state and dashboard both match same uuid", () => { - const m = findExistingResourceByName({ - localResourceId: "end-call", - localPayload: { function: { name: "end-call" } }, - stateSection: { "end-call-67aea057": { uuid: "uuid-aaa" } }, - remoteList: [{ id: "uuid-aaa", function: { name: "end-call" } }], - }); - assert.equal(m?.source, "both"); - assert.equal(m?.ambiguous, false); -}); - -test("findExistingResourceByName: ambiguous → lex-smallest UUID + duplicates surfaced", () => { - const m = findExistingResourceByName({ - localResourceId: "end-call", - localPayload: { function: { name: "end-call" } }, - stateSection: { - "end-call-67aea057": { uuid: "uuid-zzz" }, - "end-call-16ff08ed": { uuid: "uuid-aaa" }, - }, - }); - assert.equal(m?.uuid, "uuid-aaa"); - assert.equal(m?.ambiguous, true); - assert.deepEqual(m?.duplicateUuids, ["uuid-zzz"]); -}); - -test("findExistingResourceByName: no name on payload → undefined", () => { - const m = findExistingResourceByName({ - localResourceId: "x", - localPayload: {}, - stateSection: { "end-call-67aea057": { uuid: "uuid-aaa" } }, - }); - assert.equal(m, undefined); -}); - -test("findExistingResourceByName: localResourceId exact match excluded (caller's job)", () => { - const m = findExistingResourceByName({ - localResourceId: "end-call-67aea057", - localPayload: { function: { name: "end-call" } }, - stateSection: { "end-call-67aea057": { uuid: "uuid-aaa" } }, - }); - // Helper excludes the exact-key, leaving no match. Caller should have - // short-circuited on the exact-key check before calling. - assert.equal(m, undefined); -}); - -test("findExistingResourceByName: no match → undefined", () => { - const m = findExistingResourceByName({ - localResourceId: "transfer-to-sales", - localPayload: { function: { name: "transfer-to-sales" } }, - stateSection: { "end-call-67aea057": { uuid: "uuid-aaa" } }, - remoteList: [{ id: "uuid-bbb", function: { name: "voicemail" } }], - }); - assert.equal(m, undefined); -}); - -test("findExistingResourceByName: ambiguous across state vs dashboard → lex-smallest, both surfaced", () => { - // State has one UUID under a bootstrap-renamed key, dashboard has a - // distinct UUID under the same canonical name (real on-dashboard - // duplicate from a prior bug run). Both must surface in duplicateUuids - // and the winner must be lex-smallest. Source must be "both" only when - // the SAME uuid appears in both — here the winner appears in only one, - // so source is whichever side it came from. - const m = findExistingResourceByName({ - localResourceId: "b2b-invoice-end-call", - localPayload: { function: { name: "end-call" } }, - stateSection: { "end-call-67aea057": { uuid: "uuid-zzz" } }, - remoteList: [{ id: "uuid-aaa", function: { name: "end-call" } }], - }); - assert.equal(m?.uuid, "uuid-aaa"); - assert.equal(m?.ambiguous, true); - assert.equal(m?.source, "dashboard"); - assert.deepEqual(m?.duplicateUuids, ["uuid-zzz"]); -}); - -test("findExistingResourceByName: empty stateSection AND empty remoteList → undefined", () => { - // Defensive: a fresh push with no prior state and no dashboard population - // must short-circuit to undefined so the auto-create path runs. - const m = findExistingResourceByName({ - localResourceId: "anything", - localPayload: { function: { name: "anything" } }, - stateSection: {}, - remoteList: [], - }); - assert.equal(m, undefined); -}); - -test("findExistingResourceByName: remote payload uses top-level `name` (not function.name)", () => { - // Pull-side / dashboard list payloads for non-tool resources (and some - // tool list endpoints) expose `name` directly instead of nested in - // `function.name`. The dedup helper must recognize both shapes. - const m = findExistingResourceByName({ - localResourceId: "post-call-summary", - localPayload: { name: "post-call-summary" }, - stateSection: {}, - remoteList: [{ id: "uuid-ccc", name: "post-call-summary" }], - }); - assert.deepEqual(m, { - uuid: "uuid-ccc", - source: "dashboard", - ambiguous: false, - duplicateUuids: [], - }); +test("no name, no match, and exact-key entries do not authorize alias reuse", () => { + for (const localPayload of [{}, { name: "Other" }, { name: "Stop" }]) { + assert.equal( + findExistingResourceByName({ + localResourceId: "stop", + localPayload, + stateSection: { stop: { uuid: "uuid", origin: "pushed" } }, + }), + undefined, + ); + } }); diff --git a/tests/find-existing-resource-id.test.ts b/tests/find-existing-resource-id.test.ts deleted file mode 100644 index 2fd4cba..0000000 --- a/tests/find-existing-resource-id.test.ts +++ /dev/null @@ -1,172 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import type { ResourceState } from "../src/types.ts"; - -// pull.ts depends on config.ts which calls process.exit(1) at module load -// time if VAPI_TOKEN is not set or if argv[2] is not a valid slug. Set both -// before dynamic-importing the module under test. Same pattern as -// `clean-resource.test.ts`. -process.argv = ["node", "test", "test-fixture-org"]; -process.env.VAPI_TOKEN = process.env.VAPI_TOKEN || "test-token-not-used"; - -const { findExistingResourceId } = await import("../src/pull.ts"); - -// Helper: build a minimal resource shape with the id+name fields the function -// reads. Other fields are irrelevant for adoption logic. -function resource(id: string, name: string) { - return { id, name }; -} - -function stateEntry(uuid: string): ResourceState { - return { uuid }; -} - -// ───────────────────────────────────────────────────────────────────────────── -// Adoption: positive cases (the function reuses an on-disk file's slug) -// ───────────────────────────────────────────────────────────────────────────── - -test("adoption: state empty, one file matches name → adopt (cross-env pull)", () => { - // Classic cross-env pull: dev shipped a file `riley-8102e715.md`, prod is - // a fresh clone with no state entry for it. Pull should reuse the file - // even though the UUID-suffix on disk differs from prod's UUID. - const onDisk = ["riley-8102e715"]; - const newState: Record = {}; - const result = findExistingResourceId( - onDisk, - resource("uuid-prod-aaaa", "Riley"), - newState, - ); - assert.equal(result, "riley-8102e715"); -}); - -test("adoption: file claimed in state by the SAME UUID → adopt (re-pull is idempotent)", () => { - // Second pull of an already-tracked resource. State maps the slug to - // THIS resource's UUID, so reusing the slug is correct. - const onDisk = ["riley"]; - const newState: Record = { - riley: stateEntry("uuid-aaaa"), - }; - const result = findExistingResourceId( - onDisk, - resource("uuid-aaaa", "Riley"), - newState, - ); - assert.equal(result, "riley"); -}); - -test("adoption: two matches but only one is adoptable (the unclaimed one) → adopt it", () => { - // The dashboard has 2 same-named resources. The first was already - // processed earlier in this same pull loop and adopted `riley.md`. - // Now a different file `riley-deadbeef.md` (e.g. from cross-env pull - // history) is on disk, unclaimed in state, and the current resource - // can adopt it without conflict. - const onDisk = ["riley", "riley-deadbeef"]; - const newState: Record = { - riley: stateEntry("uuid-aaaa"), - }; - const result = findExistingResourceId( - onDisk, - resource("uuid-bbbb", "Riley"), - newState, - ); - assert.equal(result, "riley-deadbeef"); -}); - -// ───────────────────────────────────────────────────────────────────────────── -// No adoption: the fix's core case + the existing 0-or-2+ behavior -// ───────────────────────────────────────────────────────────────────────────── - -test("no adoption: file claimed by DIFFERENT UUID → undefined (the fix's main case)", () => { - // This is the clobber scenario the fix prevents: state already maps - // `riley` to UUID A; a new resource with the same name but a NEW UUID - // (B) must NOT adopt `riley.md` — doing so would overwrite A's content. - const onDisk = ["riley"]; - const newState: Record = { - riley: stateEntry("uuid-aaaa"), - }; - const result = findExistingResourceId( - onDisk, - resource("uuid-bbbb", "Riley"), - newState, - ); - assert.equal(result, undefined); -}); - -test("no adoption: N+ matches with mixed claims → undefined", () => { - // Two on-disk files both name-match. One is unclaimed (adoptable), - // one is claimed by a different UUID (NOT adoptable). But ALSO a - // third match exists, claimed by yet another different UUID. With - // multiple adoptable candidates the 1:1 ambiguity guard still kicks - // in. Here we test a related shape: 2 adoptable matches → ambiguous. - const onDisk = ["riley", "riley-aaaa1111", "riley-bbbb2222"]; - const newState: Record = { - riley: stateEntry("uuid-other"), - // riley-aaaa1111 and riley-bbbb2222 are both unclaimed → 2 adoptable - }; - const result = findExistingResourceId( - onDisk, - resource("uuid-cccc", "Riley"), - newState, - ); - assert.equal(result, undefined); -}); - -test("no adoption: N+ matches but all claimed by other UUIDs → undefined", () => { - // Every name-matching file is claimed by some other UUID. No file is - // adoptable for the current resource; fall through to - // generateResourceId in the caller. - const onDisk = ["riley", "riley-aaaa1111"]; - const newState: Record = { - riley: stateEntry("uuid-aaaa"), - "riley-aaaa1111": stateEntry("uuid-bbbb"), - }; - const result = findExistingResourceId( - onDisk, - resource("uuid-cccc", "Riley"), - newState, - ); - assert.equal(result, undefined); -}); - -test("no adoption: no name-matching files on disk → undefined", () => { - const onDisk = ["alex", "morgan-1234abcd"]; - const newState: Record = {}; - const result = findExistingResourceId( - onDisk, - resource("uuid-aaaa", "Riley"), - newState, - ); - assert.equal(result, undefined); -}); - -// ───────────────────────────────────────────────────────────────────────────── -// Edge cases (regression guards, unchanged behavior) -// ───────────────────────────────────────────────────────────────────────────── - -test("regression: resource without a name → undefined (unchanged)", () => { - // Tools store their name under function.name (see extractName). A - // resource with neither a top-level name nor a function.name is - // un-adoptable by design — no slug to compute. - const onDisk = ["riley"]; - const newState: Record = {}; - const result = findExistingResourceId( - onDisk, - { id: "uuid-aaaa" }, // no name - newState, - ); - assert.equal(result, undefined); -}); - -test("regression: two same-name files, state empty → undefined (unchanged ambiguity)", () => { - // Pre-fix behavior: 2+ matches without a state discriminator → ambiguous, - // refuse adoption. Fix should preserve this — both files are adoptable - // (unclaimed), so `adoptable.length === 2` and the 1:1 guard fires. - const onDisk = ["riley", "riley-deadbeef"]; - const newState: Record = {}; - const result = findExistingResourceId( - onDisk, - resource("uuid-aaaa", "Riley"), - newState, - ); - assert.equal(result, undefined); -}); diff --git a/tests/name-collisions.test.ts b/tests/name-collisions.test.ts new file mode 100644 index 0000000..b4883b6 --- /dev/null +++ b/tests/name-collisions.test.ts @@ -0,0 +1,56 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { NameCollisionReport } from "../src/name-collisions.ts"; + +test("empty or nonmatching POST plans report no collisions", async () => { + const report = new NameCollisionReport(async () => [ + { id: "other", name: "Other" }, + ]); + assert.equal(await report.format(), "Name collisions: none"); + report.recordPost("assistants", "reception", { name: "Reception" }, {}); + assert.equal(await report.format(), "Name collisions: none"); +}); + +test("collision report includes state and live matches by slug, deduplicated per POST", async () => { + let calls = 0; + const report = new NameCollisionReport(async () => { + calls++; + return [ + { id: "shared", function: { name: "Call_Helper" } }, + { id: "live", name: "Call Helper" }, + ]; + }); + report.recordPost( + "tools", + "helper", + { function: { name: "call-helper" } }, + { + "call-helper-aaaaaaaa": { uuid: "shared", origin: "pulled" }, + "call-helper-bbbbbbbb": { uuid: "state-only" }, + "call-helper-cccccccc": { uuid: "dry-run-post-1" }, + "other-dddddddd": { uuid: "not-a-match" }, + }, + ); + report.recordPost("tools", "helper-two", { name: "Call Helper" }, {}); + const output = await report.format(); + assert.match( + output, + /tools "Call_Helper" \(shared\): helper would create a new resource; --adopt helper to take this over/, + ); + assert.match(output, /\(state-only\)/); + assert.match(output, /\(live\)/); + assert.doesNotMatch(output, /dry-run-post|not-a-match/); + assert.equal(output.match(/\(shared\): helper /g)?.length, 1); + assert.equal(calls, 1); +}); + +test("failed inventory lookup reports an incomplete check rather than none", async () => { + const report = new NameCollisionReport(async () => { + throw new Error("lookup unavailable"); + }); + report.recordPost("squads", "triage", { name: "Triage" }, {}); + const output = await report.format(); + assert.match(output, /Inventory unavailable for squads: lookup unavailable/); + assert.match(output, /Collision check incomplete/); + assert.doesNotMatch(output, /Name collisions: none/); +}); diff --git a/tests/new-file-gate.test.ts b/tests/new-file-gate.test.ts index bca14c2..855a23a 100644 --- a/tests/new-file-gate.test.ts +++ b/tests/new-file-gate.test.ts @@ -4,6 +4,7 @@ import { cpSync, mkdirSync, mkdtempSync, + readFileSync, rmSync, symlinkSync, writeFileSync, @@ -340,38 +341,40 @@ test("formatGateMessage: includes all orphan relative paths", () => { assert.ok(out.includes("resources/test/tools/bar.yml")); }); -test("formatGateMessage: includes the rename-sources block with state-only entries", () => { - const out = formatGateMessage(sampleReport(), "test-env", { color: false }); - assert.match(out, /possible rename SOURCES/); - assert.match(out, /assistants\/old-foo/); - // Short UUID display (first 8 chars). - assert.match(out, /64df6206/); +test("formatGateMessage: every file has exact fix commands", () => { + const out = formatGateMessage(sampleReport(), "test-env"); + assert.match( + out, + /npm run push -- test-env --allow-new-files resources\/test\/assistants\/foo.md/, + ); + assert.match(out, /rm -- resources\/test\/tools\/bar.yml/); + assert.doesNotMatch(out, /orphan/i); }); test("formatGateMessage: includes the AI-agent paragraph and the --allow-new-files hint", () => { const out = formatGateMessage(sampleReport(), "test-env", { color: false }); - assert.match(out, /FOR AI AGENTS/); - assert.match(out, /do NOT auto-pass --allow-new-files/); + assert.match(out, /explicit approval/); + assert.match(out, /Do not auto-pass --adopt or --allow-new-files/); assert.match(out, /--allow-new-files/); }); test("formatGateMessage: scopedToPaths=true surfaces the scope note", () => { const report = { ...sampleReport(), scopedToPaths: true }; const out = formatGateMessage(report, "test-env", { color: false }); - assert.match(out, /scoped to the selective-push file set/); + assert.match(out, /Not linked to any resource/); }); test("formatGateMessage: empty rename-sources block prints '(none — …)' message", () => { const report = { ...sampleReport(), possibleRenameSources: [] }; const out = formatGateMessage(report, "test-env", { color: false }); - assert.match(out, /no plausible rename pairings found/); + assert.match(out, /Human choice needed/); }); test("formatGateMessage: environment name appears in the headline", () => { const out = formatGateMessage(sampleReport(), "prod-cluster", { color: false, }); - assert.match(out, /env "prod-cluster"/); + assert.match(out, /for prod-cluster/); }); // ───────────────────────────────────────────────────────────────────────────── @@ -535,9 +538,9 @@ test("integration: orphan + no flag + --dry-run → exit 1, gate fires, no API c 1, `expected exit 1; stdout=${res.stdout}\nstderr=${res.stderr}`, ); - assert.match(res.stderr, /Push refused/); + assert.match(res.stderr, /Push stopped/); assert.match(res.stderr, /resources\/[^/]+\/assistants\/foo\.md/); - assert.match(res.stderr, /FOR AI AGENTS/); + assert.match(res.stderr, /explicit approval/); // The gate must fire BEFORE the apply loops — no "would PATCH/POST" lines // should appear for the orphan. assert.doesNotMatch(res.stdout, /would (PATCH|POST)/); @@ -559,11 +562,11 @@ test("integration: orphan + --allow-new-files + --dry-run → gate bypassed with // gate is the only thing that would exit 1 in this minimal fixture). assert.match( res.stdout, - /bypassing new-file gate/, + /Would create/, `expected bypass notice; stdout=${res.stdout}`, ); // The gate's error message must NOT appear when bypassed. - assert.doesNotMatch(res.stderr, /Push refused/); + assert.doesNotMatch(res.stderr, /Push stopped/); } finally { fx.cleanup(); } @@ -579,7 +582,7 @@ test("integration: orphan + --bootstrap → gate suppressed (bootstrap legitimat try { const res = runPush(fx, ["--dry-run", "--bootstrap"]); // The gate must not fire under --bootstrap. - assert.doesNotMatch(res.stderr, /Push refused/); + assert.doesNotMatch(res.stderr, /Push stopped/); assert.doesNotMatch(res.stdout, /bypassing new-file gate/); } finally { fx.cleanup(); @@ -618,10 +621,42 @@ test("integration: selective push with orphan OUTSIDE the selection → gate doe // the gate must scope to the file set and not block. assert.doesNotMatch( res.stderr, - /Push refused/, + /Push stopped/, `gate should not fire for orphan outside selection; stderr=${res.stderr}`, ); } finally { fx.cleanup(); } }); + +test("integration: bootstrap UUID-suffixed mapping never takes over a local slug", () => { + const state = { + ...stateWithSentinel(), + assistants: { + "foo-abcd1234": { + uuid: "abcd1234-1111-1111-1111-111111111111", + origin: "pulled", + }, + }, + }; + const fx = setupFixture({ + resources: { "assistants/foo.md": MINIMAL_ASSISTANT_FOO }, + state, + }); + try { + const statePath = join(fx.dir, `.vapi-state.${fx.env}.json`); + const before = readFileSync(statePath, "utf8"); + const res = runPush(fx, []); + assert.equal(res.code, 1, res.stdout + res.stderr); + assert.match(res.stderr, /Push stopped/); + assert.match(res.stderr, /NOT linked/); + assert.match(res.stderr, /--adopt foo/); + assert.doesNotMatch( + res.stdout, + /Updating assistant|Creating assistant|PATCH|POST/, + ); + assert.equal(readFileSync(statePath, "utf8"), before); + } finally { + fx.cleanup(); + } +}); diff --git a/tests/pull-same-name-clobber.test.ts b/tests/pull-same-name-clobber.test.ts index 5c20b79..a6bb7c5 100644 --- a/tests/pull-same-name-clobber.test.ts +++ b/tests/pull-same-name-clobber.test.ts @@ -16,6 +16,8 @@ import { dirname, join } from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; import { Worker } from "node:worker_threads"; +import { parseResourceDataFromFile } from "../src/resource-parse.ts"; +import { hashPayload } from "../src/state-serialize.ts"; // ───────────────────────────────────────────────────────────────────────────── // Integration test for the state-aware adoption fix in pull.ts. @@ -55,9 +57,18 @@ function startStub( const http = require('node:http'); const { parentPort, workerData } = require('node:worker_threads'); const routes = workerData.routes; + const requests = []; const server = http.createServer((req, res) => { const url = req.url || ''; const method = (req.method || 'GET').toUpperCase(); + const request = { method, url, body: '' }; + requests.push(request); + req.on('data', chunk => { request.body += chunk.toString(); }); + if (url === '/__requests') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(requests)); + return; + } const match = routes.find( (r) => r.method === method && url.startsWith(r.pathStartsWith), ); @@ -133,6 +144,8 @@ marker:A-original async function runClobberScenario( testName: string, dashboardOrder: "A-first" | "B-first", + untracked = false, + bootstrap = false, ): Promise { const dir = mkdtempSync(join(tmpdir(), "vapi-pull-clobber-")); @@ -164,7 +177,7 @@ async function runClobberScenario( { credentials: {}, assistants: { - riley: { uuid: UUID_A }, + ...(untracked ? {} : { riley: { uuid: UUID_A } }), }, structuredOutputs: {}, tools: {}, @@ -218,7 +231,14 @@ async function runClobberScenario( // content lands there or A's content stays). const res = spawnSync( "node", - ["--import", "tsx", "src/pull.ts", ENV, "--force"], + [ + "--import", + "tsx", + "src/pull.ts", + ENV, + "--force", + ...(bootstrap ? ["--bootstrap"] : []), + ], { cwd: dir, env: { @@ -246,7 +266,7 @@ async function runClobberScenario( const rileyContent = readFileSync(rileyPath, "utf-8"); assert.match( rileyContent, - /marker:A-fresh-from-platform/, + untracked ? /marker:A-original/ : /marker:A-fresh-from-platform/, `[${testName}] riley.md must hold A's content (the file mapped to A in state); got:\n${rileyContent}`, ); assert.doesNotMatch( @@ -255,19 +275,23 @@ async function runClobberScenario( `[${testName}] riley.md must NOT have been clobbered by B; got:\n${rileyContent}`, ); - // B must have landed in its own file `riley-.md`. - const expectedBSlug = `riley-${UUID_B.slice(0, 8)}`; - const bPath = join(assistantsDir, `${expectedBSlug}.md`); - assert.ok( - existsSync(bPath), - `[${testName}] expected B's file at ${bPath}; assistants dir contents: ${readdirSync(assistantsDir).join(", ")}`, - ); - const bContent = readFileSync(bPath, "utf-8"); - assert.match( - bContent, - /marker:B-new-twin/, - `[${testName}] ${expectedBSlug}.md must hold B's content; got:\n${bContent}`, - ); + if (bootstrap) { + assert.deepEqual(readdirSync(assistantsDir), ["riley.md"]); + } else { + // B must have landed in its own file `riley-.md`. + const expectedBSlug = `riley-${UUID_B.slice(0, 8)}`; + const bPath = join(assistantsDir, `${expectedBSlug}.md`); + assert.ok( + existsSync(bPath), + `[${testName}] expected B's file at ${bPath}; assistants dir contents: ${readdirSync(assistantsDir).join(", ")}`, + ); + const bContent = readFileSync(bPath, "utf-8"); + assert.match( + bContent, + /marker:B-new-twin/, + `[${testName}] ${expectedBSlug}.md must hold B's content; got:\n${bContent}`, + ); + } // ── State assertions ───────────────────────────────────────────────── const finalState = JSON.parse( @@ -275,14 +299,23 @@ async function runClobberScenario( ); assert.equal( finalState.assistants.riley?.uuid, - UUID_A, + untracked ? undefined : UUID_A, `[${testName}] state[riley] must still map to A (${UUID_A}); got ${JSON.stringify(finalState.assistants.riley)}`, ); + const expectedBSlug = `riley-${UUID_B.slice(0, 8)}`; assert.equal( finalState.assistants[expectedBSlug]?.uuid, UUID_B, `[${testName}] state[${expectedBSlug}] must map to B (${UUID_B}); got ${JSON.stringify(finalState.assistants[expectedBSlug])}`, ); + assert.equal(finalState.assistants[expectedBSlug].origin, "pulled"); + if (!untracked) + assert.deepEqual(finalState.assistants.riley, { uuid: UUID_A }); + else + assert.equal( + finalState.assistants[`riley-${UUID_A.slice(0, 8)}`].origin, + "pulled", + ); } finally { worker.postMessage({ type: "shutdown" }); await new Promise((resolveShutdown) => { @@ -309,3 +342,566 @@ test("pull: 2 same-name resources (B-first ordering) — fix prevents clobber re // sees `riley.md` as "unclaimed in flight" — but prior state has it). await runClobberScenario("B-first", "B-first"); }); + +test("pull: untracked same-name remote leaves local file alone", async () => { + await runClobberScenario("untracked", "A-first", true); +}); + +test("bootstrap pull: records pulled origin without linking local file", async () => { + await runClobberScenario("bootstrap", "A-first", true, true); +}); + +test("push POST records pushed provenance", async () => { + const dir = mkdtempSync(join(tmpdir(), "vapi-post-origin-")); + cpSync(join(REPO_ROOT, "src"), join(dir, "src"), { recursive: true }); + cpSync(join(REPO_ROOT, "package.json"), join(dir, "package.json")); + symlinkSync( + join(REPO_ROOT, "node_modules"), + join(dir, "node_modules"), + "dir", + ); + const { worker, port } = await startStub([ + { + method: "POST", + pathStartsWith: "/tool", + body: { id: UUID_A, type: "endCall" }, + }, + ]); + try { + const script = ` + process.argv = ["node", "test", "test-origin"]; + const { applyTool } = await import("./src/push.ts"); + const { createEmptyState } = await import("./src/state.ts"); + const state = createEmptyState(); + await applyTool({ resourceId: "stop", data: { type: "endCall" } }, state); + console.log("STATE:" + JSON.stringify(state.tools.stop)); + `; + const result = spawnSync( + "node", + ["--import", "tsx", "--input-type=module", "-e", script], + { + cwd: dir, + encoding: "utf8", + timeout: 30000, + env: { + ...process.env, + VAPI_TOKEN: "fake-token-not-used", + VAPI_BASE_URL: `http://127.0.0.1:${port}`, + }, + }, + ); + assert.equal(result.status, 0, result.stdout + result.stderr); + assert.match( + result.stdout, + /STATE:{"uuid":"aaaaaaaa-1111-1111-1111-111111111111","origin":"pushed"}/, + ); + } finally { + await worker.terminate(); + rmSync(dir, { recursive: true, force: true }); + } +}); + +for (const mode of ["push", "dry-run", "apply"]) { + const dryRun = mode === "dry-run"; + test(`push --adopt integrates lookup, scoped PATCH, provenance in ${mode}`, async () => { + const dir = mkdtempSync(join(tmpdir(), "vapi-adopt-cli-")); + cpSync(join(REPO_ROOT, "src"), join(dir, "src"), { recursive: true }); + cpSync(join(REPO_ROOT, "package.json"), join(dir, "package.json")); + symlinkSync( + join(REPO_ROOT, "node_modules"), + join(dir, "node_modules"), + "dir", + ); + const assistantsDir = join(dir, "resources", ENV, "assistants"); + mkdirSync(assistantsDir, { recursive: true }); + writeFileSync(join(assistantsDir, "riley.md"), PREEXISTING_RILEY_MD); + const statePath = join(dir, `.vapi-state.${ENV}.json`); + const initial = JSON.stringify({ + assistants: { "riley-aaaaaaaa": { uuid: UUID_A, origin: "pulled" } }, + credentials: { fake: { uuid: "cred" } }, + }); + writeFileSync(statePath, initial); + const { worker, port } = await startStub([ + { + method: "GET", + pathStartsWith: `/assistant/${UUID_A}`, + body: rileyDashboardBody(UUID_A, "A"), + }, + { + method: "GET", + pathStartsWith: "/assistant", + body: [rileyDashboardBody(UUID_A, "A")], + }, + { + method: "PATCH", + pathStartsWith: `/assistant/${UUID_A}`, + body: rileyDashboardBody(UUID_A, "patched"), + }, + ]); + try { + const res = spawnSync( + "node", + [ + "--import", + "tsx", + mode === "apply" ? "src/apply.ts" : "src/push.ts", + ENV, + ...(dryRun ? ["--dry-run", "--adopt=riley"] : ["--adopt", "riley"]), + "assistants/riley.md", + ], + { + cwd: dir, + encoding: "utf8", + timeout: 30000, + env: { + ...process.env, + VAPI_PRIVATE_API_KEY: "fake-token-not-used", + VAPI_BASE_URL: `http://127.0.0.1:${port}`, + }, + }, + ); + assert.equal(res.status, 0, res.stdout + res.stderr); + assert.match(res.stdout, dryRun ? /would adopt riley/ : /Adopting riley/); + assert.match(res.stdout, /Updating assistant: riley/); + assert.doesNotMatch(res.stdout, /Creating assistant|Push refused/); + if (dryRun) { + assert.equal(readFileSync(statePath, "utf8"), initial); + assert.match(res.stdout, /would PATCH/); + } else { + const saved = JSON.parse(readFileSync(statePath, "utf8")); + assert.deepEqual(saved.assistants.riley, { + uuid: UUID_A, + origin: "adopted", + }); + assert.equal(saved.assistants["riley-aaaaaaaa"], undefined); + } + } finally { + await worker.terminate(); + rmSync(dir, { recursive: true, force: true }); + } + }); +} + +for (const origin of ["pulled", undefined, "pushed", "dashboard"] as const) { + test(`dependency auto-apply with ${origin} name match uses only owned UUIDs`, async () => { + const dir = mkdtempSync(join(tmpdir(), "vapi-dep-origin-")); + cpSync(join(REPO_ROOT, "src"), join(dir, "src"), { recursive: true }); + cpSync(join(REPO_ROOT, "package.json"), join(dir, "package.json")); + symlinkSync( + join(REPO_ROOT, "node_modules"), + join(dir, "node_modules"), + "dir", + ); + const { worker, port } = await startStub([ + { + method: "POST", + pathStartsWith: "/tool", + body: { id: UUID_B, type: "endCall" }, + }, + { + method: "GET", + pathStartsWith: `/tool/${UUID_A}`, + body: { id: UUID_A, type: "endCall" }, + }, + { + method: "PATCH", + pathStartsWith: `/tool/${UUID_A}`, + body: { id: UUID_A, type: "endCall" }, + }, + ]); + try { + const script = ` + process.argv = ["node", "test", "test-origin"]; + const { applyTool } = await import("./src/push.ts"); + const { reconcileStateKeyForResource } = await import("./src/reconcile-state-key.ts"); + const { createEmptyState } = await import("./src/state.ts"); + const state = createEmptyState(); + ${origin === "dashboard" ? "" : `state.tools["stop-aaaaaaaa"] = ${JSON.stringify({ uuid: UUID_A, ...(origin ? { origin } : {}) })};`} + const touched = Object.fromEntries(Object.keys(state).map(k => [k, new Set()])); + const applied = Object.fromEntries(Object.keys(state).map(k => [k, 0])); + await reconcileStateKeyForResource({ + resourceType: "tools", resource: { resourceId: "stop", filePath: "tools/stop.yml", data: { type: "endCall", function: { name: "stop" } } }, + state, touched, applied, autoApplied: new Set(), pushToAutoAppliedList: () => {}, + getRemoteList: async () => [{ id: "${UUID_A}", function: { name: "stop" } }], + applyFn: applyTool, vapiEnv: "test-origin", formatError: (_,e) => String(e), + }); + console.log("FINAL:" + JSON.stringify(state.tools.stop)); + `; + const res = spawnSync( + "node", + ["--import", "tsx", "--input-type=module", "-e", script], + { + cwd: dir, + encoding: "utf8", + timeout: 30000, + env: { + ...process.env, + VAPI_PRIVATE_API_KEY: "fake-token-not-used", + VAPI_BASE_URL: `http://127.0.0.1:${port}`, + }, + }, + ); + assert.equal(res.status, 0, res.stdout + res.stderr); + assert.match( + res.stdout, + origin === "pushed" ? /Updating tool: stop/ : /Creating tool: stop/, + ); + assert.match( + res.stdout, + new RegExp(origin === "pushed" ? UUID_A : UUID_B), + ); + if (origin !== "pushed") { + assert.match( + res.stderr, + /tools.*stop.*aaaaaaaa-1111-1111-1111-111111111111.*--adopt stop/, + ); + } + } finally { + await worker.terminate(); + rmSync(dir, { recursive: true, force: true }); + } + }); +} + +for (const command of ["push", "apply"]) { + test(`${command} dry-run lists top-level and dependency collisions without writes or mutations`, async () => { + const dir = mkdtempSync(join(tmpdir(), "vapi-collisions-")); + cpSync(join(REPO_ROOT, "src"), join(dir, "src"), { recursive: true }); + cpSync(join(REPO_ROOT, "package.json"), join(dir, "package.json")); + symlinkSync( + join(REPO_ROOT, "node_modules"), + join(dir, "node_modules"), + "dir", + ); + const assistantsDir = join(dir, "resources", ENV, "assistants"); + const toolsDir = join(dir, "resources", ENV, "tools"); + mkdirSync(assistantsDir, { recursive: true }); + mkdirSync(toolsDir, { recursive: true }); + const local = PREEXISTING_RILEY_MD.replace( + "model:\n", + "model:\n toolIds:\n - stop\n", + ); + writeFileSync(join(assistantsDir, "riley.md"), local); + writeFileSync( + join(toolsDir, "stop.yml"), + "type: endCall\nfunction:\n name: stop\n", + ); + const statePath = join(dir, `.vapi-state.${ENV}.json`); + const initial = JSON.stringify({ + assistants: { "riley-aaaaaaaa": { uuid: UUID_A, origin: "pulled" } }, + tools: { "stop-aaaaaaaa": { uuid: UUID_A, origin: "pulled" } }, + credentials: { fake: { uuid: "cred" } }, + }); + writeFileSync(statePath, initial); + const { worker, port } = await startStub([ + { + method: "GET", + pathStartsWith: "/assistant", + body: [rileyDashboardBody(UUID_A, "existing")], + }, + { + method: "GET", + pathStartsWith: "/tool", + body: [{ id: UUID_B, type: "endCall", function: { name: "stop" } }], + }, + ]); + try { + const res = spawnSync( + "node", + [ + "--import", + "tsx", + `src/${command}.ts`, + ENV, + "--dry-run", + "--allow-new-files", + "assistants/riley.md", + ], + { + cwd: dir, + encoding: "utf8", + timeout: 30000, + env: { + ...process.env, + VAPI_PRIVATE_API_KEY: "fake-token-not-used", + VAPI_BASE_URL: `http://127.0.0.1:${port}`, + }, + }, + ); + assert.equal(res.status, 0, res.stdout + res.stderr); + const section = res.stdout.slice( + res.stdout.lastIndexOf("Name collisions:"), + ); + assert.match( + section, + new RegExp( + `assistants "Riley" \\(${UUID_A}\\).*would create a new resource; --adopt riley to take this over`, + ), + ); + assert.match( + section, + new RegExp(`tools "stop" \\(${UUID_A}\\).*--adopt stop`), + ); + assert.match( + section, + new RegExp(`tools "stop" \\(${UUID_B}\\).*--adopt stop`), + ); + assert.equal(readFileSync(statePath, "utf8"), initial); + assert.equal( + readFileSync(join(assistantsDir, "riley.md"), "utf8"), + local, + ); + const requests = (await ( + await fetch(`http://127.0.0.1:${port}/__requests`) + ).json()) as { method: string; url: string }[]; + assert.ok(requests.some((r) => r.url.startsWith("/tool"))); + assert.ok(requests.some((r) => r.url.startsWith("/assistant"))); + assert.ok( + requests.every((r) => r.method === "GET"), + JSON.stringify(requests), + ); + assert.equal(existsSync(join(dir, ".vapi-state-hash")), false); + } finally { + await worker.terminate(); + rmSync(dir, { recursive: true, force: true }); + } + }); +} + +for (const mode of [ + "push", + "apply", + "dry-run", + "dry-run-json", + "edited", + "missing-baseline", + "automatic", + "edited-apply", + "grouped-json", + "grouped-text", + "grouped-apply", + "grouped-safe", + "suggestions", + "suggestions-approved", + "ambiguous", +]) { + test(`adoption cleans alias files safely: ${mode}`, async () => { + const dir = mkdtempSync(join(tmpdir(), "vapi-alias-")); + cpSync(join(REPO_ROOT, "src"), join(dir, "src"), { recursive: true }); + cpSync(join(REPO_ROOT, "package.json"), join(dir, "package.json")); + symlinkSync( + join(REPO_ROOT, "node_modules"), + join(dir, "node_modules"), + "dir", + ); + const assistants = join(dir, "resources", ENV, "assistants"); + mkdirSync(assistants, { recursive: true }); + writeFileSync(join(assistants, "riley.md"), PREEXISTING_RILEY_MD); + const alias = join(assistants, "riley-aaaaaaaa.md"); + writeFileSync(alias, PREEXISTING_RILEY_MD.replace("A-original", "A")); + const hashes = join(dir, ".vapi-state-hash", ENV); + mkdirSync(hashes, { recursive: true }); + if (mode !== "missing-baseline") + writeFileSync( + join(hashes, UUID_A), + hashPayload(parseResourceDataFromFile(alias)), + ); + if ( + mode === "edited" || + (mode.startsWith("grouped") && mode !== "grouped-safe") || + mode === "edited-apply" + ) + writeFileSync( + alias, + PREEXISTING_RILEY_MD.replace("A-original", "edited"), + ); + const originalAlias = readFileSync(alias, "utf8"); + const statePath = join(dir, `.vapi-state.${ENV}.json`); + const initial = JSON.stringify({ + assistants: + mode === "automatic" + ? { riley: { uuid: UUID_A, origin: "adopted" } } + : { "riley-aaaaaaaa": { uuid: UUID_A, origin: "pulled" } }, + credentials: { fake: { uuid: "cred" } }, + }); + writeFileSync(statePath, initial); + const { worker, port } = await startStub([ + { + method: "GET", + pathStartsWith: `/assistant/${UUID_A}`, + body: rileyDashboardBody(UUID_A, "A"), + }, + { + method: "GET", + pathStartsWith: "/assistant", + body: [ + rileyDashboardBody(UUID_A, "A"), + ...(mode === "ambiguous" ? [rileyDashboardBody(UUID_B, "B")] : []), + ...(mode === "suggestions-approved" + ? [{ ...rileyDashboardBody(UUID_B, "B"), name: "New Remote" }] + : []), + ], + }, + { + method: "PATCH", + pathStartsWith: "/assistant", + body: rileyDashboardBody(UUID_A, "A-original"), + }, + ]); + const run = (command: string, args: string[]) => + spawnSync( + "node", + ["--import", "tsx", `src/${command}.ts`, ENV, ...args], + { + cwd: dir, + encoding: "utf8", + timeout: 30000, + env: { + ...process.env, + VAPI_PRIVATE_API_KEY: "fake-token-not-used", + VAPI_BASE_URL: `http://127.0.0.1:${port}`, + }, + }, + ); + try { + if (mode === "suggestions-approved") + writeFileSync( + join(assistants, "new.md"), + PREEXISTING_RILEY_MD.replace("name: Riley", "name: New Remote"), + ); + if (mode.startsWith("grouped")) + writeFileSync( + join(assistants, "new.md"), + PREEXISTING_RILEY_MD.replace("name: Riley", "name: Brand New"), + ); + const res = run( + mode === "apply" || mode === "edited-apply" || mode === "grouped-apply" + ? "apply" + : "push", + [ + ...(["automatic", "suggestions", "ambiguous"].includes(mode) + ? [] + : ["--adopt", "riley"]), + ...(mode.startsWith("grouped") + ? ["--adopt", "absent", "--adopt", "other-missing"] + : []), + ...(mode === "grouped-json" || + mode === "grouped-apply" || + mode === "dry-run-json" + ? ["--json"] + : []), + ...(mode === "dry-run" || mode === "dry-run-json" + ? ["--dry-run"] + : []), + ], + ); + const blocked = + mode === "edited" || + mode === "missing-baseline" || + mode === "edited-apply" || + mode === "suggestions" || + mode === "suggestions-approved" || + mode === "ambiguous" || + mode.startsWith("grouped"); + assert.equal(res.status, blocked ? 1 : 0, res.stdout + res.stderr); + if (blocked || mode === "dry-run" || mode === "dry-run-json") { + assert.equal(readFileSync(alias, "utf8"), originalAlias); + assert.equal(readFileSync(statePath, "utf8"), initial); + assert.match( + res.stdout + res.stderr, + mode.startsWith("suggestions") || mode === "ambiguous" + ? /Not linked to any resource/ + : mode === "grouped-safe" + ? /no such file/ + : blocked + ? /Delete it by hand/ + : /would delete .*riley-aaaaaaaa.md/, + ); + if (mode === "dry-run-json") + assert.deepEqual(JSON.parse(res.stdout), []); + const requests = (await ( + await fetch(`http://127.0.0.1:${port}/__requests`) + ).json()) as { method: string }[]; + assert.ok(requests.every((r) => r.method === "GET")); + if (mode !== "missing-baseline") + assert.ok(existsSync(join(hashes, UUID_A))); + if (mode === "grouped-json" || mode === "grouped-apply") { + const issues = JSON.parse(res.stdout); + assert.equal(issues.length, 4, res.stdout); + assert.ok( + issues.some((issue: { file: string }) => + issue.file.endsWith("riley-aaaaaaaa.md"), + ), + ); + assert.ok( + issues.some((issue: { file: string }) => + issue.file.endsWith("new.md"), + ), + ); + assert.ok( + issues.some((issue: { file: string }) => issue.file === "absent"), + ); + assert.doesNotMatch(res.stdout + res.stderr, /orphan/i); + } + if (mode === "suggestions") { + assert.match( + res.stderr, + /Suggested command.*npm run push -- test-clobber --adopt riley resources\/test-clobber\/assistants\/riley.md/, + ); + } + if (mode === "suggestions-approved") { + assert.match( + res.stderr, + /Suggested command.*--adopt riley resources\/test-clobber\/assistants\/riley.md --adopt new resources\/test-clobber\/assistants\/new.md/, + ); + } + if (mode === "ambiguous") { + assert.doesNotMatch(res.stderr, /Suggested command/); + assert.match(res.stderr, new RegExp("--adopt riley=" + UUID_A)); + assert.match(res.stderr, new RegExp("--adopt riley=" + UUID_B)); + assert.match(res.stderr, /Human choice needed/); + } + if (mode === "grouped-text") { + assert.equal(res.stderr.match(/Push stopped:/g)?.length, 1); + assert.doesNotMatch(res.stderr, /Apply failed|orphan/i); + } + } else { + const requests = (await ( + await fetch(`http://127.0.0.1:${port}/__requests`) + ).json()) as { method: string; body: string }[]; + assert.equal( + requests.filter((request) => request.method === "PATCH").length, + 1, + JSON.stringify(requests), + ); + assert.ok( + requests.every( + (request) => request.method === "GET" || request.method === "PATCH", + ), + ); + assert.match( + requests.find((request) => request.method === "PATCH")!.body, + /marker:A-original/, + ); + assert.equal(existsSync(alias), false); + assert.match( + res.stdout, + /Deleted .*riley-aaaaaaaa.md: same remote resource, now adopted as riley/, + ); + assert.deepEqual( + JSON.parse(readFileSync(statePath, "utf8")).assistants, + { riley: { uuid: UUID_A, origin: "adopted" } }, + ); + const next = run("push", []); + assert.doesNotMatch( + next.stdout + next.stderr, + /Push stopped|Files without state entry/, + ); + assert.equal(existsSync(alias), false); + } + } finally { + await worker.terminate(); + rmSync(dir, { recursive: true, force: true }); + } + }); +} diff --git a/tests/recanonicalize.test.ts b/tests/recanonicalize.test.ts deleted file mode 100644 index 076b644..0000000 --- a/tests/recanonicalize.test.ts +++ /dev/null @@ -1,535 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; - -// recanonicalize.ts → config.ts: config.ts asserts argv[2] / VAPI_TOKEN at -// module load. Prime both before importing the module under test. Mirrors -// the pattern in tests/new-file-gate.test.ts. -process.argv = ["node", "test", "test-fixture-org"]; -process.env.VAPI_TOKEN = process.env.VAPI_TOKEN || "test-token-not-used"; - -const { recanonicalizeStateKeys, formatRecanonicalizeReport } = await import( - "../src/recanonicalize.ts" -); - -import type { ResourceState, ResourceType, StateFile } from "../src/types.ts"; - -// ───────────────────────────────────────────────────────────────────────────── -// Helpers — DI-style, filesystem-free. The module exposes a `fileExists` -// seam; tests pass a stub keyed on the relative paths the production code -// would have probed. -// ───────────────────────────────────────────────────────────────────────────── - -function makeStateEntry(uuid: string): ResourceState { - return { uuid }; -} - -function makeStateFile(overrides: Partial = {}): StateFile { - return { - credentials: {}, - assistants: {}, - structuredOutputs: {}, - tools: {}, - squads: {}, - personalities: {}, - scenarios: {}, - simulations: {}, - simulationSuites: {}, - evals: {}, - ...overrides, - }; -} - -function makeFileExists(paths: Set) { - return (relativePath: string): boolean => paths.has(relativePath); -} - -// ───────────────────────────────────────────────────────────────────────────── -// Happy path — the recurring duplicate scenario the fix targets. -// ───────────────────────────────────────────────────────────────────────────── - -test("recanonicalize: collapses UUID-suffixed key to canonical when local file present and canonical slot empty (the duplicate-generation root cause)", () => { - // State has `foo-vmd-004c5108` (rekey'd by a prior pull during a name - // collision). The conflicting twin has since been deleted on the - // dashboard. Local has only `squads/foo-vmd.md`. Canonical slot in state - // is empty. We should collapse. - const state = makeStateFile({ - squads: { - "foo-vmd-004c5108": makeStateEntry( - "004c5108-aaaa-bbbb-cccc-dddddddddddd", - ), - }, - }); - const report = recanonicalizeStateKeys({ - state, - fileExists: makeFileExists(new Set(["squads/foo-vmd.yml"])), - }); - assert.equal(report.rekeys.length, 1); - assert.equal(report.rekeys[0]!.fromKey, "foo-vmd-004c5108"); - assert.equal(report.rekeys[0]!.toKey, "foo-vmd"); - assert.equal(report.conflicts.length, 0); - assert.deepEqual(Object.keys(state.squads), ["foo-vmd"]); - assert.equal( - state.squads["foo-vmd"]!.uuid, - "004c5108-aaaa-bbbb-cccc-dddddddddddd", - ); -}); - -test("recanonicalize: applies uniformly across every resource type", () => { - // One stale UUID-suffixed entry per type. All should collapse — the pass - // is type-agnostic. Folder paths come from FOLDER_MAP so the fileExists - // stub keys must match those folders. - const state = makeStateFile({ - tools: { - "t-aaaaaaaa": makeStateEntry("aaaaaaaa-0000-0000-0000-000000000000"), - }, - structuredOutputs: { - "s-bbbbbbbb": makeStateEntry("bbbbbbbb-0000-0000-0000-000000000000"), - }, - assistants: { - "a-cccccccc": makeStateEntry("cccccccc-0000-0000-0000-000000000000"), - }, - squads: { - "q-dddddddd": makeStateEntry("dddddddd-0000-0000-0000-000000000000"), - }, - personalities: { - "p-eeeeeeee": makeStateEntry("eeeeeeee-0000-0000-0000-000000000000"), - }, - scenarios: { - "sc-ffffffff": makeStateEntry("ffffffff-0000-0000-0000-000000000000"), - }, - simulations: { - "sim-12345678": makeStateEntry("12345678-0000-0000-0000-000000000000"), - }, - simulationSuites: { - "suite-87654321": makeStateEntry("87654321-0000-0000-0000-000000000000"), - }, - evals: { - "e-abcdef01": makeStateEntry("abcdef01-0000-0000-0000-000000000000"), - }, - }); - const fileExists = makeFileExists( - new Set([ - "tools/t.yml", - "structuredOutputs/s.yml", - "assistants/a.md", - "squads/q.yml", - "simulations/personalities/p.yml", - "simulations/scenarios/sc.yml", - "simulations/tests/sim.yml", - "simulations/suites/suite.yml", - "evals/e.yml", - ]), - ); - const report = recanonicalizeStateKeys({ state, fileExists }); - assert.equal(report.rekeys.length, 9); - assert.equal(report.conflicts.length, 0); - // Each section now keyed canonically. - assert.deepEqual(Object.keys(state.tools), ["t"]); - assert.deepEqual(Object.keys(state.structuredOutputs), ["s"]); - assert.deepEqual(Object.keys(state.assistants), ["a"]); - assert.deepEqual(Object.keys(state.squads), ["q"]); - assert.deepEqual(Object.keys(state.personalities), ["p"]); - assert.deepEqual(Object.keys(state.scenarios), ["sc"]); - assert.deepEqual(Object.keys(state.simulations), ["sim"]); - assert.deepEqual(Object.keys(state.simulationSuites), ["suite"]); - assert.deepEqual(Object.keys(state.evals), ["e"]); -}); - -// ───────────────────────────────────────────────────────────────────────────── -// Safety preconditions — each one MUST block the rekey. -// ───────────────────────────────────────────────────────────────────────────── - -test("recanonicalize: refuses when UUID suffix doesn't match entry's UUID prefix (user-named resource that coincidentally ends in -<8hex>)", () => { - // The key looks suffixed but the captured 8 hex chars (`deadbeef`) are - // NOT the prefix of the entry's UUID (`004c5108...`). This is a - // user-given name like "my-tool-deadbeef" — DO NOT touch it. - const state = makeStateFile({ - tools: { - "my-tool-deadbeef": makeStateEntry( - "004c5108-aaaa-bbbb-cccc-dddddddddddd", - ), - }, - }); - const report = recanonicalizeStateKeys({ - state, - fileExists: makeFileExists(new Set(["tools/my-tool.yml"])), - }); - assert.equal(report.rekeys.length, 0); - assert.equal(report.conflicts.length, 0); - assert.deepEqual(Object.keys(state.tools), ["my-tool-deadbeef"]); -}); - -test("recanonicalize: refuses when canonical slug is claimed by a DIFFERENT UUID (legitimate same-name twin)", () => { - // Both `foo` (uuid_A, live) and `foo-bbbbbbbb` (uuid_B, live twin) exist - // in state — the dashboard genuinely has two resources sharing a name. - // Collapsing `foo-bbbbbbbb` onto `foo` would clobber uuid_A. - const state = makeStateFile({ - squads: { - foo: makeStateEntry("aaaaaaaa-0000-0000-0000-000000000000"), - "foo-bbbbbbbb": makeStateEntry("bbbbbbbb-0000-0000-0000-000000000000"), - }, - }); - const report = recanonicalizeStateKeys({ - state, - fileExists: makeFileExists(new Set(["squads/foo.yml"])), - }); - assert.equal(report.rekeys.length, 0); - assert.equal(report.conflicts.length, 1); - assert.equal( - report.conflicts[0]!.reason, - "canonical-slug-claimed-by-different-uuid", - ); - // State unchanged. - assert.deepEqual(Object.keys(state.squads).sort(), ["foo", "foo-bbbbbbbb"]); -}); - -test("recanonicalize: AUTO-RESOLVES when canonical slug claims the SAME UUID (duplicate alias) — the H1 self-inflicted shape", () => { - // After a scoped push that pre-dated the touched-aware fix, state on - // disk can end up with both `foo` and `foo-aaaaaaaa` pointing at the - // SAME uuid_A. This is not a twin — it's one resource aliased twice. - // Safe action: drop the UUID-suffixed key (canonical wins). Reported - // as a rekey, not a conflict. - const canonical = makeStateEntry("aaaaaaaa-0000-0000-0000-000000000000"); - const state = makeStateFile({ - squads: { - foo: canonical, - "foo-aaaaaaaa": makeStateEntry("aaaaaaaa-0000-0000-0000-000000000000"), - }, - }); - const report = recanonicalizeStateKeys({ - state, - // No fileExists probing needed for the auto-resolve branch (skipped - // before files are checked). Pass an empty set to prove that. - fileExists: makeFileExists(new Set()), - }); - assert.equal(report.rekeys.length, 1); - assert.equal(report.rekeys[0]!.fromKey, "foo-aaaaaaaa"); - assert.equal(report.rekeys[0]!.toKey, "foo"); - assert.equal(report.conflicts.length, 0); - // Canonical entry survives unchanged (its metadata is presumed - // authoritative — we discard the stale alias, not merge metadata). - assert.deepEqual(Object.keys(state.squads), ["foo"]); - assert.equal(state.squads["foo"], canonical); -}); - -test("recanonicalize: refuses when canonical local file is missing (would create phantom state mapping)", () => { - const state = makeStateFile({ - squads: { - "foo-aaaaaaaa": makeStateEntry("aaaaaaaa-0000-0000-0000-000000000000"), - }, - }); - // No local files at all. - const report = recanonicalizeStateKeys({ - state, - fileExists: makeFileExists(new Set()), - }); - assert.equal(report.rekeys.length, 0); - assert.equal(report.conflicts.length, 1); - assert.equal(report.conflicts[0]!.reason, "canonical-local-file-missing"); - assert.deepEqual(Object.keys(state.squads), ["foo-aaaaaaaa"]); -}); - -test("recanonicalize: skips UUID-suffixed keys when only the matching local file exists (normal post-pull layout)", () => { - const state = makeStateFile({ - assistants: { - "call-transfer-test-c95f4c6b": makeStateEntry( - "c95f4c6b-bfde-4e90-af7e-ea8870b9f2d6", - ), - }, - }); - const report = recanonicalizeStateKeys({ - state, - fileExists: makeFileExists( - new Set(["assistants/call-transfer-test-c95f4c6b.md"]), - ), - }); - assert.equal(report.rekeys.length, 0); - assert.equal(report.conflicts.length, 0); -}); - -test("recanonicalize: respects all loader-recognized extensions (.yml/.yaml/.ts/.md) for precondition 4", () => { - // VALID_EXTENSIONS in src/resources.ts includes `.ts` (TypeScript - // resources via dynamic import). Without importing the canonical - // list, precondition 4 would mis-report a `.ts`-authored canonical - // file as missing. Regression guard for the should-fix surfaced in - // post-merge review. - for (const ext of [".yml", ".yaml", ".ts", ".md"]) { - const state = makeStateFile({ - tools: { - "foo-aaaaaaaa": makeStateEntry("aaaaaaaa-0000-0000-0000-000000000000"), - }, - }); - const report = recanonicalizeStateKeys({ - state, - fileExists: makeFileExists(new Set([`tools/foo${ext}`])), - }); - assert.equal( - report.rekeys.length, - 1, - `extension ${ext} should be recognized as a canonical file`, - ); - assert.equal(report.conflicts.length, 0); - } -}); - -test("recanonicalize: refuses when BOTH local files exist as `.ts` (precondition 5 covers every loader extension)", () => { - // Direct regression guard for the data-loss shape: a `.ts`-authored - // resource paired with a UUID-suffixed `.ts` twin must trigger the - // "both files exist" conflict, not silently rekey. - const state = makeStateFile({ - tools: { - "foo-aaaaaaaa": makeStateEntry("aaaaaaaa-0000-0000-0000-000000000000"), - }, - }); - const report = recanonicalizeStateKeys({ - state, - fileExists: makeFileExists( - new Set(["tools/foo.ts", "tools/foo-aaaaaaaa.ts"]), - ), - }); - assert.equal(report.rekeys.length, 0); - assert.equal(report.conflicts.length, 1); - assert.equal(report.conflicts[0]!.reason, "both-local-files-exist"); -}); - -test("recanonicalize: refuses when BOTH local files exist (would silently swap which file PATCHes which dashboard UUID)", () => { - // The user has both `foo.yml` (original content) and `foo-aaaaaaaa.yml` - // (the new twin's content) on disk. Rekeying state would make `foo.yml` - // PATCH the wrong dashboard UUID. Refuse — operator must consolidate. - const state = makeStateFile({ - squads: { - "foo-aaaaaaaa": makeStateEntry("aaaaaaaa-0000-0000-0000-000000000000"), - }, - }); - const report = recanonicalizeStateKeys({ - state, - fileExists: makeFileExists( - new Set(["squads/foo.yml", "squads/foo-aaaaaaaa.yml"]), - ), - }); - assert.equal(report.rekeys.length, 0); - assert.equal(report.conflicts.length, 1); - assert.equal(report.conflicts[0]!.reason, "both-local-files-exist"); - assert.deepEqual(Object.keys(state.squads), ["foo-aaaaaaaa"]); -}); - -test("recanonicalize: ignores keys without UUID-suffix shape", () => { - // Plain canonical keys are left alone. - const state = makeStateFile({ - squads: { - "ordinary-squad": makeStateEntry("aaaaaaaa-0000-0000-0000-000000000000"), - }, - }); - const report = recanonicalizeStateKeys({ - state, - fileExists: makeFileExists(new Set(["squads/ordinary-squad.yml"])), - }); - assert.equal(report.rekeys.length, 0); - assert.equal(report.conflicts.length, 0); -}); - -test("recanonicalize: handles UUID prefix match case-insensitively", () => { - // UUIDs in state are typically lowercase, but be defensive. - const state = makeStateFile({ - squads: { - "foo-AAAAAAAA": makeStateEntry("AAAAAAAA-0000-0000-0000-000000000000"), - }, - }); - const report = recanonicalizeStateKeys({ - state, - fileExists: makeFileExists(new Set(["squads/foo.yml"])), - }); - assert.equal(report.rekeys.length, 1); - assert.equal(report.rekeys[0]!.toKey, "foo"); -}); - -// ───────────────────────────────────────────────────────────────────────────── -// Multi-segment-before-uuid8 — the exact shape from the user's bug report. -// ───────────────────────────────────────────────────────────────────────────── - -test("recanonicalize: collapses multi-dash base slug ('foo-vmd-') — the exact shape the orphan-gate pairing missed", () => { - // From the live incident: state key was - // `voicemail-triage-squad-llm-only-vmd-004c5108`. The orphan-gate's - // extractBaseSlug pairing failed because base = "...-vmd" not "...". - // This pass operates on raw UUID-suffix shape, so it recanonicalizes - // regardless of how many dash-segments precede the UUID8 — as long as - // the canonical local file exists. - const state = makeStateFile({ - squads: { - "voicemail-triage-squad-llm-only-vmd-004c5108": makeStateEntry( - "004c5108-aaaa-bbbb-cccc-dddddddddddd", - ), - }, - }); - const report = recanonicalizeStateKeys({ - state, - fileExists: makeFileExists( - new Set(["squads/voicemail-triage-squad-llm-only-vmd.yml"]), - ), - }); - assert.equal(report.rekeys.length, 1); - assert.equal( - report.rekeys[0]!.toKey, - "voicemail-triage-squad-llm-only-vmd", - ); - assert.equal(report.conflicts.length, 0); -}); - -// ───────────────────────────────────────────────────────────────────────────── -// Scoped-push integration — H1 regression guard -// ───────────────────────────────────────────────────────────────────────────── - -test("recanonicalize: passing `touched` marks both old and new keys so mergeScoped flushes the rename (H1 regression)", async () => { - // Without `touched`, mergeScoped re-overlays the on-disk stale key over - // our in-memory rename, persisting a state file with BOTH keys pointing - // at the same UUID. With `touched`, both the deleted UUID-suffixed key - // (so the deletion flushes) and the new canonical key (so the new entry - // is overlaid) are marked. - const { mergeScoped } = await import("../src/state-merge.ts"); - const emptyTouched = () => ({ - tools: new Set(), - structuredOutputs: new Set(), - assistants: new Set(), - squads: new Set(), - personalities: new Set(), - scenarios: new Set(), - simulations: new Set(), - simulationSuites: new Set(), - evals: new Set(), - credentials: new Set(), - }); - - const onDisk = makeStateFile({ - squads: { - "foo-aaaaaaaa": makeStateEntry("aaaaaaaa-0000-0000-0000-000000000000"), - }, - }); - // Simulate the push pipeline: load disk state → recanonicalize - // (mutates in-place) → run apply phase → save via mergeScoped. - const inMemory = makeStateFile({ - squads: { - "foo-aaaaaaaa": makeStateEntry("aaaaaaaa-0000-0000-0000-000000000000"), - }, - }); - const touched = emptyTouched(); - const report = recanonicalizeStateKeys({ - state: inMemory, - fileExists: makeFileExists(new Set(["squads/foo.yml"])), - touched, - }); - assert.equal(report.rekeys.length, 1); - assert.ok(touched.squads.has("foo-aaaaaaaa")); - assert.ok(touched.squads.has("foo")); - - // The save-time merge must produce a state with ONLY the canonical key. - const merged = mergeScoped(onDisk, inMemory, touched); - assert.deepEqual(Object.keys(merged.squads), ["foo"]); - assert.equal( - merged.squads["foo"]!.uuid, - "aaaaaaaa-0000-0000-0000-000000000000", - ); -}); - -test("recanonicalize: omitting `touched` is allowed (pull path saves wholesale)", () => { - // Pull's saveState replaces the entire state file, so it doesn't need - // `touched`. The pass should not throw when omitted. - const state = makeStateFile({ - squads: { - "foo-aaaaaaaa": makeStateEntry("aaaaaaaa-0000-0000-0000-000000000000"), - }, - }); - const report = recanonicalizeStateKeys({ - state, - fileExists: makeFileExists(new Set(["squads/foo.yml"])), - }); - assert.equal(report.rekeys.length, 1); -}); - -// ───────────────────────────────────────────────────────────────────────────── -// Cross-section safety -// ───────────────────────────────────────────────────────────────────────────── - -test("recanonicalize: state.credentials section is never touched (credentials are name-keyed, not slug-uuid8)", () => { - // Credentials use credential names as keys ('twilio-prod'), not the - // engine-generated `-` shape. Even if a credential name - // happened to look UUID-suffixed, recanonicalize must not touch the - // credentials section because it's not in VALID_RESOURCE_TYPES. - const state = makeStateFile({ - credentials: { - "looks-suffixed-aaaaaaaa": makeStateEntry( - "aaaaaaaa-0000-0000-0000-000000000000", - ), - }, - }); - const report = recanonicalizeStateKeys({ - state, - fileExists: makeFileExists(new Set()), - }); - assert.equal(report.rekeys.length, 0); - assert.equal(report.conflicts.length, 0); - assert.deepEqual(Object.keys(state.credentials), ["looks-suffixed-aaaaaaaa"]); -}); - -test("recanonicalize: `types` option restricts the pass to the named types only (typeFilter wiring)", () => { - // Used by pull's typeFilter gate so a `--type squads` pull doesn't sweep - // tools/assistants that this run didn't refresh. - const state = makeStateFile({ - squads: { - "foo-aaaaaaaa": makeStateEntry("aaaaaaaa-0000-0000-0000-000000000000"), - }, - tools: { - "bar-bbbbbbbb": makeStateEntry("bbbbbbbb-0000-0000-0000-000000000000"), - }, - }); - const report = recanonicalizeStateKeys({ - state, - types: ["squads"], - fileExists: makeFileExists(new Set(["squads/foo.yml", "tools/bar.yml"])), - }); - assert.equal(report.rekeys.length, 1); - assert.equal(report.rekeys[0]!.type, "squads"); - // Tools section unchanged because it wasn't in `types`. - assert.deepEqual(Object.keys(state.tools), ["bar-bbbbbbbb"]); -}); - -// ───────────────────────────────────────────────────────────────────────────── -// Reporter formatting -// ───────────────────────────────────────────────────────────────────────────── - -test("formatRecanonicalizeReport: empty report renders empty string (callers can unconditionally log)", () => { - const out = formatRecanonicalizeReport({ rekeys: [], conflicts: [] }); - assert.equal(out, ""); -}); - -test("formatRecanonicalizeReport: rekeys section lists each from→to mapping", () => { - const out = formatRecanonicalizeReport({ - rekeys: [ - { - type: "squads" as ResourceType, - fromKey: "foo-aaaaaaaa", - toKey: "foo", - uuid: "aaaaaaaa-0000-0000-0000-000000000000", - }, - ], - conflicts: [], - }); - assert.match(out, /Recanonicalized 1 state key/); - assert.match(out, /squads\/foo-aaaaaaaa → squads\/foo/); -}); - -test("formatRecanonicalizeReport: conflicts carry actionable per-reason hints", () => { - const out = formatRecanonicalizeReport({ - rekeys: [], - conflicts: [ - { - type: "squads" as ResourceType, - uuidSuffixedKey: "foo-aaaaaaaa", - canonicalKey: "foo", - reason: "both-local-files-exist", - uuid: "aaaaaaaa-0000-0000-0000-000000000000", - }, - ], - }); - assert.match(out, /both .* exist/); - assert.match(out, /pick one and delete the other/); -}); diff --git a/tests/reconcile-state-key.test.ts b/tests/reconcile-state-key.test.ts index c1953ff..1141e96 100644 --- a/tests/reconcile-state-key.test.ts +++ b/tests/reconcile-state-key.test.ts @@ -161,7 +161,10 @@ for (const rtype of RTYPES) { const h = makeHarness(); const sharedUuid = "00000000-0000-0000-0000-000000000aaa"; // Pre-existing alias under a bootstrap-renamed key, same UUID. - h.state[rtype]["my-resource-12345678"] = { uuid: sharedUuid }; + h.state[rtype]["my-resource-12345678"] = { + uuid: sharedUuid, + origin: "pushed", + }; const resource = makeResource(rtype, "my-resource", "my-resource"); await runReconcile({ @@ -174,7 +177,10 @@ for (const rtype of RTYPES) { // Canonical key now points at the adopted UUID. The entry is a bare // { uuid }: the drift baseline is recorded by applyFn's own push path in // the hash store, never in state. - assert.deepEqual(h.state[rtype]["my-resource"], { uuid: sharedUuid }); + assert.deepEqual(h.state[rtype]["my-resource"], { + uuid: sharedUuid, + origin: "pushed", + }); // Alias was deleted. assert.equal(h.state[rtype]["my-resource-12345678"], undefined); // Both keys marked touched: the deletion AND the new canonical entry. @@ -200,7 +206,10 @@ for (const rtype of RTYPES) { test(`[${rtype}] scenario 2: state hit, different uuid, adopts and rekeys`, async () => { const h = makeHarness(); const adoptedUuid = "11111111-1111-1111-1111-111111111aaa"; - h.state[rtype]["end-call-67aea057"] = { uuid: adoptedUuid }; + h.state[rtype]["end-call-67aea057"] = { + uuid: adoptedUuid, + origin: "pushed", + }; const resource = makeResource(rtype, "end-call", "end-call"); await runReconcile({ @@ -226,7 +235,7 @@ for (const rtype of RTYPES) { // ───────────────────────────────────────────────────────────────────────────── for (const rtype of RTYPES) { - test(`[${rtype}] scenario 3: dashboard hit only, adopts remote UUID`, async () => { + test(`[${rtype}] scenario 3: dashboard hit only creates new UUID`, async () => { const h = makeHarness(); const dashboardUuid = "22222222-2222-2222-2222-222222222aaa"; const resource = makeResource(rtype, "my-resource", "My Resource"); @@ -238,7 +247,10 @@ for (const rtype of RTYPES) { harness: h, }); - assert.equal(h.state[rtype]["my-resource"]?.uuid, dashboardUuid); + assert.equal( + h.state[rtype]["my-resource"]?.uuid, + "uuid-my-resource-created", + ); assert.equal(h.applyCalls.length, 1); assert.equal(h.applied[rtype], 1); assert.ok(h.autoApplied.has(`${rtype}:my-resource`)); @@ -253,7 +265,7 @@ for (const rtype of RTYPES) { // ───────────────────────────────────────────────────────────────────────────── for (const rtype of RTYPES) { - test(`[${rtype}] scenario 4: ambiguous dashboard match, picks lex-smallest`, async () => { + test(`[${rtype}] scenario 4: ambiguous dashboard matches only warn`, async () => { const h = makeHarness(); const uuidA = "11111111-1111-1111-1111-111111111aaa"; const uuidB = "22222222-2222-2222-2222-222222222aaa"; @@ -280,8 +292,8 @@ for (const rtype of RTYPES) { } // Lex-smallest wins → uuidA. - assert.equal(h.state[rtype]["dup"]?.uuid, uuidA); - assert.ok(warnings.some((w) => w.includes("Multiple"))); + assert.equal(h.state[rtype]["dup"]?.uuid, "uuid-dup-created"); + assert.ok(warnings.some((w) => w.includes("NOT linked"))); assert.ok(warnings.some((w) => w.includes(uuidB))); assert.equal(h.applied[rtype], 1); }); @@ -400,7 +412,7 @@ for (const rtype of RTYPES) { // - alias A pointing at the adopted uuid → MUST be deleted // - alias B pointing at the duplicate uuid → MUST be preserved // - alias C pointing at an unrelated uuid → MUST be preserved - h.state[rtype]["dup-aaaaaaaa"] = { uuid: adoptedUuid }; + h.state[rtype]["dup-aaaaaaaa"] = { uuid: adoptedUuid, origin: "pushed" }; h.state[rtype]["dup-bbbbbbbb"] = { uuid: duplicateUuid }; h.state[rtype]["unrelated-cccccccc"] = { uuid: "99999999-9999-9999-9999-999999999aaa", @@ -442,3 +454,41 @@ for (const rtype of RTYPES) { assert.equal(h.touched[rtype].has("unrelated-cccccccc"), false); }); } + +for (const rtype of RTYPES) { + for (const origin of ["pulled", undefined] as const) { + test(`[${rtype}] ${origin} state match is warned about, never rekeyed`, async () => { + const h = makeHarness(); + h.state[rtype]["stop-abcd1234"] = { + uuid: "old", + ...(origin ? { origin } : {}), + }; + const warnings: string[] = []; + const original = console.warn; + console.warn = (message: string) => { + warnings.push(message); + }; + try { + await runReconcile({ + rtype, + resource: makeResource(rtype, "stop", "Stop"), + harness: h, + }); + } finally { + console.warn = original; + } + assert.equal(h.state[rtype].stop?.uuid, "uuid-stop-created"); + assert.equal(h.state[rtype]["stop-abcd1234"]?.uuid, "old"); + assert.equal(h.touched[rtype].has("stop-abcd1234"), false); + assert.ok( + warnings.some( + (line) => + line.includes(rtype) && + line.includes("Stop") && + line.includes("old") && + line.includes("--adopt stop"), + ), + ); + }); + } +} diff --git a/tests/state-migration.test.ts b/tests/state-migration.test.ts index 069bcef..ea8c219 100644 --- a/tests/state-migration.test.ts +++ b/tests/state-migration.test.ts @@ -99,3 +99,22 @@ test("canonicalize: preserves array order", () => { const result = canonicalize({ ids: ["c", "a", "b"] }); assert.deepEqual(result, { ids: ["c", "a", "b"] }); }); + +test("state provenance survives serialization and updates without backfilling legacy entries", () => { + for (const origin of ["pushed", "pulled", "adopted"] as const) { + const entry = { uuid: "u", origin }; + assert.deepEqual(asResourceState(JSON.parse(JSON.stringify(entry))), entry); + const section = { agent: entry }; + upsertState(section, "agent", { uuid: "u", origin: "pulled" }); + assert.deepEqual(section.agent, entry); + } + const legacy: Record = { agent: { uuid: "u" } }; + upsertState(legacy, "agent", { uuid: "u", origin: "pulled" }); + assert.deepEqual(legacy.agent, { uuid: "u" }); + const fresh: Record = {}; + upsertState(fresh, "agent", { uuid: "u", origin: "pushed" }); + assert.deepEqual(fresh.agent, { uuid: "u", origin: "pushed" }); + assert.deepEqual(asResourceState({ uuid: "u", origin: "invalid" }), { + uuid: "u", + }); +}); diff --git a/tests/stop-report.test.ts b/tests/stop-report.test.ts new file mode 100644 index 0000000..37bca6e --- /dev/null +++ b/tests/stop-report.test.ts @@ -0,0 +1,45 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + formatStopReport, + jsonStopReport, + type StopIssue, + shellQuote, +} from "../src/stop-report.ts"; + +const issue = (id: string): StopIssue => ({ + file: `assistants/${id}.md`, + resourceType: "assistants", + problem: "Not linked yet", + fix: "Explicitly approve adoption", + command: `npm run push -- test --adopt ${id} assistants/${id}.md`, + args: [`--adopt ${id}`, `assistants/${id}.md`], +}); +test("one grouped report ends with one combined command for unique suggestions", () => { + const output = formatStopReport([issue("foo"), issue("bar")], "test"); + assert.equal(output.match(/Push stopped:/g)?.length, 1); + assert.match( + output, + /Suggested command.*npm run push -- test --adopt foo assistants\/foo.md --adopt bar assistants\/bar.md/, + ); + assert.doesNotMatch(output, /orphan/i); +}); +test("a human choice prevents a combined command", () => { + const output = formatStopReport( + [{ ...issue("foo"), needsChoice: true }], + "test", + ); + assert.match(output, /Human choice needed: assistants\/foo.md/); + assert.doesNotMatch(output, /Suggested command/); +}); +test("JSON is an array of only the documented fields, including empty reports", () => { + assert.deepEqual(Object.keys(JSON.parse(jsonStopReport([issue("foo")]))[0]), [ + "file", + "resourceType", + "problem", + "fix", + "command", + ]); + assert.equal(jsonStopReport([]), "[]"); + assert.equal(shellQuote("path with spaces"), "'path with spaces'"); +});